code_text
stringlengths
604
999k
repo_name
stringlengths
4
100
file_path
stringlengths
4
873
language
stringclasses
23 values
license
stringclasses
15 values
size
int32
1.02k
999k
/*:nodoc:* * class ActionVersion * * Support action for printing program version * This class inherited from [[Action]] **/ 'use strict'; var util = require('util'); var Action = require('../action'); // // Constants // var $$ = require('../const'); /*:nodoc:* * new ActionVersion(options) * - options (object): options hash see [[Action.new]] * **/ var ActionVersion = module.exports = function ActionVersion(options) { options = options || {}; options.defaultValue = (!!options.defaultValue ? options.defaultValue: $$.SUPPRESS); options.dest = (options.dest || $$.SUPPRESS); options.nargs = 0; this.version = options.version; Action.call(this, options); }; util.inherits(ActionVersion, Action); /*:nodoc:* * ActionVersion#call(parser, namespace, values, optionString) -> Void * - parser (ArgumentParser): current parser * - namespace (Namespace): namespace for output data * - values (Array): parsed values * - optionString (Array): input option string(not parsed) * * Print version and exit **/ ActionVersion.prototype.call = function (parser) { var version = this.version || parser.version; var formatter = parser._getFormatter(); formatter.addText(version); parser.exit(0, formatter.formatHelp()); };
srednakun/bandNameGenerator
node_modules/grunt/node_modules/js-yaml/node_modules/argparse/lib/action/version.js
JavaScript
apache-2.0
1,251
/** * 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.component.hdfs2; import java.io.Closeable; import java.io.IOException; import java.util.concurrent.atomic.AtomicLong; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IOUtils; public class HdfsInputStream implements Closeable { private HdfsFileType fileType; private String actualPath; private String suffixedPath; private String suffixedReadPath; private Closeable in; private boolean opened; private int chunkSize; private final AtomicLong numOfReadBytes = new AtomicLong(0L); private final AtomicLong numOfReadMessages = new AtomicLong(0L); protected HdfsInputStream() { } public static HdfsInputStream createInputStream(String hdfsPath, HdfsConfiguration configuration) throws IOException { HdfsInputStream ret = new HdfsInputStream(); ret.fileType = configuration.getFileType(); ret.actualPath = hdfsPath; ret.suffixedPath = ret.actualPath + '.' + configuration.getOpenedSuffix(); ret.suffixedReadPath = ret.actualPath + '.' + configuration.getReadSuffix(); ret.chunkSize = configuration.getChunkSize(); HdfsInfo info = HdfsInfoFactory.newHdfsInfo(ret.actualPath); if (info.getFileSystem().rename(new Path(ret.actualPath), new Path(ret.suffixedPath))) { ret.in = ret.fileType.createInputStream(ret.suffixedPath, configuration); ret.opened = true; } else { ret.opened = false; } return ret; } @Override public final void close() throws IOException { if (opened) { IOUtils.closeStream(in); HdfsInfo info = HdfsInfoFactory.newHdfsInfo(actualPath); info.getFileSystem().rename(new Path(suffixedPath), new Path(suffixedReadPath)); opened = false; } } /** * Reads next record/chunk specific to give file type. * @param key * @param value * @return number of bytes read. 0 is correct number of bytes (empty file), -1 indicates no record was read */ public final long next(Holder<Object> key, Holder<Object> value) { long nb = fileType.next(this, key, value); // when zero bytes was read from given type of file, we may still have a record (e.g., empty file) // null value.value is the only indication that no (new) record/chunk was read if (nb == 0 && numOfReadMessages.get() > 0) { // we've read all chunks from file, which size is exact multiple the chunk size return -1; } if (value.value != null) { numOfReadBytes.addAndGet(nb); numOfReadMessages.incrementAndGet(); return nb; } return -1; } public final long getNumOfReadBytes() { return numOfReadBytes.longValue(); } public final long getNumOfReadMessages() { return numOfReadMessages.longValue(); } public final String getActualPath() { return actualPath; } public final int getChunkSize() { return chunkSize; } public final Closeable getIn() { return in; } public boolean isOpened() { return opened; } }
stravag/camel
components/camel-hdfs2/src/main/java/org/apache/camel/component/hdfs2/HdfsInputStream.java
Java
apache-2.0
4,025
/** * 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.itest.mail; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Ignore; import org.junit.Test; import org.jvnet.mock_javamail.Mailbox; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; /** * Unit testing Mail configured using spring bean */ @ContextConfiguration @Ignore public class SpringMailEndpointTest extends AbstractJUnit4SpringContextTests { @Autowired protected ProducerTemplate template; @EndpointInject(uri = "mock:result") protected MockEndpoint result; @Test public void testMailEndpointAsSpringBean() throws Exception { Mailbox.clearAll(); String body = "Hello Claus.\nYes it does.\n\nRegards James."; result.expectedBodiesReceived(body); result.expectedHeaderReceived("subject", "Hello Camel"); template.sendBodyAndHeader("smtp://james2@localhost", body, "subject", "Hello Camel"); result.assertIsSatisfied(); } }
jlpedrosa/camel
tests/camel-itest/src/test/java/org/apache/camel/itest/mail/SpringMailEndpointTest.java
Java
apache-2.0
2,001
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.action.admin.indices.forcemerge; import org.elasticsearch.action.support.broadcast.BroadcastOperationRequestBuilder; import org.elasticsearch.client.ElasticsearchClient; /** * A request to force merge one or more indices. In order to force merge all * indices, pass an empty array or <tt>null</tt> for the indices. * {@link #setMaxNumSegments(int)} allows to control the number of segments to force * merge down to. By default, will cause the force merge process to merge down * to half the configured number of segments. */ public class ForceMergeRequestBuilder extends BroadcastOperationRequestBuilder<ForceMergeRequest, ForceMergeResponse, ForceMergeRequestBuilder> { public ForceMergeRequestBuilder(ElasticsearchClient client, ForceMergeAction action) { super(client, action, new ForceMergeRequest()); } /** * Will force merge the index down to &lt;= maxNumSegments. By default, will * cause the merge process to merge down to half the configured number of * segments. */ public ForceMergeRequestBuilder setMaxNumSegments(int maxNumSegments) { request.maxNumSegments(maxNumSegments); return this; } /** * Should the merge only expunge deletes from the index, without full merging. * Defaults to full merging (<tt>false</tt>). */ public ForceMergeRequestBuilder setOnlyExpungeDeletes(boolean onlyExpungeDeletes) { request.onlyExpungeDeletes(onlyExpungeDeletes); return this; } /** * Should flush be performed after the merge. Defaults to <tt>true</tt>. */ public ForceMergeRequestBuilder setFlush(boolean flush) { request.flush(flush); return this; } }
Kamapcuc/elasticsearch
core/src/main/java/org/elasticsearch/action/admin/indices/forcemerge/ForceMergeRequestBuilder.java
Java
apache-2.0
2,529
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Loader Class * * Loads views and files * * @package CodeIgniter * @subpackage Libraries * @author ExpressionEngine Dev Team * @category Loader * @link http://codeigniter.com/user_guide/libraries/loader.html */ class CI_Loader { // All these are set automatically. Don't mess with them. /** * Nesting level of the output buffering mechanism * * @var int * @access protected */ protected $_ci_ob_level; /** * List of paths to load views from * * @var array * @access protected */ protected $_ci_view_paths = array(); /** * List of paths to load libraries from * * @var array * @access protected */ protected $_ci_library_paths = array(); /** * List of paths to load models from * * @var array * @access protected */ protected $_ci_model_paths = array(); /** * List of paths to load helpers from * * @var array * @access protected */ protected $_ci_helper_paths = array(); /** * List of loaded base classes * Set by the controller class * * @var array * @access protected */ protected $_base_classes = array(); // Set by the controller class /** * List of cached variables * * @var array * @access protected */ protected $_ci_cached_vars = array(); /** * List of loaded classes * * @var array * @access protected */ protected $_ci_classes = array(); /** * List of loaded files * * @var array * @access protected */ protected $_ci_loaded_files = array(); /** * List of loaded models * * @var array * @access protected */ protected $_ci_models = array(); /** * List of loaded helpers * * @var array * @access protected */ protected $_ci_helpers = array(); /** * List of class name mappings * * @var array * @access protected */ protected $_ci_varmap = array('unit_test' => 'unit', 'user_agent' => 'agent'); /** * Constructor * * Sets the path to the view files and gets the initial output buffering level */ public function __construct() { $this->_ci_ob_level = ob_get_level(); $this->_ci_library_paths = array(APPPATH, BASEPATH); $this->_ci_helper_paths = array(APPPATH, BASEPATH); $this->_ci_model_paths = array(APPPATH); $this->_ci_view_paths = array(APPPATH.'views/' => TRUE); log_message('debug', "Loader Class Initialized"); } // -------------------------------------------------------------------- /** * Initialize the Loader * * This method is called once in CI_Controller. * * @param array * @return object */ public function initialize() { $this->_ci_classes = array(); $this->_ci_loaded_files = array(); $this->_ci_models = array(); $this->_base_classes =& is_loaded(); $this->_ci_autoloader(); return $this; } // -------------------------------------------------------------------- /** * Is Loaded * * A utility function to test if a class is in the self::$_ci_classes array. * This function returns the object name if the class tested for is loaded, * and returns FALSE if it isn't. * * It is mainly used in the form_helper -> _get_validation_object() * * @param string class being checked for * @return mixed class object name on the CI SuperObject or FALSE */ public function is_loaded($class) { if (isset($this->_ci_classes[$class])) { return $this->_ci_classes[$class]; } return FALSE; } // -------------------------------------------------------------------- /** * Class Loader * * This function lets users load and instantiate classes. * It is designed to be called from a user's app controllers. * * @param string the name of the class * @param mixed the optional parameters * @param string an optional object name * @return void */ public function library($library = '', $params = NULL, $object_name = NULL) { if (is_array($library)) { foreach ($library as $class) { $this->library($class, $params); } return; } if ($library == '' OR isset($this->_base_classes[$library])) { return FALSE; } if ( ! is_null($params) && ! is_array($params)) { $params = NULL; } $this->_ci_load_class($library, $params, $object_name); } // -------------------------------------------------------------------- /** * Model Loader * * This function lets users load and instantiate models. * * @param string the name of the class * @param string name for the model * @param bool database connection * @return void */ public function model($model, $name = '', $db_conn = FALSE) { if (is_array($model)) { foreach ($model as $babe) { $this->model($babe); } return; } if ($model == '') { return; } $path = ''; // Is the model in a sub-folder? If so, parse out the filename and path. if (($last_slash = strrpos($model, '/')) !== FALSE) { // The path is in front of the last slash $path = substr($model, 0, $last_slash + 1); // And the model name behind it $model = substr($model, $last_slash + 1); } if ($name == '') { $name = $model; } if (in_array($name, $this->_ci_models, TRUE)) { return; } $CI =& get_instance(); if (isset($CI->$name)) { show_error('The model name you are loading is the name of a resource that is already being used: '.$name); } $model = strtolower($model); foreach ($this->_ci_model_paths as $mod_path) { if ( ! file_exists($mod_path.'models/'.$path.$model.'.php')) { continue; } if ($db_conn !== FALSE AND ! class_exists('CI_DB')) { if ($db_conn === TRUE) { $db_conn = ''; } $CI->load->database($db_conn, FALSE, TRUE); } if ( ! class_exists('CI_Model')) { load_class('Model', 'core'); } require_once($mod_path.'models/'.$path.$model.'.php'); $model = ucfirst($model); $CI->$name = new $model(); $this->_ci_models[] = $name; return; } // couldn't find the model show_error('Unable to locate the model you have specified: '.$model); } // -------------------------------------------------------------------- /** * Database Loader * * @param string the DB credentials * @param bool whether to return the DB object * @param bool whether to enable active record (this allows us to override the config setting) * @return object */ public function database($params = '', $return = FALSE, $active_record = NULL) { // Grab the super object $CI =& get_instance(); // Do we even need to load the database class? if (class_exists('CI_DB') AND $return == FALSE AND $active_record == NULL AND isset($CI->db) AND is_object($CI->db)) { return FALSE; } require_once(BASEPATH.'database/DB.php'); if ($return === TRUE) { return DB($params, $active_record); } // Initialize the db variable. Needed to prevent // reference errors with some configurations $CI->db = ''; // Load the DB class $CI->db =& DB($params, $active_record); } // -------------------------------------------------------------------- /** * Load the Utilities Class * * @return string */ public function dbutil() { if ( ! class_exists('CI_DB')) { $this->database(); } $CI =& get_instance(); // for backwards compatibility, load dbforge so we can extend dbutils off it // this use is deprecated and strongly discouraged $CI->load->dbforge(); require_once(BASEPATH.'database/DB_utility.php'); require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_utility.php'); $class = 'CI_DB_'.$CI->db->dbdriver.'_utility'; $CI->dbutil = new $class(); } // -------------------------------------------------------------------- /** * Load the Database Forge Class * * @return string */ public function dbforge() { if ( ! class_exists('CI_DB')) { $this->database(); } $CI =& get_instance(); require_once(BASEPATH.'database/DB_forge.php'); require_once(BASEPATH.'database/drivers/'.$CI->db->dbdriver.'/'.$CI->db->dbdriver.'_forge.php'); $class = 'CI_DB_'.$CI->db->dbdriver.'_forge'; $CI->dbforge = new $class(); } // -------------------------------------------------------------------- /** * Load View * * This function is used to load a "view" file. It has three parameters: * * 1. The name of the "view" file to be included. * 2. An associative array of data to be extracted for use in the view. * 3. TRUE/FALSE - whether to return the data or load it. In * some cases it's advantageous to be able to return data so that * a developer can process it in some way. * * @param string * @param array * @param bool * @return void */ public function view($view, $vars = array(), $return = FALSE) { return $this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return)); } // -------------------------------------------------------------------- /** * Load File * * This is a generic file loader * * @param string * @param bool * @return string */ public function file($path, $return = FALSE) { return $this->_ci_load(array('_ci_path' => $path, '_ci_return' => $return)); } // -------------------------------------------------------------------- /** * Set Variables * * Once variables are set they become available within * the controller class and its "view" files. * * @param array * @param string * @return void */ public function vars($vars = array(), $val = '') { if ($val != '' AND is_string($vars)) { $vars = array($vars => $val); } $vars = $this->_ci_object_to_array($vars); if (is_array($vars) AND count($vars) > 0) { foreach ($vars as $key => $val) { $this->_ci_cached_vars[$key] = $val; } } } // -------------------------------------------------------------------- /** * Get Variable * * Check if a variable is set and retrieve it. * * @param array * @return void */ public function get_var($key) { return isset($this->_ci_cached_vars[$key]) ? $this->_ci_cached_vars[$key] : NULL; } // -------------------------------------------------------------------- /** * Load Helper * * This function loads the specified helper file. * * @param mixed * @return void */ public function helper($helpers = array()) { foreach ($this->_ci_prep_filename($helpers, '_helper') as $helper) { if (isset($this->_ci_helpers[$helper])) { continue; } $ext_helper = APPPATH.'helpers/'.config_item('subclass_prefix').$helper.'.php'; // Is this a helper extension request? if (file_exists($ext_helper)) { $base_helper = BASEPATH.'helpers/'.$helper.'.php'; if ( ! file_exists($base_helper)) { show_error('Unable to load the requested file: helpers/'.$helper.'.php'); } include_once($ext_helper); include_once($base_helper); $this->_ci_helpers[$helper] = TRUE; log_message('debug', 'Helper loaded: '.$helper); continue; } // Try to load the helper foreach ($this->_ci_helper_paths as $path) { if (file_exists($path.'helpers/'.$helper.'.php')) { include_once($path.'helpers/'.$helper.'.php'); $this->_ci_helpers[$helper] = TRUE; log_message('debug', 'Helper loaded: '.$helper); break; } } // unable to load the helper if ( ! isset($this->_ci_helpers[$helper])) { show_error('Unable to load the requested file: helpers/'.$helper.'.php'); } } } // -------------------------------------------------------------------- /** * Load Helpers * * This is simply an alias to the above function in case the * user has written the plural form of this function. * * @param array * @return void */ public function helpers($helpers = array()) { $this->helper($helpers); } // -------------------------------------------------------------------- /** * Loads a language file * * @param array * @param string * @return void */ public function language($file = array(), $lang = '') { $CI =& get_instance(); if ( ! is_array($file)) { $file = array($file); } foreach ($file as $langfile) { $CI->lang->load($langfile, $lang); } } // -------------------------------------------------------------------- /** * Loads a config file * * @param string * @param bool * @param bool * @return void */ public function config($file = '', $use_sections = FALSE, $fail_gracefully = FALSE) { $CI =& get_instance(); $CI->config->load($file, $use_sections, $fail_gracefully); } // -------------------------------------------------------------------- /** * Driver * * Loads a driver library * * @param string the name of the class * @param mixed the optional parameters * @param string an optional object name * @return void */ public function driver($library = '', $params = NULL, $object_name = NULL) { if ( ! class_exists('CI_Driver_Library')) { // we aren't instantiating an object here, that'll be done by the Library itself require BASEPATH.'libraries/Driver.php'; } if ($library == '') { return FALSE; } // We can save the loader some time since Drivers will *always* be in a subfolder, // and typically identically named to the library if ( ! strpos($library, '/')) { $library = ucfirst($library).'/'.$library; } return $this->library($library, $params, $object_name); } // -------------------------------------------------------------------- /** * Add Package Path * * Prepends a parent path to the library, model, helper, and config path arrays * * @param string * @param boolean * @return void */ public function add_package_path($path, $view_cascade=TRUE) { $path = rtrim($path, '/').'/'; array_unshift($this->_ci_library_paths, $path); array_unshift($this->_ci_model_paths, $path); array_unshift($this->_ci_helper_paths, $path); $this->_ci_view_paths = array($path.'views/' => $view_cascade) + $this->_ci_view_paths; // Add config file path $config =& $this->_ci_get_component('config'); array_unshift($config->_config_paths, $path); } // -------------------------------------------------------------------- /** * Get Package Paths * * Return a list of all package paths, by default it will ignore BASEPATH. * * @param string * @return void */ public function get_package_paths($include_base = FALSE) { return $include_base === TRUE ? $this->_ci_library_paths : $this->_ci_model_paths; } // -------------------------------------------------------------------- /** * Remove Package Path * * Remove a path from the library, model, and helper path arrays if it exists * If no path is provided, the most recently added path is removed. * * @param type * @param bool * @return type */ public function remove_package_path($path = '', $remove_config_path = TRUE) { $config =& $this->_ci_get_component('config'); if ($path == '') { $void = array_shift($this->_ci_library_paths); $void = array_shift($this->_ci_model_paths); $void = array_shift($this->_ci_helper_paths); $void = array_shift($this->_ci_view_paths); $void = array_shift($config->_config_paths); } else { $path = rtrim($path, '/').'/'; foreach (array('_ci_library_paths', '_ci_model_paths', '_ci_helper_paths') as $var) { if (($key = array_search($path, $this->{$var})) !== FALSE) { unset($this->{$var}[$key]); } } if (isset($this->_ci_view_paths[$path.'views/'])) { unset($this->_ci_view_paths[$path.'views/']); } if (($key = array_search($path, $config->_config_paths)) !== FALSE) { unset($config->_config_paths[$key]); } } // make sure the application default paths are still in the array $this->_ci_library_paths = array_unique(array_merge($this->_ci_library_paths, array(APPPATH, BASEPATH))); $this->_ci_helper_paths = array_unique(array_merge($this->_ci_helper_paths, array(APPPATH, BASEPATH))); $this->_ci_model_paths = array_unique(array_merge($this->_ci_model_paths, array(APPPATH))); $this->_ci_view_paths = array_merge($this->_ci_view_paths, array(APPPATH.'views/' => TRUE)); $config->_config_paths = array_unique(array_merge($config->_config_paths, array(APPPATH))); } // -------------------------------------------------------------------- /** * Loader * * This function is used to load views and files. * Variables are prefixed with _ci_ to avoid symbol collision with * variables made available to view files * * @param array * @return void */ protected function _ci_load($_ci_data) { // Set the default data variables foreach (array('_ci_view', '_ci_vars', '_ci_path', '_ci_return') as $_ci_val) { $$_ci_val = ( ! isset($_ci_data[$_ci_val])) ? FALSE : $_ci_data[$_ci_val]; } $file_exists = FALSE; // Set the path to the requested file if ($_ci_path != '') { $_ci_x = explode('/', $_ci_path); $_ci_file = end($_ci_x); } else { $_ci_ext = pathinfo($_ci_view, PATHINFO_EXTENSION); $_ci_file = ($_ci_ext == '') ? $_ci_view.'.php' : $_ci_view; foreach ($this->_ci_view_paths as $view_file => $cascade) { if (file_exists($view_file.$_ci_file)) { $_ci_path = $view_file.$_ci_file; $file_exists = TRUE; break; } if ( ! $cascade) { break; } } } if ( ! $file_exists && ! file_exists($_ci_path)) { show_error('Unable to load the requested file: '.$_ci_file); } // This allows anything loaded using $this->load (views, files, etc.) // to become accessible from within the Controller and Model functions. $_ci_CI =& get_instance(); foreach (get_object_vars($_ci_CI) as $_ci_key => $_ci_var) { if ( ! isset($this->$_ci_key)) { $this->$_ci_key =& $_ci_CI->$_ci_key; } } /* * Extract and cache variables * * You can either set variables using the dedicated $this->load_vars() * function or via the second parameter of this function. We'll merge * the two types and cache them so that views that are embedded within * other views can have access to these variables. */ if (is_array($_ci_vars)) { $this->_ci_cached_vars = array_merge($this->_ci_cached_vars, $_ci_vars); } extract($this->_ci_cached_vars); /* * Buffer the output * * We buffer the output for two reasons: * 1. Speed. You get a significant speed boost. * 2. So that the final rendered template can be * post-processed by the output class. Why do we * need post processing? For one thing, in order to * show the elapsed page load time. Unless we * can intercept the content right before it's sent to * the browser and then stop the timer it won't be accurate. */ ob_start(); // If the PHP installation does not support short tags we'll // do a little string replacement, changing the short tags // to standard PHP echo statements. if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE) { echo eval('?>'.preg_replace("/;*\s*\?>/", "; ?>", str_replace('<?=', '<?php echo ', file_get_contents($_ci_path)))); } else { include($_ci_path); // include() vs include_once() allows for multiple views with the same name } log_message('debug', 'File loaded: '.$_ci_path); // Return the file data if requested if ($_ci_return === TRUE) { $buffer = ob_get_contents(); @ob_end_clean(); return $buffer; } /* * Flush the buffer... or buff the flusher? * * In order to permit views to be nested within * other views, we need to flush the content back out whenever * we are beyond the first level of output buffering so that * it can be seen and included properly by the first included * template and any subsequent ones. Oy! * */ if (ob_get_level() > $this->_ci_ob_level + 1) { ob_end_flush(); } else { $_ci_CI->output->append_output(ob_get_contents()); @ob_end_clean(); } } // -------------------------------------------------------------------- /** * Load class * * This function loads the requested class. * * @param string the item that is being loaded * @param mixed any additional parameters * @param string an optional object name * @return void */ protected function _ci_load_class($class, $params = NULL, $object_name = NULL) { // Get the class name, and while we're at it trim any slashes. // The directory path can be included as part of the class name, // but we don't want a leading slash $class = str_replace('.php', '', trim($class, '/')); // Was the path included with the class name? // We look for a slash to determine this $subdir = ''; if (($last_slash = strrpos($class, '/')) !== FALSE) { // Extract the path $subdir = substr($class, 0, $last_slash + 1); // Get the filename from the path $class = substr($class, $last_slash + 1); } // We'll test for both lowercase and capitalized versions of the file name foreach (array(ucfirst($class), strtolower($class)) as $class) { $subclass = APPPATH.'libraries/'.$subdir.config_item('subclass_prefix').$class.'.php'; // Is this a class extension request? if (file_exists($subclass)) { $baseclass = BASEPATH.'libraries/'.ucfirst($class).'.php'; if ( ! file_exists($baseclass)) { log_message('error', "Unable to load the requested class: ".$class); show_error("Unable to load the requested class: ".$class); } // Safety: Was the class already loaded by a previous call? if (in_array($subclass, $this->_ci_loaded_files)) { // Before we deem this to be a duplicate request, let's see // if a custom object name is being supplied. If so, we'll // return a new instance of the object if ( ! is_null($object_name)) { $CI =& get_instance(); if ( ! isset($CI->$object_name)) { return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name); } } $is_duplicate = TRUE; log_message('debug', $class." class already loaded. Second attempt ignored."); return; } include_once($baseclass); include_once($subclass); $this->_ci_loaded_files[] = $subclass; return $this->_ci_init_class($class, config_item('subclass_prefix'), $params, $object_name); } // Lets search for the requested library file and load it. $is_duplicate = FALSE; foreach ($this->_ci_library_paths as $path) { $filepath = $path.'libraries/'.$subdir.$class.'.php'; // Does the file exist? No? Bummer... if ( ! file_exists($filepath)) { continue; } // Safety: Was the class already loaded by a previous call? if (in_array($filepath, $this->_ci_loaded_files)) { // Before we deem this to be a duplicate request, let's see // if a custom object name is being supplied. If so, we'll // return a new instance of the object if ( ! is_null($object_name)) { $CI =& get_instance(); if ( ! isset($CI->$object_name)) { return $this->_ci_init_class($class, '', $params, $object_name); } } $is_duplicate = TRUE; log_message('debug', $class." class already loaded. Second attempt ignored."); return; } include_once($filepath); $this->_ci_loaded_files[] = $filepath; return $this->_ci_init_class($class, '', $params, $object_name); } } // END FOREACH // One last attempt. Maybe the library is in a subdirectory, but it wasn't specified? if ($subdir == '') { $path = strtolower($class).'/'.$class; return $this->_ci_load_class($path, $params); } // If we got this far we were unable to find the requested class. // We do not issue errors if the load call failed due to a duplicate request if ($is_duplicate == FALSE) { log_message('error', "Unable to load the requested class: ".$class); show_error("Unable to load the requested class: ".$class); } } // -------------------------------------------------------------------- /** * Instantiates a class * * @param string * @param string * @param bool * @param string an optional object name * @return null */ protected function _ci_init_class($class, $prefix = '', $config = FALSE, $object_name = NULL) { // Is there an associated config file for this class? Note: these should always be lowercase if ($config === NULL) { // Fetch the config paths containing any package paths $config_component = $this->_ci_get_component('config'); if (is_array($config_component->_config_paths)) { // Break on the first found file, thus package files // are not overridden by default paths foreach ($config_component->_config_paths as $path) { // We test for both uppercase and lowercase, for servers that // are case-sensitive with regard to file names. Check for environment // first, global next if (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php')) { include($path .'config/'.ENVIRONMENT.'/'.strtolower($class).'.php'); break; } elseif (defined('ENVIRONMENT') AND file_exists($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php')) { include($path .'config/'.ENVIRONMENT.'/'.ucfirst(strtolower($class)).'.php'); break; } elseif (file_exists($path .'config/'.strtolower($class).'.php')) { include($path .'config/'.strtolower($class).'.php'); break; } elseif (file_exists($path .'config/'.ucfirst(strtolower($class)).'.php')) { include($path .'config/'.ucfirst(strtolower($class)).'.php'); break; } } } } if ($prefix == '') { if (class_exists('CI_'.$class)) { $name = 'CI_'.$class; } elseif (class_exists(config_item('subclass_prefix').$class)) { $name = config_item('subclass_prefix').$class; } else { $name = $class; } } else { $name = $prefix.$class; } // Is the class name valid? if ( ! class_exists($name)) { log_message('error', "Non-existent class: ".$name); show_error("Non-existent class: ".$class); } // Set the variable name we will assign the class to // Was a custom class name supplied? If so we'll use it $class = strtolower($class); if (is_null($object_name)) { $classvar = ( ! isset($this->_ci_varmap[$class])) ? $class : $this->_ci_varmap[$class]; } else { $classvar = $object_name; } // Save the class name and object name $this->_ci_classes[$class] = $classvar; // Instantiate the class $CI =& get_instance(); if ($config !== NULL) { $CI->$classvar = new $name($config); } else { $CI->$classvar = new $name; } } // -------------------------------------------------------------------- /** * Autoloader * * The config/autoload.php file contains an array that permits sub-systems, * libraries, and helpers to be loaded automatically. * * @param array * @return void */ private function _ci_autoloader() { if (defined('ENVIRONMENT') AND file_exists(APPPATH.'config/'.ENVIRONMENT.'/autoload.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/autoload.php'); } else { include(APPPATH.'config/autoload.php'); } if ( ! isset($autoload)) { return FALSE; } // Autoload packages if (isset($autoload['packages'])) { foreach ($autoload['packages'] as $package_path) { $this->add_package_path($package_path); } } // Load any custom config file if (count($autoload['config']) > 0) { $CI =& get_instance(); foreach ($autoload['config'] as $key => $val) { $CI->config->load($val); } } // Autoload helpers and languages foreach (array('helper', 'language') as $type) { if (isset($autoload[$type]) AND count($autoload[$type]) > 0) { $this->$type($autoload[$type]); } } // A little tweak to remain backward compatible // The $autoload['core'] item was deprecated if ( ! isset($autoload['libraries']) AND isset($autoload['core'])) { $autoload['libraries'] = $autoload['core']; } // Load libraries if (isset($autoload['libraries']) AND count($autoload['libraries']) > 0) { // Load the database driver. if (in_array('database', $autoload['libraries'])) { $this->database(); $autoload['libraries'] = array_diff($autoload['libraries'], array('database')); } // Load all other libraries foreach ($autoload['libraries'] as $item) { $this->library($item); } } // Autoload models if (isset($autoload['model'])) { $this->model($autoload['model']); } } // -------------------------------------------------------------------- /** * Object to Array * * Takes an object as input and converts the class variables to array key/vals * * @param object * @return array */ protected function _ci_object_to_array($object) { return (is_object($object)) ? get_object_vars($object) : $object; } // -------------------------------------------------------------------- /** * Get a reference to a specific library or model * * @param string * @return bool */ protected function &_ci_get_component($component) { $CI =& get_instance(); return $CI->$component; } // -------------------------------------------------------------------- /** * Prep filename * * This function preps the name of various items to make loading them more reliable. * * @param mixed * @param string * @return array */ protected function _ci_prep_filename($filename, $extension) { if ( ! is_array($filename)) { return array(strtolower(str_replace('.php', '', str_replace($extension, '', $filename)).$extension)); } else { foreach ($filename as $key => $val) { $filename[$key] = strtolower(str_replace('.php', '', str_replace($extension, '', $val)).$extension); } return $filename; } } } /* End of file Loader.php */ /* Location: ./system/core/Loader.php */
dev-wiqi/CMS
system/core/Loader.php
PHP
apache-2.0
30,576
/* NUGET: BEGIN LICENSE TEXT * * Microsoft grants you the right to use these script files for the sole * purpose of either: (i) interacting through your browser with the Microsoft * website or online service, subject to the applicable licensing or use * terms; or (ii) using the files as included with a Microsoft product subject * to that product's license terms. Microsoft reserves all other rights to the * files not expressly granted by Microsoft, whether by implication, estoppel * or otherwise. Insofar as a script file is dual licensed under GPL, * Microsoft neither took the code under GPL nor distributes it thereunder but * under the terms set out in this paragraph. All notices and licenses * below are for informational purposes only. * * NUGET: END LICENSE TEXT */ /*! matchMedia() polyfill - Test a CSS media type/query in JS. Authors & copyright (c) 2012: Scott Jehl, Paul Irish, Nicholas Zakas. Dual MIT/BSD license */ /*! NOTE: If you're already including a window.matchMedia polyfill via Modernizr or otherwise, you don't need this part */ window.matchMedia=window.matchMedia||(function(e,f){var c,a=e.documentElement,b=a.firstElementChild||a.firstChild,d=e.createElement("body"),g=e.createElement("div");g.id="mq-test-1";g.style.cssText="position:absolute;top:-100em";d.style.background="none";d.appendChild(g);return function(h){g.innerHTML='&shy;<style media="'+h+'"> #mq-test-1 { width: 42px; }</style>';a.insertBefore(d,b);c=g.offsetWidth==42;a.removeChild(d);return{matches:c,media:h}}})(document); /*! Respond.js v1.2.0: min/max-width media query polyfill. (c) Scott Jehl. MIT/GPLv2 Lic. j.mp/respondjs */ (function(e){e.respond={};respond.update=function(){};respond.mediaQueriesSupported=e.matchMedia&&e.matchMedia("only all").matches;if(respond.mediaQueriesSupported){return}var w=e.document,s=w.documentElement,i=[],k=[],q=[],o={},h=30,f=w.getElementsByTagName("head")[0]||s,g=w.getElementsByTagName("base")[0],b=f.getElementsByTagName("link"),d=[],a=function(){var D=b,y=D.length,B=0,A,z,C,x;for(;B<y;B++){A=D[B],z=A.href,C=A.media,x=A.rel&&A.rel.toLowerCase()==="stylesheet";if(!!z&&x&&!o[z]){if(A.styleSheet&&A.styleSheet.rawCssText){m(A.styleSheet.rawCssText,z,C);o[z]=true}else{if((!/^([a-zA-Z:]*\/\/)/.test(z)&&!g)||z.replace(RegExp.$1,"").split("/")[0]===e.location.host){d.push({href:z,media:C})}}}}u()},u=function(){if(d.length){var x=d.shift();n(x.href,function(y){m(y,x.href,x.media);o[x.href]=true;u()})}},m=function(I,x,z){var G=I.match(/@media[^\{]+\{([^\{\}]*\{[^\}\{]*\})+/gi),J=G&&G.length||0,x=x.substring(0,x.lastIndexOf("/")),y=function(K){return K.replace(/(url\()['"]?([^\/\)'"][^:\)'"]+)['"]?(\))/g,"$1"+x+"$2$3")},A=!J&&z,D=0,C,E,F,B,H;if(x.length){x+="/"}if(A){J=1}for(;D<J;D++){C=0;if(A){E=z;k.push(y(I))}else{E=G[D].match(/@media *([^\{]+)\{([\S\s]+?)$/)&&RegExp.$1;k.push(RegExp.$2&&y(RegExp.$2))}B=E.split(",");H=B.length;for(;C<H;C++){F=B[C];i.push({media:F.split("(")[0].match(/(only\s+)?([a-zA-Z]+)\s?/)&&RegExp.$2||"all",rules:k.length-1,hasquery:F.indexOf("(")>-1,minw:F.match(/\(min\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||""),maxw:F.match(/\(max\-width:[\s]*([\s]*[0-9\.]+)(px|em)[\s]*\)/)&&parseFloat(RegExp.$1)+(RegExp.$2||"")})}}j()},l,r,v=function(){var z,A=w.createElement("div"),x=w.body,y=false;A.style.cssText="position:absolute;font-size:1em;width:1em";if(!x){x=y=w.createElement("body");x.style.background="none"}x.appendChild(A);s.insertBefore(x,s.firstChild);z=A.offsetWidth;if(y){s.removeChild(x)}else{x.removeChild(A)}z=p=parseFloat(z);return z},p,j=function(I){var x="clientWidth",B=s[x],H=w.compatMode==="CSS1Compat"&&B||w.body[x]||B,D={},G=b[b.length-1],z=(new Date()).getTime();if(I&&l&&z-l<h){clearTimeout(r);r=setTimeout(j,h);return}else{l=z}for(var E in i){var K=i[E],C=K.minw,J=K.maxw,A=C===null,L=J===null,y="em";if(!!C){C=parseFloat(C)*(C.indexOf(y)>-1?(p||v()):1)}if(!!J){J=parseFloat(J)*(J.indexOf(y)>-1?(p||v()):1)}if(!K.hasquery||(!A||!L)&&(A||H>=C)&&(L||H<=J)){if(!D[K.media]){D[K.media]=[]}D[K.media].push(k[K.rules])}}for(var E in q){if(q[E]&&q[E].parentNode===f){f.removeChild(q[E])}}for(var E in D){var M=w.createElement("style"),F=D[E].join("\n");M.type="text/css";M.media=E;f.insertBefore(M,G.nextSibling);if(M.styleSheet){M.styleSheet.cssText=F}else{M.appendChild(w.createTextNode(F))}q.push(M)}},n=function(x,z){var y=c();if(!y){return}y.open("GET",x,true);y.onreadystatechange=function(){if(y.readyState!=4||y.status!=200&&y.status!=304){return}z(y.responseText)};if(y.readyState==4){return}y.send(null)},c=(function(){var x=false;try{x=new XMLHttpRequest()}catch(y){x=new ActiveXObject("Microsoft.XMLHTTP")}return function(){return x}})();a();respond.update=a;function t(){j(true)}if(e.addEventListener){e.addEventListener("resize",t,false)}else{if(e.attachEvent){e.attachEvent("onresize",t)}}})(this);
MaurizioPz/PnP
Samples/BusinessApps.RemoteCalendarAccess/BusinessApps.RemoteCalendarAccessWeb/Scripts/respond.min.js
JavaScript
apache-2.0
4,860
// Copyright 2016 The etcd 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 clientv3 import ( "io/ioutil" "log" "os" "reflect" "testing" "github.com/ghodss/yaml" ) var ( certPath = "../integration/fixtures/server.crt" privateKeyPath = "../integration/fixtures/server.key.insecure" caPath = "../integration/fixtures/ca.crt" ) func TestConfigFromFile(t *testing.T) { tests := []struct { ym *yamlConfig werr bool }{ { &yamlConfig{}, false, }, { &yamlConfig{ InsecureTransport: true, }, false, }, { &yamlConfig{ Keyfile: privateKeyPath, Certfile: certPath, CAfile: caPath, InsecureSkipTLSVerify: true, }, false, }, { &yamlConfig{ Keyfile: "bad", Certfile: "bad", }, true, }, { &yamlConfig{ Keyfile: privateKeyPath, Certfile: certPath, CAfile: "bad", }, true, }, } for i, tt := range tests { tmpfile, err := ioutil.TempFile("", "clientcfg") if err != nil { log.Fatal(err) } b, err := yaml.Marshal(tt.ym) if err != nil { t.Fatal(err) } _, err = tmpfile.Write(b) if err != nil { t.Fatal(err) } err = tmpfile.Close() if err != nil { t.Fatal(err) } cfg, cerr := configFromFile(tmpfile.Name()) if cerr != nil && !tt.werr { t.Errorf("#%d: err = %v, want %v", i, cerr, tt.werr) continue } if cerr != nil { continue } if !reflect.DeepEqual(cfg.Endpoints, tt.ym.Endpoints) { t.Errorf("#%d: endpoint = %v, want %v", i, cfg.Endpoints, tt.ym.Endpoints) } if tt.ym.InsecureTransport != (cfg.TLS == nil) { t.Errorf("#%d: insecureTransport = %v, want %v", i, cfg.TLS == nil, tt.ym.InsecureTransport) } if !tt.ym.InsecureTransport { if tt.ym.Certfile != "" && len(cfg.TLS.Certificates) == 0 { t.Errorf("#%d: failed to load in cert", i) } if tt.ym.CAfile != "" && cfg.TLS.RootCAs == nil { t.Errorf("#%d: failed to load in ca cert", i) } if cfg.TLS.InsecureSkipVerify != tt.ym.InsecureSkipTLSVerify { t.Errorf("#%d: skipTLSVeify = %v, want %v", i, cfg.TLS.InsecureSkipVerify, tt.ym.InsecureSkipTLSVerify) } } os.Remove(tmpfile.Name()) } }
rf232/dashboard
vendor/github.com/coreos/etcd/clientv3/config_test.go
GO
apache-2.0
2,740
/** * 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.component.jms.issues; import java.util.Collections; import org.apache.camel.builder.AdviceWithRouteBuilder; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class AdviceWithIssueTest extends CamelTestSupport { final String pub = "activemq:topic:integrations?allowNullBody=false&asyncConsumer=true&concurrentConsumers=10&jmsMessageType=Map&preserveMessageQos=true"; final String advicedPub = "activemq:topic:integrations"; @Override public boolean isUseAdviceWith() { return true; } @Test public void testAdviceWith() throws Exception { context.getRouteDefinition("starter").adviceWith(context, new AdviceWithRouteBuilder() { @Override public void configure() throws Exception { // when advicing then use wildcard as URI options cannot be matched mockEndpointsAndSkip(advicedPub + "?*"); } }); context.start(); MockEndpoint topicEndpointMock = getMockEndpoint("mock:" + advicedPub); topicEndpointMock.expectedMessageCount(1); template.sendBody("direct:start", Collections.singletonMap("foo", "bar")); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId("starter") .to(pub).to("mock:result"); } }; } }
lowwool/camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/AdviceWithIssueTest.java
Java
apache-2.0
2,502
/** * 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.component.netty.http; import org.apache.camel.builder.RouteBuilder; import org.junit.Test; public class NettyHttpSuspendResume503Test extends BaseNettyTest { private String serverUri = "netty-http:http://localhost:" + getPort() + "/cool?disconnect=true"; @Test public void testNettySuspendResume() throws Exception { // these tests does not run well on Windows if (isPlatform("windows")) { return; } context.getShutdownStrategy().setTimeout(50); String reply = template.requestBody(serverUri, "World", String.class); assertEquals("Bye World", reply); // now suspend netty NettyHttpConsumer consumer = (NettyHttpConsumer) context.getRoute("foo").getConsumer(); assertNotNull(consumer); // suspend consumer.suspend(); try { template.requestBody(serverUri, "Moon", String.class); fail("Should throw exception"); } catch (Exception e) { NettyHttpOperationFailedException cause = assertIsInstanceOf(NettyHttpOperationFailedException.class, e.getCause()); assertEquals(503, cause.getStatusCode()); } // resume consumer.resume(); Thread.sleep(2000); // and send request which should be processed reply = template.requestBody(serverUri, "Moon", String.class); assertEquals("Bye Moon", reply); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from(serverUri).routeId("foo") .transform(body().prepend("Bye ")); } }; } }
brreitme/camel
components/camel-netty-http/src/test/java/org/apache/camel/component/netty/http/NettyHttpSuspendResume503Test.java
Java
apache-2.0
2,596
/** * 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.component.metrics.routepolicy; import java.util.Set; import javax.management.MBeanServer; import javax.management.ObjectName; import com.codahale.metrics.MetricRegistry; import org.apache.camel.CamelContext; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.metrics.MetricsComponent; import org.apache.camel.impl.JndiRegistry; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; public class ManagedMetricsRoutePolicyTest extends CamelTestSupport { private MetricRegistry metricRegistry = new MetricRegistry(); @Override protected boolean useJmx() { return true; } protected MBeanServer getMBeanServer() { return context.getManagementStrategy().getManagementAgent().getMBeanServer(); } // Setup the common MetricsRegistry for MetricsComponent and MetricsRoutePolicy to use @Override protected JndiRegistry createRegistry() throws Exception { JndiRegistry registry = super.createRegistry(); registry.bind(MetricsComponent.METRIC_REGISTRY_NAME, metricRegistry); return registry; } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); MetricsRoutePolicyFactory factory = new MetricsRoutePolicyFactory(); factory.setUseJmx(true); factory.setPrettyPrint(true); context.addRoutePolicyFactory(factory); return context; } @Test public void testMetricsRoutePolicy() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(10); for (int i = 0; i < 10; i++) { if (i % 2 == 0) { template.sendBody("seda:foo", "Hello " + i); } else { template.sendBody("seda:bar", "Hello " + i); } } assertMockEndpointsSatisfied(); // there should be 3 names assertEquals(3, metricRegistry.getNames().size()); // there should be 3 mbeans Set<ObjectName> set = getMBeanServer().queryNames(new ObjectName("org.apache.camel.metrics:*"), null); assertEquals(3, set.size()); String name = String.format("org.apache.camel:context=%s,type=services,name=MetricsRegistryService", context.getManagementName()); ObjectName on = ObjectName.getInstance(name); String json = (String) getMBeanServer().invoke(on, "dumpStatisticsAsJson", null, null); assertNotNull(json); log.info(json); assertTrue(json.contains("test")); assertTrue(json.contains("bar.responses")); assertTrue(json.contains("foo.responses")); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("seda:foo").routeId("foo").to("metrics:counter:test") .to("mock:result"); from("seda:bar").routeId("bar") .to("mock:result"); } }; } }
chanakaudaya/camel
components/camel-metrics/src/test/java/org/apache/camel/component/metrics/routepolicy/ManagedMetricsRoutePolicyTest.java
Java
apache-2.0
3,955
/** * 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.component.syslog; public final class SyslogConstants { /** * The socket address of local machine that received the message. */ public static final String SYSLOG_LOCAL_ADDRESS = "CamelSyslogLocalAddress"; /** * The socket address of the remote machine that send the message. */ public static final String SYSLOG_REMOTE_ADDRESS = "CamelSyslogRemoteAddress"; /** * The Sylog message Facility */ public static final String SYSLOG_FACILITY = "CamelSyslogFacility"; /** * The Syslog severity */ public static final String SYSLOG_SEVERITY = "CamelSyslogSeverity"; /** * The hostname in the syslog message */ public static final String SYSLOG_HOSTNAME = "CamelSyslogHostname"; /** * The syslog timestamp */ public static final String SYSLOG_TIMESTAMP = "CamelSyslogTimestamp"; private SyslogConstants() { // Utility class } }
joakibj/camel
components/camel-syslog/src/main/java/org/apache/camel/component/syslog/SyslogConstants.java
Java
apache-2.0
1,779
/** * 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.processor; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; /** * @version */ public class TracePerRouteManualTest extends ContextTestSupport { public void testTracingPerRoute() throws Exception { getMockEndpoint("mock:a").expectedMessageCount(1); getMockEndpoint("mock:b").expectedMessageCount(1); getMockEndpoint("mock:c").expectedMessageCount(1); template.sendBody("direct:a", "Hello World"); template.sendBody("direct:b", "Bye World"); template.sendBody("direct:c", "Gooday World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:a").tracing().streamCaching().to("mock:a"); from("direct:b").noTracing().to("mock:b"); from("direct:c").tracing().to("mock:c"); } }; } }
MrCoder/camel
camel-core/src/test/java/org/apache/camel/processor/TracePerRouteManualTest.java
Java
apache-2.0
1,881
define(function (require) { 'use strict'; var createListFromArray = require('../helper/createListFromArray'); var SeriesModel = require('../../model/Series'); return SeriesModel.extend({ type: 'series.scatter', dependencies: ['grid', 'polar'], getInitialData: function (option, ecModel) { var list = createListFromArray(option.data, this, ecModel); return list; }, defaultOption: { coordinateSystem: 'cartesian2d', zlevel: 0, z: 2, legendHoverLink: true, hoverAnimation: true, // Cartesian coordinate system xAxisIndex: 0, yAxisIndex: 0, // Polar coordinate system polarIndex: 0, // Geo coordinate system geoIndex: 0, // symbol: null, // 图形类型 symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2 // symbolRotate: null, // 图形旋转控制 large: false, // Available when large is true largeThreshold: 2000, // label: { // normal: { // show: false // distance: 5, // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调 // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为 // 'inside'|'left'|'right'|'top'|'bottom' // textStyle: null // 默认使用全局文本样式,详见TEXTSTYLE // } // }, itemStyle: { normal: { opacity: 0.8 // color: 各异 } } } }); });
aohanyao/CodeMall
code/ServerCode/CodeMallServer/target/mailshop/backend/vendors/echarts/src/chart/scatter/ScatterSeries.js
JavaScript
apache-2.0
1,925
/** * 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.component.bean; import org.apache.camel.EndpointInject; import org.apache.camel.ProducerTemplate; import org.apache.camel.component.mock.MockEndpoint; import org.apache.camel.spring.SpringRunWithTestSupport; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; /** * @version */ @ContextConfiguration public class BeanWithRecipientListTest extends SpringRunWithTestSupport { @Autowired protected ProducerTemplate template; @EndpointInject(uri = "mock:a") protected MockEndpoint a; @EndpointInject(uri = "mock:b") protected MockEndpoint b; protected String body = "James"; @Test public void testSendBody() throws Exception { a.expectedBodiesReceived(body); b.expectedBodiesReceived(body); template.sendBody("direct:start", body); MockEndpoint.assertIsSatisfied(a, b); } }
mnki/camel
components/camel-spring/src/test/java/org/apache/camel/component/bean/BeanWithRecipientListTest.java
Java
apache-2.0
1,775
// Code generated by protoc-gen-gogo. DO NOT EDIT. // source: gogo.proto /* Package gogoproto is a generated protocol buffer package. It is generated from these files: gogo.proto It has these top-level messages: */ package gogoproto import proto "github.com/gogo/protobuf/proto" import fmt "fmt" import math "math" import google_protobuf "github.com/gogo/protobuf/protoc-gen-gogo/descriptor" // Reference imports to suppress errors if they are not otherwise used. var _ = proto.Marshal var _ = fmt.Errorf var _ = math.Inf // This is a compile-time assertion to ensure that this generated file // is compatible with the proto package it is being compiled against. // A compilation error at this line likely means your copy of the // proto package needs to be updated. const _ = proto.GoGoProtoPackageIsVersion2 // please upgrade the proto package var E_GoprotoEnumPrefix = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62001, Name: "gogoproto.goproto_enum_prefix", Tag: "varint,62001,opt,name=goproto_enum_prefix,json=goprotoEnumPrefix", Filename: "gogo.proto", } var E_GoprotoEnumStringer = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62021, Name: "gogoproto.goproto_enum_stringer", Tag: "varint,62021,opt,name=goproto_enum_stringer,json=goprotoEnumStringer", Filename: "gogo.proto", } var E_EnumStringer = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62022, Name: "gogoproto.enum_stringer", Tag: "varint,62022,opt,name=enum_stringer,json=enumStringer", Filename: "gogo.proto", } var E_EnumCustomname = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*string)(nil), Field: 62023, Name: "gogoproto.enum_customname", Tag: "bytes,62023,opt,name=enum_customname,json=enumCustomname", Filename: "gogo.proto", } var E_Enumdecl = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumOptions)(nil), ExtensionType: (*bool)(nil), Field: 62024, Name: "gogoproto.enumdecl", Tag: "varint,62024,opt,name=enumdecl", Filename: "gogo.proto", } var E_EnumvalueCustomname = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.EnumValueOptions)(nil), ExtensionType: (*string)(nil), Field: 66001, Name: "gogoproto.enumvalue_customname", Tag: "bytes,66001,opt,name=enumvalue_customname,json=enumvalueCustomname", Filename: "gogo.proto", } var E_GoprotoGettersAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63001, Name: "gogoproto.goproto_getters_all", Tag: "varint,63001,opt,name=goproto_getters_all,json=goprotoGettersAll", Filename: "gogo.proto", } var E_GoprotoEnumPrefixAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63002, Name: "gogoproto.goproto_enum_prefix_all", Tag: "varint,63002,opt,name=goproto_enum_prefix_all,json=goprotoEnumPrefixAll", Filename: "gogo.proto", } var E_GoprotoStringerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63003, Name: "gogoproto.goproto_stringer_all", Tag: "varint,63003,opt,name=goproto_stringer_all,json=goprotoStringerAll", Filename: "gogo.proto", } var E_VerboseEqualAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63004, Name: "gogoproto.verbose_equal_all", Tag: "varint,63004,opt,name=verbose_equal_all,json=verboseEqualAll", Filename: "gogo.proto", } var E_FaceAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63005, Name: "gogoproto.face_all", Tag: "varint,63005,opt,name=face_all,json=faceAll", Filename: "gogo.proto", } var E_GostringAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63006, Name: "gogoproto.gostring_all", Tag: "varint,63006,opt,name=gostring_all,json=gostringAll", Filename: "gogo.proto", } var E_PopulateAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63007, Name: "gogoproto.populate_all", Tag: "varint,63007,opt,name=populate_all,json=populateAll", Filename: "gogo.proto", } var E_StringerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63008, Name: "gogoproto.stringer_all", Tag: "varint,63008,opt,name=stringer_all,json=stringerAll", Filename: "gogo.proto", } var E_OnlyoneAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63009, Name: "gogoproto.onlyone_all", Tag: "varint,63009,opt,name=onlyone_all,json=onlyoneAll", Filename: "gogo.proto", } var E_EqualAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63013, Name: "gogoproto.equal_all", Tag: "varint,63013,opt,name=equal_all,json=equalAll", Filename: "gogo.proto", } var E_DescriptionAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63014, Name: "gogoproto.description_all", Tag: "varint,63014,opt,name=description_all,json=descriptionAll", Filename: "gogo.proto", } var E_TestgenAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63015, Name: "gogoproto.testgen_all", Tag: "varint,63015,opt,name=testgen_all,json=testgenAll", Filename: "gogo.proto", } var E_BenchgenAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63016, Name: "gogoproto.benchgen_all", Tag: "varint,63016,opt,name=benchgen_all,json=benchgenAll", Filename: "gogo.proto", } var E_MarshalerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63017, Name: "gogoproto.marshaler_all", Tag: "varint,63017,opt,name=marshaler_all,json=marshalerAll", Filename: "gogo.proto", } var E_UnmarshalerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63018, Name: "gogoproto.unmarshaler_all", Tag: "varint,63018,opt,name=unmarshaler_all,json=unmarshalerAll", Filename: "gogo.proto", } var E_StableMarshalerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63019, Name: "gogoproto.stable_marshaler_all", Tag: "varint,63019,opt,name=stable_marshaler_all,json=stableMarshalerAll", Filename: "gogo.proto", } var E_SizerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63020, Name: "gogoproto.sizer_all", Tag: "varint,63020,opt,name=sizer_all,json=sizerAll", Filename: "gogo.proto", } var E_GoprotoEnumStringerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63021, Name: "gogoproto.goproto_enum_stringer_all", Tag: "varint,63021,opt,name=goproto_enum_stringer_all,json=goprotoEnumStringerAll", Filename: "gogo.proto", } var E_EnumStringerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63022, Name: "gogoproto.enum_stringer_all", Tag: "varint,63022,opt,name=enum_stringer_all,json=enumStringerAll", Filename: "gogo.proto", } var E_UnsafeMarshalerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63023, Name: "gogoproto.unsafe_marshaler_all", Tag: "varint,63023,opt,name=unsafe_marshaler_all,json=unsafeMarshalerAll", Filename: "gogo.proto", } var E_UnsafeUnmarshalerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63024, Name: "gogoproto.unsafe_unmarshaler_all", Tag: "varint,63024,opt,name=unsafe_unmarshaler_all,json=unsafeUnmarshalerAll", Filename: "gogo.proto", } var E_GoprotoExtensionsMapAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63025, Name: "gogoproto.goproto_extensions_map_all", Tag: "varint,63025,opt,name=goproto_extensions_map_all,json=goprotoExtensionsMapAll", Filename: "gogo.proto", } var E_GoprotoUnrecognizedAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63026, Name: "gogoproto.goproto_unrecognized_all", Tag: "varint,63026,opt,name=goproto_unrecognized_all,json=goprotoUnrecognizedAll", Filename: "gogo.proto", } var E_GogoprotoImport = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63027, Name: "gogoproto.gogoproto_import", Tag: "varint,63027,opt,name=gogoproto_import,json=gogoprotoImport", Filename: "gogo.proto", } var E_ProtosizerAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63028, Name: "gogoproto.protosizer_all", Tag: "varint,63028,opt,name=protosizer_all,json=protosizerAll", Filename: "gogo.proto", } var E_CompareAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63029, Name: "gogoproto.compare_all", Tag: "varint,63029,opt,name=compare_all,json=compareAll", Filename: "gogo.proto", } var E_TypedeclAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63030, Name: "gogoproto.typedecl_all", Tag: "varint,63030,opt,name=typedecl_all,json=typedeclAll", Filename: "gogo.proto", } var E_EnumdeclAll = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63031, Name: "gogoproto.enumdecl_all", Tag: "varint,63031,opt,name=enumdecl_all,json=enumdeclAll", Filename: "gogo.proto", } var E_GoprotoRegistration = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FileOptions)(nil), ExtensionType: (*bool)(nil), Field: 63032, Name: "gogoproto.goproto_registration", Tag: "varint,63032,opt,name=goproto_registration,json=goprotoRegistration", Filename: "gogo.proto", } var E_GoprotoGetters = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64001, Name: "gogoproto.goproto_getters", Tag: "varint,64001,opt,name=goproto_getters,json=goprotoGetters", Filename: "gogo.proto", } var E_GoprotoStringer = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64003, Name: "gogoproto.goproto_stringer", Tag: "varint,64003,opt,name=goproto_stringer,json=goprotoStringer", Filename: "gogo.proto", } var E_VerboseEqual = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64004, Name: "gogoproto.verbose_equal", Tag: "varint,64004,opt,name=verbose_equal,json=verboseEqual", Filename: "gogo.proto", } var E_Face = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64005, Name: "gogoproto.face", Tag: "varint,64005,opt,name=face", Filename: "gogo.proto", } var E_Gostring = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64006, Name: "gogoproto.gostring", Tag: "varint,64006,opt,name=gostring", Filename: "gogo.proto", } var E_Populate = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64007, Name: "gogoproto.populate", Tag: "varint,64007,opt,name=populate", Filename: "gogo.proto", } var E_Stringer = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 67008, Name: "gogoproto.stringer", Tag: "varint,67008,opt,name=stringer", Filename: "gogo.proto", } var E_Onlyone = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64009, Name: "gogoproto.onlyone", Tag: "varint,64009,opt,name=onlyone", Filename: "gogo.proto", } var E_Equal = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64013, Name: "gogoproto.equal", Tag: "varint,64013,opt,name=equal", Filename: "gogo.proto", } var E_Description = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64014, Name: "gogoproto.description", Tag: "varint,64014,opt,name=description", Filename: "gogo.proto", } var E_Testgen = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64015, Name: "gogoproto.testgen", Tag: "varint,64015,opt,name=testgen", Filename: "gogo.proto", } var E_Benchgen = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64016, Name: "gogoproto.benchgen", Tag: "varint,64016,opt,name=benchgen", Filename: "gogo.proto", } var E_Marshaler = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64017, Name: "gogoproto.marshaler", Tag: "varint,64017,opt,name=marshaler", Filename: "gogo.proto", } var E_Unmarshaler = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64018, Name: "gogoproto.unmarshaler", Tag: "varint,64018,opt,name=unmarshaler", Filename: "gogo.proto", } var E_StableMarshaler = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64019, Name: "gogoproto.stable_marshaler", Tag: "varint,64019,opt,name=stable_marshaler,json=stableMarshaler", Filename: "gogo.proto", } var E_Sizer = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64020, Name: "gogoproto.sizer", Tag: "varint,64020,opt,name=sizer", Filename: "gogo.proto", } var E_UnsafeMarshaler = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64023, Name: "gogoproto.unsafe_marshaler", Tag: "varint,64023,opt,name=unsafe_marshaler,json=unsafeMarshaler", Filename: "gogo.proto", } var E_UnsafeUnmarshaler = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64024, Name: "gogoproto.unsafe_unmarshaler", Tag: "varint,64024,opt,name=unsafe_unmarshaler,json=unsafeUnmarshaler", Filename: "gogo.proto", } var E_GoprotoExtensionsMap = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64025, Name: "gogoproto.goproto_extensions_map", Tag: "varint,64025,opt,name=goproto_extensions_map,json=goprotoExtensionsMap", Filename: "gogo.proto", } var E_GoprotoUnrecognized = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64026, Name: "gogoproto.goproto_unrecognized", Tag: "varint,64026,opt,name=goproto_unrecognized,json=goprotoUnrecognized", Filename: "gogo.proto", } var E_Protosizer = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64028, Name: "gogoproto.protosizer", Tag: "varint,64028,opt,name=protosizer", Filename: "gogo.proto", } var E_Compare = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64029, Name: "gogoproto.compare", Tag: "varint,64029,opt,name=compare", Filename: "gogo.proto", } var E_Typedecl = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.MessageOptions)(nil), ExtensionType: (*bool)(nil), Field: 64030, Name: "gogoproto.typedecl", Tag: "varint,64030,opt,name=typedecl", Filename: "gogo.proto", } var E_Nullable = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*bool)(nil), Field: 65001, Name: "gogoproto.nullable", Tag: "varint,65001,opt,name=nullable", Filename: "gogo.proto", } var E_Embed = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*bool)(nil), Field: 65002, Name: "gogoproto.embed", Tag: "varint,65002,opt,name=embed", Filename: "gogo.proto", } var E_Customtype = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65003, Name: "gogoproto.customtype", Tag: "bytes,65003,opt,name=customtype", Filename: "gogo.proto", } var E_Customname = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65004, Name: "gogoproto.customname", Tag: "bytes,65004,opt,name=customname", Filename: "gogo.proto", } var E_Jsontag = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65005, Name: "gogoproto.jsontag", Tag: "bytes,65005,opt,name=jsontag", Filename: "gogo.proto", } var E_Moretags = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65006, Name: "gogoproto.moretags", Tag: "bytes,65006,opt,name=moretags", Filename: "gogo.proto", } var E_Casttype = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65007, Name: "gogoproto.casttype", Tag: "bytes,65007,opt,name=casttype", Filename: "gogo.proto", } var E_Castkey = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65008, Name: "gogoproto.castkey", Tag: "bytes,65008,opt,name=castkey", Filename: "gogo.proto", } var E_Castvalue = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*string)(nil), Field: 65009, Name: "gogoproto.castvalue", Tag: "bytes,65009,opt,name=castvalue", Filename: "gogo.proto", } var E_Stdtime = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*bool)(nil), Field: 65010, Name: "gogoproto.stdtime", Tag: "varint,65010,opt,name=stdtime", Filename: "gogo.proto", } var E_Stdduration = &proto.ExtensionDesc{ ExtendedType: (*google_protobuf.FieldOptions)(nil), ExtensionType: (*bool)(nil), Field: 65011, Name: "gogoproto.stdduration", Tag: "varint,65011,opt,name=stdduration", Filename: "gogo.proto", } func init() { proto.RegisterExtension(E_GoprotoEnumPrefix) proto.RegisterExtension(E_GoprotoEnumStringer) proto.RegisterExtension(E_EnumStringer) proto.RegisterExtension(E_EnumCustomname) proto.RegisterExtension(E_Enumdecl) proto.RegisterExtension(E_EnumvalueCustomname) proto.RegisterExtension(E_GoprotoGettersAll) proto.RegisterExtension(E_GoprotoEnumPrefixAll) proto.RegisterExtension(E_GoprotoStringerAll) proto.RegisterExtension(E_VerboseEqualAll) proto.RegisterExtension(E_FaceAll) proto.RegisterExtension(E_GostringAll) proto.RegisterExtension(E_PopulateAll) proto.RegisterExtension(E_StringerAll) proto.RegisterExtension(E_OnlyoneAll) proto.RegisterExtension(E_EqualAll) proto.RegisterExtension(E_DescriptionAll) proto.RegisterExtension(E_TestgenAll) proto.RegisterExtension(E_BenchgenAll) proto.RegisterExtension(E_MarshalerAll) proto.RegisterExtension(E_UnmarshalerAll) proto.RegisterExtension(E_StableMarshalerAll) proto.RegisterExtension(E_SizerAll) proto.RegisterExtension(E_GoprotoEnumStringerAll) proto.RegisterExtension(E_EnumStringerAll) proto.RegisterExtension(E_UnsafeMarshalerAll) proto.RegisterExtension(E_UnsafeUnmarshalerAll) proto.RegisterExtension(E_GoprotoExtensionsMapAll) proto.RegisterExtension(E_GoprotoUnrecognizedAll) proto.RegisterExtension(E_GogoprotoImport) proto.RegisterExtension(E_ProtosizerAll) proto.RegisterExtension(E_CompareAll) proto.RegisterExtension(E_TypedeclAll) proto.RegisterExtension(E_EnumdeclAll) proto.RegisterExtension(E_GoprotoRegistration) proto.RegisterExtension(E_GoprotoGetters) proto.RegisterExtension(E_GoprotoStringer) proto.RegisterExtension(E_VerboseEqual) proto.RegisterExtension(E_Face) proto.RegisterExtension(E_Gostring) proto.RegisterExtension(E_Populate) proto.RegisterExtension(E_Stringer) proto.RegisterExtension(E_Onlyone) proto.RegisterExtension(E_Equal) proto.RegisterExtension(E_Description) proto.RegisterExtension(E_Testgen) proto.RegisterExtension(E_Benchgen) proto.RegisterExtension(E_Marshaler) proto.RegisterExtension(E_Unmarshaler) proto.RegisterExtension(E_StableMarshaler) proto.RegisterExtension(E_Sizer) proto.RegisterExtension(E_UnsafeMarshaler) proto.RegisterExtension(E_UnsafeUnmarshaler) proto.RegisterExtension(E_GoprotoExtensionsMap) proto.RegisterExtension(E_GoprotoUnrecognized) proto.RegisterExtension(E_Protosizer) proto.RegisterExtension(E_Compare) proto.RegisterExtension(E_Typedecl) proto.RegisterExtension(E_Nullable) proto.RegisterExtension(E_Embed) proto.RegisterExtension(E_Customtype) proto.RegisterExtension(E_Customname) proto.RegisterExtension(E_Jsontag) proto.RegisterExtension(E_Moretags) proto.RegisterExtension(E_Casttype) proto.RegisterExtension(E_Castkey) proto.RegisterExtension(E_Castvalue) proto.RegisterExtension(E_Stdtime) proto.RegisterExtension(E_Stdduration) } func init() { proto.RegisterFile("gogo.proto", fileDescriptorGogo) } var fileDescriptorGogo = []byte{ // 1201 bytes of a gzipped FileDescriptorProto 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0x94, 0x98, 0xcb, 0x6f, 0x1c, 0x45, 0x13, 0xc0, 0xf5, 0xe9, 0x73, 0x64, 0x6f, 0xf9, 0x85, 0xd7, 0xc6, 0x84, 0x08, 0x44, 0x72, 0xe3, 0xe4, 0x9c, 0x22, 0x94, 0xb6, 0x22, 0xcb, 0xb1, 0x1c, 0x2b, 0x11, 0x06, 0x63, 0xe2, 0x00, 0xe2, 0xb0, 0x9a, 0xdd, 0x6d, 0x4f, 0x06, 0x66, 0xa6, 0x87, 0x99, 0x9e, 0x28, 0xce, 0x0d, 0x85, 0x87, 0x10, 0xe2, 0x8d, 0x04, 0x09, 0x49, 0x80, 0x03, 0xef, 0x67, 0x78, 0x1f, 0xb9, 0xf0, 0xb8, 0xf2, 0x3f, 0x70, 0x01, 0xcc, 0xdb, 0x37, 0x5f, 0x50, 0xcd, 0x56, 0xcd, 0xf6, 0xac, 0x57, 0xea, 0xde, 0xdb, 0xec, 0xba, 0x7f, 0xbf, 0xad, 0xa9, 0x9a, 0xae, 0xea, 0x31, 0x80, 0xaf, 0x7c, 0x35, 0x97, 0xa4, 0x4a, 0xab, 0x7a, 0x0d, 0xaf, 0x8b, 0xcb, 0x03, 0x07, 0x7d, 0xa5, 0xfc, 0x50, 0x1e, 0x2e, 0x3e, 0x35, 0xf3, 0xcd, 0xc3, 0x6d, 0x99, 0xb5, 0xd2, 0x20, 0xd1, 0x2a, 0xed, 0x2c, 0x16, 0x77, 0xc1, 0x34, 0x2d, 0x6e, 0xc8, 0x38, 0x8f, 0x1a, 0x49, 0x2a, 0x37, 0x83, 0xf3, 0xf5, 0x5b, 0xe6, 0x3a, 0xe4, 0x1c, 0x93, 0x73, 0xcb, 0x71, 0x1e, 0xdd, 0x9d, 0xe8, 0x40, 0xc5, 0xd9, 0xfe, 0xeb, 0x3f, 0xff, 0xff, 0xe0, 0xff, 0x6e, 0x1f, 0x59, 0x9f, 0x22, 0x14, 0xff, 0xb6, 0x56, 0x80, 0x62, 0x1d, 0x6e, 0xac, 0xf8, 0x32, 0x9d, 0x06, 0xb1, 0x2f, 0x53, 0x8b, 0xf1, 0x3b, 0x32, 0x4e, 0x1b, 0xc6, 0x7b, 0x09, 0x15, 0x4b, 0x30, 0x3e, 0x88, 0xeb, 0x7b, 0x72, 0x8d, 0x49, 0x53, 0xb2, 0x02, 0x93, 0x85, 0xa4, 0x95, 0x67, 0x5a, 0x45, 0xb1, 0x17, 0x49, 0x8b, 0xe6, 0x87, 0x42, 0x53, 0x5b, 0x9f, 0x40, 0x6c, 0xa9, 0xa4, 0x84, 0x80, 0x11, 0xfc, 0xa6, 0x2d, 0x5b, 0xa1, 0xc5, 0xf0, 0x23, 0x05, 0x52, 0xae, 0x17, 0x67, 0x60, 0x06, 0xaf, 0xcf, 0x79, 0x61, 0x2e, 0xcd, 0x48, 0x0e, 0xf5, 0xf5, 0x9c, 0xc1, 0x65, 0x2c, 0xfb, 0xe9, 0xe2, 0x50, 0x11, 0xce, 0x74, 0x29, 0x30, 0x62, 0x32, 0xaa, 0xe8, 0x4b, 0xad, 0x65, 0x9a, 0x35, 0xbc, 0xb0, 0x5f, 0x78, 0x27, 0x82, 0xb0, 0x34, 0x5e, 0xda, 0xae, 0x56, 0x71, 0xa5, 0x43, 0x2e, 0x86, 0xa1, 0xd8, 0x80, 0x9b, 0xfa, 0x3c, 0x15, 0x0e, 0xce, 0xcb, 0xe4, 0x9c, 0xd9, 0xf3, 0x64, 0xa0, 0x76, 0x0d, 0xf8, 0xfb, 0xb2, 0x96, 0x0e, 0xce, 0xd7, 0xc8, 0x59, 0x27, 0x96, 0x4b, 0x8a, 0xc6, 0x53, 0x30, 0x75, 0x4e, 0xa6, 0x4d, 0x95, 0xc9, 0x86, 0x7c, 0x24, 0xf7, 0x42, 0x07, 0xdd, 0x15, 0xd2, 0x4d, 0x12, 0xb8, 0x8c, 0x1c, 0xba, 0x8e, 0xc2, 0xc8, 0xa6, 0xd7, 0x92, 0x0e, 0x8a, 0xab, 0xa4, 0x18, 0xc6, 0xf5, 0x88, 0x2e, 0xc2, 0x98, 0xaf, 0x3a, 0xb7, 0xe4, 0x80, 0x5f, 0x23, 0x7c, 0x94, 0x19, 0x52, 0x24, 0x2a, 0xc9, 0x43, 0x4f, 0xbb, 0x44, 0xf0, 0x3a, 0x2b, 0x98, 0x21, 0xc5, 0x00, 0x69, 0x7d, 0x83, 0x15, 0x99, 0x91, 0xcf, 0x05, 0x18, 0x55, 0x71, 0xb8, 0xa5, 0x62, 0x97, 0x20, 0xde, 0x24, 0x03, 0x10, 0x82, 0x82, 0x79, 0xa8, 0xb9, 0x16, 0xe2, 0xad, 0x6d, 0xde, 0x1e, 0x5c, 0x81, 0x15, 0x98, 0xe4, 0x06, 0x15, 0xa8, 0xd8, 0x41, 0xf1, 0x36, 0x29, 0x26, 0x0c, 0x8c, 0x6e, 0x43, 0xcb, 0x4c, 0xfb, 0xd2, 0x45, 0xf2, 0x0e, 0xdf, 0x06, 0x21, 0x94, 0xca, 0xa6, 0x8c, 0x5b, 0x67, 0xdd, 0x0c, 0xef, 0x72, 0x2a, 0x99, 0x41, 0xc5, 0x12, 0x8c, 0x47, 0x5e, 0x9a, 0x9d, 0xf5, 0x42, 0xa7, 0x72, 0xbc, 0x47, 0x8e, 0xb1, 0x12, 0xa2, 0x8c, 0xe4, 0xf1, 0x20, 0x9a, 0xf7, 0x39, 0x23, 0x06, 0x46, 0x5b, 0x2f, 0xd3, 0x5e, 0x33, 0x94, 0x8d, 0x41, 0x6c, 0x1f, 0xf0, 0xd6, 0xeb, 0xb0, 0xab, 0xa6, 0x71, 0x1e, 0x6a, 0x59, 0x70, 0xc1, 0x49, 0xf3, 0x21, 0x57, 0xba, 0x00, 0x10, 0x7e, 0x00, 0x6e, 0xee, 0x3b, 0x26, 0x1c, 0x64, 0x1f, 0x91, 0x6c, 0xb6, 0xcf, 0xa8, 0xa0, 0x96, 0x30, 0xa8, 0xf2, 0x63, 0x6e, 0x09, 0xb2, 0xc7, 0xb5, 0x06, 0x33, 0x79, 0x9c, 0x79, 0x9b, 0x83, 0x65, 0xed, 0x13, 0xce, 0x5a, 0x87, 0xad, 0x64, 0xed, 0x34, 0xcc, 0x92, 0x71, 0xb0, 0xba, 0x7e, 0xca, 0x8d, 0xb5, 0x43, 0x6f, 0x54, 0xab, 0xfb, 0x20, 0x1c, 0x28, 0xd3, 0x79, 0x5e, 0xcb, 0x38, 0x43, 0xa6, 0x11, 0x79, 0x89, 0x83, 0xf9, 0x3a, 0x99, 0xb9, 0xe3, 0x2f, 0x97, 0x82, 0x55, 0x2f, 0x41, 0xf9, 0xfd, 0xb0, 0x9f, 0xe5, 0x79, 0x9c, 0xca, 0x96, 0xf2, 0xe3, 0xe0, 0x82, 0x6c, 0x3b, 0xa8, 0x3f, 0xeb, 0x29, 0xd5, 0x86, 0x81, 0xa3, 0xf9, 0x24, 0xdc, 0x50, 0x9e, 0x55, 0x1a, 0x41, 0x94, 0xa8, 0x54, 0x5b, 0x8c, 0x9f, 0x73, 0xa5, 0x4a, 0xee, 0x64, 0x81, 0x89, 0x65, 0x98, 0x28, 0x3e, 0xba, 0x3e, 0x92, 0x5f, 0x90, 0x68, 0xbc, 0x4b, 0x51, 0xe3, 0x68, 0xa9, 0x28, 0xf1, 0x52, 0x97, 0xfe, 0xf7, 0x25, 0x37, 0x0e, 0x42, 0xa8, 0x71, 0xe8, 0xad, 0x44, 0xe2, 0xb4, 0x77, 0x30, 0x7c, 0xc5, 0x8d, 0x83, 0x19, 0x52, 0xf0, 0x81, 0xc1, 0x41, 0xf1, 0x35, 0x2b, 0x98, 0x41, 0xc5, 0x3d, 0xdd, 0x41, 0x9b, 0x4a, 0x3f, 0xc8, 0x74, 0xea, 0xe1, 0x6a, 0x8b, 0xea, 0x9b, 0xed, 0xea, 0x21, 0x6c, 0xdd, 0x40, 0xc5, 0x29, 0x98, 0xec, 0x39, 0x62, 0xd4, 0x6f, 0xdb, 0x63, 0x5b, 0x95, 0x59, 0xe6, 0xf9, 0xa5, 0xf0, 0xd1, 0x1d, 0x6a, 0x46, 0xd5, 0x13, 0x86, 0xb8, 0x13, 0xeb, 0x5e, 0x3d, 0x07, 0xd8, 0x65, 0x17, 0x77, 0xca, 0xd2, 0x57, 0x8e, 0x01, 0xe2, 0x04, 0x8c, 0x57, 0xce, 0x00, 0x76, 0xd5, 0x63, 0xa4, 0x1a, 0x33, 0x8f, 0x00, 0xe2, 0x08, 0x0c, 0xe1, 0x3c, 0xb7, 0xe3, 0x8f, 0x13, 0x5e, 0x2c, 0x17, 0xc7, 0x60, 0x84, 0xe7, 0xb8, 0x1d, 0x7d, 0x82, 0xd0, 0x12, 0x41, 0x9c, 0x67, 0xb8, 0x1d, 0x7f, 0x92, 0x71, 0x46, 0x10, 0x77, 0x4f, 0xe1, 0xb7, 0x4f, 0x0f, 0x51, 0x1f, 0xe6, 0xdc, 0xcd, 0xc3, 0x30, 0x0d, 0x6f, 0x3b, 0xfd, 0x14, 0xfd, 0x38, 0x13, 0xe2, 0x0e, 0xd8, 0xe7, 0x98, 0xf0, 0x67, 0x08, 0xed, 0xac, 0x17, 0x4b, 0x30, 0x6a, 0x0c, 0x6c, 0x3b, 0xfe, 0x2c, 0xe1, 0x26, 0x85, 0xa1, 0xd3, 0xc0, 0xb6, 0x0b, 0x9e, 0xe3, 0xd0, 0x89, 0xc0, 0xb4, 0xf1, 0xac, 0xb6, 0xd3, 0xcf, 0x73, 0xd6, 0x19, 0x11, 0x0b, 0x50, 0x2b, 0xfb, 0xaf, 0x9d, 0x7f, 0x81, 0xf8, 0x2e, 0x83, 0x19, 0x30, 0xfa, 0xbf, 0x5d, 0xf1, 0x22, 0x67, 0xc0, 0xa0, 0x70, 0x1b, 0xf5, 0xce, 0x74, 0xbb, 0xe9, 0x25, 0xde, 0x46, 0x3d, 0x23, 0x1d, 0xab, 0x59, 0xb4, 0x41, 0xbb, 0xe2, 0x65, 0xae, 0x66, 0xb1, 0x1e, 0xc3, 0xe8, 0x1d, 0x92, 0x76, 0xc7, 0x2b, 0x1c, 0x46, 0xcf, 0x8c, 0x14, 0x6b, 0x50, 0xdf, 0x3b, 0x20, 0xed, 0xbe, 0x57, 0xc9, 0x37, 0xb5, 0x67, 0x3e, 0x8a, 0xfb, 0x60, 0xb6, 0xff, 0x70, 0xb4, 0x5b, 0x2f, 0xed, 0xf4, 0xbc, 0xce, 0x98, 0xb3, 0x51, 0x9c, 0xee, 0x76, 0x59, 0x73, 0x30, 0xda, 0xb5, 0x97, 0x77, 0xaa, 0x8d, 0xd6, 0x9c, 0x8b, 0x62, 0x11, 0xa0, 0x3b, 0x93, 0xec, 0xae, 0x2b, 0xe4, 0x32, 0x20, 0xdc, 0x1a, 0x34, 0x92, 0xec, 0xfc, 0x55, 0xde, 0x1a, 0x44, 0xe0, 0xd6, 0xe0, 0x69, 0x64, 0xa7, 0xaf, 0xf1, 0xd6, 0x60, 0x44, 0xcc, 0xc3, 0x48, 0x9c, 0x87, 0x21, 0x3e, 0x5b, 0xf5, 0x5b, 0xfb, 0x8c, 0x1b, 0x19, 0xb6, 0x19, 0xfe, 0x65, 0x97, 0x60, 0x06, 0xc4, 0x11, 0xd8, 0x27, 0xa3, 0xa6, 0x6c, 0xdb, 0xc8, 0x5f, 0x77, 0xb9, 0x9f, 0xe0, 0x6a, 0xb1, 0x00, 0xd0, 0x79, 0x99, 0xc6, 0x28, 0x6c, 0xec, 0x6f, 0xbb, 0x9d, 0xf7, 0x7a, 0x03, 0xe9, 0x0a, 0x8a, 0xb7, 0x71, 0x8b, 0x60, 0xbb, 0x2a, 0x28, 0x5e, 0xc0, 0x8f, 0xc2, 0xf0, 0x43, 0x99, 0x8a, 0xb5, 0xe7, 0xdb, 0xe8, 0xdf, 0x89, 0xe6, 0xf5, 0x98, 0xb0, 0x48, 0xa5, 0x52, 0x7b, 0x7e, 0x66, 0x63, 0xff, 0x20, 0xb6, 0x04, 0x10, 0x6e, 0x79, 0x99, 0x76, 0xb9, 0xef, 0x3f, 0x19, 0x66, 0x00, 0x83, 0xc6, 0xeb, 0x87, 0xe5, 0x96, 0x8d, 0xfd, 0x8b, 0x83, 0xa6, 0xf5, 0xe2, 0x18, 0xd4, 0xf0, 0xb2, 0xf8, 0x3f, 0x84, 0x0d, 0xfe, 0x9b, 0xe0, 0x2e, 0x81, 0xbf, 0x9c, 0xe9, 0xb6, 0x0e, 0xec, 0xc9, 0xfe, 0x87, 0x2a, 0xcd, 0xeb, 0xc5, 0x22, 0x8c, 0x66, 0xba, 0xdd, 0xce, 0xe9, 0x44, 0x63, 0xc1, 0xff, 0xdd, 0x2d, 0x5f, 0x72, 0x4b, 0xe6, 0xf8, 0x21, 0x98, 0x6e, 0xa9, 0xa8, 0x17, 0x3c, 0x0e, 0x2b, 0x6a, 0x45, 0xad, 0x15, 0xbb, 0xe8, 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0x0a, 0x9c, 0xec, 0xd8, 0x50, 0x13, 0x00, 0x00, }
mbohlool/kubernetes
vendor/github.com/gogo/protobuf/gogoproto/gogo.pb.go
GO
apache-2.0
31,435
// +build !linux /* Copyright 2014 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 selinux // SELinuxEnabled always returns false on non-linux platforms. func SELinuxEnabled() bool { return false } // realSELinuxRunner is the NOP implementation of the SELinuxRunner interface. type realSELinuxRunner struct{} var _ SELinuxRunner = &realSELinuxRunner{} func (_ *realSELinuxRunner) Getfilecon(path string) (string, error) { return "", nil } // FileLabel returns the SELinux label for this path or returns an error. func SetFileLabel(path string, label string) error { return nil }
jfrazelle/kubernetes
pkg/util/selinux/selinux_unsupported.go
GO
apache-2.0
1,101
/** * 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.component.ref; import org.apache.camel.CamelContext; import org.apache.camel.ContextTestSupport; import org.apache.camel.Exchange; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.file.FileConsumer; import org.apache.camel.impl.DefaultCamelContext; import org.apache.camel.impl.SimpleRegistry; /** * @version */ public class RefFileEndpointTest extends ContextTestSupport { private SimpleRegistry registry = new SimpleRegistry(); @Override protected void setUp() throws Exception { deleteDirectory("target/foo"); super.setUp(); } public void testRefFileEndpoint() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(1); template.sendBodyAndHeader("file:target/foo", "Hello World", Exchange.FILE_NAME, "hello.txt"); assertMockEndpointsSatisfied(); FileConsumer consumer = (FileConsumer) context.getRoute("foo").getConsumer(); assertEquals(3000, consumer.getDelay()); assertEquals(250, consumer.getInitialDelay()); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = new DefaultCamelContext(registry); registry.put("foo", context.getEndpoint("file:target/foo?initialDelay=250&delay=3000&delete=true")); return context; } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("ref:foo").routeId("foo").to("mock:result"); } }; } }
JYBESSON/camel
camel-core/src/test/java/org/apache/camel/component/ref/RefFileEndpointTest.java
Java
apache-2.0
2,474
/* 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 clusterselector import ( "testing" "github.com/stretchr/testify/require" federationapi "k8s.io/kubernetes/federation/apis/federation/v1beta1" ) func TestSendToCluster(t *testing.T) { clusterLabels := map[string]string{ "location": "europe", "environment": "prod", "version": "15", } testCases := map[string]struct { objectAnnotations map[string]string expectedResult bool expectedErr bool }{ "match with single annotation": { objectAnnotations: map[string]string{ federationapi.FederationClusterSelectorAnnotation: `[{"key": "location", "operator": "in", "values": ["europe"]}]`, }, expectedResult: true, }, "match on multiple annotations": { objectAnnotations: map[string]string{ federationapi.FederationClusterSelectorAnnotation: `[{"key": "location", "operator": "in", "values": ["europe"]}, {"key": "environment", "operator": "==", "values": ["prod"]}]`, }, expectedResult: true, }, "mismatch on one annotation": { objectAnnotations: map[string]string{ federationapi.FederationClusterSelectorAnnotation: `[{"key": "location", "operator": "in", "values": ["europe"]}, {"key": "environment", "operator": "==", "values": ["test"]}]`, }, expectedResult: false, }, "match on not equal annotation": { objectAnnotations: map[string]string{ federationapi.FederationClusterSelectorAnnotation: `[{"key": "location", "operator": "!=", "values": ["usa"]}, {"key": "environment", "operator": "in", "values": ["prod"]}]`, }, expectedResult: true, }, "match on greater than annotation": { objectAnnotations: map[string]string{ federationapi.FederationClusterSelectorAnnotation: `[{"key": "version", "operator": ">", "values": ["14"]}]`, }, expectedResult: true, }, "mismatch on greater than annotation": { objectAnnotations: map[string]string{ federationapi.FederationClusterSelectorAnnotation: `[{"key": "version", "operator": ">", "values": ["15"]}]`, }, expectedResult: false, }, "unable to parse annotation": { objectAnnotations: map[string]string{ federationapi.FederationClusterSelectorAnnotation: `[{"not able to parse",}]`, }, expectedResult: false, expectedErr: true, }, } for testName, testCase := range testCases { t.Run(testName, func(t *testing.T) { result, err := SendToCluster(clusterLabels, testCase.objectAnnotations) if testCase.expectedErr { require.Error(t, err, "An error was expected") } else { require.NoError(t, err, "An error was not expected") } require.Equal(t, testCase.expectedResult, result, "Unexpected response from SendToCluster") }) } }
pmorie/origin
cmd/cluster-capacity/go/src/github.com/kubernetes-incubator/cluster-capacity/vendor/k8s.io/kubernetes/federation/pkg/federation-controller/util/clusterselector/clusterselector_test.go
GO
apache-2.0
3,238
package nat import ( "testing" "github.com/stretchr/testify/assert" ) func TestParsePort(t *testing.T) { var ( p int err error ) p, err = ParsePort("1234") if err != nil || p != 1234 { t.Fatal("Parsing '1234' did not succeed") } // FIXME currently this is a valid port. I don't think it should be. // I'm leaving this test commented out until we make a decision. // - erikh /* p, err = ParsePort("0123") if err != nil { t.Fatal("Successfully parsed port '0123' to '123'") } */ p, err = ParsePort("asdf") if err == nil || p != 0 { t.Fatal("Parsing port 'asdf' succeeded") } p, err = ParsePort("1asdf") if err == nil || p != 0 { t.Fatal("Parsing port '1asdf' succeeded") } } func TestParsePortRangeToInt(t *testing.T) { var ( begin int end int err error ) type TestRange struct { Range string Begin int End int } validRanges := []TestRange{ {"1234", 1234, 1234}, {"1234-1234", 1234, 1234}, {"1234-1235", 1234, 1235}, {"8000-9000", 8000, 9000}, {"0", 0, 0}, {"0-0", 0, 0}, } for _, r := range validRanges { begin, end, err = ParsePortRangeToInt(r.Range) if err != nil || begin != r.Begin { t.Fatalf("Parsing port range '%s' did not succeed. Expected begin %d, got %d", r.Range, r.Begin, begin) } if err != nil || end != r.End { t.Fatalf("Parsing port range '%s' did not succeed. Expected end %d, got %d", r.Range, r.End, end) } } invalidRanges := []string{ "asdf", "1asdf", "9000-8000", "9000-", "-8000", "-8000-", } for _, r := range invalidRanges { begin, end, err = ParsePortRangeToInt(r) if err == nil || begin != 0 || end != 0 { t.Fatalf("Parsing port range '%s' succeeded", r) } } } func TestPort(t *testing.T) { p, err := NewPort("tcp", "1234") if err != nil { t.Fatalf("tcp, 1234 had a parsing issue: %v", err) } if string(p) != "1234/tcp" { t.Fatal("tcp, 1234 did not result in the string 1234/tcp") } if p.Proto() != "tcp" { t.Fatal("protocol was not tcp") } if p.Port() != "1234" { t.Fatal("port string value was not 1234") } if p.Int() != 1234 { t.Fatal("port int value was not 1234") } p, err = NewPort("tcp", "asd1234") if err == nil { t.Fatal("tcp, asd1234 was supposed to fail") } p, err = NewPort("tcp", "1234-1230") if err == nil { t.Fatal("tcp, 1234-1230 was supposed to fail") } p, err = NewPort("tcp", "1234-1242") if err != nil { t.Fatalf("tcp, 1234-1242 had a parsing issue: %v", err) } if string(p) != "1234-1242/tcp" { t.Fatal("tcp, 1234-1242 did not result in the string 1234-1242/tcp") } } func TestSplitProtoPort(t *testing.T) { var ( proto string port string ) proto, port = SplitProtoPort("1234/tcp") if proto != "tcp" || port != "1234" { t.Fatal("Could not split 1234/tcp properly") } proto, port = SplitProtoPort("") if proto != "" || port != "" { t.Fatal("parsing an empty string yielded surprising results", proto, port) } proto, port = SplitProtoPort("1234") if proto != "tcp" || port != "1234" { t.Fatal("tcp is not the default protocol for portspec '1234'", proto, port) } proto, port = SplitProtoPort("1234/") if proto != "tcp" || port != "1234" { t.Fatal("parsing '1234/' yielded:" + port + "/" + proto) } proto, port = SplitProtoPort("/tcp") if proto != "" || port != "" { t.Fatal("parsing '/tcp' yielded:" + port + "/" + proto) } } func TestParsePortSpecFull(t *testing.T) { portMappings, err := ParsePortSpec("0.0.0.0:1234-1235:3333-3334/tcp") assert.Nil(t, err) expected := []PortMapping{ { Port: "3333/tcp", Binding: PortBinding{ HostIP: "0.0.0.0", HostPort: "1234", }, }, { Port: "3334/tcp", Binding: PortBinding{ HostIP: "0.0.0.0", HostPort: "1235", }, }, } assert.Equal(t, expected, portMappings) } func TestPartPortSpecIPV6(t *testing.T) { portMappings, err := ParsePortSpec("[2001:4860:0:2001::68]::333") assert.Nil(t, err) expected := []PortMapping{ { Port: "333/tcp", Binding: PortBinding{ HostIP: "2001:4860:0:2001::68", HostPort: "", }, }, } assert.Equal(t, expected, portMappings) } func TestPartPortSpecIPV6WithHostPort(t *testing.T) { portMappings, err := ParsePortSpec("[::1]:80:80") assert.Nil(t, err) expected := []PortMapping{ { Port: "80/tcp", Binding: PortBinding{ HostIP: "::1", HostPort: "80", }, }, } assert.Equal(t, expected, portMappings) } func TestParsePortSpecs(t *testing.T) { var ( portMap map[Port]struct{} bindingMap map[Port][]PortBinding err error ) portMap, bindingMap, err = ParsePortSpecs([]string{"1234/tcp", "2345/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1234/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2345/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "" { t.Fatalf("HostIP should not be set for %s", portspec) } if bindings[0].HostPort != "" { t.Fatalf("HostPort should not be set for %s", portspec) } } portMap, bindingMap, err = ParsePortSpecs([]string{"1234:1234/tcp", "2345:2345/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1234/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2345/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { _, port := SplitProtoPort(string(portspec)) if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "" { t.Fatalf("HostIP should not be set for %s", portspec) } if bindings[0].HostPort != port { t.Fatalf("HostPort should be %s for %s", port, portspec) } } portMap, bindingMap, err = ParsePortSpecs([]string{"0.0.0.0:1234:1234/tcp", "0.0.0.0:2345:2345/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1234/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2345/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { _, port := SplitProtoPort(string(portspec)) if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "0.0.0.0" { t.Fatalf("HostIP is not 0.0.0.0 for %s", portspec) } if bindings[0].HostPort != port { t.Fatalf("HostPort should be %s for %s", port, portspec) } } _, _, err = ParsePortSpecs([]string{"localhost:1234:1234/tcp"}) if err == nil { t.Fatal("Received no error while trying to parse a hostname instead of ip") } } func TestParsePortSpecsWithRange(t *testing.T) { var ( portMap map[Port]struct{} bindingMap map[Port][]PortBinding err error ) portMap, bindingMap, err = ParsePortSpecs([]string{"1234-1236/tcp", "2345-2347/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1235/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2346/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "" { t.Fatalf("HostIP should not be set for %s", portspec) } if bindings[0].HostPort != "" { t.Fatalf("HostPort should not be set for %s", portspec) } } portMap, bindingMap, err = ParsePortSpecs([]string{"1234-1236:1234-1236/tcp", "2345-2347:2345-2347/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1235/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2346/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { _, port := SplitProtoPort(string(portspec)) if len(bindings) != 1 { t.Fatalf("%s should have exactly one binding", portspec) } if bindings[0].HostIP != "" { t.Fatalf("HostIP should not be set for %s", portspec) } if bindings[0].HostPort != port { t.Fatalf("HostPort should be %s for %s", port, portspec) } } portMap, bindingMap, err = ParsePortSpecs([]string{"0.0.0.0:1234-1236:1234-1236/tcp", "0.0.0.0:2345-2347:2345-2347/udp"}) if err != nil { t.Fatalf("Error while processing ParsePortSpecs: %s", err) } if _, ok := portMap[Port("1235/tcp")]; !ok { t.Fatal("1234/tcp was not parsed properly") } if _, ok := portMap[Port("2346/udp")]; !ok { t.Fatal("2345/udp was not parsed properly") } for portspec, bindings := range bindingMap { _, port := SplitProtoPort(string(portspec)) if len(bindings) != 1 || bindings[0].HostIP != "0.0.0.0" || bindings[0].HostPort != port { t.Fatalf("Expect single binding to port %s but found %s", port, bindings) } } _, _, err = ParsePortSpecs([]string{"localhost:1234-1236:1234-1236/tcp"}) if err == nil { t.Fatal("Received no error while trying to parse a hostname instead of ip") } } func TestParseNetworkOptsPrivateOnly(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100::80"}) if err != nil { t.Fatal(err) } if len(ports) != 1 { t.Logf("Expected 1 got %d", len(ports)) t.FailNow() } if len(bindings) != 1 { t.Logf("Expected 1 got %d", len(bindings)) t.FailNow() } for k := range ports { if k.Proto() != "tcp" { t.Logf("Expected tcp got %s", k.Proto()) t.Fail() } if k.Port() != "80" { t.Logf("Expected 80 got %s", k.Port()) t.Fail() } b, exists := bindings[k] if !exists { t.Log("Binding does not exist") t.FailNow() } if len(b) != 1 { t.Logf("Expected 1 got %d", len(b)) t.FailNow() } s := b[0] if s.HostPort != "" { t.Logf("Expected \"\" got %s", s.HostPort) t.Fail() } if s.HostIP != "192.168.1.100" { t.Fail() } } } func TestParseNetworkOptsPublic(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100:8080:80"}) if err != nil { t.Fatal(err) } if len(ports) != 1 { t.Logf("Expected 1 got %d", len(ports)) t.FailNow() } if len(bindings) != 1 { t.Logf("Expected 1 got %d", len(bindings)) t.FailNow() } for k := range ports { if k.Proto() != "tcp" { t.Logf("Expected tcp got %s", k.Proto()) t.Fail() } if k.Port() != "80" { t.Logf("Expected 80 got %s", k.Port()) t.Fail() } b, exists := bindings[k] if !exists { t.Log("Binding does not exist") t.FailNow() } if len(b) != 1 { t.Logf("Expected 1 got %d", len(b)) t.FailNow() } s := b[0] if s.HostPort != "8080" { t.Logf("Expected 8080 got %s", s.HostPort) t.Fail() } if s.HostIP != "192.168.1.100" { t.Fail() } } } func TestParseNetworkOptsPublicNoPort(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100"}) if err == nil { t.Logf("Expected error Invalid containerPort") t.Fail() } if ports != nil { t.Logf("Expected nil got %s", ports) t.Fail() } if bindings != nil { t.Logf("Expected nil got %s", bindings) t.Fail() } } func TestParseNetworkOptsNegativePorts(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100:-1:-1"}) if err == nil { t.Fail() } if len(ports) != 0 { t.Logf("Expected nil got %d", len(ports)) t.Fail() } if len(bindings) != 0 { t.Logf("Expected 0 got %d", len(bindings)) t.Fail() } } func TestParseNetworkOptsUdp(t *testing.T) { ports, bindings, err := ParsePortSpecs([]string{"192.168.1.100::6000/udp"}) if err != nil { t.Fatal(err) } if len(ports) != 1 { t.Logf("Expected 1 got %d", len(ports)) t.FailNow() } if len(bindings) != 1 { t.Logf("Expected 1 got %d", len(bindings)) t.FailNow() } for k := range ports { if k.Proto() != "udp" { t.Logf("Expected udp got %s", k.Proto()) t.Fail() } if k.Port() != "6000" { t.Logf("Expected 6000 got %s", k.Port()) t.Fail() } b, exists := bindings[k] if !exists { t.Log("Binding does not exist") t.FailNow() } if len(b) != 1 { t.Logf("Expected 1 got %d", len(b)) t.FailNow() } s := b[0] if s.HostPort != "" { t.Logf("Expected \"\" got %s", s.HostPort) t.Fail() } if s.HostIP != "192.168.1.100" { t.Fail() } } }
jgsqware/clairctl
vendor/github.com/docker/go-connections/nat/nat_test.go
GO
apache-2.0
12,624
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.VisualStudio.LanguageServices.Implementation.RQName.SimpleTree; namespace Microsoft.VisualStudio.LanguageServices.Implementation.RQName.Nodes { internal abstract class RQMethodPropertyOrEvent : RQMember { public readonly RQMethodPropertyOrEventName RqMemberName; public RQMethodPropertyOrEvent(RQUnconstructedType containingType, RQMethodPropertyOrEventName memberName) : base(containingType) { this.RqMemberName = memberName; } public override string MemberName { get { return this.RqMemberName.OrdinaryNameValue; } } protected override void AppendChildren(List<SimpleTreeNode> childList) { base.AppendChildren(childList); childList.Add(this.RqMemberName.ToSimpleTree()); } } }
OmniSharp/roslyn
src/VisualStudio/Core/Def/Implementation/RQName/Nodes/RQMethodPropertyOrEvent.cs
C#
apache-2.0
1,047
/** * 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.component.file.remote; import java.io.File; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.converter.IOConverter; import org.junit.Test; public class FtpProducerFileWithPathPathSeparatorWindowsNoStepwiseTest extends FtpServerTestSupport { private String getFtpUrl() { return "ftp://admin@localhost:" + getPort() + "/upload?password=admin&stepwise=false&separator=Windows"; } @Test public void testProducerFileWithPathNoStepwise() throws Exception { Exchange out = template.send(getFtpUrl(), new Processor() { public void process(Exchange exchange) throws Exception { exchange.getIn().setBody("Hello World"); exchange.getIn().setHeader(Exchange.FILE_NAME, "hello\\claus.txt"); } }); assertNotNull(out); File file = new File(FTP_ROOT_DIR + "/upload/hello/claus.txt"); assertTrue("The uploaded file should exists", file.exists()); assertEquals("Hello World", IOConverter.toString(file, null)); assertEquals("upload/hello\\claus.txt", out.getIn().getHeader(Exchange.FILE_NAME_PRODUCED)); } }
veithen/camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/FtpProducerFileWithPathPathSeparatorWindowsNoStepwiseTest.java
Java
apache-2.0
2,010
/** * 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.component.irc; import org.apache.camel.impl.JndiRegistry; import org.apache.camel.util.jsse.KeyStoreParameters; import org.apache.camel.util.jsse.SSLContextParameters; import org.apache.camel.util.jsse.TrustManagersParameters; import org.junit.Ignore; @Ignore public class IrcsWithSslContextParamsRouteTest extends IrcRouteTest { // TODO This test is disabled until we can find a public SSL enabled IRC // server to test against. To use this test, follow the following procedures: // 1) Download and install UnrealIRCd 3.2.9 from http://www.unrealircd.com/ // 2) Copy the contents of the src/test/unrealircd folder into the installation // folder of UnrealIRCd. // 3) Start UnrealIRCd and execute this test. Often the test executes quicker than // the IRC server responds and the assertion will fail. In order to get the test to // pass reliably, you may need to set a break point in IrcEndpoint#joinChanel in order // to slow the route creation down enough for the event listener to be in place // when camel-con joins the room. @Override protected JndiRegistry createRegistry() throws Exception { KeyStoreParameters ksp = new KeyStoreParameters(); ksp.setResource("localhost.ks"); ksp.setPassword("changeit"); TrustManagersParameters tmp = new TrustManagersParameters(); tmp.setKeyStore(ksp); SSLContextParameters sslContextParameters = new SSLContextParameters(); sslContextParameters.setTrustManagers(tmp); JndiRegistry registry = super.createRegistry(); registry.bind("sslContextParameters", sslContextParameters); return registry; } @Override protected String sendUri() { return "ircs://camel-prd-user@localhost:6669/#camel-test?nickname=camel-prd&password=password&sslContextParameters=#sslContextParameters"; } @Override protected String fromUri() { return "ircs://camel-con-user@localhost:6669/#camel-test?nickname=camel-con&password=password&sslContextParameters=#sslContextParameters"; } }
royopa/camel
components/camel-irc/src/test/java/org/apache/camel/component/irc/IrcsWithSslContextParamsRouteTest.java
Java
apache-2.0
2,975
/** * 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.component.mybatis; import org.apache.camel.ShutdownRunningTask; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; import org.junit.Before; import org.junit.Test; public class MyBatisShutdownAllTasksTest extends MyBatisTestSupport { @Override @Before public void setUp() throws Exception { super.setUp(); // super will insert 2 accounts already Account account = new Account(); account.setId(881); account.setFirstName("A"); account.setLastName("A"); account.setEmailAddress("a@gmail.com"); template.sendBody("mybatis:insertAccount?statementType=Insert", account); account = new Account(); account.setId(882); account.setFirstName("B"); account.setLastName("B"); account.setEmailAddress("b@gmail.com"); template.sendBody("mybatis:insertAccount?statementType=Insert", account); account = new Account(); account.setId(883); account.setFirstName("C"); account.setLastName("C"); account.setEmailAddress("c@gmail.com"); template.sendBody("mybatis:insertAccount?statementType=Insert", account); account = new Account(); account.setId(884); account.setFirstName("D"); account.setLastName("D"); account.setEmailAddress("d@gmail.com"); template.sendBody("mybatis:insertAccount?statementType=Insert", account); account = new Account(); account.setId(885); account.setFirstName("E"); account.setLastName("E"); account.setEmailAddress("e@gmail.com"); template.sendBody("mybatis:insertAccount?statementType=Insert", account); account = new Account(); account.setId(886); account.setFirstName("F"); account.setLastName("F"); account.setEmailAddress("f@gmail.com"); template.sendBody("mybatis:insertAccount?statementType=Insert", account); } @Test public void testShutdownAllTasks() throws Exception { context.startRoute("route1"); MockEndpoint bar = getMockEndpoint("mock:bar"); bar.expectedMinimumMessageCount(1); bar.setResultWaitTime(3000); assertMockEndpointsSatisfied(); // shutdown during processing context.stop(); // sleep a little Thread.sleep(1000); // should route all 8 assertEquals("Should complete all messages", 8, bar.getReceivedCounter()); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("mybatis:selectAllAccounts").noAutoStartup().routeId("route1") // let it complete all tasks .shutdownRunningTask(ShutdownRunningTask.CompleteAllTasks) .delay(1000).to("seda:foo"); from("seda:foo").routeId("route2").to("mock:bar"); } }; } }
tarilabs/camel
components/camel-mybatis/src/test/java/org/apache/camel/component/mybatis/MyBatisShutdownAllTasksTest.java
Java
apache-2.0
3,924
from __future__ import absolute_import import code import traceback import signal # Interactive debugging code from # http://stackoverflow.com/questions/132058/showing-the-stack-trace-from-a-running-python-application # (that link also points to code for an interactive remote debugger # setup, which we might want if we move Tornado to run in a daemon # rather than via screen). def interactive_debug(sig, frame): """Interrupt running process, and provide a python prompt for interactive debugging.""" d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) message = "Signal recieved : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i = code.InteractiveConsole(d) i.interact(message) # SIGUSR1 => Just print the stack # SIGUSR2 => Print stack + open interactive debugging shell def interactive_debug_listen(): signal.signal(signal.SIGUSR1, lambda sig, stack: traceback.print_stack(stack)) signal.signal(signal.SIGUSR2, interactive_debug)
wangdeshui/zulip
zerver/lib/debug.py
Python
apache-2.0
1,113
/* 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 v1alpha1_test import ( "reflect" "testing" "k8s.io/api/rbac/v1alpha1" "k8s.io/kubernetes/pkg/api/legacyscheme" rbacapi "k8s.io/kubernetes/pkg/apis/rbac" _ "k8s.io/kubernetes/pkg/apis/rbac/install" ) func TestConversion(t *testing.T) { testcases := map[string]struct { old *v1alpha1.RoleBinding expected *rbacapi.RoleBinding }{ "specific user": { old: &v1alpha1.RoleBinding{ RoleRef: v1alpha1.RoleRef{Name: "foo", APIGroup: v1alpha1.GroupName}, Subjects: []v1alpha1.Subject{{Kind: "User", APIVersion: v1alpha1.SchemeGroupVersion.String(), Name: "bob"}}, }, expected: &rbacapi.RoleBinding{ RoleRef: rbacapi.RoleRef{Name: "foo", APIGroup: v1alpha1.GroupName}, Subjects: []rbacapi.Subject{{Kind: "User", APIGroup: v1alpha1.GroupName, Name: "bob"}}, }, }, "wildcard user matches authenticated": { old: &v1alpha1.RoleBinding{ RoleRef: v1alpha1.RoleRef{Name: "foo", APIGroup: v1alpha1.GroupName}, Subjects: []v1alpha1.Subject{{Kind: "User", APIVersion: v1alpha1.SchemeGroupVersion.String(), Name: "*"}}, }, expected: &rbacapi.RoleBinding{ RoleRef: rbacapi.RoleRef{Name: "foo", APIGroup: v1alpha1.GroupName}, Subjects: []rbacapi.Subject{{Kind: "Group", APIGroup: v1alpha1.GroupName, Name: "system:authenticated"}}, }, }, "missing api group gets defaulted": { old: &v1alpha1.RoleBinding{ RoleRef: v1alpha1.RoleRef{Name: "foo", APIGroup: v1alpha1.GroupName}, Subjects: []v1alpha1.Subject{ {Kind: "User", Name: "myuser"}, {Kind: "Group", Name: "mygroup"}, {Kind: "ServiceAccount", Name: "mysa", Namespace: "myns"}, }, }, expected: &rbacapi.RoleBinding{ RoleRef: rbacapi.RoleRef{Name: "foo", APIGroup: v1alpha1.GroupName}, Subjects: []rbacapi.Subject{ {Kind: "User", APIGroup: v1alpha1.GroupName, Name: "myuser"}, {Kind: "Group", APIGroup: v1alpha1.GroupName, Name: "mygroup"}, {Kind: "ServiceAccount", APIGroup: "", Name: "mysa", Namespace: "myns"}, }, }, }, "bad api group gets defaulted": { old: &v1alpha1.RoleBinding{ RoleRef: v1alpha1.RoleRef{Name: "foo", APIGroup: v1alpha1.GroupName}, Subjects: []v1alpha1.Subject{ {Kind: "User", APIVersion: "rbac", Name: "myuser"}, {Kind: "Group", APIVersion: "rbac", Name: "mygroup"}, {Kind: "ServiceAccount", APIVersion: "rbac", Name: "mysa", Namespace: "myns"}, {Kind: "User", APIVersion: "rbac/v8", Name: "myuser"}, {Kind: "Group", APIVersion: "rbac/v8", Name: "mygroup"}, {Kind: "ServiceAccount", APIVersion: "rbac/v8", Name: "mysa", Namespace: "myns"}, }, }, expected: &rbacapi.RoleBinding{ RoleRef: rbacapi.RoleRef{Name: "foo", APIGroup: v1alpha1.GroupName}, Subjects: []rbacapi.Subject{ {Kind: "User", APIGroup: v1alpha1.GroupName, Name: "myuser"}, {Kind: "Group", APIGroup: v1alpha1.GroupName, Name: "mygroup"}, {Kind: "ServiceAccount", APIGroup: "", Name: "mysa", Namespace: "myns"}, {Kind: "User", APIGroup: v1alpha1.GroupName, Name: "myuser"}, {Kind: "Group", APIGroup: v1alpha1.GroupName, Name: "mygroup"}, {Kind: "ServiceAccount", APIGroup: "", Name: "mysa", Namespace: "myns"}, }, }, }, } for k, tc := range testcases { internal := &rbacapi.RoleBinding{} if err := legacyscheme.Scheme.Convert(tc.old, internal, nil); err != nil { t.Errorf("%s: unexpected error: %v", k, err) } if !reflect.DeepEqual(internal, tc.expected) { t.Errorf("%s: expected\n\t%#v, got \n\t%#v", k, tc.expected, internal) } } }
linux-on-ibm-z/kubernetes
pkg/apis/rbac/v1alpha1/conversion_test.go
GO
apache-2.0
4,102
/** * 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.example.cafe; import org.apache.camel.CamelContext; import org.apache.camel.example.cafe.test.TestDrinkRouter; import org.apache.camel.example.cafe.test.TestWaiter; import org.junit.After; import org.junit.Before; import org.springframework.context.support.AbstractApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class CafeRouteSpringTest extends CafeRouteBuilderTest { private AbstractApplicationContext applicationContext; @Before public void setUp() throws Exception { applicationContext = new ClassPathXmlApplicationContext("META-INF/camel-routes.xml"); setUseRouteBuilder(false); super.setUp(); waiter = applicationContext.getBean("waiter", TestWaiter.class); driverRouter = applicationContext.getBean("drinkRouter", TestDrinkRouter.class); } @After public void tearDown() throws Exception { super.tearDown(); if (applicationContext != null) { applicationContext.stop(); } } protected CamelContext createCamelContext() throws Exception { return applicationContext.getBean("camel", CamelContext.class); } }
neoramon/camel
examples/camel-example-cafe/src/test/java/org/apache/camel/example/cafe/CafeRouteSpringTest.java
Java
apache-2.0
2,036
# # 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. # from org.apache.hadoop.fs import Path from org.apache.hadoop.io import * from org.apache.hadoop.mapred import * from org.apache.hadoop.abacus import *; from java.util import *; import sys class AbacusWordCount(ValueAggregatorBaseDescriptor): def generateKeyValPairs(self, key, val): retv = ArrayList(); for w in val.toString().split(): en = ValueAggregatorBaseDescriptor.generateEntry(ValueAggregatorBaseDescriptor.LONG_VALUE_SUM, w, ValueAggregatorBaseDescriptor.ONE); retv.add(en); return retv;
simplegeo/hadoop
src/examples/python/pyAbacus/JyAbacusWCPlugIN.py
Python
apache-2.0
1,344
package main import ( "os" "os/exec" "os/signal" "syscall" "github.com/codegangsta/cli" "github.com/docker/libcontainer" "github.com/docker/libcontainer/utils" ) var standardEnvironment = &cli.StringSlice{ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "HOSTNAME=nsinit", "TERM=xterm", } var execCommand = cli.Command{ Name: "exec", Usage: "execute a new command inside a container", Action: execAction, Flags: append([]cli.Flag{ cli.BoolFlag{Name: "tty,t", Usage: "allocate a TTY to the container"}, cli.StringFlag{Name: "id", Value: "nsinit", Usage: "specify the ID for a container"}, cli.StringFlag{Name: "config", Value: "", Usage: "path to the configuration file"}, cli.StringFlag{Name: "user,u", Value: "root", Usage: "set the user, uid, and/or gid for the process"}, cli.StringFlag{Name: "cwd", Value: "", Usage: "set the current working dir"}, cli.StringSliceFlag{Name: "env", Value: standardEnvironment, Usage: "set environment variables for the process"}, }, createFlags...), } func execAction(context *cli.Context) { factory, err := loadFactory(context) if err != nil { fatal(err) } config, err := loadConfig(context) if err != nil { fatal(err) } created := false container, err := factory.Load(context.String("id")) if err != nil { created = true if container, err = factory.Create(context.String("id"), config); err != nil { fatal(err) } } process := &libcontainer.Process{ Args: context.Args(), Env: context.StringSlice("env"), User: context.String("user"), Cwd: context.String("cwd"), Stdin: os.Stdin, Stdout: os.Stdout, Stderr: os.Stderr, } rootuid, err := config.HostUID() if err != nil { fatal(err) } tty, err := newTty(context, process, rootuid) if err != nil { fatal(err) } if err := tty.attach(process); err != nil { fatal(err) } go handleSignals(process, tty) err = container.Start(process) if err != nil { tty.Close() if created { container.Destroy() } fatal(err) } status, err := process.Wait() if err != nil { exitError, ok := err.(*exec.ExitError) if ok { status = exitError.ProcessState } else { tty.Close() if created { container.Destroy() } fatal(err) } } if created { if err := container.Destroy(); err != nil { tty.Close() fatal(err) } } tty.Close() os.Exit(utils.ExitStatus(status.Sys().(syscall.WaitStatus))) } func handleSignals(container *libcontainer.Process, tty *tty) { sigc := make(chan os.Signal, 10) signal.Notify(sigc) tty.resize() for sig := range sigc { switch sig { case syscall.SIGWINCH: tty.resize() default: container.Signal(sig) } } }
ydhydhjanson/kubernetes
Godeps/_workspace/src/github.com/docker/libcontainer/nsinit/exec.go
GO
apache-2.0
2,685
/* Include this file in your html if you are using the CSP mode. */ .ng-animate.item:not(.left):not(.right) { -webkit-transition: 0s ease-in-out left; transition: 0s ease-in-out left } .uib-datepicker .uib-title { width: 100%; } .uib-day button, .uib-month button, .uib-year button { min-width: 100%; } .uib-left, .uib-right { width: 100% } .uib-position-measure { display: block !important; visibility: hidden !important; position: absolute !important; top: -9999px !important; left: -9999px !important; } .uib-position-scrollbar-measure { position: absolute !important; top: -9999px !important; width: 50px !important; height: 50px !important; overflow: scroll !important; } .uib-position-body-scrollbar-measure { overflow: scroll !important; } .uib-datepicker-popup.dropdown-menu { display: block; float: none; margin: 0; } .uib-button-bar { padding: 10px 9px 2px; } [uib-tooltip-popup].tooltip.top-left > .tooltip-arrow, [uib-tooltip-popup].tooltip.top-right > .tooltip-arrow, [uib-tooltip-popup].tooltip.bottom-left > .tooltip-arrow, [uib-tooltip-popup].tooltip.bottom-right > .tooltip-arrow, [uib-tooltip-popup].tooltip.left-top > .tooltip-arrow, [uib-tooltip-popup].tooltip.left-bottom > .tooltip-arrow, [uib-tooltip-popup].tooltip.right-top > .tooltip-arrow, [uib-tooltip-popup].tooltip.right-bottom > .tooltip-arrow, [uib-tooltip-html-popup].tooltip.top-left > .tooltip-arrow, [uib-tooltip-html-popup].tooltip.top-right > .tooltip-arrow, [uib-tooltip-html-popup].tooltip.bottom-left > .tooltip-arrow, [uib-tooltip-html-popup].tooltip.bottom-right > .tooltip-arrow, [uib-tooltip-html-popup].tooltip.left-top > .tooltip-arrow, [uib-tooltip-html-popup].tooltip.left-bottom > .tooltip-arrow, [uib-tooltip-html-popup].tooltip.right-top > .tooltip-arrow, [uib-tooltip-html-popup].tooltip.right-bottom > .tooltip-arrow, [uib-tooltip-template-popup].tooltip.top-left > .tooltip-arrow, [uib-tooltip-template-popup].tooltip.top-right > .tooltip-arrow, [uib-tooltip-template-popup].tooltip.bottom-left > .tooltip-arrow, [uib-tooltip-template-popup].tooltip.bottom-right > .tooltip-arrow, [uib-tooltip-template-popup].tooltip.left-top > .tooltip-arrow, [uib-tooltip-template-popup].tooltip.left-bottom > .tooltip-arrow, [uib-tooltip-template-popup].tooltip.right-top > .tooltip-arrow, [uib-tooltip-template-popup].tooltip.right-bottom > .tooltip-arrow, [uib-popover-popup].popover.top-left > .arrow, [uib-popover-popup].popover.top-right > .arrow, [uib-popover-popup].popover.bottom-left > .arrow, [uib-popover-popup].popover.bottom-right > .arrow, [uib-popover-popup].popover.left-top > .arrow, [uib-popover-popup].popover.left-bottom > .arrow, [uib-popover-popup].popover.right-top > .arrow, [uib-popover-popup].popover.right-bottom > .arrow, [uib-popover-html-popup].popover.top-left > .arrow, [uib-popover-html-popup].popover.top-right > .arrow, [uib-popover-html-popup].popover.bottom-left > .arrow, [uib-popover-html-popup].popover.bottom-right > .arrow, [uib-popover-html-popup].popover.left-top > .arrow, [uib-popover-html-popup].popover.left-bottom > .arrow, [uib-popover-html-popup].popover.right-top > .arrow, [uib-popover-html-popup].popover.right-bottom > .arrow, [uib-popover-template-popup].popover.top-left > .arrow, [uib-popover-template-popup].popover.top-right > .arrow, [uib-popover-template-popup].popover.bottom-left > .arrow, [uib-popover-template-popup].popover.bottom-right > .arrow, [uib-popover-template-popup].popover.left-top > .arrow, [uib-popover-template-popup].popover.left-bottom > .arrow, [uib-popover-template-popup].popover.right-top > .arrow, [uib-popover-template-popup].popover.right-bottom > .arrow { top: auto; bottom: auto; left: auto; right: auto; margin: 0; } [uib-popover-popup].popover, [uib-popover-html-popup].popover, [uib-popover-template-popup].popover { display: block !important; } .uib-time input { width: 50px; } [uib-typeahead-popup].dropdown-menu { display: block; }
goxhaj/gastronomee
src/main/webapp/bower_components/angular-bootstrap/ui-bootstrap-csp.css
CSS
apache-2.0
3,989
// Copyright 2013 Joshua Tacoma. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package uritemplates is a level 4 implementation of RFC 6570 (URI // Template, http://tools.ietf.org/html/rfc6570). // // To use uritemplates, parse a template string and expand it with a value // map: // // template, _ := uritemplates.Parse("https://api.github.com/repos{/user,repo}") // values := make(map[string]interface{}) // values["user"] = "jtacoma" // values["repo"] = "uritemplates" // expanded, _ := template.ExpandString(values) // fmt.Printf(expanded) // package uritemplates import ( "bytes" "errors" "fmt" "reflect" "regexp" "strconv" "strings" ) var ( unreserved = regexp.MustCompile("[^A-Za-z0-9\\-._~]") reserved = regexp.MustCompile("[^A-Za-z0-9\\-._~:/?#[\\]@!$&'()*+,;=]") validname = regexp.MustCompile("^([A-Za-z0-9_\\.]|%[0-9A-Fa-f][0-9A-Fa-f])+$") hex = []byte("0123456789ABCDEF") ) func pctEncode(src []byte) []byte { dst := make([]byte, len(src)*3) for i, b := range src { buf := dst[i*3 : i*3+3] buf[0] = 0x25 buf[1] = hex[b/16] buf[2] = hex[b%16] } return dst } func escape(s string, allowReserved bool) (escaped string) { if allowReserved { escaped = string(reserved.ReplaceAllFunc([]byte(s), pctEncode)) } else { escaped = string(unreserved.ReplaceAllFunc([]byte(s), pctEncode)) } return escaped } // A UriTemplate is a parsed representation of a URI template. type UriTemplate struct { raw string parts []templatePart } // Parse parses a URI template string into a UriTemplate object. func Parse(rawtemplate string) (template *UriTemplate, err error) { template = new(UriTemplate) template.raw = rawtemplate split := strings.Split(rawtemplate, "{") template.parts = make([]templatePart, len(split)*2-1) for i, s := range split { if i == 0 { if strings.Contains(s, "}") { err = errors.New("unexpected }") break } template.parts[i].raw = s } else { subsplit := strings.Split(s, "}") if len(subsplit) != 2 { err = errors.New("malformed template") break } expression := subsplit[0] template.parts[i*2-1], err = parseExpression(expression) if err != nil { break } template.parts[i*2].raw = subsplit[1] } } if err != nil { template = nil } return template, err } type templatePart struct { raw string terms []templateTerm first string sep string named bool ifemp string allowReserved bool } type templateTerm struct { name string explode bool truncate int } func parseExpression(expression string) (result templatePart, err error) { switch expression[0] { case '+': result.sep = "," result.allowReserved = true expression = expression[1:] case '.': result.first = "." result.sep = "." expression = expression[1:] case '/': result.first = "/" result.sep = "/" expression = expression[1:] case ';': result.first = ";" result.sep = ";" result.named = true expression = expression[1:] case '?': result.first = "?" result.sep = "&" result.named = true result.ifemp = "=" expression = expression[1:] case '&': result.first = "&" result.sep = "&" result.named = true result.ifemp = "=" expression = expression[1:] case '#': result.first = "#" result.sep = "," result.allowReserved = true expression = expression[1:] default: result.sep = "," } rawterms := strings.Split(expression, ",") result.terms = make([]templateTerm, len(rawterms)) for i, raw := range rawterms { result.terms[i], err = parseTerm(raw) if err != nil { break } } return result, err } func parseTerm(term string) (result templateTerm, err error) { if strings.HasSuffix(term, "*") { result.explode = true term = term[:len(term)-1] } split := strings.Split(term, ":") if len(split) == 1 { result.name = term } else if len(split) == 2 { result.name = split[0] var parsed int64 parsed, err = strconv.ParseInt(split[1], 10, 0) result.truncate = int(parsed) } else { err = errors.New("multiple colons in same term") } if !validname.MatchString(result.name) { err = errors.New("not a valid name: " + result.name) } if result.explode && result.truncate > 0 { err = errors.New("both explode and prefix modifers on same term") } return result, err } // Expand expands a URI template with a set of values to produce a string. func (self *UriTemplate) Expand(value interface{}) (string, error) { values, ismap := value.(map[string]interface{}) if !ismap { if m, ismap := struct2map(value); !ismap { return "", errors.New("expected map[string]interface{}, struct, or pointer to struct.") } else { return self.Expand(m) } } var buf bytes.Buffer for _, p := range self.parts { err := p.expand(&buf, values) if err != nil { return "", err } } return buf.String(), nil } func (self *templatePart) expand(buf *bytes.Buffer, values map[string]interface{}) error { if len(self.raw) > 0 { buf.WriteString(self.raw) return nil } var zeroLen = buf.Len() buf.WriteString(self.first) var firstLen = buf.Len() for _, term := range self.terms { value, exists := values[term.name] if !exists { continue } if buf.Len() != firstLen { buf.WriteString(self.sep) } switch v := value.(type) { case string: self.expandString(buf, term, v) case []interface{}: self.expandArray(buf, term, v) case map[string]interface{}: if term.truncate > 0 { return errors.New("cannot truncate a map expansion") } self.expandMap(buf, term, v) default: if m, ismap := struct2map(value); ismap { if term.truncate > 0 { return errors.New("cannot truncate a map expansion") } self.expandMap(buf, term, m) } else { str := fmt.Sprintf("%v", value) self.expandString(buf, term, str) } } } if buf.Len() == firstLen { original := buf.Bytes()[:zeroLen] buf.Reset() buf.Write(original) } return nil } func (self *templatePart) expandName(buf *bytes.Buffer, name string, empty bool) { if self.named { buf.WriteString(name) if empty { buf.WriteString(self.ifemp) } else { buf.WriteString("=") } } } func (self *templatePart) expandString(buf *bytes.Buffer, t templateTerm, s string) { if len(s) > t.truncate && t.truncate > 0 { s = s[:t.truncate] } self.expandName(buf, t.name, len(s) == 0) buf.WriteString(escape(s, self.allowReserved)) } func (self *templatePart) expandArray(buf *bytes.Buffer, t templateTerm, a []interface{}) { if len(a) == 0 { return } else if !t.explode { self.expandName(buf, t.name, false) } for i, value := range a { if t.explode && i > 0 { buf.WriteString(self.sep) } else if i > 0 { buf.WriteString(",") } var s string switch v := value.(type) { case string: s = v default: s = fmt.Sprintf("%v", v) } if len(s) > t.truncate && t.truncate > 0 { s = s[:t.truncate] } if self.named && t.explode { self.expandName(buf, t.name, len(s) == 0) } buf.WriteString(escape(s, self.allowReserved)) } } func (self *templatePart) expandMap(buf *bytes.Buffer, t templateTerm, m map[string]interface{}) { if len(m) == 0 { return } if !t.explode { self.expandName(buf, t.name, len(m) == 0) } var firstLen = buf.Len() for k, value := range m { if firstLen != buf.Len() { if t.explode { buf.WriteString(self.sep) } else { buf.WriteString(",") } } var s string switch v := value.(type) { case string: s = v default: s = fmt.Sprintf("%v", v) } if t.explode { buf.WriteString(escape(k, self.allowReserved)) buf.WriteRune('=') buf.WriteString(escape(s, self.allowReserved)) } else { buf.WriteString(escape(k, self.allowReserved)) buf.WriteRune(',') buf.WriteString(escape(s, self.allowReserved)) } } } func struct2map(v interface{}) (map[string]interface{}, bool) { value := reflect.ValueOf(v) switch value.Type().Kind() { case reflect.Ptr: return struct2map(value.Elem().Interface()) case reflect.Struct: m := make(map[string]interface{}) for i := 0; i < value.NumField(); i++ { tag := value.Type().Field(i).Tag var name string if strings.Contains(string(tag), ":") { name = tag.Get("uri") } else { name = strings.TrimSpace(string(tag)) } if len(name) == 0 { name = value.Type().Field(i).Name } m[name] = value.Field(i).Interface() } return m, true } return nil, false }
robszumski/kubernetes
Godeps/_workspace/src/google.golang.org/api/googleapi/internal/uritemplates/uritemplates.go
GO
apache-2.0
8,500
<?php //============================================================================= // File: ODOEX011.PHP // Description: Example 0 for odometer graphs // Created: 2002-02-22 // Version: $Id$ // // Comment: // Example file for odometer graph. Extends odoex10.php with graph titles // and captions and also adds individual captions for each odometer. // // Copyright (C) 2002 Johan Persson. All rights reserved. //============================================================================= require_once ('jpgraph/jpgraph.php'); require_once ('jpgraph/jpgraph_odo.php'); //--------------------------------------------------------------------- // Create a new odometer graph (width=200, height=400 pixels) //--------------------------------------------------------------------- $graph = new OdoGraph(200,370); $graph->SetShadow(); //--------------------------------------------------------------------- // Specify title and subtitle using default fonts // * Note each title may be multilines by using a '\n' as a line // divider. //--------------------------------------------------------------------- $graph->title->Set("Result from 2002"); $graph->title->SetColor("white"); $graph->subtitle->Set("O1 - W-Site"); $graph->subtitle->SetColor("white"); //--------------------------------------------------------------------- // Specify caption. // * (This is the text at the bottom of the graph.) The margins will // automatically adjust to fit the height of the text. A caption // may have multiple lines by including a '\n' character in the // string. //--------------------------------------------------------------------- $graph->caption->Set("Fig1. Values within 85%\nconfidence intervall"); $graph->caption->SetColor("white"); //--------------------------------------------------------------------- // We will display three odometers stacked vertically // The first thing to do is to create them //--------------------------------------------------------------------- $odo1 = new Odometer(); $odo2 = new Odometer(); $odo3 = new Odometer(); //--------------------------------------------------------------------- // Set caption for each odometer //--------------------------------------------------------------------- $odo1->caption->Set("April"); $odo1->caption->SetFont(FF_FONT2,FS_BOLD); $odo2->caption->Set("May"); $odo2->caption->SetFont(FF_FONT2,FS_BOLD); $odo3->caption->Set("June"); $odo3->caption->SetFont(FF_FONT2,FS_BOLD); //--------------------------------------------------------------------- // Set Indicator bands for the odometers //--------------------------------------------------------------------- $odo1->AddIndication(80,100,"red"); $odo2->AddIndication(20,30,"green"); $odo2->AddIndication(65,100,"red"); $odo3->AddIndication(60,90,"yellow"); $odo3->AddIndication(90,100,"red"); //--------------------------------------------------------------------- // Set display values for the odometers //--------------------------------------------------------------------- $odo1->needle->Set(17); $odo2->needle->Set(47); $odo3->needle->Set(86); $odo1->needle->SetFillColor("blue"); $odo2->needle->SetFillColor("yellow:0.7"); $odo3->needle->SetFillColor("black"); $odo3->needle->SetColor("black"); //--------------------------------------------------------------------- // Set scale label properties //--------------------------------------------------------------------- $odo1->scale->label->SetColor("navy"); $odo2->scale->label->SetColor("blue"); $odo3->scale->label->SetColor("darkred"); $odo1->scale->label->SetFont(FF_FONT1); $odo2->scale->label->SetFont(FF_FONT2,FS_BOLD); $odo3->scale->label->SetFont(FF_ARIAL,FS_BOLD,10); //--------------------------------------------------------------------- // Add the odometers to the graph using a vertical layout //--------------------------------------------------------------------- $l1 = new LayoutVert( array($odo1,$odo2,$odo3) ) ; $graph->Add( $l1 ); //--------------------------------------------------------------------- // ... and finally stroke and stream the image back to the browser //--------------------------------------------------------------------- $graph->Stroke(); // EOF ?>
atikahremle/bengkeltika_git
jpgraph/src/Examples/odoex011.php
PHP
apache-2.0
4,179
/** * 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.component.cxf.transport; import java.io.IOException; import java.io.OutputStream; import org.apache.camel.CamelContext; import org.apache.camel.Endpoint; import org.apache.camel.Producer; import org.apache.camel.ProducerTemplate; import org.apache.camel.RuntimeCamelException; import org.apache.camel.spi.HeaderFilterStrategy; import org.apache.camel.util.ObjectHelper; import org.apache.cxf.Bus; import org.apache.cxf.common.logging.LogUtils; import org.apache.cxf.configuration.Configurable; import org.apache.cxf.configuration.Configurer; import org.apache.cxf.message.Message; import org.apache.cxf.service.model.EndpointInfo; import org.apache.cxf.transport.AbstractConduit; import org.apache.cxf.ws.addressing.EndpointReferenceType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @version */ public class CamelConduit extends AbstractConduit implements Configurable { protected static final String BASE_BEAN_NAME_SUFFIX = ".camel-conduit"; private static final Logger LOG = LoggerFactory.getLogger(CamelConduit.class); // used for places where CXF requires JUL private static final java.util.logging.Logger JUL_LOG = LogUtils.getL7dLogger(CamelConduit.class); private CamelContext camelContext; private EndpointInfo endpointInfo; private String targetCamelEndpointUri; private Producer producer; private ProducerTemplate camelTemplate; private Bus bus; private HeaderFilterStrategy headerFilterStrategy; public CamelConduit(CamelContext context, Bus b, EndpointInfo endpointInfo) { this(context, b, endpointInfo, null); } public CamelConduit(CamelContext context, Bus b, EndpointInfo epInfo, EndpointReferenceType targetReference) { this(context, b, epInfo, targetReference, null); } public CamelConduit(CamelContext context, Bus b, EndpointInfo epInfo, EndpointReferenceType targetReference, HeaderFilterStrategy headerFilterStrategy) { super(getTargetReference(epInfo, targetReference, b)); String address = epInfo.getAddress(); if (address != null) { targetCamelEndpointUri = address.substring(CamelTransportConstants.CAMEL_TRANSPORT_PREFIX.length()); if (targetCamelEndpointUri.startsWith("//")) { targetCamelEndpointUri = targetCamelEndpointUri.substring(2); } } camelContext = context; endpointInfo = epInfo; bus = b; initConfig(); this.headerFilterStrategy = headerFilterStrategy; Endpoint target = getCamelContext().getEndpoint(targetCamelEndpointUri); try { producer = target.createProducer(); producer.start(); } catch (Exception e) { throw new RuntimeCamelException("Cannot create the producer rightly", e); } } public void setCamelContext(CamelContext context) { camelContext = context; } public CamelContext getCamelContext() { ObjectHelper.notNull(camelContext, "CamelContext", this); return camelContext; } // prepare the message for send out , not actually send out the message public void prepare(Message message) throws IOException { LOG.trace("CamelConduit send message"); CamelOutputStream os = new CamelOutputStream(this.targetCamelEndpointUri, this.producer, this.headerFilterStrategy, this.getMessageObserver(), message); message.setContent(OutputStream.class, os); } public void close() { LOG.trace("CamelConduit closed "); // shutdown the producer try { producer.stop(); } catch (Exception e) { LOG.warn("CamelConduit producer stop with the exception", e); } } protected java.util.logging.Logger getLogger() { return JUL_LOG; } public String getBeanName() { if (endpointInfo == null || endpointInfo.getName() == null) { return "default" + BASE_BEAN_NAME_SUFFIX; } return endpointInfo.getName().toString() + BASE_BEAN_NAME_SUFFIX; } private void initConfig() { // we could configure the camel context here if (bus != null) { Configurer configurer = bus.getExtension(Configurer.class); if (null != configurer) { configurer.configureBean(this); } } } @Deprecated public ProducerTemplate getCamelTemplate() throws Exception { if (camelTemplate == null) { camelTemplate = getCamelContext().createProducerTemplate(); } return camelTemplate; } @Deprecated public void setCamelTemplate(ProducerTemplate template) { camelTemplate = template; } }
jollygeorge/camel
components/camel-cxf-transport/src/main/java/org/apache/camel/component/cxf/transport/CamelConduit.java
Java
apache-2.0
5,797
/** * 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.core.xml.util.jsse; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlTransient; import org.apache.camel.util.jsse.SecureRandomParameters; @XmlAccessorType(XmlAccessType.FIELD) public abstract class AbstractSecureRandomParametersFactoryBean extends AbstractJsseUtilFactoryBean<SecureRandomParameters> { @XmlAttribute(required = true) protected String algorithm; @XmlAttribute protected String provider; @XmlTransient private SecureRandomParameters instance; public String getAlgorithm() { return algorithm; } public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } public String getProvider() { return provider; } public void setProvider(String provider) { this.provider = provider; } @Override public SecureRandomParameters getObject() throws Exception { if (this.isSingleton()) { if (instance == null) { instance = createInstance(); } return instance; } else { return createInstance(); } } protected SecureRandomParameters createInstance() { SecureRandomParameters newInstance = new SecureRandomParameters(); newInstance.setAlgorithm(algorithm); newInstance.setProvider(provider); newInstance.setCamelContext(getCamelContext()); return newInstance; } @Override public Class<? extends SecureRandomParameters> getObjectType() { return SecureRandomParameters.class; } }
dkhanolkar/camel
components/camel-core-xml/src/main/java/org/apache/camel/core/xml/util/jsse/AbstractSecureRandomParametersFactoryBean.java
Java
apache-2.0
2,561
/** * 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.builder.xml; import javax.xml.transform.Result; import javax.xml.transform.dom.DOMResult; import org.apache.camel.Message; /** * Uses DOM to handle results of the transformation * * @version */ public class DomResultHandler implements ResultHandler { private DOMResult result = new DOMResult(); public Result getResult() { return result; } public void setBody(Message in) { in.setBody(result.getNode()); } }
brreitme/camel
camel-core/src/main/java/org/apache/camel/builder/xml/DomResultHandler.java
Java
apache-2.0
1,283
/** * 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.component.velocity; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.test.junit4.CamelTestSupport; import org.junit.Test; /** * @version */ public class VelocityConcurrentTest extends CamelTestSupport { @Test public void testNoConcurrentProducers() throws Exception { doSendMessages(1, 1); } @Test public void testConcurrentProducers() throws Exception { doSendMessages(10, 5); } private void doSendMessages(int files, int poolSize) throws Exception { getMockEndpoint("mock:result").expectedMessageCount(files); getMockEndpoint("mock:result").assertNoDuplicates(body()); getMockEndpoint("mock:result").message(0).body().contains("Bye"); ExecutorService executor = Executors.newFixedThreadPool(poolSize); for (int i = 0; i < files; i++) { final int index = i; executor.submit(new Callable<Object>() { public Object call() throws Exception { template.sendBody("direct:start", "Hello " + index); return null; } }); } assertMockEndpointsSatisfied(); executor.shutdownNow(); } protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start"). to("velocity:org/apache/camel/component/velocity/Concurrent.vm"). to("mock:result"); } }; } }
anoordover/camel
components/camel-velocity/src/test/java/org/apache/camel/component/velocity/VelocityConcurrentTest.java
Java
apache-2.0
2,505
// Copyright 2015 go-swagger maintainers // // 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 spec import ( "encoding/json" "fmt" "net/url" "strings" "github.com/go-openapi/jsonpointer" "github.com/go-openapi/swag" ) // BooleanProperty creates a boolean property func BooleanProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"boolean"}}} } // BoolProperty creates a boolean property func BoolProperty() *Schema { return BooleanProperty() } // StringProperty creates a string property func StringProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} } // CharProperty creates a string property func CharProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}}} } // Float64Property creates a float64/double property func Float64Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "double"}} } // Float32Property creates a float32/float property func Float32Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"number"}, Format: "float"}} } // Int8Property creates an int8 property func Int8Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int8"}} } // Int16Property creates an int16 property func Int16Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int16"}} } // Int32Property creates an int32 property func Int32Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int32"}} } // Int64Property creates an int64 property func Int64Property() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"integer"}, Format: "int64"}} } // StrFmtProperty creates a property for the named string format func StrFmtProperty(format string) *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: format}} } // DateProperty creates a date property func DateProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date"}} } // DateTimeProperty creates a date time property func DateTimeProperty() *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"string"}, Format: "date-time"}} } // MapProperty creates a map property func MapProperty(property *Schema) *Schema { return &Schema{SchemaProps: SchemaProps{Type: []string{"object"}, AdditionalProperties: &SchemaOrBool{Allows: true, Schema: property}}} } // RefProperty creates a ref property func RefProperty(name string) *Schema { return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} } // RefSchema creates a ref property func RefSchema(name string) *Schema { return &Schema{SchemaProps: SchemaProps{Ref: MustCreateRef(name)}} } // ArrayProperty creates an array property func ArrayProperty(items *Schema) *Schema { if items == nil { return &Schema{SchemaProps: SchemaProps{Type: []string{"array"}}} } return &Schema{SchemaProps: SchemaProps{Items: &SchemaOrArray{Schema: items}, Type: []string{"array"}}} } // ComposedSchema creates a schema with allOf func ComposedSchema(schemas ...Schema) *Schema { s := new(Schema) s.AllOf = schemas return s } // SchemaURL represents a schema url type SchemaURL string // MarshalJSON marshal this to JSON func (r SchemaURL) MarshalJSON() ([]byte, error) { if r == "" { return []byte("{}"), nil } v := map[string]interface{}{"$schema": string(r)} return json.Marshal(v) } // UnmarshalJSON unmarshal this from JSON func (r *SchemaURL) UnmarshalJSON(data []byte) error { var v map[string]interface{} if err := json.Unmarshal(data, &v); err != nil { return err } return r.fromMap(v) } func (r *SchemaURL) fromMap(v map[string]interface{}) error { if v == nil { return nil } if vv, ok := v["$schema"]; ok { if str, ok := vv.(string); ok { u, err := url.Parse(str) if err != nil { return err } *r = SchemaURL(u.String()) } } return nil } // type ExtraSchemaProps map[string]interface{} // // JSONSchema represents a structure that is a json schema draft 04 // type JSONSchema struct { // SchemaProps // ExtraSchemaProps // } // // MarshalJSON marshal this to JSON // func (s JSONSchema) MarshalJSON() ([]byte, error) { // b1, err := json.Marshal(s.SchemaProps) // if err != nil { // return nil, err // } // b2, err := s.Ref.MarshalJSON() // if err != nil { // return nil, err // } // b3, err := s.Schema.MarshalJSON() // if err != nil { // return nil, err // } // b4, err := json.Marshal(s.ExtraSchemaProps) // if err != nil { // return nil, err // } // return swag.ConcatJSON(b1, b2, b3, b4), nil // } // // UnmarshalJSON marshal this from JSON // func (s *JSONSchema) UnmarshalJSON(data []byte) error { // var sch JSONSchema // if err := json.Unmarshal(data, &sch.SchemaProps); err != nil { // return err // } // if err := json.Unmarshal(data, &sch.Ref); err != nil { // return err // } // if err := json.Unmarshal(data, &sch.Schema); err != nil { // return err // } // if err := json.Unmarshal(data, &sch.ExtraSchemaProps); err != nil { // return err // } // *s = sch // return nil // } type SchemaProps struct { ID string `json:"id,omitempty"` Ref Ref `json:"-"` Schema SchemaURL `json:"-"` Description string `json:"description,omitempty"` Type StringOrArray `json:"type,omitempty"` Format string `json:"format,omitempty"` Title string `json:"title,omitempty"` Default interface{} `json:"default,omitempty"` Maximum *float64 `json:"maximum,omitempty"` ExclusiveMaximum bool `json:"exclusiveMaximum,omitempty"` Minimum *float64 `json:"minimum,omitempty"` ExclusiveMinimum bool `json:"exclusiveMinimum,omitempty"` MaxLength *int64 `json:"maxLength,omitempty"` MinLength *int64 `json:"minLength,omitempty"` Pattern string `json:"pattern,omitempty"` MaxItems *int64 `json:"maxItems,omitempty"` MinItems *int64 `json:"minItems,omitempty"` UniqueItems bool `json:"uniqueItems,omitempty"` MultipleOf *float64 `json:"multipleOf,omitempty"` Enum []interface{} `json:"enum,omitempty"` MaxProperties *int64 `json:"maxProperties,omitempty"` MinProperties *int64 `json:"minProperties,omitempty"` Required []string `json:"required,omitempty"` Items *SchemaOrArray `json:"items,omitempty"` AllOf []Schema `json:"allOf,omitempty"` OneOf []Schema `json:"oneOf,omitempty"` AnyOf []Schema `json:"anyOf,omitempty"` Not *Schema `json:"not,omitempty"` Properties map[string]Schema `json:"properties,omitempty"` AdditionalProperties *SchemaOrBool `json:"additionalProperties,omitempty"` PatternProperties map[string]Schema `json:"patternProperties,omitempty"` Dependencies Dependencies `json:"dependencies,omitempty"` AdditionalItems *SchemaOrBool `json:"additionalItems,omitempty"` Definitions Definitions `json:"definitions,omitempty"` } type SwaggerSchemaProps struct { Discriminator string `json:"discriminator,omitempty"` ReadOnly bool `json:"readOnly,omitempty"` XML *XMLObject `json:"xml,omitempty"` ExternalDocs *ExternalDocumentation `json:"externalDocs,omitempty"` Example interface{} `json:"example,omitempty"` } // Schema the schema object allows the definition of input and output data types. // These types can be objects, but also primitives and arrays. // This object is based on the [JSON Schema Specification Draft 4](http://json-schema.org/) // and uses a predefined subset of it. // On top of this subset, there are extensions provided by this specification to allow for more complete documentation. // // For more information: http://goo.gl/8us55a#schemaObject type Schema struct { VendorExtensible SchemaProps SwaggerSchemaProps ExtraProps map[string]interface{} `json:"-"` } // JSONLookup implements an interface to customize json pointer lookup func (s Schema) JSONLookup(token string) (interface{}, error) { if ex, ok := s.Extensions[token]; ok { return &ex, nil } if ex, ok := s.ExtraProps[token]; ok { return &ex, nil } r, _, err := jsonpointer.GetForToken(s.SchemaProps, token) if r != nil || (err != nil && !strings.HasPrefix(err.Error(), "object has no field")) { return r, err } r, _, err = jsonpointer.GetForToken(s.SwaggerSchemaProps, token) return r, err } // WithID sets the id for this schema, allows for chaining func (s *Schema) WithID(id string) *Schema { s.ID = id return s } // WithTitle sets the title for this schema, allows for chaining func (s *Schema) WithTitle(title string) *Schema { s.Title = title return s } // WithDescription sets the description for this schema, allows for chaining func (s *Schema) WithDescription(description string) *Schema { s.Description = description return s } // WithProperties sets the properties for this schema func (s *Schema) WithProperties(schemas map[string]Schema) *Schema { s.Properties = schemas return s } // SetProperty sets a property on this schema func (s *Schema) SetProperty(name string, schema Schema) *Schema { if s.Properties == nil { s.Properties = make(map[string]Schema) } s.Properties[name] = schema return s } // WithAllOf sets the all of property func (s *Schema) WithAllOf(schemas ...Schema) *Schema { s.AllOf = schemas return s } // WithMaxProperties sets the max number of properties an object can have func (s *Schema) WithMaxProperties(max int64) *Schema { s.MaxProperties = &max return s } // WithMinProperties sets the min number of properties an object must have func (s *Schema) WithMinProperties(min int64) *Schema { s.MinProperties = &min return s } // Typed sets the type of this schema for a single value item func (s *Schema) Typed(tpe, format string) *Schema { s.Type = []string{tpe} s.Format = format return s } // AddType adds a type with potential format to the types for this schema func (s *Schema) AddType(tpe, format string) *Schema { s.Type = append(s.Type, tpe) if format != "" { s.Format = format } return s } // CollectionOf a fluent builder method for an array parameter func (s *Schema) CollectionOf(items Schema) *Schema { s.Type = []string{"array"} s.Items = &SchemaOrArray{Schema: &items} return s } // WithDefault sets the default value on this parameter func (s *Schema) WithDefault(defaultValue interface{}) *Schema { s.Default = defaultValue return s } // WithRequired flags this parameter as required func (s *Schema) WithRequired(items ...string) *Schema { s.Required = items return s } // AddRequired adds field names to the required properties array func (s *Schema) AddRequired(items ...string) *Schema { s.Required = append(s.Required, items...) return s } // WithMaxLength sets a max length value func (s *Schema) WithMaxLength(max int64) *Schema { s.MaxLength = &max return s } // WithMinLength sets a min length value func (s *Schema) WithMinLength(min int64) *Schema { s.MinLength = &min return s } // WithPattern sets a pattern value func (s *Schema) WithPattern(pattern string) *Schema { s.Pattern = pattern return s } // WithMultipleOf sets a multiple of value func (s *Schema) WithMultipleOf(number float64) *Schema { s.MultipleOf = &number return s } // WithMaximum sets a maximum number value func (s *Schema) WithMaximum(max float64, exclusive bool) *Schema { s.Maximum = &max s.ExclusiveMaximum = exclusive return s } // WithMinimum sets a minimum number value func (s *Schema) WithMinimum(min float64, exclusive bool) *Schema { s.Minimum = &min s.ExclusiveMinimum = exclusive return s } // WithEnum sets a the enum values (replace) func (s *Schema) WithEnum(values ...interface{}) *Schema { s.Enum = append([]interface{}{}, values...) return s } // WithMaxItems sets the max items func (s *Schema) WithMaxItems(size int64) *Schema { s.MaxItems = &size return s } // WithMinItems sets the min items func (s *Schema) WithMinItems(size int64) *Schema { s.MinItems = &size return s } // UniqueValues dictates that this array can only have unique items func (s *Schema) UniqueValues() *Schema { s.UniqueItems = true return s } // AllowDuplicates this array can have duplicates func (s *Schema) AllowDuplicates() *Schema { s.UniqueItems = false return s } // AddToAllOf adds a schema to the allOf property func (s *Schema) AddToAllOf(schemas ...Schema) *Schema { s.AllOf = append(s.AllOf, schemas...) return s } // WithDiscriminator sets the name of the discriminator field func (s *Schema) WithDiscriminator(discriminator string) *Schema { s.Discriminator = discriminator return s } // AsReadOnly flags this schema as readonly func (s *Schema) AsReadOnly() *Schema { s.ReadOnly = true return s } // AsWritable flags this schema as writeable (not read-only) func (s *Schema) AsWritable() *Schema { s.ReadOnly = false return s } // WithExample sets the example for this schema func (s *Schema) WithExample(example interface{}) *Schema { s.Example = example return s } // WithExternalDocs sets/removes the external docs for/from this schema. // When you pass empty strings as params the external documents will be removed. // When you pass non-empty string as one value then those values will be used on the external docs object. // So when you pass a non-empty description, you should also pass the url and vice versa. func (s *Schema) WithExternalDocs(description, url string) *Schema { if description == "" && url == "" { s.ExternalDocs = nil return s } if s.ExternalDocs == nil { s.ExternalDocs = &ExternalDocumentation{} } s.ExternalDocs.Description = description s.ExternalDocs.URL = url return s } // WithXMLName sets the xml name for the object func (s *Schema) WithXMLName(name string) *Schema { if s.XML == nil { s.XML = new(XMLObject) } s.XML.Name = name return s } // WithXMLNamespace sets the xml namespace for the object func (s *Schema) WithXMLNamespace(namespace string) *Schema { if s.XML == nil { s.XML = new(XMLObject) } s.XML.Namespace = namespace return s } // WithXMLPrefix sets the xml prefix for the object func (s *Schema) WithXMLPrefix(prefix string) *Schema { if s.XML == nil { s.XML = new(XMLObject) } s.XML.Prefix = prefix return s } // AsXMLAttribute flags this object as xml attribute func (s *Schema) AsXMLAttribute() *Schema { if s.XML == nil { s.XML = new(XMLObject) } s.XML.Attribute = true return s } // AsXMLElement flags this object as an xml node func (s *Schema) AsXMLElement() *Schema { if s.XML == nil { s.XML = new(XMLObject) } s.XML.Attribute = false return s } // AsWrappedXML flags this object as wrapped, this is mostly useful for array types func (s *Schema) AsWrappedXML() *Schema { if s.XML == nil { s.XML = new(XMLObject) } s.XML.Wrapped = true return s } // AsUnwrappedXML flags this object as an xml node func (s *Schema) AsUnwrappedXML() *Schema { if s.XML == nil { s.XML = new(XMLObject) } s.XML.Wrapped = false return s } // MarshalJSON marshal this to JSON func (s Schema) MarshalJSON() ([]byte, error) { b1, err := json.Marshal(s.SchemaProps) if err != nil { return nil, fmt.Errorf("schema props %v", err) } b2, err := json.Marshal(s.VendorExtensible) if err != nil { return nil, fmt.Errorf("vendor props %v", err) } b3, err := s.Ref.MarshalJSON() if err != nil { return nil, fmt.Errorf("ref prop %v", err) } b4, err := s.Schema.MarshalJSON() if err != nil { return nil, fmt.Errorf("schema prop %v", err) } b5, err := json.Marshal(s.SwaggerSchemaProps) if err != nil { return nil, fmt.Errorf("common validations %v", err) } var b6 []byte if s.ExtraProps != nil { jj, err := json.Marshal(s.ExtraProps) if err != nil { return nil, fmt.Errorf("extra props %v", err) } b6 = jj } return swag.ConcatJSON(b1, b2, b3, b4, b5, b6), nil } // UnmarshalJSON marshal this from JSON func (s *Schema) UnmarshalJSON(data []byte) error { props := struct { SchemaProps SwaggerSchemaProps }{} if err := json.Unmarshal(data, &props); err != nil { return err } sch := Schema{ SchemaProps: props.SchemaProps, SwaggerSchemaProps: props.SwaggerSchemaProps, } var d map[string]interface{} if err := json.Unmarshal(data, &d); err != nil { return err } sch.Ref.fromMap(d) sch.Schema.fromMap(d) delete(d, "$ref") delete(d, "$schema") for _, pn := range swag.DefaultJSONNameProvider.GetJSONNames(s) { delete(d, pn) } for k, vv := range d { lk := strings.ToLower(k) if strings.HasPrefix(lk, "x-") { if sch.Extensions == nil { sch.Extensions = map[string]interface{}{} } sch.Extensions[k] = vv continue } if sch.ExtraProps == nil { sch.ExtraProps = map[string]interface{}{} } sch.ExtraProps[k] = vv } *s = sch return nil }
jlowdermilk/kubernetes
vendor/github.com/go-openapi/spec/schema.go
GO
apache-2.0
17,911
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "dimanche", "lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi" ], "ERANAMES": [ "avant J\u00e9sus-Christ", "apr\u00e8s J\u00e9sus-Christ" ], "ERAS": [ "av. J.-C.", "ap. J.-C." ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "janvier", "f\u00e9vrier", "mars", "avril", "mai", "juin", "juillet", "ao\u00fbt", "septembre", "octobre", "novembre", "d\u00e9cembre" ], "SHORTDAY": [ "dim.", "lun.", "mar.", "mer.", "jeu.", "ven.", "sam." ], "SHORTMONTH": [ "janv.", "f\u00e9vr.", "mars", "avr.", "mai", "juin", "juil.", "ao\u00fbt", "sept.", "oct.", "nov.", "d\u00e9c." ], "STANDALONEMONTH": [ "Janvier", "F\u00e9vrier", "Mars", "Avril", "Mai", "Juin", "Juillet", "Ao\u00fbt", "Septembre", "Octobre", "Novembre", "D\u00e9cembre" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y HH:mm:ss", "mediumDate": "d MMM y", "mediumTime": "HH:mm:ss", "short": "dd/MM/y HH:mm", "shortDate": "dd/MM/y", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "RF", "DECIMAL_SEP": ",", "GROUP_SEP": "\u00a0", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "fr-rw", "localeID": "fr_RW", "pluralCat": function(n, opt_precision) { var i = n | 0; if (i == 0 || i == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
seniya2/reference_webui_template
src/main/resources/static/scripts/angular-i18n/angular-locale_fr-rw.js
JavaScript
apache-2.0
2,455
/* mbed Microcontroller Library - stackheap * Setup a fixed single stack/heap memory model, * between the top of the RW/ZI region and the stackpointer ******************************************************************************* * Copyright (c) 2014, STMicroelectronics * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. 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. * 3. Neither the name of STMicroelectronics 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. ******************************************************************************* */ #ifdef __cplusplus extern "C" { #endif #include <rt_misc.h> #include <stdint.h> extern char Image$$RW_IRAM1$$ZI$$Limit[]; extern __value_in_regs struct __initial_stackheap __user_setup_stackheap(uint32_t R0, uint32_t R1, uint32_t R2, uint32_t R3) { uint32_t zi_limit = (uint32_t)Image$$RW_IRAM1$$ZI$$Limit; uint32_t sp_limit = __current_sp(); zi_limit = (zi_limit + 7) & ~0x7; // ensure zi_limit is 8-byte aligned struct __initial_stackheap r; r.heap_base = zi_limit; r.heap_limit = sp_limit; return r; } #ifdef __cplusplus } #endif
mnlipp/mbed
libraries/mbed/targets/cmsis/TARGET_STM/TARGET_STM32F0/TARGET_NUCLEO_F030R8/TOOLCHAIN_ARM_STD/sys.cpp
C++
apache-2.0
2,466
'use strict'; var chai = require('chai'); var expect = chai.expect; var NodeType = require('../lib/NodeType.js'); var Parser = require('../lib/Parser.js'); describe('Parser', function() { it('should return a type name node when "TypeName" arrived', function() { var typeExprStr = 'TypeName'; var node = Parser.parse(typeExprStr); var expectedNode = createTypeNameNode(typeExprStr); expect(node).to.deep.equal(expectedNode); }); it('should return a type name node when "$" arrived', function() { var typeExprStr = '$'; var node = Parser.parse(typeExprStr); var expectedNode = createTypeNameNode(typeExprStr); expect(node).to.deep.equal(expectedNode); }); it('should return a type name node when "_" arrived', function() { var typeExprStr = '_'; var node = Parser.parse(typeExprStr); var expectedNode = createTypeNameNode(typeExprStr); expect(node).to.deep.equal(expectedNode); }); it('should return an any type node when "*" arrived', function() { var typeExprStr = '*'; var node = Parser.parse(typeExprStr); var expectedNode = createAnyTypeNode(); expect(node).to.deep.equal(expectedNode); }); it('should return an unknown type node when "?" arrived', function() { var typeExprStr = '?'; var node = Parser.parse(typeExprStr); var expectedNode = createUnknownTypeNode(); expect(node).to.deep.equal(expectedNode); }); it('should return a module name node when "module:path/to/file.js" arrived', function() { var typeExprStr = 'module:path/to/file.js'; var node = Parser.parse(typeExprStr); var expectedNode = createModuleNameNode('path/to/file.js'); expect(node).to.deep.equal(expectedNode); }); it('should return a module name node when "module : path/to/file.js" arrived', function() { var typeExprStr = 'module : path/to/file.js'; var node = Parser.parse(typeExprStr); var expectedNode = createModuleNameNode('path/to/file.js'); expect(node).to.deep.equal(expectedNode); }); it('should return a member node when "(module:path/to/file.js).member" arrived', function() { var typeExprStr = '(module:path/to/file.js).member'; var node = Parser.parse(typeExprStr); var expectedNode = createMemberTypeNode( createModuleNameNode('path/to/file.js'), 'member' ); expect(node).to.deep.equal(expectedNode); }); it('should return a member type node when "owner.Member" arrived', function() { var typeExprStr = 'owner.Member'; var node = Parser.parse(typeExprStr); var expectedNode = createMemberTypeNode( createTypeNameNode('owner'), 'Member'); expect(node).to.deep.equal(expectedNode); }); it('should return a member type node when "owner . Member" arrived', function() { var typeExprStr = 'owner . Member'; var node = Parser.parse(typeExprStr); var expectedNode = createMemberTypeNode( createTypeNameNode('owner'), 'Member'); expect(node).to.deep.equal(expectedNode); }); it('should return a member type node when "superOwner.owner.Member" arrived', function() { var typeExprStr = 'superOwner.owner.Member'; var node = Parser.parse(typeExprStr); var expectedNode = createMemberTypeNode( createMemberTypeNode( createTypeNameNode('superOwner'), 'owner'), 'Member'); expect(node).to.deep.equal(expectedNode); }); it('should return a member type node when "superOwner.owner.Member=" arrived', function() { var typeExprStr = 'superOwner.owner.Member='; var node = Parser.parse(typeExprStr); var expectedNode = createOptionalTypeNode( createMemberTypeNode( createMemberTypeNode( createTypeNameNode('superOwner'), 'owner'), 'Member') ); expect(node).to.deep.equal(expectedNode); }); it('should return an inner member type node when "owner~innerMember" arrived', function() { var typeExprStr = 'owner~innerMember'; var node = Parser.parse(typeExprStr); var expectedNode = createInnerMemberTypeNode( createTypeNameNode('owner'), 'innerMember'); expect(node).to.deep.equal(expectedNode); }); it('should return an inner member type node when "owner ~ innerMember" arrived', function() { var typeExprStr = 'owner ~ innerMember'; var node = Parser.parse(typeExprStr); var expectedNode = createInnerMemberTypeNode( createTypeNameNode('owner'), 'innerMember'); expect(node).to.deep.equal(expectedNode); }); it('should return an inner member type node when "superOwner~owner~innerMember" ' + 'arrived', function() { var typeExprStr = 'superOwner~owner~innerMember'; var node = Parser.parse(typeExprStr); var expectedNode = createInnerMemberTypeNode( createInnerMemberTypeNode( createTypeNameNode('superOwner'), 'owner'), 'innerMember'); expect(node).to.deep.equal(expectedNode); }); it('should return an inner member type node when "superOwner~owner~innerMember=" ' + 'arrived', function() { var typeExprStr = 'superOwner~owner~innerMember='; var node = Parser.parse(typeExprStr); var expectedNode = createOptionalTypeNode( createInnerMemberTypeNode( createInnerMemberTypeNode( createTypeNameNode('superOwner'), 'owner'), 'innerMember') ); expect(node).to.deep.equal(expectedNode); }); it('should return an instance member type node when "owner#instanceMember" arrived', function() { var typeExprStr = 'owner#instanceMember'; var node = Parser.parse(typeExprStr); var expectedNode = createInstanceMemberTypeNode( createTypeNameNode('owner'), 'instanceMember'); expect(node).to.deep.equal(expectedNode); }); it('should return an instance member type node when "owner # instanceMember" ' + 'arrived', function() { var typeExprStr = 'owner # instanceMember'; var node = Parser.parse(typeExprStr); var expectedNode = createInstanceMemberTypeNode( createTypeNameNode('owner'), 'instanceMember'); expect(node).to.deep.equal(expectedNode); }); it('should return an instance member type node when "superOwner#owner#instanceMember" ' + 'arrived', function() { var typeExprStr = 'superOwner#owner#instanceMember'; var node = Parser.parse(typeExprStr); var expectedNode = createInstanceMemberTypeNode( createInstanceMemberTypeNode( createTypeNameNode('superOwner'), 'owner'), 'instanceMember'); expect(node).to.deep.equal(expectedNode); }); it('should return an instance member type node when "superOwner#owner#instanceMember=" ' + 'arrived', function() { var typeExprStr = 'superOwner#owner#instanceMember='; var node = Parser.parse(typeExprStr); var expectedNode = createOptionalTypeNode( createInstanceMemberTypeNode( createInstanceMemberTypeNode( createTypeNameNode('superOwner'), 'owner'), 'instanceMember') ); expect(node).to.deep.equal(expectedNode); }); it('should return an union type when "LeftType|RightType" arrived', function() { var typeExprStr = 'LeftType|RightType'; var node = Parser.parse(typeExprStr); var expectedNode = createUnionTypeNode( createTypeNameNode('LeftType'), createTypeNameNode('RightType') ); expect(node).to.deep.equal(expectedNode); }); it('should return an union type when "LeftType|MiddleType|RightType" arrived', function() { var typeExprStr = 'LeftType|MiddleType|RightType'; var node = Parser.parse(typeExprStr); var expectedNode = createUnionTypeNode( createTypeNameNode('LeftType'), createUnionTypeNode( createTypeNameNode('MiddleType'), createTypeNameNode('RightType') )); expect(node).to.deep.equal(expectedNode); }); it('should return an union type when "(LeftType|RightType)" arrived', function() { var typeExprStr = '(LeftType|RightType)'; var node = Parser.parse(typeExprStr); var expectedNode = createUnionTypeNode( createTypeNameNode('LeftType'), createTypeNameNode('RightType') ); expect(node).to.deep.equal(expectedNode); }); it('should return an union type when "( LeftType | RightType )" arrived', function() { var typeExprStr = '( LeftType | RightType )'; var node = Parser.parse(typeExprStr); var expectedNode = createUnionTypeNode( createTypeNameNode('LeftType'), createTypeNameNode('RightType') ); expect(node).to.deep.equal(expectedNode); }); it('should return a variadic type node when "...variadicType" arrived', function() { var typeExprStr = '...variadicType'; var node = Parser.parse(typeExprStr); var expectedNode = createVariadicTypeNode( createTypeNameNode('variadicType')); expect(node).to.deep.equal(expectedNode); }); it('should return a record type node when "{}" arrived', function() { var typeExprStr = '{}'; var node = Parser.parse(typeExprStr); var expectedNode = createRecordTypeNode([]); expect(node).to.deep.equal(expectedNode); }); it('should return a record type node when "{key:ValueType}" arrived', function() { var typeExprStr = '{key:ValueType}'; var node = Parser.parse(typeExprStr); var expectedNode = createRecordTypeNode([ createRecordEntryNode('key', createTypeNameNode('ValueType')), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a record type node when "{keyOnly}" arrived', function() { var typeExprStr = '{keyOnly}'; var node = Parser.parse(typeExprStr); var expectedNode = createRecordTypeNode([ createRecordEntryNode('keyOnly', null), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a record type node when "{key1:ValueType1,key2:ValueType2}"' + ' arrived', function() { var typeExprStr = '{key1:ValueType1,key2:ValueType2}'; var node = Parser.parse(typeExprStr); var expectedNode = createRecordTypeNode([ createRecordEntryNode('key1', createTypeNameNode('ValueType1')), createRecordEntryNode('key2', createTypeNameNode('ValueType2')), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a record type node when "{key:ValueType1,keyOnly}"' + ' arrived', function() { var typeExprStr = '{key:ValueType1,keyOnly}'; var node = Parser.parse(typeExprStr); var expectedNode = createRecordTypeNode([ createRecordEntryNode('key', createTypeNameNode('ValueType1')), createRecordEntryNode('keyOnly', null), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a record type node when "{ key1 : ValueType1 , key2 : ValueType2 }"' + ' arrived', function() { var typeExprStr = '{ key1 : ValueType1 , key2 : ValueType2 }'; var node = Parser.parse(typeExprStr); var expectedNode = createRecordTypeNode([ createRecordEntryNode('key1', createTypeNameNode('ValueType1')), createRecordEntryNode('key2', createTypeNameNode('ValueType2')), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "Generic<ParamType>" arrived', function() { var typeExprStr = 'Generic<ParamType>'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Generic'), [ createTypeNameNode('ParamType'), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "Generic<Inner<ParamType>>" arrived', function() { var typeExprStr = 'Generic<Inner<ParamType>>'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Generic'), [ createGenericTypeNode( createTypeNameNode('Inner'), [ createTypeNameNode('ParamType') ] ), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "Generic<ParamType1,ParamType2>"' + ' arrived', function() { var typeExprStr = 'Generic<ParamType1,ParamType2>'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Generic'), [ createTypeNameNode('ParamType1'), createTypeNameNode('ParamType2'), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "Generic < ParamType1 , ParamType2 >"' + ' arrived', function() { var typeExprStr = 'Generic < ParamType1, ParamType2 >'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Generic'), [ createTypeNameNode('ParamType1'), createTypeNameNode('ParamType2'), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "Generic.<ParamType>" arrived', function() { var typeExprStr = 'Generic.<ParamType>'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Generic'), [ createTypeNameNode('ParamType'), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "Generic.<ParamType1,ParamType2>"' + ' arrived', function() { var typeExprStr = 'Generic.<ParamType1,ParamType2>'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Generic'), [ createTypeNameNode('ParamType1'), createTypeNameNode('ParamType2'), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "Generic .< ParamType1 , ParamType2 >"' + ' arrived', function() { var typeExprStr = 'Generic .< ParamType1 , ParamType2 >'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Generic'), [ createTypeNameNode('ParamType1'), createTypeNameNode('ParamType2'), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "ParamType[]" arrived', function() { var typeExprStr = 'ParamType[]'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Array'), [ createTypeNameNode('ParamType'), ]); expect(node).to.deep.equal(expectedNode); }); it('should return a generic type node when "ParamType[][]" arrived', function() { var typeExprStr = 'ParamType[][]'; var node = Parser.parse(typeExprStr); var expectedNode = createGenericTypeNode( createTypeNameNode('Array'), [ createGenericTypeNode( createTypeNameNode('Array'), [ createTypeNameNode('ParamType'), ]), ]); expect(node).to.deep.equal(expectedNode); }); it('should return an optional type node when "string=" arrived', function() { var typeExprStr = 'string='; var node = Parser.parse(typeExprStr); var expectedNode = createOptionalTypeNode( createTypeNameNode('string') ); expect(node).to.deep.equal(expectedNode); }); it('should return an optional type node when "=string" arrived (deprecated)', function() { var typeExprStr = '=string'; var node = Parser.parse(typeExprStr); var expectedNode = createOptionalTypeNode( createTypeNameNode('string') ); expect(node).to.deep.equal(expectedNode); }); it('should return a nullable type node when "?string" arrived', function() { var typeExprStr = '?string'; var node = Parser.parse(typeExprStr); var expectedNode = createNullableTypeNode( createTypeNameNode('string') ); expect(node).to.deep.equal(expectedNode); }); it('should return a nullable type node when "string?" arrived (deprecated)', function() { var typeExprStr = 'string?'; var node = Parser.parse(typeExprStr); var expectedNode = createNullableTypeNode( createTypeNameNode('string') ); expect(node).to.deep.equal(expectedNode); }); it('should return an optional type node when "?string=" arrived', function() { var typeExprStr = '?string='; var node = Parser.parse(typeExprStr); var expectedNode = createNullableTypeNode( createOptionalTypeNode(createTypeNameNode('string')) ); expect(node).to.deep.equal(expectedNode); }); it('should return a variadic type node when "...!Object" arrived', function() { var typeExprStr = '...!Object'; var node = Parser.parse(typeExprStr); var expectedNode = createVariadicTypeNode( createNotNullableTypeNode(createTypeNameNode('Object')) ); expect(node).to.deep.equal(expectedNode); }); it('should return a not nullable type node when "!Object" arrived', function() { var typeExprStr = '!Object'; var node = Parser.parse(typeExprStr); var expectedNode = createNotNullableTypeNode( createTypeNameNode('Object') ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node when "function()" arrived', function() { var typeExprStr = 'function()'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [], null, { thisValue: null, newValue: null } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node with a param when "function(Param)" arrived', function() { var typeExprStr = 'function(Param)'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [ createTypeNameNode('Param') ], null, { thisValue: null, newValue: null } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node with several params when "function(Param1,Param2)"' + ' arrived', function() { var typeExprStr = 'function(Param1,Param2)'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [ createTypeNameNode('Param1'), createTypeNameNode('Param2') ], null, { thisValue: null, newValue: null } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node with returns when "function():Returned"' + ' arrived', function() { var typeExprStr = 'function():Returned'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [], createTypeNameNode('Returned'), { thisValue: null, newValue: null } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node with a context type when "function(this:ThisObject)"' + ' arrived', function() { var typeExprStr = 'function(this:ThisObject)'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [], null, { thisValue: createTypeNameNode('ThisObject'), newValue: null } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node with a context type when ' + '"function(this:ThisObject, param1)" arrived', function() { var typeExprStr = 'function(this:ThisObject, param1)'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [createTypeNameNode('param1')], null, { thisValue: createTypeNameNode('ThisObject'), newValue: null } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node as a constructor when "function(new:NewObject)"' + ' arrived', function() { var typeExprStr = 'function(new:NewObject)'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [], null, { thisValue: null, newValue: createTypeNameNode('NewObject') } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node as a constructor when ' + '"function(new:NewObject, param1)" arrived', function() { var typeExprStr = 'function(new:NewObject, param1)'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [createTypeNameNode('param1')], null, { thisValue: null, newValue: createTypeNameNode('NewObject') } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node as a constructor when ' + '"function(new:NewObject, this:ThisObject, param1)" arrived', function() { var typeExprStr = 'function(new:NewObject, this:ThisObject, param1)'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [ createTypeNameNode('param1') ], null, { thisValue: createTypeNameNode('ThisObject'), newValue: createTypeNameNode('NewObject'), } ); expect(node).to.deep.equal(expectedNode); }); it('should return a function type node when "function( Param1 , Param2 ) : Returned"' + ' arrived', function() { var typeExprStr = 'function( Param1 , Param2 ) : Returned'; var node = Parser.parse(typeExprStr); var expectedNode = createFunctionTypeNode( [ createTypeNameNode('Param1'), createTypeNameNode('Param2') ], createTypeNameNode('Returned'), { thisValue: null, newValue: null } ); expect(node).to.deep.equal(expectedNode); }); it('should throw a syntax error when "" arrived', function() { var typeExprStr = ''; expect(function() { Parser.parse(typeExprStr); }).to.throw(Parser.SyntaxError); }); it('should throw a syntax error when "Invalid type" arrived', function() { var typeExprStr = 'Invalid type'; expect(function() { Parser.parse(typeExprStr); }).to.throw(Parser.SyntaxError); }); it('should throw a syntax error when "Promise*Error" arrived', function() { var typeExprStr = 'Promise*Error'; expect(function() { Parser.parse(typeExprStr); }).to.throw(Parser.SyntaxError); }); it('should throw a syntax error when "(unclosedParenthesis, " arrived', function() { var typeExprStr = '(unclosedParenthesis, '; expect(function() { Parser.parse(typeExprStr); }).to.throw(Parser.SyntaxError); }); }); function createTypeNameNode(typeName) { return { type: NodeType.NAME, name: typeName, }; } function createAnyTypeNode() { return { type: NodeType.ANY, }; } function createUnknownTypeNode() { return { type: NodeType.UNKNOWN, }; } function createModuleNameNode(moduleName) { return { type: NodeType.MODULE, path: moduleName, }; } function createOptionalTypeNode(optionalTypeExpr) { return { type: NodeType.OPTIONAL, value: optionalTypeExpr, }; } function createNullableTypeNode(nullableTypeExpr) { return { type: NodeType.NULLABLE, value: nullableTypeExpr, }; } function createNotNullableTypeNode(nullableTypeExpr) { return { type: NodeType.NOT_NULLABLE, value: nullableTypeExpr, }; } function createMemberTypeNode(ownerTypeExpr, memberTypeName) { return { type: NodeType.MEMBER, owner: ownerTypeExpr, name: memberTypeName, }; } function createInnerMemberTypeNode(ownerTypeExpr, memberTypeName) { return { type: NodeType.INNER_MEMBER, owner: ownerTypeExpr, name: memberTypeName, }; } function createInstanceMemberTypeNode(ownerTypeExpr, memberTypeName) { return { type: NodeType.INSTANCE_MEMBER, owner: ownerTypeExpr, name: memberTypeName, }; } function createUnionTypeNode(leftTypeExpr, rightTypeExpr) { return { type: NodeType.UNION, left: leftTypeExpr, right: rightTypeExpr, }; } function createVariadicTypeNode(variadicTypeExpr) { return { type: NodeType.VARIADIC, value: variadicTypeExpr, }; } function createRecordTypeNode(recordEntries) { return { type: NodeType.RECORD, entries: recordEntries, }; } function createRecordEntryNode(key, valueTypeExpr) { return { type: NodeType.RECORD_ENTRY, key: key, value: valueTypeExpr, hasValue: Boolean(valueTypeExpr), }; } function createGenericTypeNode(genericTypeName, paramExprs) { return { type: NodeType.GENERIC, subject: genericTypeName, objects: paramExprs, }; } function createFunctionTypeNode(paramNodes, returnedNode, modifierMap) { return { type: NodeType.FUNCTION, params: paramNodes, returns: returnedNode, thisValue: modifierMap.thisValue, newValue: modifierMap.newValue, }; }
Discounty/Discounty
client/node_modules/jscs/node_modules/jscs-jsdoc/node_modules/jsdoctypeparser/test/test_Parser.js
JavaScript
apache-2.0
24,671
/* 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 sync import ( "context" "fmt" "net" "time" "github.com/golang/glog" "k8s.io/api/core/v1" "k8s.io/kubernetes/pkg/controller/nodeipam/ipam/cidrset" ) const ( // InvalidPodCIDR is the event recorded when a node is found with an // invalid PodCIDR. InvalidPodCIDR = "CloudCIDRAllocatorInvalidPodCIDR" // InvalidModeEvent is the event recorded when the CIDR range cannot be // sync'd due to the cluster running in the wrong mode. InvalidModeEvent = "CloudCIDRAllocatorInvalidMode" // MismatchEvent is the event recorded when the CIDR range allocated in the // node spec does not match what has been allocated in the cloud. MismatchEvent = "CloudCIDRAllocatorMismatch" ) // cloudAlias is the interface to the cloud platform APIs. type cloudAlias interface { // Alias returns the IP alias for the node. Alias(ctx context.Context, nodeName string) (*net.IPNet, error) // AddAlias adds an alias to the node. AddAlias(ctx context.Context, nodeName string, cidrRange *net.IPNet) error } // kubeAPI is the interface to the Kubernetes APIs. type kubeAPI interface { // Node returns the spec for the Node object. Node(ctx context.Context, name string) (*v1.Node, error) // UpdateNodePodCIDR updates the PodCIDR in the Node spec. UpdateNodePodCIDR(ctx context.Context, node *v1.Node, cidrRange *net.IPNet) error // UpdateNodeNetworkUnavailable updates the network unavailable status for the node. UpdateNodeNetworkUnavailable(nodeName string, unavailable bool) error // EmitNodeWarningEvent emits an event for the given node. EmitNodeWarningEvent(nodeName, reason, fmt string, args ...interface{}) } // controller is the interface to the controller. type controller interface { // ReportResult updates the controller with the result of the latest // sync operation. ReportResult(err error) // ResyncTimeout returns the amount of time to wait before retrying // a sync with a node. ResyncTimeout() time.Duration } // NodeSyncMode is the mode the cloud CIDR allocator runs in. type NodeSyncMode string var ( // SyncFromCloud is the mode that synchronizes the IP allocation from the cloud // platform to the node. SyncFromCloud NodeSyncMode = "SyncFromCloud" // SyncFromCluster is the mode that synchronizes the IP allocation determined // by the k8s controller to the cloud provider. SyncFromCluster NodeSyncMode = "SyncFromCluster" ) // IsValidMode returns true if the given mode is valid. func IsValidMode(m NodeSyncMode) bool { switch m { case SyncFromCloud: case SyncFromCluster: default: return false } return true } // NodeSync synchronizes the state for a single node in the cluster. type NodeSync struct { c controller cloudAlias cloudAlias kubeAPI kubeAPI mode NodeSyncMode nodeName string opChan chan syncOp set *cidrset.CidrSet } // New returns a new syncer for a given node. func New(c controller, cloudAlias cloudAlias, kubeAPI kubeAPI, mode NodeSyncMode, nodeName string, set *cidrset.CidrSet) *NodeSync { return &NodeSync{ c: c, cloudAlias: cloudAlias, kubeAPI: kubeAPI, mode: mode, nodeName: nodeName, opChan: make(chan syncOp, 1), set: set, } } // Loop runs the sync loop for a given node. done is an optional channel that // is closed when the Loop() returns. func (sync *NodeSync) Loop(done chan struct{}) { glog.V(2).Infof("Starting sync loop for node %q", sync.nodeName) defer func() { if done != nil { close(done) } }() timeout := sync.c.ResyncTimeout() delayTimer := time.NewTimer(timeout) glog.V(4).Infof("Resync node %q in %v", sync.nodeName, timeout) for { select { case op, more := <-sync.opChan: if !more { glog.V(2).Infof("Stopping sync loop") return } sync.c.ReportResult(op.run(sync)) if !delayTimer.Stop() { <-delayTimer.C } case <-delayTimer.C: glog.V(4).Infof("Running resync for node %q", sync.nodeName) sync.c.ReportResult((&updateOp{}).run(sync)) } timeout := sync.c.ResyncTimeout() delayTimer.Reset(timeout) glog.V(4).Infof("Resync node %q in %v", sync.nodeName, timeout) } } // Update causes an update operation on the given node. If node is nil, then // the syncer will fetch the node spec from the API server before syncing. // // This method is safe to call from multiple goroutines. func (sync *NodeSync) Update(node *v1.Node) { sync.opChan <- &updateOp{node} } // Delete performs the sync operations necessary to remove the node from the // IPAM state. // // This method is safe to call from multiple goroutines. func (sync *NodeSync) Delete(node *v1.Node) { sync.opChan <- &deleteOp{node} close(sync.opChan) } // syncOp is the interface for generic sync operation. type syncOp interface { // run the requested sync operation. run(sync *NodeSync) error } // updateOp handles creation and updates of a node. type updateOp struct { node *v1.Node } func (op *updateOp) String() string { if op.node == nil { return fmt.Sprintf("updateOp(nil)") } return fmt.Sprintf("updateOp(%q,%v)", op.node.Name, op.node.Spec.PodCIDR) } func (op *updateOp) run(sync *NodeSync) error { glog.V(3).Infof("Running updateOp %+v", op) ctx := context.Background() if op.node == nil { glog.V(3).Infof("Getting node spec for %q", sync.nodeName) node, err := sync.kubeAPI.Node(ctx, sync.nodeName) if err != nil { glog.Errorf("Error getting node %q spec: %v", sync.nodeName, err) return err } op.node = node } aliasRange, err := sync.cloudAlias.Alias(ctx, sync.nodeName) if err != nil { glog.Errorf("Error getting cloud alias for node %q: %v", sync.nodeName, err) return err } switch { case op.node.Spec.PodCIDR == "" && aliasRange == nil: err = op.allocateRange(ctx, sync, op.node) case op.node.Spec.PodCIDR == "" && aliasRange != nil: err = op.updateNodeFromAlias(ctx, sync, op.node, aliasRange) case op.node.Spec.PodCIDR != "" && aliasRange == nil: err = op.updateAliasFromNode(ctx, sync, op.node) case op.node.Spec.PodCIDR != "" && aliasRange != nil: err = op.validateRange(ctx, sync, op.node, aliasRange) } return err } // validateRange checks that the allocated range and the alias range // match. func (op *updateOp) validateRange(ctx context.Context, sync *NodeSync, node *v1.Node, aliasRange *net.IPNet) error { if node.Spec.PodCIDR != aliasRange.String() { glog.Errorf("Inconsistency detected between node PodCIDR and node alias (%v != %v)", node.Spec.PodCIDR, aliasRange) sync.kubeAPI.EmitNodeWarningEvent(node.Name, MismatchEvent, "Node.Spec.PodCIDR != cloud alias (%v != %v)", node.Spec.PodCIDR, aliasRange) // User intervention is required in this case, as this is most likely due // to the user mucking around with their VM aliases on the side. } else { glog.V(4).Infof("Node %q CIDR range %v is matches cloud assignment", node.Name, node.Spec.PodCIDR) } return nil } // updateNodeFromAlias updates the the node from the cloud allocated // alias. func (op *updateOp) updateNodeFromAlias(ctx context.Context, sync *NodeSync, node *v1.Node, aliasRange *net.IPNet) error { if sync.mode != SyncFromCloud { sync.kubeAPI.EmitNodeWarningEvent(node.Name, InvalidModeEvent, "Cannot sync from cloud in mode %q", sync.mode) return fmt.Errorf("cannot sync from cloud in mode %q", sync.mode) } glog.V(2).Infof("Updating node spec with alias range, node.PodCIDR = %v", aliasRange) if err := sync.set.Occupy(aliasRange); err != nil { glog.Errorf("Error occupying range %v for node %v", aliasRange, sync.nodeName) return err } if err := sync.kubeAPI.UpdateNodePodCIDR(ctx, node, aliasRange); err != nil { glog.Errorf("Could not update node %q PodCIDR to %v: %v", node.Name, aliasRange, err) return err } glog.V(2).Infof("Node %q PodCIDR set to %v", node.Name, aliasRange) if err := sync.kubeAPI.UpdateNodeNetworkUnavailable(node.Name, false); err != nil { glog.Errorf("Could not update node NetworkUnavailable status to false: %v", err) return err } glog.V(2).Infof("Updated node %q PodCIDR from cloud alias %v", node.Name, aliasRange) return nil } // updateAliasFromNode updates the cloud alias given the node allocation. func (op *updateOp) updateAliasFromNode(ctx context.Context, sync *NodeSync, node *v1.Node) error { if sync.mode != SyncFromCluster { sync.kubeAPI.EmitNodeWarningEvent( node.Name, InvalidModeEvent, "Cannot sync to cloud in mode %q", sync.mode) return fmt.Errorf("cannot sync to cloud in mode %q", sync.mode) } _, aliasRange, err := net.ParseCIDR(node.Spec.PodCIDR) if err != nil { glog.Errorf("Could not parse PodCIDR (%q) for node %q: %v", node.Spec.PodCIDR, node.Name, err) return err } if err := sync.set.Occupy(aliasRange); err != nil { glog.Errorf("Error occupying range %v for node %v", aliasRange, sync.nodeName) return err } if err := sync.cloudAlias.AddAlias(ctx, node.Name, aliasRange); err != nil { glog.Errorf("Could not add alias %v for node %q: %v", aliasRange, node.Name, err) return err } if err := sync.kubeAPI.UpdateNodeNetworkUnavailable(node.Name, false); err != nil { glog.Errorf("Could not update node NetworkUnavailable status to false: %v", err) return err } glog.V(2).Infof("Updated node %q cloud alias with node spec, node.PodCIDR = %v", node.Name, node.Spec.PodCIDR) return nil } // allocateRange allocates a new range and updates both the cloud // platform and the node allocation. func (op *updateOp) allocateRange(ctx context.Context, sync *NodeSync, node *v1.Node) error { if sync.mode != SyncFromCluster { sync.kubeAPI.EmitNodeWarningEvent(node.Name, InvalidModeEvent, "Cannot allocate CIDRs in mode %q", sync.mode) return fmt.Errorf("controller cannot allocate CIDRS in mode %q", sync.mode) } cidrRange, err := sync.set.AllocateNext() if err != nil { return err } // If addAlias returns a hard error, cidrRange will be leaked as there // is no durable record of the range. The missing space will be // recovered on the next restart of the controller. if err := sync.cloudAlias.AddAlias(ctx, node.Name, cidrRange); err != nil { glog.Errorf("Could not add alias %v for node %q: %v", cidrRange, node.Name, err) return err } if err := sync.kubeAPI.UpdateNodePodCIDR(ctx, node, cidrRange); err != nil { glog.Errorf("Could not update node %q PodCIDR to %v: %v", node.Name, cidrRange, err) return err } if err := sync.kubeAPI.UpdateNodeNetworkUnavailable(node.Name, false); err != nil { glog.Errorf("Could not update node NetworkUnavailable status to false: %v", err) return err } glog.V(2).Infof("Allocated PodCIDR %v for node %q", cidrRange, node.Name) return nil } // deleteOp handles deletion of a node. type deleteOp struct { node *v1.Node } func (op *deleteOp) String() string { if op.node == nil { return fmt.Sprintf("deleteOp(nil)") } return fmt.Sprintf("deleteOp(%q,%v)", op.node.Name, op.node.Spec.PodCIDR) } func (op *deleteOp) run(sync *NodeSync) error { glog.V(3).Infof("Running deleteOp %+v", op) if op.node.Spec.PodCIDR == "" { glog.V(2).Infof("Node %q was deleted, node had no PodCIDR range assigned", op.node.Name) return nil } _, cidrRange, err := net.ParseCIDR(op.node.Spec.PodCIDR) if err != nil { glog.Errorf("Deleted node %q has an invalid podCIDR %q: %v", op.node.Name, op.node.Spec.PodCIDR, err) sync.kubeAPI.EmitNodeWarningEvent(op.node.Name, InvalidPodCIDR, "Node %q has an invalid PodCIDR: %q", op.node.Name, op.node.Spec.PodCIDR) return nil } sync.set.Release(cidrRange) glog.V(2).Infof("Node %q was deleted, releasing CIDR range %v", op.node.Name, op.node.Spec.PodCIDR) return nil }
apcera/kubernetes
pkg/controller/nodeipam/ipam/sync/sync.go
GO
apache-2.0
12,202
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Jumapili", "Jumatatu", "Jumanne", "Jumatano", "Alhamisi", "Ijumaa", "Jumamosi" ], "ERANAMES": [ "Kabla ya Kristo", "Baada ya Kristo" ], "ERAS": [ "BC", "AD" ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba" ], "SHORTDAY": [ "Jumapili", "Jumatatu", "Jumanne", "Jumatano", "Alhamisi", "Ijumaa", "Jumamosi" ], "SHORTMONTH": [ "Jan", "Feb", "Mac", "Apr", "Mei", "Jun", "Jul", "Ago", "Sep", "Okt", "Nov", "Des" ], "STANDALONEMONTH": [ "Januari", "Februari", "Machi", "Aprili", "Mei", "Juni", "Julai", "Agosti", "Septemba", "Oktoba", "Novemba", "Desemba" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, d MMMM y", "longDate": "d MMMM y", "medium": "d MMM y h:mm:ss a", "mediumDate": "d MMM y", "mediumTime": "h:mm:ss a", "short": "dd/MM/y h:mm a", "shortDate": "dd/MM/y", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "TSh", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "sw", "localeID": "sw", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
tianzhidao28/SpringQuickService
src/main/webapp/bower_components/angular-i18n/angular-locale_sw.js
JavaScript
apache-2.0
2,743
define([ "./core", "./var/pnum", "./core/access", "./css/var/rmargin", "./css/var/rnumnonpx", "./css/var/cssExpand", "./css/var/isHidden", "./css/var/getStyles", "./css/curCSS", "./css/defaultDisplay", "./css/addGetHookIf", "./css/support", "./data/var/data_priv", "./core/init", "./css/swap", "./core/ready", "./selector" // contains ], function( jQuery, pnum, access, rmargin, rnumnonpx, cssExpand, isHidden, getStyles, curCSS, defaultDisplay, addGetHookIf, support, data_priv ) { var // Swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // See here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ), rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ), cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: "0", fontWeight: "400" }, cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // Return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // Shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // Check for vendor prefixed names var capName = name[0].toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // Both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // At this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // At this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // At this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // Some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // Check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // Use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = data_priv.get( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) ); } } else { hidden = isHidden( elem ); if ( display !== "none" || !hidden ) { data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Don't automatically add "px" to these possibly-unitless properties cssNumber: { "columnCount": true, "fillOpacity": true, "flexGrow": true, "flexShrink": true, "fontWeight": true, "lineHeight": true, "opacity": true, "order": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { "float": "cssFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // Gets hook for the prefixed version, then unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // Convert "+=" or "-=" to relative numbers (#7345) if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that null and NaN values aren't set (#7116) if ( value == null || value !== value ) { return; } // If a number, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Support: IE9-11+ // background-* props affect original clone's values if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { style[ name ] = value; } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var val, num, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // Try prefixed name followed by the unprefixed name hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } // Convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Make numeric if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; } }); jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // Certain elements can have dimension info if we invisibly show them // but it must have a current display style that would benefit return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); // Support: Android 2.3 jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight, function( elem, computed ) { if ( computed ) { return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } ); // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // Assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); jQuery.fn.extend({ css: function( name, value ) { return access( this, function( elem, name, value ) { var styles, len, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { if ( typeof state === "boolean" ) { return state ? this.show() : this.hide(); } return this.each(function() { if ( isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); return jQuery; });
diego91964/presentations
events/pitagoras-04-05-2016/bower_components/jquery/src/css.js
JavaScript
apache-2.0
12,346
/** * 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.hdfs.nfs.nfs3; import java.io.IOException; import java.net.DatagramSocket; import org.apache.hadoop.hdfs.nfs.conf.NfsConfigKeys; import org.apache.hadoop.hdfs.nfs.conf.NfsConfiguration; import org.apache.hadoop.hdfs.nfs.mount.Mountd; import org.apache.hadoop.nfs.nfs3.Nfs3Base; import org.apache.hadoop.util.StringUtils; import com.google.common.annotations.VisibleForTesting; /** * Nfs server. Supports NFS v3 using {@link RpcProgramNfs3}. * Currently Mountd program is also started inside this class. * Only TCP server is supported and UDP is not supported. */ public class Nfs3 extends Nfs3Base { private Mountd mountd; public Nfs3(NfsConfiguration conf) throws IOException { this(conf, null, true); } public Nfs3(NfsConfiguration conf, DatagramSocket registrationSocket, boolean allowInsecurePorts) throws IOException { super(RpcProgramNfs3.createRpcProgramNfs3(conf, registrationSocket, allowInsecurePorts), conf); mountd = new Mountd(conf, registrationSocket, allowInsecurePorts); } public Mountd getMountd() { return mountd; } @VisibleForTesting public void startServiceInternal(boolean register) throws IOException { mountd.start(register); // Start mountd start(register); } static void startService(String[] args, DatagramSocket registrationSocket) throws IOException { StringUtils.startupShutdownMessage(Nfs3.class, args, LOG); NfsConfiguration conf = new NfsConfiguration(); boolean allowInsecurePorts = conf.getBoolean( NfsConfigKeys.DFS_NFS_PORT_MONITORING_DISABLED_KEY, NfsConfigKeys.DFS_NFS_PORT_MONITORING_DISABLED_DEFAULT); final Nfs3 nfsServer = new Nfs3(conf, registrationSocket, allowInsecurePorts); nfsServer.startServiceInternal(true); } public static void main(String[] args) throws IOException { startService(args, null); } }
StephanieMak/hadoop
hadoop-hdfs-project/hadoop-hdfs-nfs/src/main/java/org/apache/hadoop/hdfs/nfs/nfs3/Nfs3.java
Java
apache-2.0
2,728
<?php define('LARAVEL_START', microtime(true)); /* |-------------------------------------------------------------------------- | Register The Composer Auto Loader |-------------------------------------------------------------------------- | | Composer provides a convenient, automatically generated class loader | for our application. We just need to utilize it! We'll require it | into the script here so that we do not have to worry about the | loading of any our classes "manually". Feels great to relax. | */ require __DIR__.'/../vendor/autoload.php'; /* |-------------------------------------------------------------------------- | Include The Compiled Class File |-------------------------------------------------------------------------- | | To dramatically increase your application's performance, you may use a | compiled class file which contains all of the classes commonly used | by a request. The Artisan "optimize" is used to create this file. | */ if (file_exists($compiled = __DIR__.'/compiled.php')) { require $compiled; } /* |-------------------------------------------------------------------------- | Setup Patchwork UTF-8 Handling |-------------------------------------------------------------------------- | | The Patchwork library provides solid handling of UTF-8 strings as well | as provides replacements for all mb_* and iconv type functions that | are not available by default in PHP. We'll setup this stuff here. | */ Patchwork\Utf8\Bootup::initMbstring(); /* |-------------------------------------------------------------------------- | Register The Laravel Auto Loader |-------------------------------------------------------------------------- | | We register an auto-loader "behind" the Composer loader that can load | model classes on the fly, even if the autoload files have not been | regenerated for the application. We'll add it to the stack here. | */ Illuminate\Support\ClassLoader::register(); /* |-------------------------------------------------------------------------- | Register The Workbench Loaders |-------------------------------------------------------------------------- | | The Laravel workbench provides a convenient place to develop packages | when working locally. However we will need to load in the Composer | auto-load files for the packages so that these can be used here. | */ if (is_dir($workbench = __DIR__.'/../workbench')) { Illuminate\Workbench\Starter::start($workbench); }
JoaXax/Podcast-server
bootstrap/autoload.php
PHP
apache-2.0
2,453
package org.apache.hadoop.tools; /** * 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 static org.junit.Assert.*; import java.io.ByteArrayOutputStream; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.PrintStream; import org.apache.hadoop.hdfs.tools.DFSAdmin; import org.apache.hadoop.hdfs.tools.DelegationTokenFetcher; import org.apache.hadoop.hdfs.tools.JMXGet; import org.apache.hadoop.util.ExitUtil; import org.apache.hadoop.util.ToolRunner; import org.apache.hadoop.util.ExitUtil.ExitException; import org.junit.BeforeClass; import org.junit.Test; import com.google.common.collect.ImmutableSet; import com.google.common.io.ByteStreams; public class TestTools { private static final int PIPE_BUFFER_SIZE = 1024 * 5; private final static String INVALID_OPTION = "-invalidOption"; private static final String[] OPTIONS = new String[2]; @BeforeClass public static void before() { ExitUtil.disableSystemExit(); OPTIONS[1] = INVALID_OPTION; } @Test public void testDelegationTokenFetcherPrintUsage() { String pattern = "Options:"; checkOutput(new String[] { "-help" }, pattern, System.out, DelegationTokenFetcher.class); } @Test public void testDelegationTokenFetcherErrorOption() { String pattern = "ERROR: Only specify cancel, renew or print."; checkOutput(new String[] { "-cancel", "-renew" }, pattern, System.err, DelegationTokenFetcher.class); } @Test public void testJMXToolHelp() { String pattern = "usage: jmxget options are:"; checkOutput(new String[] { "-help" }, pattern, System.out, JMXGet.class); } @Test public void testJMXToolAdditionParameter() { String pattern = "key = -addition"; checkOutput(new String[] { "-service=NameNode", "-server=localhost", "-addition" }, pattern, System.err, JMXGet.class); } @Test public void testDFSAdminInvalidUsageHelp() { ImmutableSet<String> args = ImmutableSet.of("-report", "-saveNamespace", "-rollEdits", "-restoreFailedStorage", "-refreshNodes", "-finalizeUpgrade", "-metasave", "-refreshUserToGroupsMappings", "-printTopology", "-refreshNamenodes", "-deleteBlockPool", "-setBalancerBandwidth", "-fetchImage"); try { for (String arg : args) assertTrue(ToolRunner.run(new DFSAdmin(), fillArgs(arg)) == -1); assertTrue(ToolRunner.run(new DFSAdmin(), new String[] { "-help", "-some" }) == 0); } catch (Exception e) { fail("testDFSAdminHelp error" + e); } String pattern = "Usage: hdfs dfsadmin"; checkOutput(new String[] { "-cancel", "-renew" }, pattern, System.err, DFSAdmin.class); } private static String[] fillArgs(String arg) { OPTIONS[0] = arg; return OPTIONS; } private void checkOutput(String[] args, String pattern, PrintStream out, Class<?> clazz) { ByteArrayOutputStream outBytes = new ByteArrayOutputStream(); try { PipedOutputStream pipeOut = new PipedOutputStream(); PipedInputStream pipeIn = new PipedInputStream(pipeOut, PIPE_BUFFER_SIZE); if (out == System.out) { System.setOut(new PrintStream(pipeOut)); } else if (out == System.err) { System.setErr(new PrintStream(pipeOut)); } if (clazz == DelegationTokenFetcher.class) { expectDelegationTokenFetcherExit(args); } else if (clazz == JMXGet.class) { expectJMXGetExit(args); } else if (clazz == DFSAdmin.class) { expectDfsAdminPrint(args); } pipeOut.close(); ByteStreams.copy(pipeIn, outBytes); pipeIn.close(); assertTrue(new String(outBytes.toByteArray()).contains(pattern)); } catch (Exception ex) { fail("checkOutput error " + ex); } } private void expectDfsAdminPrint(String[] args) { try { ToolRunner.run(new DFSAdmin(), args); } catch (Exception ex) { fail("expectDelegationTokenFetcherExit ex error " + ex); } } private static void expectDelegationTokenFetcherExit(String[] args) { try { DelegationTokenFetcher.main(args); fail("should call exit"); } catch (ExitException e) { ExitUtil.resetFirstExitException(); } catch (Exception ex) { fail("expectDelegationTokenFetcherExit ex error " + ex); } } private static void expectJMXGetExit(String[] args) { try { JMXGet.main(args); fail("should call exit"); } catch (ExitException e) { ExitUtil.resetFirstExitException(); } catch (Exception ex) { fail("expectJMXGetExit ex error " + ex); } } }
samuelan/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/tools/TestTools.java
Java
apache-2.0
5,399
package com.mogujie.tt.imservice.event; import com.mogujie.tt.DB.entity.GroupEntity; import java.util.List; /** * @author : yingmu on 14-12-30. * @email : yingmu@mogujie.com. */ public class GroupEvent { private GroupEntity groupEntity; private Event event; /**很多的场景只是关心改变的类型以及change的Ids*/ private int changeType; private List<Integer> changeList; public GroupEvent(Event event){ this.event = event; } public GroupEvent(Event event,GroupEntity groupEntity){ this.groupEntity = groupEntity; this.event = event; } public enum Event{ NONE, GROUP_INFO_OK, GROUP_INFO_UPDATED, CHANGE_GROUP_MEMBER_SUCCESS, CHANGE_GROUP_MEMBER_FAIL, CHANGE_GROUP_MEMBER_TIMEOUT, CREATE_GROUP_OK, CREATE_GROUP_FAIL, CREATE_GROUP_TIMEOUT, SHIELD_GROUP_OK, SHIELD_GROUP_TIMEOUT, SHIELD_GROUP_FAIL } public int getChangeType() { return changeType; } public void setChangeType(int changeType) { this.changeType = changeType; } public List<Integer> getChangeList() { return changeList; } public void setChangeList(List<Integer> changeList) { this.changeList = changeList; } public GroupEntity getGroupEntity() { return groupEntity; } public void setGroupEntity(GroupEntity groupEntity) { this.groupEntity = groupEntity; } public Event getEvent() { return event; } public void setEvent(Event event) { this.event = event; } }
christisall/TeamTalk
android/app/src/main/java/com/mogujie/tt/imservice/event/GroupEvent.java
Java
apache-2.0
1,645
/** * 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.kafka.common; import java.util.Map; /** * A Mix-in style interface for classes that are instantiated by reflection and need to take configuration parameters */ public interface Configurable { /** * Configure this class with the given key-value pairs */ public void configure(Map<String, ?> configs); }
cocosli/kafka
clients/src/main/java/org/apache/kafka/common/Configurable.java
Java
apache-2.0
1,147
# 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. from distutils.core import setup, Extension zookeeper_basedir = "../../../" zookeepermodule = Extension("zookeeper", sources=["src/c/zookeeper.c"], include_dirs=[zookeeper_basedir + "/src/c/include", zookeeper_basedir + "/build/c", zookeeper_basedir + "/src/c/generated"], libraries=["zookeeper_mt"], library_dirs=[zookeeper_basedir + "/src/c/.libs/", zookeeper_basedir + "/build/c/.libs/", zookeeper_basedir + "/build/test/test-cppunit/.libs", "/usr/local/lib" ]) setup( name="ZooKeeper", version = "0.4", description = "ZooKeeper Python bindings", ext_modules=[zookeepermodule] )
sanjeevtripurari/zookeeper
src/contrib/zkpython/src/python/setup.py
Python
apache-2.0
1,754
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.tests.utils; import com.badlogic.gdx.files.FileHandle; /** Used to generate an assets.txt file for a specific directory. * @author mzechner */ public class AssetsFileGenerator { public static void main (String[] args) { FileHandle file = new FileHandle(args[0]); StringBuffer list = new StringBuffer(); args[0] = args[0].replace("\\", "/"); if (!args[0].endsWith("/")) args[0] = args[0] + "/"; traverse(file, args[0], list); new FileHandle(args[0] + "/assets.txt").writeString(list.toString(), false); } private static final void traverse (FileHandle directory, String base, StringBuffer list) { if (directory.name().equals(".svn")) return; String dirName = directory.toString().replace("\\", "/").replace(base, "") + "/"; System.out.println(dirName); for (FileHandle file : directory.list()) { if (file.isDirectory()) { traverse(file, base, list); } else { String fileName = file.toString().replace("\\", "/").replace(base, ""); if (fileName.endsWith(".png") || fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")) { list.append("i:" + fileName + "\n"); System.out.println(fileName); } else if (fileName.endsWith(".glsl") || fileName.endsWith(".fnt") || fileName.endsWith(".pack") || fileName.endsWith(".obj") || file.extension().equals("") || fileName.endsWith("txt")) { list.append("t:" + fileName + "\n"); System.out.println(fileName); } else { if (fileName.endsWith(".mp3") || fileName.endsWith(".ogg") || fileName.endsWith(".wav")) continue; list.append("b:" + fileName + "\n"); System.out.println(fileName); } } } } }
Badazdz/libgdx
tests/gdx-tests/src/com/badlogic/gdx/tests/utils/AssetsFileGenerator.java
Java
apache-2.0
2,472
/* * Copyright 2014 The Netty Project * * The Netty Project 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.netty.handler.codec.json; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufUtil; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import io.netty.channel.ChannelHandler; import io.netty.handler.codec.CorruptedFrameException; import io.netty.handler.codec.TooLongFrameException; import io.netty.channel.ChannelPipeline; import java.util.List; /** * Splits a byte stream of JSON objects and arrays into individual objects/arrays and passes them up the * {@link ChannelPipeline}. * * This class does not do any real parsing or validation. A sequence of bytes is considered a JSON object/array * if it contains a matching number of opening and closing braces/brackets. It's up to a subsequent * {@link ChannelHandler} to parse the JSON text into a more usable form i.e. a POJO. */ public class JsonObjectDecoder extends ByteToMessageDecoder { private static final int ST_CORRUPTED = -1; private static final int ST_INIT = 0; private static final int ST_DECODING_NORMAL = 1; private static final int ST_DECODING_ARRAY_STREAM = 2; private int openBraces; private int idx; private int state; private boolean insideString; private final int maxObjectLength; private final boolean streamArrayElements; public JsonObjectDecoder() { // 1 MB this(1024 * 1024); } public JsonObjectDecoder(int maxObjectLength) { this(maxObjectLength, false); } public JsonObjectDecoder(boolean streamArrayElements) { this(1024 * 1024, streamArrayElements); } /** * @param maxObjectLength maximum number of bytes a JSON object/array may use (including braces and all). * Objects exceeding this length are dropped and an {@link TooLongFrameException} * is thrown. * @param streamArrayElements if set to true and the "top level" JSON object is an array, each of its entries * is passed through the pipeline individually and immediately after it was fully * received, allowing for arrays with "infinitely" many elements. * */ public JsonObjectDecoder(int maxObjectLength, boolean streamArrayElements) { if (maxObjectLength < 1) { throw new IllegalArgumentException("maxObjectLength must be a positive int"); } this.maxObjectLength = maxObjectLength; this.streamArrayElements = streamArrayElements; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { if (state == ST_CORRUPTED) { in.skipBytes(in.readableBytes()); return; } // index of next byte to process. int idx = this.idx; int wrtIdx = in.writerIndex(); if (wrtIdx > maxObjectLength) { // buffer size exceeded maxObjectLength; discarding the complete buffer. in.skipBytes(in.readableBytes()); reset(); throw new TooLongFrameException( "object length exceeds " + maxObjectLength + ": " + wrtIdx + " bytes discarded"); } for (/* use current idx */; idx < wrtIdx; idx++) { byte c = in.getByte(idx); if (state == ST_DECODING_NORMAL) { decodeByte(c, in, idx); // All opening braces/brackets have been closed. That's enough to conclude // that the JSON object/array is complete. if (openBraces == 0) { ByteBuf json = extractObject(ctx, in, in.readerIndex(), idx + 1 - in.readerIndex()); if (json != null) { out.add(json); } // The JSON object/array was extracted => discard the bytes from // the input buffer. in.readerIndex(idx + 1); // Reset the object state to get ready for the next JSON object/text // coming along the byte stream. reset(); } } else if (state == ST_DECODING_ARRAY_STREAM) { decodeByte(c, in, idx); if (!insideString && (openBraces == 1 && c == ',' || openBraces == 0 && c == ']')) { // skip leading spaces. No range check is needed and the loop will terminate // because the byte at position idx is not a whitespace. for (int i = in.readerIndex(); Character.isWhitespace(in.getByte(i)); i++) { in.skipBytes(1); } // skip trailing spaces. int idxNoSpaces = idx - 1; while (idxNoSpaces >= in.readerIndex() && Character.isWhitespace(in.getByte(idxNoSpaces))) { idxNoSpaces--; } ByteBuf json = extractObject(ctx, in, in.readerIndex(), idxNoSpaces + 1 - in.readerIndex()); if (json != null) { out.add(json); } in.readerIndex(idx + 1); if (c == ']') { reset(); } } // JSON object/array detected. Accumulate bytes until all braces/brackets are closed. } else if (c == '{' || c == '[') { initDecoding(c); if (state == ST_DECODING_ARRAY_STREAM) { // Discard the array bracket in.skipBytes(1); } // Discard leading spaces in front of a JSON object/array. } else if (Character.isWhitespace(c)) { in.skipBytes(1); } else { state = ST_CORRUPTED; throw new CorruptedFrameException( "invalid JSON received at byte position " + idx + ": " + ByteBufUtil.hexDump(in)); } } if (in.readableBytes() == 0) { this.idx = 0; } else { this.idx = idx; } } /** * Override this method if you want to filter the json objects/arrays that get passed through the pipeline. */ @SuppressWarnings("UnusedParameters") protected ByteBuf extractObject(ChannelHandlerContext ctx, ByteBuf buffer, int index, int length) { return buffer.slice(index, length).retain(); } private void decodeByte(byte c, ByteBuf in, int idx) { if ((c == '{' || c == '[') && !insideString) { openBraces++; } else if ((c == '}' || c == ']') && !insideString) { openBraces--; } else if (c == '"') { // start of a new JSON string. It's necessary to detect strings as they may // also contain braces/brackets and that could lead to incorrect results. if (!insideString) { insideString = true; // If the double quote wasn't escaped then this is the end of a string. } else if (in.getByte(idx - 1) != '\\') { insideString = false; } } } private void initDecoding(byte openingBrace) { openBraces = 1; if (openingBrace == '[' && streamArrayElements) { state = ST_DECODING_ARRAY_STREAM; } else { state = ST_DECODING_NORMAL; } } private void reset() { insideString = false; state = ST_INIT; openBraces = 0; } }
huuthang1993/netty
codec/src/main/java/io/netty/handler/codec/json/JsonObjectDecoder.java
Java
apache-2.0
8,302
package jwt import ( "bytes" "encoding/json" "fmt" "strings" ) type Parser struct { ValidMethods []string // If populated, only these methods will be considered valid UseJSONNumber bool // Use JSON Number format in JSON decoder SkipClaimsValidation bool // Skip claims validation during token parsing } // Parse, validate, and return a token. // keyFunc will receive the parsed token and should return the key for validating. // If everything is kosher, err will be nil func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) } func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { token, parts, err := p.ParseUnverified(tokenString, claims) if err != nil { return token, err } // Verify signing method is in the required set if p.ValidMethods != nil { var signingMethodValid = false var alg = token.Method.Alg() for _, m := range p.ValidMethods { if m == alg { signingMethodValid = true break } } if !signingMethodValid { // signing method is not in the listed set return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) } } // Lookup key var key interface{} if keyFunc == nil { // keyFunc was not provided. short circuiting validation return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) } if key, err = keyFunc(token); err != nil { // keyFunc returned an error if ve, ok := err.(*ValidationError); ok { return token, ve } return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} } vErr := &ValidationError{} // Validate Claims if !p.SkipClaimsValidation { if err := token.Claims.Valid(); err != nil { // If the Claims Valid returned an error, check if it is a validation error, // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set if e, ok := err.(*ValidationError); !ok { vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} } else { vErr = e } } } // Perform validation token.Signature = parts[2] if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { vErr.Inner = err vErr.Errors |= ValidationErrorSignatureInvalid } if vErr.valid() { token.Valid = true return token, nil } return token, vErr } // WARNING: Don't use this method unless you know what you're doing // // This method parses the token but doesn't validate the signature. It's only // ever useful in cases where you know the signature is valid (because it has // been checked previously in the stack) and you want to extract values from // it. func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { parts = strings.Split(tokenString, ".") if len(parts) != 3 { return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) } token = &Token{Raw: tokenString} // parse Header var headerBytes []byte if headerBytes, err = DecodeSegment(parts[0]); err != nil { if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) } return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} } if err = json.Unmarshal(headerBytes, &token.Header); err != nil { return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} } // parse Claims var claimBytes []byte token.Claims = claims if claimBytes, err = DecodeSegment(parts[1]); err != nil { return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} } dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) if p.UseJSONNumber { dec.UseNumber() } // JSON Decode. Special case for map type to avoid weird pointer behavior if c, ok := token.Claims.(MapClaims); ok { err = dec.Decode(&c) } else { err = dec.Decode(&claims) } // Handle decode error if err != nil { return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} } // Lookup signature method if method, ok := token.Header["alg"].(string); ok { if token.Method = GetSigningMethod(method); token.Method == nil { return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) } } else { return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) } return token, parts, nil }
pwittrock/kubernetes
vendor/github.com/dgrijalva/jwt-go/parser.go
GO
apache-2.0
4,721
<div class="apiDetail"> <div> <h2><span>Boolean</span><span class="path">setting.edit.</span>enable</h2> <h3>Overview<span class="h3_info">[ depends on <span class="highlight_green">jquery.ztree.exedit</span> js ]</span></h3> <div class="desc"> <p></p> <div class="longdesc"> <p>Set zTree is in edit mode</p> <p class="highlight_red">Please set this attribute before zTree initialization. If you need to change the edit mode after the initialization, please use zTreeObj.setEditable() method.</p> <p>Default: false</p> </div> </div> <h3>Boolean Format</h3> <div class="desc"> <p> true means: zTree is in edit mode.</p> <p> false means: zTree is not in edit mode.</p> </div> <h3>Editing Rules Description</h3> <div class="desc"> <p>1. When click the node, it will not open '<span class="highlight_red">node.url</span>' specified URL. <br/>2. Support for dynamic tree editing. <br/>3. You can drag-drop nodes, and support drag-drop nodes between multiple trees. <br/>4. Support use drag-drop to copy or move the node. (Reference: <span class="highlight_red">setting.edit.drag.isCopy / setting.edit.drag.isMove</span>) <br/>5. You can use the Edit button to modify the name attribute. <br/>6. You can use the Remove button to remove the node. <br/> </p> <p class="highlight_red">Please note that letter case, do not change.</p> </div> <h3>Examples of setting</h3> <h4>1. edit the tree</h4> <pre xmlns=""><code>var setting = { edit: { enable: true } }; ......</code></pre> </div> </div>
blacksea3/medit
medit/blog/static/blog/lib/zTree/v3/api/en/setting.edit.enable.html
HTML
apache-2.0
1,519
// cgo -godefs types_aix.go | go run mkpost.go // Code generated by the command above; see README.md. DO NOT EDIT. //go:build ppc && aix // +build ppc,aix package unix const ( SizeofPtr = 0x4 SizeofShort = 0x2 SizeofInt = 0x4 SizeofLong = 0x4 SizeofLongLong = 0x8 PathMax = 0x3ff ) type ( _C_short int16 _C_int int32 _C_long int32 _C_long_long int64 ) type off64 int64 type off int32 type Mode_t uint32 type Timespec struct { Sec int32 Nsec int32 } type Timeval struct { Sec int32 Usec int32 } type Timeval32 struct { Sec int32 Usec int32 } type Timex struct{} type Time_t int32 type Tms struct{} type Utimbuf struct { Actime int32 Modtime int32 } type Timezone struct { Minuteswest int32 Dsttime int32 } type Rusage struct { Utime Timeval Stime Timeval Maxrss int32 Ixrss int32 Idrss int32 Isrss int32 Minflt int32 Majflt int32 Nswap int32 Inblock int32 Oublock int32 Msgsnd int32 Msgrcv int32 Nsignals int32 Nvcsw int32 Nivcsw int32 } type Rlimit struct { Cur uint64 Max uint64 } type Pid_t int32 type _Gid_t uint32 type dev_t uint32 type Stat_t struct { Dev uint32 Ino uint32 Mode uint32 Nlink int16 Flag uint16 Uid uint32 Gid uint32 Rdev uint32 Size int32 Atim Timespec Mtim Timespec Ctim Timespec Blksize int32 Blocks int32 Vfstype int32 Vfs uint32 Type uint32 Gen uint32 Reserved [9]uint32 } type StatxTimestamp struct{} type Statx_t struct{} type Dirent struct { Offset uint32 Ino uint32 Reclen uint16 Namlen uint16 Name [256]uint8 } type RawSockaddrInet4 struct { Len uint8 Family uint8 Port uint16 Addr [4]byte /* in_addr */ Zero [8]uint8 } type RawSockaddrInet6 struct { Len uint8 Family uint8 Port uint16 Flowinfo uint32 Addr [16]byte /* in6_addr */ Scope_id uint32 } type RawSockaddrUnix struct { Len uint8 Family uint8 Path [1023]uint8 } type RawSockaddrDatalink struct { Len uint8 Family uint8 Index uint16 Type uint8 Nlen uint8 Alen uint8 Slen uint8 Data [120]uint8 } type RawSockaddr struct { Len uint8 Family uint8 Data [14]uint8 } type RawSockaddrAny struct { Addr RawSockaddr Pad [1012]uint8 } type _Socklen uint32 type Cmsghdr struct { Len uint32 Level int32 Type int32 } type ICMPv6Filter struct { Filt [8]uint32 } type Iovec struct { Base *byte Len uint32 } type IPMreq struct { Multiaddr [4]byte /* in_addr */ Interface [4]byte /* in_addr */ } type IPv6Mreq struct { Multiaddr [16]byte /* in6_addr */ Interface uint32 } type IPv6MTUInfo struct { Addr RawSockaddrInet6 Mtu uint32 } type Linger struct { Onoff int32 Linger int32 } type Msghdr struct { Name *byte Namelen uint32 Iov *Iovec Iovlen int32 Control *byte Controllen uint32 Flags int32 } const ( SizeofSockaddrInet4 = 0x10 SizeofSockaddrInet6 = 0x1c SizeofSockaddrAny = 0x404 SizeofSockaddrUnix = 0x401 SizeofSockaddrDatalink = 0x80 SizeofLinger = 0x8 SizeofIovec = 0x8 SizeofIPMreq = 0x8 SizeofIPv6Mreq = 0x14 SizeofIPv6MTUInfo = 0x20 SizeofMsghdr = 0x1c SizeofCmsghdr = 0xc SizeofICMPv6Filter = 0x20 ) const ( SizeofIfMsghdr = 0x10 ) type IfMsgHdr struct { Msglen uint16 Version uint8 Type uint8 Addrs int32 Flags int32 Index uint16 Addrlen uint8 _ [1]byte } type FdSet struct { Bits [2048]int32 } type Utsname struct { Sysname [32]byte Nodename [32]byte Release [32]byte Version [32]byte Machine [32]byte } type Ustat_t struct{} type Sigset_t struct { Losigs uint32 Hisigs uint32 } const ( AT_FDCWD = -0x2 AT_REMOVEDIR = 0x1 AT_SYMLINK_NOFOLLOW = 0x1 ) type Termios struct { Iflag uint32 Oflag uint32 Cflag uint32 Lflag uint32 Cc [16]uint8 } type Termio struct { Iflag uint16 Oflag uint16 Cflag uint16 Lflag uint16 Line uint8 Cc [8]uint8 _ [1]byte } type Winsize struct { Row uint16 Col uint16 Xpixel uint16 Ypixel uint16 } type PollFd struct { Fd int32 Events uint16 Revents uint16 } const ( POLLERR = 0x4000 POLLHUP = 0x2000 POLLIN = 0x1 POLLNVAL = 0x8000 POLLOUT = 0x2 POLLPRI = 0x4 POLLRDBAND = 0x20 POLLRDNORM = 0x10 POLLWRBAND = 0x40 POLLWRNORM = 0x2 ) type Flock_t struct { Type int16 Whence int16 Sysid uint32 Pid int32 Vfs int32 Start int64 Len int64 } type Fsid_t struct { Val [2]uint32 } type Fsid64_t struct { Val [2]uint64 } type Statfs_t struct { Version int32 Type int32 Bsize uint32 Blocks uint32 Bfree uint32 Bavail uint32 Files uint32 Ffree uint32 Fsid Fsid_t Vfstype int32 Fsize uint32 Vfsnumber int32 Vfsoff int32 Vfslen int32 Vfsvers int32 Fname [32]uint8 Fpack [32]uint8 Name_max int32 } const RNDGETENTCNT = 0x80045200
docker/docker
vendor/golang.org/x/sys/unix/ztypes_aix_ppc.go
GO
apache-2.0
5,049
// mkerrors.sh // MACHINE GENERATED BY THE COMMAND ABOVE; DO NOT EDIT // Created by cgo -godefs - DO NOT EDIT // cgo -godefs -- _const.go // +build arm,darwin package unix import "syscall" const ( AF_APPLETALK = 0x10 AF_CCITT = 0xa AF_CHAOS = 0x5 AF_CNT = 0x15 AF_COIP = 0x14 AF_DATAKIT = 0x9 AF_DECnet = 0xc AF_DLI = 0xd AF_E164 = 0x1c AF_ECMA = 0x8 AF_HYLINK = 0xf AF_IEEE80211 = 0x25 AF_IMPLINK = 0x3 AF_INET = 0x2 AF_INET6 = 0x1e AF_IPX = 0x17 AF_ISDN = 0x1c AF_ISO = 0x7 AF_LAT = 0xe AF_LINK = 0x12 AF_LOCAL = 0x1 AF_MAX = 0x28 AF_NATM = 0x1f AF_NDRV = 0x1b AF_NETBIOS = 0x21 AF_NS = 0x6 AF_OSI = 0x7 AF_PPP = 0x22 AF_PUP = 0x4 AF_RESERVED_36 = 0x24 AF_ROUTE = 0x11 AF_SIP = 0x18 AF_SNA = 0xb AF_SYSTEM = 0x20 AF_UNIX = 0x1 AF_UNSPEC = 0x0 AF_UTUN = 0x26 B0 = 0x0 B110 = 0x6e B115200 = 0x1c200 B1200 = 0x4b0 B134 = 0x86 B14400 = 0x3840 B150 = 0x96 B1800 = 0x708 B19200 = 0x4b00 B200 = 0xc8 B230400 = 0x38400 B2400 = 0x960 B28800 = 0x7080 B300 = 0x12c B38400 = 0x9600 B4800 = 0x12c0 B50 = 0x32 B57600 = 0xe100 B600 = 0x258 B7200 = 0x1c20 B75 = 0x4b B76800 = 0x12c00 B9600 = 0x2580 BIOCFLUSH = 0x20004268 BIOCGBLEN = 0x40044266 BIOCGDLT = 0x4004426a BIOCGDLTLIST = 0xc00c4279 BIOCGETIF = 0x4020426b BIOCGHDRCMPLT = 0x40044274 BIOCGRSIG = 0x40044272 BIOCGRTIMEOUT = 0x4010426e BIOCGSEESENT = 0x40044276 BIOCGSTATS = 0x4008426f BIOCIMMEDIATE = 0x80044270 BIOCPROMISC = 0x20004269 BIOCSBLEN = 0xc0044266 BIOCSDLT = 0x80044278 BIOCSETF = 0x80104267 BIOCSETIF = 0x8020426c BIOCSHDRCMPLT = 0x80044275 BIOCSRSIG = 0x80044273 BIOCSRTIMEOUT = 0x8010426d BIOCSSEESENT = 0x80044277 BIOCVERSION = 0x40044271 BPF_A = 0x10 BPF_ABS = 0x20 BPF_ADD = 0x0 BPF_ALIGNMENT = 0x4 BPF_ALU = 0x4 BPF_AND = 0x50 BPF_B = 0x10 BPF_DIV = 0x30 BPF_H = 0x8 BPF_IMM = 0x0 BPF_IND = 0x40 BPF_JA = 0x0 BPF_JEQ = 0x10 BPF_JGE = 0x30 BPF_JGT = 0x20 BPF_JMP = 0x5 BPF_JSET = 0x40 BPF_K = 0x0 BPF_LD = 0x0 BPF_LDX = 0x1 BPF_LEN = 0x80 BPF_LSH = 0x60 BPF_MAJOR_VERSION = 0x1 BPF_MAXBUFSIZE = 0x80000 BPF_MAXINSNS = 0x200 BPF_MEM = 0x60 BPF_MEMWORDS = 0x10 BPF_MINBUFSIZE = 0x20 BPF_MINOR_VERSION = 0x1 BPF_MISC = 0x7 BPF_MSH = 0xa0 BPF_MUL = 0x20 BPF_NEG = 0x80 BPF_OR = 0x40 BPF_RELEASE = 0x30bb6 BPF_RET = 0x6 BPF_RSH = 0x70 BPF_ST = 0x2 BPF_STX = 0x3 BPF_SUB = 0x10 BPF_TAX = 0x0 BPF_TXA = 0x80 BPF_W = 0x0 BPF_X = 0x8 BRKINT = 0x2 CFLUSH = 0xf CLOCAL = 0x8000 CREAD = 0x800 CS5 = 0x0 CS6 = 0x100 CS7 = 0x200 CS8 = 0x300 CSIZE = 0x300 CSTART = 0x11 CSTATUS = 0x14 CSTOP = 0x13 CSTOPB = 0x400 CSUSP = 0x1a CTL_MAXNAME = 0xc CTL_NET = 0x4 DLT_APPLE_IP_OVER_IEEE1394 = 0x8a DLT_ARCNET = 0x7 DLT_ATM_CLIP = 0x13 DLT_ATM_RFC1483 = 0xb DLT_AX25 = 0x3 DLT_CHAOS = 0x5 DLT_CHDLC = 0x68 DLT_C_HDLC = 0x68 DLT_EN10MB = 0x1 DLT_EN3MB = 0x2 DLT_FDDI = 0xa DLT_IEEE802 = 0x6 DLT_IEEE802_11 = 0x69 DLT_IEEE802_11_RADIO = 0x7f DLT_IEEE802_11_RADIO_AVS = 0xa3 DLT_LINUX_SLL = 0x71 DLT_LOOP = 0x6c DLT_NULL = 0x0 DLT_PFLOG = 0x75 DLT_PFSYNC = 0x12 DLT_PPP = 0x9 DLT_PPP_BSDOS = 0x10 DLT_PPP_SERIAL = 0x32 DLT_PRONET = 0x4 DLT_RAW = 0xc DLT_SLIP = 0x8 DLT_SLIP_BSDOS = 0xf DT_BLK = 0x6 DT_CHR = 0x2 DT_DIR = 0x4 DT_FIFO = 0x1 DT_LNK = 0xa DT_REG = 0x8 DT_SOCK = 0xc DT_UNKNOWN = 0x0 DT_WHT = 0xe ECHO = 0x8 ECHOCTL = 0x40 ECHOE = 0x2 ECHOK = 0x4 ECHOKE = 0x1 ECHONL = 0x10 ECHOPRT = 0x20 EVFILT_AIO = -0x3 EVFILT_FS = -0x9 EVFILT_MACHPORT = -0x8 EVFILT_PROC = -0x5 EVFILT_READ = -0x1 EVFILT_SIGNAL = -0x6 EVFILT_SYSCOUNT = 0xe EVFILT_THREADMARKER = 0xe EVFILT_TIMER = -0x7 EVFILT_USER = -0xa EVFILT_VM = -0xc EVFILT_VNODE = -0x4 EVFILT_WRITE = -0x2 EV_ADD = 0x1 EV_CLEAR = 0x20 EV_DELETE = 0x2 EV_DISABLE = 0x8 EV_DISPATCH = 0x80 EV_ENABLE = 0x4 EV_EOF = 0x8000 EV_ERROR = 0x4000 EV_FLAG0 = 0x1000 EV_FLAG1 = 0x2000 EV_ONESHOT = 0x10 EV_OOBAND = 0x2000 EV_POLL = 0x1000 EV_RECEIPT = 0x40 EV_SYSFLAGS = 0xf000 EXTA = 0x4b00 EXTB = 0x9600 EXTPROC = 0x800 FD_CLOEXEC = 0x1 FD_SETSIZE = 0x400 FLUSHO = 0x800000 F_ADDFILESIGS = 0x3d F_ADDSIGS = 0x3b F_ALLOCATEALL = 0x4 F_ALLOCATECONTIG = 0x2 F_CHKCLEAN = 0x29 F_DUPFD = 0x0 F_DUPFD_CLOEXEC = 0x43 F_FINDSIGS = 0x4e F_FLUSH_DATA = 0x28 F_FREEZE_FS = 0x35 F_FULLFSYNC = 0x33 F_GETCODEDIR = 0x48 F_GETFD = 0x1 F_GETFL = 0x3 F_GETLK = 0x7 F_GETLKPID = 0x42 F_GETNOSIGPIPE = 0x4a F_GETOWN = 0x5 F_GETPATH = 0x32 F_GETPATH_MTMINFO = 0x47 F_GETPROTECTIONCLASS = 0x3f F_GETPROTECTIONLEVEL = 0x4d F_GLOBAL_NOCACHE = 0x37 F_LOG2PHYS = 0x31 F_LOG2PHYS_EXT = 0x41 F_NOCACHE = 0x30 F_NODIRECT = 0x3e F_OK = 0x0 F_PATHPKG_CHECK = 0x34 F_PEOFPOSMODE = 0x3 F_PREALLOCATE = 0x2a F_RDADVISE = 0x2c F_RDAHEAD = 0x2d F_RDLCK = 0x1 F_SETBACKINGSTORE = 0x46 F_SETFD = 0x2 F_SETFL = 0x4 F_SETLK = 0x8 F_SETLKW = 0x9 F_SETLKWTIMEOUT = 0xa F_SETNOSIGPIPE = 0x49 F_SETOWN = 0x6 F_SETPROTECTIONCLASS = 0x40 F_SETSIZE = 0x2b F_SINGLE_WRITER = 0x4c F_THAW_FS = 0x36 F_TRANSCODEKEY = 0x4b F_UNLCK = 0x2 F_VOLPOSMODE = 0x4 F_WRLCK = 0x3 HUPCL = 0x4000 ICANON = 0x100 ICMP6_FILTER = 0x12 ICRNL = 0x100 IEXTEN = 0x400 IFF_ALLMULTI = 0x200 IFF_ALTPHYS = 0x4000 IFF_BROADCAST = 0x2 IFF_DEBUG = 0x4 IFF_LINK0 = 0x1000 IFF_LINK1 = 0x2000 IFF_LINK2 = 0x4000 IFF_LOOPBACK = 0x8 IFF_MULTICAST = 0x8000 IFF_NOARP = 0x80 IFF_NOTRAILERS = 0x20 IFF_OACTIVE = 0x400 IFF_POINTOPOINT = 0x10 IFF_PROMISC = 0x100 IFF_RUNNING = 0x40 IFF_SIMPLEX = 0x800 IFF_UP = 0x1 IFNAMSIZ = 0x10 IFT_1822 = 0x2 IFT_AAL5 = 0x31 IFT_ARCNET = 0x23 IFT_ARCNETPLUS = 0x24 IFT_ATM = 0x25 IFT_BRIDGE = 0xd1 IFT_CARP = 0xf8 IFT_CELLULAR = 0xff IFT_CEPT = 0x13 IFT_DS3 = 0x1e IFT_ENC = 0xf4 IFT_EON = 0x19 IFT_ETHER = 0x6 IFT_FAITH = 0x38 IFT_FDDI = 0xf IFT_FRELAY = 0x20 IFT_FRELAYDCE = 0x2c IFT_GIF = 0x37 IFT_HDH1822 = 0x3 IFT_HIPPI = 0x2f IFT_HSSI = 0x2e IFT_HY = 0xe IFT_IEEE1394 = 0x90 IFT_IEEE8023ADLAG = 0x88 IFT_ISDNBASIC = 0x14 IFT_ISDNPRIMARY = 0x15 IFT_ISO88022LLC = 0x29 IFT_ISO88023 = 0x7 IFT_ISO88024 = 0x8 IFT_ISO88025 = 0x9 IFT_ISO88026 = 0xa IFT_L2VLAN = 0x87 IFT_LAPB = 0x10 IFT_LOCALTALK = 0x2a IFT_LOOP = 0x18 IFT_MIOX25 = 0x26 IFT_MODEM = 0x30 IFT_NSIP = 0x1b IFT_OTHER = 0x1 IFT_P10 = 0xc IFT_P80 = 0xd IFT_PARA = 0x22 IFT_PDP = 0xff IFT_PFLOG = 0xf5 IFT_PFSYNC = 0xf6 IFT_PPP = 0x17 IFT_PROPMUX = 0x36 IFT_PROPVIRTUAL = 0x35 IFT_PTPSERIAL = 0x16 IFT_RS232 = 0x21 IFT_SDLC = 0x11 IFT_SIP = 0x1f IFT_SLIP = 0x1c IFT_SMDSDXI = 0x2b IFT_SMDSICIP = 0x34 IFT_SONET = 0x27 IFT_SONETPATH = 0x32 IFT_SONETVT = 0x33 IFT_STARLAN = 0xb IFT_STF = 0x39 IFT_T1 = 0x12 IFT_ULTRA = 0x1d IFT_V35 = 0x2d IFT_X25 = 0x5 IFT_X25DDN = 0x4 IFT_X25PLE = 0x28 IFT_XETHER = 0x1a IGNBRK = 0x1 IGNCR = 0x80 IGNPAR = 0x4 IMAXBEL = 0x2000 INLCR = 0x40 INPCK = 0x10 IN_CLASSA_HOST = 0xffffff IN_CLASSA_MAX = 0x80 IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 0x18 IN_CLASSB_HOST = 0xffff IN_CLASSB_MAX = 0x10000 IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 0x10 IN_CLASSC_HOST = 0xff IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 0x8 IN_CLASSD_HOST = 0xfffffff IN_CLASSD_NET = 0xf0000000 IN_CLASSD_NSHIFT = 0x1c IN_LINKLOCALNETNUM = 0xa9fe0000 IN_LOOPBACKNET = 0x7f IPPROTO_3PC = 0x22 IPPROTO_ADFS = 0x44 IPPROTO_AH = 0x33 IPPROTO_AHIP = 0x3d IPPROTO_APES = 0x63 IPPROTO_ARGUS = 0xd IPPROTO_AX25 = 0x5d IPPROTO_BHA = 0x31 IPPROTO_BLT = 0x1e IPPROTO_BRSATMON = 0x4c IPPROTO_CFTP = 0x3e IPPROTO_CHAOS = 0x10 IPPROTO_CMTP = 0x26 IPPROTO_CPHB = 0x49 IPPROTO_CPNX = 0x48 IPPROTO_DDP = 0x25 IPPROTO_DGP = 0x56 IPPROTO_DIVERT = 0xfe IPPROTO_DONE = 0x101 IPPROTO_DSTOPTS = 0x3c IPPROTO_EGP = 0x8 IPPROTO_EMCON = 0xe IPPROTO_ENCAP = 0x62 IPPROTO_EON = 0x50 IPPROTO_ESP = 0x32 IPPROTO_ETHERIP = 0x61 IPPROTO_FRAGMENT = 0x2c IPPROTO_GGP = 0x3 IPPROTO_GMTP = 0x64 IPPROTO_GRE = 0x2f IPPROTO_HELLO = 0x3f IPPROTO_HMP = 0x14 IPPROTO_HOPOPTS = 0x0 IPPROTO_ICMP = 0x1 IPPROTO_ICMPV6 = 0x3a IPPROTO_IDP = 0x16 IPPROTO_IDPR = 0x23 IPPROTO_IDRP = 0x2d IPPROTO_IGMP = 0x2 IPPROTO_IGP = 0x55 IPPROTO_IGRP = 0x58 IPPROTO_IL = 0x28 IPPROTO_INLSP = 0x34 IPPROTO_INP = 0x20 IPPROTO_IP = 0x0 IPPROTO_IPCOMP = 0x6c IPPROTO_IPCV = 0x47 IPPROTO_IPEIP = 0x5e IPPROTO_IPIP = 0x4 IPPROTO_IPPC = 0x43 IPPROTO_IPV4 = 0x4 IPPROTO_IPV6 = 0x29 IPPROTO_IRTP = 0x1c IPPROTO_KRYPTOLAN = 0x41 IPPROTO_LARP = 0x5b IPPROTO_LEAF1 = 0x19 IPPROTO_LEAF2 = 0x1a IPPROTO_MAX = 0x100 IPPROTO_MAXID = 0x34 IPPROTO_MEAS = 0x13 IPPROTO_MHRP = 0x30 IPPROTO_MICP = 0x5f IPPROTO_MTP = 0x5c IPPROTO_MUX = 0x12 IPPROTO_ND = 0x4d IPPROTO_NHRP = 0x36 IPPROTO_NONE = 0x3b IPPROTO_NSP = 0x1f IPPROTO_NVPII = 0xb IPPROTO_OSPFIGP = 0x59 IPPROTO_PGM = 0x71 IPPROTO_PIGP = 0x9 IPPROTO_PIM = 0x67 IPPROTO_PRM = 0x15 IPPROTO_PUP = 0xc IPPROTO_PVP = 0x4b IPPROTO_RAW = 0xff IPPROTO_RCCMON = 0xa IPPROTO_RDP = 0x1b IPPROTO_ROUTING = 0x2b IPPROTO_RSVP = 0x2e IPPROTO_RVD = 0x42 IPPROTO_SATEXPAK = 0x40 IPPROTO_SATMON = 0x45 IPPROTO_SCCSP = 0x60 IPPROTO_SCTP = 0x84 IPPROTO_SDRP = 0x2a IPPROTO_SEP = 0x21 IPPROTO_SRPC = 0x5a IPPROTO_ST = 0x7 IPPROTO_SVMTP = 0x52 IPPROTO_SWIPE = 0x35 IPPROTO_TCF = 0x57 IPPROTO_TCP = 0x6 IPPROTO_TP = 0x1d IPPROTO_TPXX = 0x27 IPPROTO_TRUNK1 = 0x17 IPPROTO_TRUNK2 = 0x18 IPPROTO_TTP = 0x54 IPPROTO_UDP = 0x11 IPPROTO_VINES = 0x53 IPPROTO_VISA = 0x46 IPPROTO_VMTP = 0x51 IPPROTO_WBEXPAK = 0x4f IPPROTO_WBMON = 0x4e IPPROTO_WSN = 0x4a IPPROTO_XNET = 0xf IPPROTO_XTP = 0x24 IPV6_2292DSTOPTS = 0x17 IPV6_2292HOPLIMIT = 0x14 IPV6_2292HOPOPTS = 0x16 IPV6_2292NEXTHOP = 0x15 IPV6_2292PKTINFO = 0x13 IPV6_2292PKTOPTIONS = 0x19 IPV6_2292RTHDR = 0x18 IPV6_BINDV6ONLY = 0x1b IPV6_BOUND_IF = 0x7d IPV6_CHECKSUM = 0x1a IPV6_DEFAULT_MULTICAST_HOPS = 0x1 IPV6_DEFAULT_MULTICAST_LOOP = 0x1 IPV6_DEFHLIM = 0x40 IPV6_FAITH = 0x1d IPV6_FLOWINFO_MASK = 0xffffff0f IPV6_FLOWLABEL_MASK = 0xffff0f00 IPV6_FRAGTTL = 0x78 IPV6_FW_ADD = 0x1e IPV6_FW_DEL = 0x1f IPV6_FW_FLUSH = 0x20 IPV6_FW_GET = 0x22 IPV6_FW_ZERO = 0x21 IPV6_HLIMDEC = 0x1 IPV6_IPSEC_POLICY = 0x1c IPV6_JOIN_GROUP = 0xc IPV6_LEAVE_GROUP = 0xd IPV6_MAXHLIM = 0xff IPV6_MAXOPTHDR = 0x800 IPV6_MAXPACKET = 0xffff IPV6_MAX_GROUP_SRC_FILTER = 0x200 IPV6_MAX_MEMBERSHIPS = 0xfff IPV6_MAX_SOCK_SRC_FILTER = 0x80 IPV6_MIN_MEMBERSHIPS = 0x1f IPV6_MMTU = 0x500 IPV6_MULTICAST_HOPS = 0xa IPV6_MULTICAST_IF = 0x9 IPV6_MULTICAST_LOOP = 0xb IPV6_PORTRANGE = 0xe IPV6_PORTRANGE_DEFAULT = 0x0 IPV6_PORTRANGE_HIGH = 0x1 IPV6_PORTRANGE_LOW = 0x2 IPV6_RECVTCLASS = 0x23 IPV6_RTHDR_LOOSE = 0x0 IPV6_RTHDR_STRICT = 0x1 IPV6_RTHDR_TYPE_0 = 0x0 IPV6_SOCKOPT_RESERVED1 = 0x3 IPV6_TCLASS = 0x24 IPV6_UNICAST_HOPS = 0x4 IPV6_V6ONLY = 0x1b IPV6_VERSION = 0x60 IPV6_VERSION_MASK = 0xf0 IP_ADD_MEMBERSHIP = 0xc IP_ADD_SOURCE_MEMBERSHIP = 0x46 IP_BLOCK_SOURCE = 0x48 IP_BOUND_IF = 0x19 IP_DEFAULT_MULTICAST_LOOP = 0x1 IP_DEFAULT_MULTICAST_TTL = 0x1 IP_DF = 0x4000 IP_DROP_MEMBERSHIP = 0xd IP_DROP_SOURCE_MEMBERSHIP = 0x47 IP_DUMMYNET_CONFIGURE = 0x3c IP_DUMMYNET_DEL = 0x3d IP_DUMMYNET_FLUSH = 0x3e IP_DUMMYNET_GET = 0x40 IP_FAITH = 0x16 IP_FW_ADD = 0x28 IP_FW_DEL = 0x29 IP_FW_FLUSH = 0x2a IP_FW_GET = 0x2c IP_FW_RESETLOG = 0x2d IP_FW_ZERO = 0x2b IP_HDRINCL = 0x2 IP_IPSEC_POLICY = 0x15 IP_MAXPACKET = 0xffff IP_MAX_GROUP_SRC_FILTER = 0x200 IP_MAX_MEMBERSHIPS = 0xfff IP_MAX_SOCK_MUTE_FILTER = 0x80 IP_MAX_SOCK_SRC_FILTER = 0x80 IP_MF = 0x2000 IP_MIN_MEMBERSHIPS = 0x1f IP_MSFILTER = 0x4a IP_MSS = 0x240 IP_MULTICAST_IF = 0x9 IP_MULTICAST_IFINDEX = 0x42 IP_MULTICAST_LOOP = 0xb IP_MULTICAST_TTL = 0xa IP_MULTICAST_VIF = 0xe IP_NAT__XXX = 0x37 IP_OFFMASK = 0x1fff IP_OLD_FW_ADD = 0x32 IP_OLD_FW_DEL = 0x33 IP_OLD_FW_FLUSH = 0x34 IP_OLD_FW_GET = 0x36 IP_OLD_FW_RESETLOG = 0x38 IP_OLD_FW_ZERO = 0x35 IP_OPTIONS = 0x1 IP_PKTINFO = 0x1a IP_PORTRANGE = 0x13 IP_PORTRANGE_DEFAULT = 0x0 IP_PORTRANGE_HIGH = 0x1 IP_PORTRANGE_LOW = 0x2 IP_RECVDSTADDR = 0x7 IP_RECVIF = 0x14 IP_RECVOPTS = 0x5 IP_RECVPKTINFO = 0x1a IP_RECVRETOPTS = 0x6 IP_RECVTTL = 0x18 IP_RETOPTS = 0x8 IP_RF = 0x8000 IP_RSVP_OFF = 0x10 IP_RSVP_ON = 0xf IP_RSVP_VIF_OFF = 0x12 IP_RSVP_VIF_ON = 0x11 IP_STRIPHDR = 0x17 IP_TOS = 0x3 IP_TRAFFIC_MGT_BACKGROUND = 0x41 IP_TTL = 0x4 IP_UNBLOCK_SOURCE = 0x49 ISIG = 0x80 ISTRIP = 0x20 IUTF8 = 0x4000 IXANY = 0x800 IXOFF = 0x400 IXON = 0x200 LOCK_EX = 0x2 LOCK_NB = 0x4 LOCK_SH = 0x1 LOCK_UN = 0x8 MADV_CAN_REUSE = 0x9 MADV_DONTNEED = 0x4 MADV_FREE = 0x5 MADV_FREE_REUSABLE = 0x7 MADV_FREE_REUSE = 0x8 MADV_NORMAL = 0x0 MADV_RANDOM = 0x1 MADV_SEQUENTIAL = 0x2 MADV_WILLNEED = 0x3 MADV_ZERO_WIRED_PAGES = 0x6 MAP_ANON = 0x1000 MAP_COPY = 0x2 MAP_FILE = 0x0 MAP_FIXED = 0x10 MAP_HASSEMAPHORE = 0x200 MAP_JIT = 0x800 MAP_NOCACHE = 0x400 MAP_NOEXTEND = 0x100 MAP_NORESERVE = 0x40 MAP_PRIVATE = 0x2 MAP_RENAME = 0x20 MAP_RESERVED0080 = 0x80 MAP_SHARED = 0x1 MCL_CURRENT = 0x1 MCL_FUTURE = 0x2 MSG_CTRUNC = 0x20 MSG_DONTROUTE = 0x4 MSG_DONTWAIT = 0x80 MSG_EOF = 0x100 MSG_EOR = 0x8 MSG_FLUSH = 0x400 MSG_HAVEMORE = 0x2000 MSG_HOLD = 0x800 MSG_NEEDSA = 0x10000 MSG_OOB = 0x1 MSG_PEEK = 0x2 MSG_RCVMORE = 0x4000 MSG_SEND = 0x1000 MSG_TRUNC = 0x10 MSG_WAITALL = 0x40 MSG_WAITSTREAM = 0x200 MS_ASYNC = 0x1 MS_DEACTIVATE = 0x8 MS_INVALIDATE = 0x2 MS_KILLPAGES = 0x4 MS_SYNC = 0x10 NAME_MAX = 0xff NET_RT_DUMP = 0x1 NET_RT_DUMP2 = 0x7 NET_RT_FLAGS = 0x2 NET_RT_IFLIST = 0x3 NET_RT_IFLIST2 = 0x6 NET_RT_MAXID = 0xa NET_RT_STAT = 0x4 NET_RT_TRASH = 0x5 NOFLSH = 0x80000000 NOTE_ABSOLUTE = 0x8 NOTE_ATTRIB = 0x8 NOTE_BACKGROUND = 0x40 NOTE_CHILD = 0x4 NOTE_CRITICAL = 0x20 NOTE_DELETE = 0x1 NOTE_EXEC = 0x20000000 NOTE_EXIT = 0x80000000 NOTE_EXITSTATUS = 0x4000000 NOTE_EXIT_CSERROR = 0x40000 NOTE_EXIT_DECRYPTFAIL = 0x10000 NOTE_EXIT_DETAIL = 0x2000000 NOTE_EXIT_DETAIL_MASK = 0x70000 NOTE_EXIT_MEMORY = 0x20000 NOTE_EXIT_REPARENTED = 0x80000 NOTE_EXTEND = 0x4 NOTE_FFAND = 0x40000000 NOTE_FFCOPY = 0xc0000000 NOTE_FFCTRLMASK = 0xc0000000 NOTE_FFLAGSMASK = 0xffffff NOTE_FFNOP = 0x0 NOTE_FFOR = 0x80000000 NOTE_FORK = 0x40000000 NOTE_LEEWAY = 0x10 NOTE_LINK = 0x10 NOTE_LOWAT = 0x1 NOTE_NONE = 0x80 NOTE_NSECONDS = 0x4 NOTE_PCTRLMASK = -0x100000 NOTE_PDATAMASK = 0xfffff NOTE_REAP = 0x10000000 NOTE_RENAME = 0x20 NOTE_REVOKE = 0x40 NOTE_SECONDS = 0x1 NOTE_SIGNAL = 0x8000000 NOTE_TRACK = 0x1 NOTE_TRACKERR = 0x2 NOTE_TRIGGER = 0x1000000 NOTE_USECONDS = 0x2 NOTE_VM_ERROR = 0x10000000 NOTE_VM_PRESSURE = 0x80000000 NOTE_VM_PRESSURE_SUDDEN_TERMINATE = 0x20000000 NOTE_VM_PRESSURE_TERMINATE = 0x40000000 NOTE_WRITE = 0x2 OCRNL = 0x10 OFDEL = 0x20000 OFILL = 0x80 ONLCR = 0x2 ONLRET = 0x40 ONOCR = 0x20 ONOEOT = 0x8 OPOST = 0x1 O_ACCMODE = 0x3 O_ALERT = 0x20000000 O_APPEND = 0x8 O_ASYNC = 0x40 O_CLOEXEC = 0x1000000 O_CREAT = 0x200 O_DIRECTORY = 0x100000 O_DP_GETRAWENCRYPTED = 0x1 O_DSYNC = 0x400000 O_EVTONLY = 0x8000 O_EXCL = 0x800 O_EXLOCK = 0x20 O_FSYNC = 0x80 O_NDELAY = 0x4 O_NOCTTY = 0x20000 O_NOFOLLOW = 0x100 O_NONBLOCK = 0x4 O_POPUP = 0x80000000 O_RDONLY = 0x0 O_RDWR = 0x2 O_SHLOCK = 0x10 O_SYMLINK = 0x200000 O_SYNC = 0x80 O_TRUNC = 0x400 O_WRONLY = 0x1 PARENB = 0x1000 PARMRK = 0x8 PARODD = 0x2000 PENDIN = 0x20000000 PRIO_PGRP = 0x1 PRIO_PROCESS = 0x0 PRIO_USER = 0x2 PROT_EXEC = 0x4 PROT_NONE = 0x0 PROT_READ = 0x1 PROT_WRITE = 0x2 PT_ATTACH = 0xa PT_ATTACHEXC = 0xe PT_CONTINUE = 0x7 PT_DENY_ATTACH = 0x1f PT_DETACH = 0xb PT_FIRSTMACH = 0x20 PT_FORCEQUOTA = 0x1e PT_KILL = 0x8 PT_READ_D = 0x2 PT_READ_I = 0x1 PT_READ_U = 0x3 PT_SIGEXC = 0xc PT_STEP = 0x9 PT_THUPDATE = 0xd PT_TRACE_ME = 0x0 PT_WRITE_D = 0x5 PT_WRITE_I = 0x4 PT_WRITE_U = 0x6 RLIMIT_AS = 0x5 RLIMIT_CORE = 0x4 RLIMIT_CPU = 0x0 RLIMIT_CPU_USAGE_MONITOR = 0x2 RLIMIT_DATA = 0x2 RLIMIT_FSIZE = 0x1 RLIMIT_NOFILE = 0x8 RLIMIT_STACK = 0x3 RLIM_INFINITY = 0x7fffffffffffffff RTAX_AUTHOR = 0x6 RTAX_BRD = 0x7 RTAX_DST = 0x0 RTAX_GATEWAY = 0x1 RTAX_GENMASK = 0x3 RTAX_IFA = 0x5 RTAX_IFP = 0x4 RTAX_MAX = 0x8 RTAX_NETMASK = 0x2 RTA_AUTHOR = 0x40 RTA_BRD = 0x80 RTA_DST = 0x1 RTA_GATEWAY = 0x2 RTA_GENMASK = 0x8 RTA_IFA = 0x20 RTA_IFP = 0x10 RTA_NETMASK = 0x4 RTF_BLACKHOLE = 0x1000 RTF_BROADCAST = 0x400000 RTF_CLONING = 0x100 RTF_CONDEMNED = 0x2000000 RTF_DELCLONE = 0x80 RTF_DONE = 0x40 RTF_DYNAMIC = 0x10 RTF_GATEWAY = 0x2 RTF_HOST = 0x4 RTF_IFREF = 0x4000000 RTF_IFSCOPE = 0x1000000 RTF_LLINFO = 0x400 RTF_LOCAL = 0x200000 RTF_MODIFIED = 0x20 RTF_MULTICAST = 0x800000 RTF_PINNED = 0x100000 RTF_PRCLONING = 0x10000 RTF_PROTO1 = 0x8000 RTF_PROTO2 = 0x4000 RTF_PROTO3 = 0x40000 RTF_PROXY = 0x8000000 RTF_REJECT = 0x8 RTF_ROUTER = 0x10000000 RTF_STATIC = 0x800 RTF_UP = 0x1 RTF_WASCLONED = 0x20000 RTF_XRESOLVE = 0x200 RTM_ADD = 0x1 RTM_CHANGE = 0x3 RTM_DELADDR = 0xd RTM_DELETE = 0x2 RTM_DELMADDR = 0x10 RTM_GET = 0x4 RTM_GET2 = 0x14 RTM_IFINFO = 0xe RTM_IFINFO2 = 0x12 RTM_LOCK = 0x8 RTM_LOSING = 0x5 RTM_MISS = 0x7 RTM_NEWADDR = 0xc RTM_NEWMADDR = 0xf RTM_NEWMADDR2 = 0x13 RTM_OLDADD = 0x9 RTM_OLDDEL = 0xa RTM_REDIRECT = 0x6 RTM_RESOLVE = 0xb RTM_RTTUNIT = 0xf4240 RTM_VERSION = 0x5 RTV_EXPIRE = 0x4 RTV_HOPCOUNT = 0x2 RTV_MTU = 0x1 RTV_RPIPE = 0x8 RTV_RTT = 0x40 RTV_RTTVAR = 0x80 RTV_SPIPE = 0x10 RTV_SSTHRESH = 0x20 RUSAGE_CHILDREN = -0x1 RUSAGE_SELF = 0x0 SCM_CREDS = 0x3 SCM_RIGHTS = 0x1 SCM_TIMESTAMP = 0x2 SCM_TIMESTAMP_MONOTONIC = 0x4 SHUT_RD = 0x0 SHUT_RDWR = 0x2 SHUT_WR = 0x1 SIOCADDMULTI = 0x80206931 SIOCAIFADDR = 0x8040691a SIOCARPIPLL = 0xc0206928 SIOCATMARK = 0x40047307 SIOCAUTOADDR = 0xc0206926 SIOCAUTONETMASK = 0x80206927 SIOCDELMULTI = 0x80206932 SIOCDIFADDR = 0x80206919 SIOCDIFPHYADDR = 0x80206941 SIOCGDRVSPEC = 0xc028697b SIOCGETVLAN = 0xc020697f SIOCGHIWAT = 0x40047301 SIOCGIFADDR = 0xc0206921 SIOCGIFALTMTU = 0xc0206948 SIOCGIFASYNCMAP = 0xc020697c SIOCGIFBOND = 0xc0206947 SIOCGIFBRDADDR = 0xc0206923 SIOCGIFCAP = 0xc020695b SIOCGIFCONF = 0xc00c6924 SIOCGIFDEVMTU = 0xc0206944 SIOCGIFDSTADDR = 0xc0206922 SIOCGIFFLAGS = 0xc0206911 SIOCGIFGENERIC = 0xc020693a SIOCGIFKPI = 0xc0206987 SIOCGIFMAC = 0xc0206982 SIOCGIFMEDIA = 0xc02c6938 SIOCGIFMETRIC = 0xc0206917 SIOCGIFMTU = 0xc0206933 SIOCGIFNETMASK = 0xc0206925 SIOCGIFPDSTADDR = 0xc0206940 SIOCGIFPHYS = 0xc0206935 SIOCGIFPSRCADDR = 0xc020693f SIOCGIFSTATUS = 0xc331693d SIOCGIFVLAN = 0xc020697f SIOCGIFWAKEFLAGS = 0xc0206988 SIOCGLOWAT = 0x40047303 SIOCGPGRP = 0x40047309 SIOCIFCREATE = 0xc0206978 SIOCIFCREATE2 = 0xc020697a SIOCIFDESTROY = 0x80206979 SIOCIFGCLONERS = 0xc0106981 SIOCRSLVMULTI = 0xc010693b SIOCSDRVSPEC = 0x8028697b SIOCSETVLAN = 0x8020697e SIOCSHIWAT = 0x80047300 SIOCSIFADDR = 0x8020690c SIOCSIFALTMTU = 0x80206945 SIOCSIFASYNCMAP = 0x8020697d SIOCSIFBOND = 0x80206946 SIOCSIFBRDADDR = 0x80206913 SIOCSIFCAP = 0x8020695a SIOCSIFDSTADDR = 0x8020690e SIOCSIFFLAGS = 0x80206910 SIOCSIFGENERIC = 0x80206939 SIOCSIFKPI = 0x80206986 SIOCSIFLLADDR = 0x8020693c SIOCSIFMAC = 0x80206983 SIOCSIFMEDIA = 0xc0206937 SIOCSIFMETRIC = 0x80206918 SIOCSIFMTU = 0x80206934 SIOCSIFNETMASK = 0x80206916 SIOCSIFPHYADDR = 0x8040693e SIOCSIFPHYS = 0x80206936 SIOCSIFVLAN = 0x8020697e SIOCSLOWAT = 0x80047302 SIOCSPGRP = 0x80047308 SOCK_DGRAM = 0x2 SOCK_MAXADDRLEN = 0xff SOCK_RAW = 0x3 SOCK_RDM = 0x4 SOCK_SEQPACKET = 0x5 SOCK_STREAM = 0x1 SOL_SOCKET = 0xffff SOMAXCONN = 0x80 SO_ACCEPTCONN = 0x2 SO_BROADCAST = 0x20 SO_DEBUG = 0x1 SO_DONTROUTE = 0x10 SO_DONTTRUNC = 0x2000 SO_ERROR = 0x1007 SO_KEEPALIVE = 0x8 SO_LABEL = 0x1010 SO_LINGER = 0x80 SO_LINGER_SEC = 0x1080 SO_NKE = 0x1021 SO_NOADDRERR = 0x1023 SO_NOSIGPIPE = 0x1022 SO_NOTIFYCONFLICT = 0x1026 SO_NP_EXTENSIONS = 0x1083 SO_NREAD = 0x1020 SO_NUMRCVPKT = 0x1112 SO_NWRITE = 0x1024 SO_OOBINLINE = 0x100 SO_PEERLABEL = 0x1011 SO_RANDOMPORT = 0x1082 SO_RCVBUF = 0x1002 SO_RCVLOWAT = 0x1004 SO_RCVTIMEO = 0x1006 SO_REUSEADDR = 0x4 SO_REUSEPORT = 0x200 SO_REUSESHAREUID = 0x1025 SO_SNDBUF = 0x1001 SO_SNDLOWAT = 0x1003 SO_SNDTIMEO = 0x1005 SO_TIMESTAMP = 0x400 SO_TIMESTAMP_MONOTONIC = 0x800 SO_TYPE = 0x1008 SO_UPCALLCLOSEWAIT = 0x1027 SO_USELOOPBACK = 0x40 SO_WANTMORE = 0x4000 SO_WANTOOBFLAG = 0x8000 S_IEXEC = 0x40 S_IFBLK = 0x6000 S_IFCHR = 0x2000 S_IFDIR = 0x4000 S_IFIFO = 0x1000 S_IFLNK = 0xa000 S_IFMT = 0xf000 S_IFREG = 0x8000 S_IFSOCK = 0xc000 S_IFWHT = 0xe000 S_IREAD = 0x100 S_IRGRP = 0x20 S_IROTH = 0x4 S_IRUSR = 0x100 S_IRWXG = 0x38 S_IRWXO = 0x7 S_IRWXU = 0x1c0 S_ISGID = 0x400 S_ISTXT = 0x200 S_ISUID = 0x800 S_ISVTX = 0x200 S_IWGRP = 0x10 S_IWOTH = 0x2 S_IWRITE = 0x80 S_IWUSR = 0x80 S_IXGRP = 0x8 S_IXOTH = 0x1 S_IXUSR = 0x40 TCIFLUSH = 0x1 TCIOFLUSH = 0x3 TCOFLUSH = 0x2 TCP_CONNECTIONTIMEOUT = 0x20 TCP_ENABLE_ECN = 0x104 TCP_KEEPALIVE = 0x10 TCP_KEEPCNT = 0x102 TCP_KEEPINTVL = 0x101 TCP_MAXHLEN = 0x3c TCP_MAXOLEN = 0x28 TCP_MAXSEG = 0x2 TCP_MAXWIN = 0xffff TCP_MAX_SACK = 0x4 TCP_MAX_WINSHIFT = 0xe TCP_MINMSS = 0xd8 TCP_MSS = 0x200 TCP_NODELAY = 0x1 TCP_NOOPT = 0x8 TCP_NOPUSH = 0x4 TCP_NOTSENT_LOWAT = 0x201 TCP_RXT_CONNDROPTIME = 0x80 TCP_RXT_FINDROP = 0x100 TCP_SENDMOREACKS = 0x103 TCSAFLUSH = 0x2 TIOCCBRK = 0x2000747a TIOCCDTR = 0x20007478 TIOCCONS = 0x80047462 TIOCDCDTIMESTAMP = 0x40107458 TIOCDRAIN = 0x2000745e TIOCDSIMICROCODE = 0x20007455 TIOCEXCL = 0x2000740d TIOCEXT = 0x80047460 TIOCFLUSH = 0x80047410 TIOCGDRAINWAIT = 0x40047456 TIOCGETA = 0x40487413 TIOCGETD = 0x4004741a TIOCGPGRP = 0x40047477 TIOCGWINSZ = 0x40087468 TIOCIXOFF = 0x20007480 TIOCIXON = 0x20007481 TIOCMBIC = 0x8004746b TIOCMBIS = 0x8004746c TIOCMGDTRWAIT = 0x4004745a TIOCMGET = 0x4004746a TIOCMODG = 0x40047403 TIOCMODS = 0x80047404 TIOCMSDTRWAIT = 0x8004745b TIOCMSET = 0x8004746d TIOCM_CAR = 0x40 TIOCM_CD = 0x40 TIOCM_CTS = 0x20 TIOCM_DSR = 0x100 TIOCM_DTR = 0x2 TIOCM_LE = 0x1 TIOCM_RI = 0x80 TIOCM_RNG = 0x80 TIOCM_RTS = 0x4 TIOCM_SR = 0x10 TIOCM_ST = 0x8 TIOCNOTTY = 0x20007471 TIOCNXCL = 0x2000740e TIOCOUTQ = 0x40047473 TIOCPKT = 0x80047470 TIOCPKT_DATA = 0x0 TIOCPKT_DOSTOP = 0x20 TIOCPKT_FLUSHREAD = 0x1 TIOCPKT_FLUSHWRITE = 0x2 TIOCPKT_IOCTL = 0x40 TIOCPKT_NOSTOP = 0x10 TIOCPKT_START = 0x8 TIOCPKT_STOP = 0x4 TIOCPTYGNAME = 0x40807453 TIOCPTYGRANT = 0x20007454 TIOCPTYUNLK = 0x20007452 TIOCREMOTE = 0x80047469 TIOCSBRK = 0x2000747b TIOCSCONS = 0x20007463 TIOCSCTTY = 0x20007461 TIOCSDRAINWAIT = 0x80047457 TIOCSDTR = 0x20007479 TIOCSETA = 0x80487414 TIOCSETAF = 0x80487416 TIOCSETAW = 0x80487415 TIOCSETD = 0x8004741b TIOCSIG = 0x2000745f TIOCSPGRP = 0x80047476 TIOCSTART = 0x2000746e TIOCSTAT = 0x20007465 TIOCSTI = 0x80017472 TIOCSTOP = 0x2000746f TIOCSWINSZ = 0x80087467 TIOCTIMESTAMP = 0x40107459 TIOCUCNTL = 0x80047466 TOSTOP = 0x400000 VDISCARD = 0xf VDSUSP = 0xb VEOF = 0x0 VEOL = 0x1 VEOL2 = 0x2 VERASE = 0x3 VINTR = 0x8 VKILL = 0x5 VLNEXT = 0xe VMIN = 0x10 VQUIT = 0x9 VREPRINT = 0x6 VSTART = 0xc VSTATUS = 0x12 VSTOP = 0xd VSUSP = 0xa VT0 = 0x0 VT1 = 0x10000 VTDLY = 0x10000 VTIME = 0x11 VWERASE = 0x4 WCONTINUED = 0x10 WCOREFLAG = 0x80 WEXITED = 0x4 WNOHANG = 0x1 WNOWAIT = 0x20 WORDSIZE = 0x40 WSTOPPED = 0x8 WUNTRACED = 0x2 ) // Errors const ( E2BIG = syscall.Errno(0x7) EACCES = syscall.Errno(0xd) EADDRINUSE = syscall.Errno(0x30) EADDRNOTAVAIL = syscall.Errno(0x31) EAFNOSUPPORT = syscall.Errno(0x2f) EAGAIN = syscall.Errno(0x23) EALREADY = syscall.Errno(0x25) EAUTH = syscall.Errno(0x50) EBADARCH = syscall.Errno(0x56) EBADEXEC = syscall.Errno(0x55) EBADF = syscall.Errno(0x9) EBADMACHO = syscall.Errno(0x58) EBADMSG = syscall.Errno(0x5e) EBADRPC = syscall.Errno(0x48) EBUSY = syscall.Errno(0x10) ECANCELED = syscall.Errno(0x59) ECHILD = syscall.Errno(0xa) ECONNABORTED = syscall.Errno(0x35) ECONNREFUSED = syscall.Errno(0x3d) ECONNRESET = syscall.Errno(0x36) EDEADLK = syscall.Errno(0xb) EDESTADDRREQ = syscall.Errno(0x27) EDEVERR = syscall.Errno(0x53) EDOM = syscall.Errno(0x21) EDQUOT = syscall.Errno(0x45) EEXIST = syscall.Errno(0x11) EFAULT = syscall.Errno(0xe) EFBIG = syscall.Errno(0x1b) EFTYPE = syscall.Errno(0x4f) EHOSTDOWN = syscall.Errno(0x40) EHOSTUNREACH = syscall.Errno(0x41) EIDRM = syscall.Errno(0x5a) EILSEQ = syscall.Errno(0x5c) EINPROGRESS = syscall.Errno(0x24) EINTR = syscall.Errno(0x4) EINVAL = syscall.Errno(0x16) EIO = syscall.Errno(0x5) EISCONN = syscall.Errno(0x38) EISDIR = syscall.Errno(0x15) ELAST = syscall.Errno(0x6a) ELOOP = syscall.Errno(0x3e) EMFILE = syscall.Errno(0x18) EMLINK = syscall.Errno(0x1f) EMSGSIZE = syscall.Errno(0x28) EMULTIHOP = syscall.Errno(0x5f) ENAMETOOLONG = syscall.Errno(0x3f) ENEEDAUTH = syscall.Errno(0x51) ENETDOWN = syscall.Errno(0x32) ENETRESET = syscall.Errno(0x34) ENETUNREACH = syscall.Errno(0x33) ENFILE = syscall.Errno(0x17) ENOATTR = syscall.Errno(0x5d) ENOBUFS = syscall.Errno(0x37) ENODATA = syscall.Errno(0x60) ENODEV = syscall.Errno(0x13) ENOENT = syscall.Errno(0x2) ENOEXEC = syscall.Errno(0x8) ENOLCK = syscall.Errno(0x4d) ENOLINK = syscall.Errno(0x61) ENOMEM = syscall.Errno(0xc) ENOMSG = syscall.Errno(0x5b) ENOPOLICY = syscall.Errno(0x67) ENOPROTOOPT = syscall.Errno(0x2a) ENOSPC = syscall.Errno(0x1c) ENOSR = syscall.Errno(0x62) ENOSTR = syscall.Errno(0x63) ENOSYS = syscall.Errno(0x4e) ENOTBLK = syscall.Errno(0xf) ENOTCONN = syscall.Errno(0x39) ENOTDIR = syscall.Errno(0x14) ENOTEMPTY = syscall.Errno(0x42) ENOTRECOVERABLE = syscall.Errno(0x68) ENOTSOCK = syscall.Errno(0x26) ENOTSUP = syscall.Errno(0x2d) ENOTTY = syscall.Errno(0x19) ENXIO = syscall.Errno(0x6) EOPNOTSUPP = syscall.Errno(0x66) EOVERFLOW = syscall.Errno(0x54) EOWNERDEAD = syscall.Errno(0x69) EPERM = syscall.Errno(0x1) EPFNOSUPPORT = syscall.Errno(0x2e) EPIPE = syscall.Errno(0x20) EPROCLIM = syscall.Errno(0x43) EPROCUNAVAIL = syscall.Errno(0x4c) EPROGMISMATCH = syscall.Errno(0x4b) EPROGUNAVAIL = syscall.Errno(0x4a) EPROTO = syscall.Errno(0x64) EPROTONOSUPPORT = syscall.Errno(0x2b) EPROTOTYPE = syscall.Errno(0x29) EPWROFF = syscall.Errno(0x52) EQFULL = syscall.Errno(0x6a) ERANGE = syscall.Errno(0x22) EREMOTE = syscall.Errno(0x47) EROFS = syscall.Errno(0x1e) ERPCMISMATCH = syscall.Errno(0x49) ESHLIBVERS = syscall.Errno(0x57) ESHUTDOWN = syscall.Errno(0x3a) ESOCKTNOSUPPORT = syscall.Errno(0x2c) ESPIPE = syscall.Errno(0x1d) ESRCH = syscall.Errno(0x3) ESTALE = syscall.Errno(0x46) ETIME = syscall.Errno(0x65) ETIMEDOUT = syscall.Errno(0x3c) ETOOMANYREFS = syscall.Errno(0x3b) ETXTBSY = syscall.Errno(0x1a) EUSERS = syscall.Errno(0x44) EWOULDBLOCK = syscall.Errno(0x23) EXDEV = syscall.Errno(0x12) ) // Signals const ( SIGABRT = syscall.Signal(0x6) SIGALRM = syscall.Signal(0xe) SIGBUS = syscall.Signal(0xa) SIGCHLD = syscall.Signal(0x14) SIGCONT = syscall.Signal(0x13) SIGEMT = syscall.Signal(0x7) SIGFPE = syscall.Signal(0x8) SIGHUP = syscall.Signal(0x1) SIGILL = syscall.Signal(0x4) SIGINFO = syscall.Signal(0x1d) SIGINT = syscall.Signal(0x2) SIGIO = syscall.Signal(0x17) SIGIOT = syscall.Signal(0x6) SIGKILL = syscall.Signal(0x9) SIGPIPE = syscall.Signal(0xd) SIGPROF = syscall.Signal(0x1b) SIGQUIT = syscall.Signal(0x3) SIGSEGV = syscall.Signal(0xb) SIGSTOP = syscall.Signal(0x11) SIGSYS = syscall.Signal(0xc) SIGTERM = syscall.Signal(0xf) SIGTRAP = syscall.Signal(0x5) SIGTSTP = syscall.Signal(0x12) SIGTTIN = syscall.Signal(0x15) SIGTTOU = syscall.Signal(0x16) SIGURG = syscall.Signal(0x10) SIGUSR1 = syscall.Signal(0x1e) SIGUSR2 = syscall.Signal(0x1f) SIGVTALRM = syscall.Signal(0x1a) SIGWINCH = syscall.Signal(0x1c) SIGXCPU = syscall.Signal(0x18) SIGXFSZ = syscall.Signal(0x19) )
doronp/swarm
vendor/golang.org/x/sys/unix/zerrors_darwin_arm.go
GO
apache-2.0
54,025
/* * Copyright (C) 2010 ZXing 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. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded; import com.google.zxing.BarcodeFormat; import com.google.zxing.MultiFormatReader; import com.google.zxing.common.AbstractBlackBoxTestCase; public final class RSSExpandedBlackBox2TestCase extends AbstractBlackBoxTestCase { public RSSExpandedBlackBox2TestCase() { super("src/test/resources/blackbox/rssexpanded-2", new MultiFormatReader(), BarcodeFormat.RSS_EXPANDED); addTest(21, 23, 0.0f); addTest(21, 23, 180.0f); } }
DONIKAN/zxing
core/src/test/java/com/google/zxing/oned/rss/expanded/RSSExpandedBlackBox2TestCase.java
Java
apache-2.0
1,432
package truncindex import ( "math/rand" "testing" "github.com/docker/docker/pkg/stringid" ) // Test the behavior of TruncIndex, an index for querying IDs from a non-conflicting prefix. func TestTruncIndex(t *testing.T) { ids := []string{} index := NewTruncIndex(ids) // Get on an empty index if _, err := index.Get("foobar"); err == nil { t.Fatal("Get on an empty index should return an error") } // Spaces should be illegal in an id if err := index.Add("I have a space"); err == nil { t.Fatalf("Adding an id with ' ' should return an error") } id := "99b36c2c326ccc11e726eee6ee78a0baf166ef96" // Add an id if err := index.Add(id); err != nil { t.Fatal(err) } // Add an empty id (should fail) if err := index.Add(""); err == nil { t.Fatalf("Adding an empty id should return an error") } // Get a non-existing id assertIndexGet(t, index, "abracadabra", "", true) // Get an empty id assertIndexGet(t, index, "", "", true) // Get the exact id assertIndexGet(t, index, id, id, false) // The first letter should match assertIndexGet(t, index, id[:1], id, false) // The first half should match assertIndexGet(t, index, id[:len(id)/2], id, false) // The second half should NOT match assertIndexGet(t, index, id[len(id)/2:], "", true) id2 := id[:6] + "blabla" // Add an id if err := index.Add(id2); err != nil { t.Fatal(err) } // Both exact IDs should work assertIndexGet(t, index, id, id, false) assertIndexGet(t, index, id2, id2, false) // 6 characters or less should conflict assertIndexGet(t, index, id[:6], "", true) assertIndexGet(t, index, id[:4], "", true) assertIndexGet(t, index, id[:1], "", true) // An ambiguous id prefix should return an error if _, err := index.Get(id[:4]); err == nil { t.Fatal("An ambiguous id prefix should return an error") } // 7 characters should NOT conflict assertIndexGet(t, index, id[:7], id, false) assertIndexGet(t, index, id2[:7], id2, false) // Deleting a non-existing id should return an error if err := index.Delete("non-existing"); err == nil { t.Fatalf("Deleting a non-existing id should return an error") } // Deleting an empty id should return an error if err := index.Delete(""); err == nil { t.Fatal("Deleting an empty id should return an error") } // Deleting id2 should remove conflicts if err := index.Delete(id2); err != nil { t.Fatal(err) } // id2 should no longer work assertIndexGet(t, index, id2, "", true) assertIndexGet(t, index, id2[:7], "", true) assertIndexGet(t, index, id2[:11], "", true) // conflicts between id and id2 should be gone assertIndexGet(t, index, id[:6], id, false) assertIndexGet(t, index, id[:4], id, false) assertIndexGet(t, index, id[:1], id, false) // non-conflicting substrings should still not conflict assertIndexGet(t, index, id[:7], id, false) assertIndexGet(t, index, id[:15], id, false) assertIndexGet(t, index, id, id, false) assertIndexIterate(t) } func assertIndexIterate(t *testing.T) { ids := []string{ "19b36c2c326ccc11e726eee6ee78a0baf166ef96", "28b36c2c326ccc11e726eee6ee78a0baf166ef96", "37b36c2c326ccc11e726eee6ee78a0baf166ef96", "46b36c2c326ccc11e726eee6ee78a0baf166ef96", } index := NewTruncIndex(ids) index.Iterate(func(targetId string) { for _, id := range ids { if targetId == id { return } } t.Fatalf("An unknown ID '%s'", targetId) }) } func assertIndexGet(t *testing.T, index *TruncIndex, input, expectedResult string, expectError bool) { if result, err := index.Get(input); err != nil && !expectError { t.Fatalf("Unexpected error getting '%s': %s", input, err) } else if err == nil && expectError { t.Fatalf("Getting '%s' should return an error, not '%s'", input, result) } else if result != expectedResult { t.Fatalf("Getting '%s' returned '%s' instead of '%s'", input, result, expectedResult) } } func BenchmarkTruncIndexAdd100(b *testing.B) { var testSet []string for i := 0; i < 100; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexAdd250(b *testing.B) { var testSet []string for i := 0; i < 250; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexAdd500(b *testing.B) { var testSet []string for i := 0; i < 500; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexGet100(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 100; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexGet250(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 250; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexGet500(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 500; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexDelete100(b *testing.B) { var testSet []string for i := 0; i < 100; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } b.StartTimer() for _, id := range testSet { if err := index.Delete(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexDelete250(b *testing.B) { var testSet []string for i := 0; i < 250; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } b.StartTimer() for _, id := range testSet { if err := index.Delete(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexDelete500(b *testing.B) { var testSet []string for i := 0; i < 500; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { b.StopTimer() index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } b.StartTimer() for _, id := range testSet { if err := index.Delete(id); err != nil { b.Fatal(err) } } } } func BenchmarkTruncIndexNew100(b *testing.B) { var testSet []string for i := 0; i < 100; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { NewTruncIndex(testSet) } } func BenchmarkTruncIndexNew250(b *testing.B) { var testSet []string for i := 0; i < 250; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { NewTruncIndex(testSet) } } func BenchmarkTruncIndexNew500(b *testing.B) { var testSet []string for i := 0; i < 500; i++ { testSet = append(testSet, stringid.GenerateNonCryptoID()) } b.ResetTimer() for i := 0; i < b.N; i++ { NewTruncIndex(testSet) } } func BenchmarkTruncIndexAddGet100(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 500; i++ { id := stringid.GenerateNonCryptoID() testSet = append(testSet, id) l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexAddGet250(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 500; i++ { id := stringid.GenerateNonCryptoID() testSet = append(testSet, id) l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } } func BenchmarkTruncIndexAddGet500(b *testing.B) { var testSet []string var testKeys []string for i := 0; i < 500; i++ { id := stringid.GenerateNonCryptoID() testSet = append(testSet, id) l := rand.Intn(12) + 12 testKeys = append(testKeys, id[:l]) } b.ResetTimer() for i := 0; i < b.N; i++ { index := NewTruncIndex([]string{}) for _, id := range testSet { if err := index.Add(id); err != nil { b.Fatal(err) } } for _, id := range testKeys { if res, err := index.Get(id); err != nil { b.Fatal(res, err) } } } }
vlajos/docker
pkg/truncindex/truncindex_test.go
GO
apache-2.0
10,308
// Platform: browser // c517ca811b4948b630e0b74dbae6c9637939da24 /* 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. */ ;(function() { var PLATFORM_VERSION_BUILD_LABEL = '4.1.0'; // file: src/scripts/require.js /*jshint -W079 */ /*jshint -W020 */ var require, define; (function () { var modules = {}, // Stack of moduleIds currently being built. requireStack = [], // Map of module ID -> index into requireStack of modules currently being built. inProgressModules = {}, SEPARATOR = "."; function build(module) { var factory = module.factory, localRequire = function (id) { var resultantId = id; //Its a relative path, so lop off the last portion and add the id (minus "./") if (id.charAt(0) === ".") { resultantId = module.id.slice(0, module.id.lastIndexOf(SEPARATOR)) + SEPARATOR + id.slice(2); } return require(resultantId); }; module.exports = {}; delete module.factory; factory(localRequire, module.exports, module); return module.exports; } require = function (id) { if (!modules[id]) { throw "module " + id + " not found"; } else if (id in inProgressModules) { var cycle = requireStack.slice(inProgressModules[id]).join('->') + '->' + id; throw "Cycle in require graph: " + cycle; } if (modules[id].factory) { try { inProgressModules[id] = requireStack.length; requireStack.push(id); return build(modules[id]); } finally { delete inProgressModules[id]; requireStack.pop(); } } return modules[id].exports; }; define = function (id, factory) { if (modules[id]) { throw "module " + id + " already defined"; } modules[id] = { id: id, factory: factory }; }; define.remove = function (id) { delete modules[id]; }; define.moduleMap = modules; })(); //Export for use in node if (typeof module === "object" && typeof require === "function") { module.exports.require = require; module.exports.define = define; } // file: src/cordova.js define("cordova", function(require, exports, module) { // Workaround for Windows 10 in hosted environment case // http://www.w3.org/html/wg/drafts/html/master/browsers.html#named-access-on-the-window-object if (window.cordova && !(window.cordova instanceof HTMLElement)) { throw new Error("cordova already defined"); } var channel = require('cordova/channel'); var platform = require('cordova/platform'); /** * Intercept calls to addEventListener + removeEventListener and handle deviceready, * resume, and pause events. */ var m_document_addEventListener = document.addEventListener; var m_document_removeEventListener = document.removeEventListener; var m_window_addEventListener = window.addEventListener; var m_window_removeEventListener = window.removeEventListener; /** * Houses custom event handlers to intercept on document + window event listeners. */ var documentEventHandlers = {}, windowEventHandlers = {}; document.addEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); if (typeof documentEventHandlers[e] != 'undefined') { documentEventHandlers[e].subscribe(handler); } else { m_document_addEventListener.call(document, evt, handler, capture); } }; window.addEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); if (typeof windowEventHandlers[e] != 'undefined') { windowEventHandlers[e].subscribe(handler); } else { m_window_addEventListener.call(window, evt, handler, capture); } }; document.removeEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); // If unsubscribing from an event that is handled by a plugin if (typeof documentEventHandlers[e] != "undefined") { documentEventHandlers[e].unsubscribe(handler); } else { m_document_removeEventListener.call(document, evt, handler, capture); } }; window.removeEventListener = function(evt, handler, capture) { var e = evt.toLowerCase(); // If unsubscribing from an event that is handled by a plugin if (typeof windowEventHandlers[e] != "undefined") { windowEventHandlers[e].unsubscribe(handler); } else { m_window_removeEventListener.call(window, evt, handler, capture); } }; function createEvent(type, data) { var event = document.createEvent('Events'); event.initEvent(type, false, false); if (data) { for (var i in data) { if (data.hasOwnProperty(i)) { event[i] = data[i]; } } } return event; } var cordova = { define:define, require:require, version:PLATFORM_VERSION_BUILD_LABEL, platformVersion:PLATFORM_VERSION_BUILD_LABEL, platformId:platform.id, /** * Methods to add/remove your own addEventListener hijacking on document + window. */ addWindowEventHandler:function(event) { return (windowEventHandlers[event] = channel.create(event)); }, addStickyDocumentEventHandler:function(event) { return (documentEventHandlers[event] = channel.createSticky(event)); }, addDocumentEventHandler:function(event) { return (documentEventHandlers[event] = channel.create(event)); }, removeWindowEventHandler:function(event) { delete windowEventHandlers[event]; }, removeDocumentEventHandler:function(event) { delete documentEventHandlers[event]; }, /** * Retrieve original event handlers that were replaced by Cordova * * @return object */ getOriginalHandlers: function() { return {'document': {'addEventListener': m_document_addEventListener, 'removeEventListener': m_document_removeEventListener}, 'window': {'addEventListener': m_window_addEventListener, 'removeEventListener': m_window_removeEventListener}}; }, /** * Method to fire event from native code * bNoDetach is required for events which cause an exception which needs to be caught in native code */ fireDocumentEvent: function(type, data, bNoDetach) { var evt = createEvent(type, data); if (typeof documentEventHandlers[type] != 'undefined') { if( bNoDetach ) { documentEventHandlers[type].fire(evt); } else { setTimeout(function() { // Fire deviceready on listeners that were registered before cordova.js was loaded. if (type == 'deviceready') { document.dispatchEvent(evt); } documentEventHandlers[type].fire(evt); }, 0); } } else { document.dispatchEvent(evt); } }, fireWindowEvent: function(type, data) { var evt = createEvent(type,data); if (typeof windowEventHandlers[type] != 'undefined') { setTimeout(function() { windowEventHandlers[type].fire(evt); }, 0); } else { window.dispatchEvent(evt); } }, /** * Plugin callback mechanism. */ // Randomize the starting callbackId to avoid collisions after refreshing or navigating. // This way, it's very unlikely that any new callback would get the same callbackId as an old callback. callbackId: Math.floor(Math.random() * 2000000000), callbacks: {}, callbackStatus: { NO_RESULT: 0, OK: 1, CLASS_NOT_FOUND_EXCEPTION: 2, ILLEGAL_ACCESS_EXCEPTION: 3, INSTANTIATION_EXCEPTION: 4, MALFORMED_URL_EXCEPTION: 5, IO_EXCEPTION: 6, INVALID_ACTION: 7, JSON_EXCEPTION: 8, ERROR: 9 }, /** * Called by native code when returning successful result from an action. */ callbackSuccess: function(callbackId, args) { cordova.callbackFromNative(callbackId, true, args.status, [args.message], args.keepCallback); }, /** * Called by native code when returning error result from an action. */ callbackError: function(callbackId, args) { // TODO: Deprecate callbackSuccess and callbackError in favour of callbackFromNative. // Derive success from status. cordova.callbackFromNative(callbackId, false, args.status, [args.message], args.keepCallback); }, /** * Called by native code when returning the result from an action. */ callbackFromNative: function(callbackId, isSuccess, status, args, keepCallback) { try { var callback = cordova.callbacks[callbackId]; if (callback) { if (isSuccess && status == cordova.callbackStatus.OK) { callback.success && callback.success.apply(null, args); } else if (!isSuccess) { callback.fail && callback.fail.apply(null, args); } /* else Note, this case is intentionally not caught. this can happen if isSuccess is true, but callbackStatus is NO_RESULT which is used to remove a callback from the list without calling the callbacks typically keepCallback is false in this case */ // Clear callback if not expecting any more results if (!keepCallback) { delete cordova.callbacks[callbackId]; } } } catch (err) { var msg = "Error in " + (isSuccess ? "Success" : "Error") + " callbackId: " + callbackId + " : " + err; console && console.log && console.log(msg); cordova.fireWindowEvent("cordovacallbackerror", { 'message': msg }); throw err; } }, addConstructor: function(func) { channel.onCordovaReady.subscribe(function() { try { func(); } catch(e) { console.log("Failed to run constructor: " + e); } }); } }; module.exports = cordova; }); // file: src/common/argscheck.js define("cordova/argscheck", function(require, exports, module) { var utils = require('cordova/utils'); var moduleExports = module.exports; var typeMap = { 'A': 'Array', 'D': 'Date', 'N': 'Number', 'S': 'String', 'F': 'Function', 'O': 'Object' }; function extractParamName(callee, argIndex) { return (/.*?\((.*?)\)/).exec(callee)[1].split(', ')[argIndex]; } function checkArgs(spec, functionName, args, opt_callee) { if (!moduleExports.enableChecks) { return; } var errMsg = null; var typeName; for (var i = 0; i < spec.length; ++i) { var c = spec.charAt(i), cUpper = c.toUpperCase(), arg = args[i]; // Asterix means allow anything. if (c == '*') { continue; } typeName = utils.typeName(arg); if ((arg === null || arg === undefined) && c == cUpper) { continue; } if (typeName != typeMap[cUpper]) { errMsg = 'Expected ' + typeMap[cUpper]; break; } } if (errMsg) { errMsg += ', but got ' + typeName + '.'; errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg; // Don't log when running unit tests. if (typeof jasmine == 'undefined') { console.error(errMsg); } throw TypeError(errMsg); } } function getValue(value, defaultValue) { return value === undefined ? defaultValue : value; } moduleExports.checkArgs = checkArgs; moduleExports.getValue = getValue; moduleExports.enableChecks = true; }); // file: src/common/base64.js define("cordova/base64", function(require, exports, module) { var base64 = exports; base64.fromArrayBuffer = function(arrayBuffer) { var array = new Uint8Array(arrayBuffer); return uint8ToBase64(array); }; base64.toArrayBuffer = function(str) { var decodedStr = typeof atob != 'undefined' ? atob(str) : new Buffer(str,'base64').toString('binary'); var arrayBuffer = new ArrayBuffer(decodedStr.length); var array = new Uint8Array(arrayBuffer); for (var i=0, len=decodedStr.length; i < len; i++) { array[i] = decodedStr.charCodeAt(i); } return arrayBuffer; }; //------------------------------------------------------------------------------ /* This code is based on the performance tests at http://jsperf.com/b64tests * This 12-bit-at-a-time algorithm was the best performing version on all * platforms tested. */ var b64_6bit = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var b64_12bit; var b64_12bitTable = function() { b64_12bit = []; for (var i=0; i<64; i++) { for (var j=0; j<64; j++) { b64_12bit[i*64+j] = b64_6bit[i] + b64_6bit[j]; } } b64_12bitTable = function() { return b64_12bit; }; return b64_12bit; }; function uint8ToBase64(rawData) { var numBytes = rawData.byteLength; var output=""; var segment; var table = b64_12bitTable(); for (var i=0;i<numBytes-2;i+=3) { segment = (rawData[i] << 16) + (rawData[i+1] << 8) + rawData[i+2]; output += table[segment >> 12]; output += table[segment & 0xfff]; } if (numBytes - i == 2) { segment = (rawData[i] << 16) + (rawData[i+1] << 8); output += table[segment >> 12]; output += b64_6bit[(segment & 0xfff) >> 6]; output += '='; } else if (numBytes - i == 1) { segment = (rawData[i] << 16); output += table[segment >> 12]; output += '=='; } return output; } }); // file: src/common/builder.js define("cordova/builder", function(require, exports, module) { var utils = require('cordova/utils'); function each(objects, func, context) { for (var prop in objects) { if (objects.hasOwnProperty(prop)) { func.apply(context, [objects[prop], prop]); } } } function clobber(obj, key, value) { exports.replaceHookForTesting(obj, key); var needsProperty = false; try { obj[key] = value; } catch (e) { needsProperty = true; } // Getters can only be overridden by getters. if (needsProperty || obj[key] !== value) { utils.defineGetter(obj, key, function() { return value; }); } } function assignOrWrapInDeprecateGetter(obj, key, value, message) { if (message) { utils.defineGetter(obj, key, function() { console.log(message); delete obj[key]; clobber(obj, key, value); return value; }); } else { clobber(obj, key, value); } } function include(parent, objects, clobber, merge) { each(objects, function (obj, key) { try { var result = obj.path ? require(obj.path) : {}; if (clobber) { // Clobber if it doesn't exist. if (typeof parent[key] === 'undefined') { assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } else if (typeof obj.path !== 'undefined') { // If merging, merge properties onto parent, otherwise, clobber. if (merge) { recursiveMerge(parent[key], result); } else { assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } } result = parent[key]; } else { // Overwrite if not currently defined. if (typeof parent[key] == 'undefined') { assignOrWrapInDeprecateGetter(parent, key, result, obj.deprecated); } else { // Set result to what already exists, so we can build children into it if they exist. result = parent[key]; } } if (obj.children) { include(result, obj.children, clobber, merge); } } catch(e) { utils.alert('Exception building Cordova JS globals: ' + e + ' for key "' + key + '"'); } }); } /** * Merge properties from one object onto another recursively. Properties from * the src object will overwrite existing target property. * * @param target Object to merge properties into. * @param src Object to merge properties from. */ function recursiveMerge(target, src) { for (var prop in src) { if (src.hasOwnProperty(prop)) { if (target.prototype && target.prototype.constructor === target) { // If the target object is a constructor override off prototype. clobber(target.prototype, prop, src[prop]); } else { if (typeof src[prop] === 'object' && typeof target[prop] === 'object') { recursiveMerge(target[prop], src[prop]); } else { clobber(target, prop, src[prop]); } } } } } exports.buildIntoButDoNotClobber = function(objects, target) { include(target, objects, false, false); }; exports.buildIntoAndClobber = function(objects, target) { include(target, objects, true, false); }; exports.buildIntoAndMerge = function(objects, target) { include(target, objects, true, true); }; exports.recursiveMerge = recursiveMerge; exports.assignOrWrapInDeprecateGetter = assignOrWrapInDeprecateGetter; exports.replaceHookForTesting = function() {}; }); // file: src/common/channel.js define("cordova/channel", function(require, exports, module) { var utils = require('cordova/utils'), nextGuid = 1; /** * Custom pub-sub "channel" that can have functions subscribed to it * This object is used to define and control firing of events for * cordova initialization, as well as for custom events thereafter. * * The order of events during page load and Cordova startup is as follows: * * onDOMContentLoaded* Internal event that is received when the web page is loaded and parsed. * onNativeReady* Internal event that indicates the Cordova native side is ready. * onCordovaReady* Internal event fired when all Cordova JavaScript objects have been created. * onDeviceReady* User event fired to indicate that Cordova is ready * onResume User event fired to indicate a start/resume lifecycle event * onPause User event fired to indicate a pause lifecycle event * * The events marked with an * are sticky. Once they have fired, they will stay in the fired state. * All listeners that subscribe after the event is fired will be executed right away. * * The only Cordova events that user code should register for are: * deviceready Cordova native code is initialized and Cordova APIs can be called from JavaScript * pause App has moved to background * resume App has returned to foreground * * Listeners can be registered as: * document.addEventListener("deviceready", myDeviceReadyListener, false); * document.addEventListener("resume", myResumeListener, false); * document.addEventListener("pause", myPauseListener, false); * * The DOM lifecycle events should be used for saving and restoring state * window.onload * window.onunload * */ /** * Channel * @constructor * @param type String the channel name */ var Channel = function(type, sticky) { this.type = type; // Map of guid -> function. this.handlers = {}; // 0 = Non-sticky, 1 = Sticky non-fired, 2 = Sticky fired. this.state = sticky ? 1 : 0; // Used in sticky mode to remember args passed to fire(). this.fireArgs = null; // Used by onHasSubscribersChange to know if there are any listeners. this.numHandlers = 0; // Function that is called when the first listener is subscribed, or when // the last listener is unsubscribed. this.onHasSubscribersChange = null; }, channel = { /** * Calls the provided function only after all of the channels specified * have been fired. All channels must be sticky channels. */ join: function(h, c) { var len = c.length, i = len, f = function() { if (!(--i)) h(); }; for (var j=0; j<len; j++) { if (c[j].state === 0) { throw Error('Can only use join with sticky channels.'); } c[j].subscribe(f); } if (!len) h(); }, create: function(type) { return channel[type] = new Channel(type, false); }, createSticky: function(type) { return channel[type] = new Channel(type, true); }, /** * cordova Channels that must fire before "deviceready" is fired. */ deviceReadyChannelsArray: [], deviceReadyChannelsMap: {}, /** * Indicate that a feature needs to be initialized before it is ready to be used. * This holds up Cordova's "deviceready" event until the feature has been initialized * and Cordova.initComplete(feature) is called. * * @param feature {String} The unique feature name */ waitForInitialization: function(feature) { if (feature) { var c = channel[feature] || this.createSticky(feature); this.deviceReadyChannelsMap[feature] = c; this.deviceReadyChannelsArray.push(c); } }, /** * Indicate that initialization code has completed and the feature is ready to be used. * * @param feature {String} The unique feature name */ initializationComplete: function(feature) { var c = this.deviceReadyChannelsMap[feature]; if (c) { c.fire(); } } }; function forceFunction(f) { if (typeof f != 'function') throw "Function required as first argument!"; } /** * Subscribes the given function to the channel. Any time that * Channel.fire is called so too will the function. * Optionally specify an execution context for the function * and a guid that can be used to stop subscribing to the channel. * Returns the guid. */ Channel.prototype.subscribe = function(f, c) { // need a function to call forceFunction(f); if (this.state == 2) { f.apply(c || this, this.fireArgs); return; } var func = f, guid = f.observer_guid; if (typeof c == "object") { func = utils.close(c, f); } if (!guid) { // first time any channel has seen this subscriber guid = '' + nextGuid++; } func.observer_guid = guid; f.observer_guid = guid; // Don't add the same handler more than once. if (!this.handlers[guid]) { this.handlers[guid] = func; this.numHandlers++; if (this.numHandlers == 1) { this.onHasSubscribersChange && this.onHasSubscribersChange(); } } }; /** * Unsubscribes the function with the given guid from the channel. */ Channel.prototype.unsubscribe = function(f) { // need a function to unsubscribe forceFunction(f); var guid = f.observer_guid, handler = this.handlers[guid]; if (handler) { delete this.handlers[guid]; this.numHandlers--; if (this.numHandlers === 0) { this.onHasSubscribersChange && this.onHasSubscribersChange(); } } }; /** * Calls all functions subscribed to this channel. */ Channel.prototype.fire = function(e) { var fail = false, fireArgs = Array.prototype.slice.call(arguments); // Apply stickiness. if (this.state == 1) { this.state = 2; this.fireArgs = fireArgs; } if (this.numHandlers) { // Copy the values first so that it is safe to modify it from within // callbacks. var toCall = []; for (var item in this.handlers) { toCall.push(this.handlers[item]); } for (var i = 0; i < toCall.length; ++i) { toCall[i].apply(this, fireArgs); } if (this.state == 2 && this.numHandlers) { this.numHandlers = 0; this.handlers = {}; this.onHasSubscribersChange && this.onHasSubscribersChange(); } } }; // defining them here so they are ready super fast! // DOM event that is received when the web page is loaded and parsed. channel.createSticky('onDOMContentLoaded'); // Event to indicate the Cordova native side is ready. channel.createSticky('onNativeReady'); // Event to indicate that all Cordova JavaScript objects have been created // and it's time to run plugin constructors. channel.createSticky('onCordovaReady'); // Event to indicate that all automatically loaded JS plugins are loaded and ready. // FIXME remove this channel.createSticky('onPluginsReady'); // Event to indicate that Cordova is ready channel.createSticky('onDeviceReady'); // Event to indicate a resume lifecycle event channel.create('onResume'); // Event to indicate a pause lifecycle event channel.create('onPause'); // Channels that must fire before "deviceready" is fired. channel.waitForInitialization('onCordovaReady'); channel.waitForInitialization('onDOMContentLoaded'); module.exports = channel; }); // file: e:/cordova/cordova-browser/cordova-js-src/confighelper.js define("cordova/confighelper", function(require, exports, module) { var config; function Config(xhr) { function loadPreferences(xhr) { var parser = new DOMParser(); var doc = parser.parseFromString(xhr.responseText, "application/xml"); var preferences = doc.getElementsByTagName("preference"); return Array.prototype.slice.call(preferences); } this.xhr = xhr; this.preferences = loadPreferences(this.xhr); } function readConfig(success, error) { var xhr; if(typeof config != 'undefined') { success(config); } function fail(msg) { console.error(msg); if(error) { error(msg); } } var xhrStatusChangeHandler = function() { if (xhr.readyState == 4) { if (xhr.status == 200 || xhr.status == 304 || xhr.status === 0 /* file:// */) { config = new Config(xhr); success(config); } else { fail('[Browser][cordova.js][xhrStatusChangeHandler] Could not XHR config.xml: ' + xhr.statusText); } } }; if ("ActiveXObject" in window) { // Needed for XHR-ing via file:// protocol in IE xhr = new window.ActiveXObject("MSXML2.XMLHTTP"); xhr.onreadystatechange = xhrStatusChangeHandler; } else { xhr = new XMLHttpRequest(); xhr.addEventListener("load", xhrStatusChangeHandler); } try { xhr.open("get", "/config.xml", true); xhr.send(); } catch(e) { fail('[Browser][cordova.js][readConfig] Could not XHR config.xml: ' + JSON.stringify(e)); } } /** * Reads a preference value from config.xml. * Returns preference value or undefined if it does not exist. * @param {String} preferenceName Preference name to read */ Config.prototype.getPreferenceValue = function getPreferenceValue(preferenceName) { var preferenceItem = this.preferences && this.preferences.filter(function(item) { return item.attributes.name && item.attributes.name.value === preferenceName; }); if(preferenceItem && preferenceItem[0] && preferenceItem[0].attributes && preferenceItem[0].attributes.value) { return preferenceItem[0].attributes.value.value; } }; exports.readConfig = readConfig; }); // file: e:/cordova/cordova-browser/cordova-js-src/exec.js define("cordova/exec", function(require, exports, module) { /*jslint sloppy:true, plusplus:true*/ /*global require, module, console */ var cordova = require('cordova'); var execProxy = require('cordova/exec/proxy'); /** * Execute a cordova command. It is up to the native side whether this action * is synchronous or asynchronous. The native side can return: * Synchronous: PluginResult object as a JSON string * Asynchronous: Empty string "" * If async, the native side will cordova.callbackSuccess or cordova.callbackError, * depending upon the result of the action. * * @param {Function} success The success callback * @param {Function} fail The fail callback * @param {String} service The name of the service to use * @param {String} action Action to be run in cordova * @param {String[]} [args] Zero or more arguments to pass to the method */ module.exports = function (success, fail, service, action, args) { var proxy = execProxy.get(service, action); args = args || []; if (proxy) { var callbackId = service + cordova.callbackId++; if (typeof success === "function" || typeof fail === "function") { cordova.callbacks[callbackId] = {success: success, fail: fail}; } try { // callbackOptions param represents additional optional parameters command could pass back, like keepCallback or // custom callbackId, for example {callbackId: id, keepCallback: true, status: cordova.callbackStatus.JSON_EXCEPTION } var onSuccess = function (result, callbackOptions) { callbackOptions = callbackOptions || {}; var callbackStatus; // covering both undefined and null. // strict null comparison was causing callbackStatus to be undefined // and then no callback was called because of the check in cordova.callbackFromNative // see CB-8996 Mobilespec app hang on windows if (callbackOptions.status !== undefined && callbackOptions.status !== null) { callbackStatus = callbackOptions.status; } else { callbackStatus = cordova.callbackStatus.OK; } cordova.callbackSuccess(callbackOptions.callbackId || callbackId, { status: callbackStatus, message: result, keepCallback: callbackOptions.keepCallback || false }); }; var onError = function (err, callbackOptions) { callbackOptions = callbackOptions || {}; var callbackStatus; // covering both undefined and null. // strict null comparison was causing callbackStatus to be undefined // and then no callback was called because of the check in cordova.callbackFromNative // note: status can be 0 if (callbackOptions.status !== undefined && callbackOptions.status !== null) { callbackStatus = callbackOptions.status; } else { callbackStatus = cordova.callbackStatus.OK; } cordova.callbackError(callbackOptions.callbackId || callbackId, { status: callbackStatus, message: err, keepCallback: callbackOptions.keepCallback || false }); }; proxy(onSuccess, onError, args); } catch (e) { console.log("Exception calling native with command :: " + service + " :: " + action + " ::exception=" + e); } } else { console.log("Error: exec proxy not found for :: " + service + " :: " + action); if(typeof fail === "function" ) { fail("Missing Command Error"); } } }; }); // file: src/common/exec/proxy.js define("cordova/exec/proxy", function(require, exports, module) { // internal map of proxy function var CommandProxyMap = {}; module.exports = { // example: cordova.commandProxy.add("Accelerometer",{getCurrentAcceleration: function(successCallback, errorCallback, options) {...},...); add:function(id,proxyObj) { console.log("adding proxy for " + id); CommandProxyMap[id] = proxyObj; return proxyObj; }, // cordova.commandProxy.remove("Accelerometer"); remove:function(id) { var proxy = CommandProxyMap[id]; delete CommandProxyMap[id]; CommandProxyMap[id] = null; return proxy; }, get:function(service,action) { return ( CommandProxyMap[service] ? CommandProxyMap[service][action] : null ); } }; }); // file: src/common/init.js define("cordova/init", function(require, exports, module) { var channel = require('cordova/channel'); var cordova = require('cordova'); var modulemapper = require('cordova/modulemapper'); var platform = require('cordova/platform'); var pluginloader = require('cordova/pluginloader'); var utils = require('cordova/utils'); var platformInitChannelsArray = [channel.onNativeReady, channel.onPluginsReady]; function logUnfiredChannels(arr) { for (var i = 0; i < arr.length; ++i) { if (arr[i].state != 2) { console.log('Channel not fired: ' + arr[i].type); } } } window.setTimeout(function() { if (channel.onDeviceReady.state != 2) { console.log('deviceready has not fired after 5 seconds.'); logUnfiredChannels(platformInitChannelsArray); logUnfiredChannels(channel.deviceReadyChannelsArray); } }, 5000); // Replace navigator before any modules are required(), to ensure it happens as soon as possible. // We replace it so that properties that can't be clobbered can instead be overridden. function replaceNavigator(origNavigator) { var CordovaNavigator = function() {}; CordovaNavigator.prototype = origNavigator; var newNavigator = new CordovaNavigator(); // This work-around really only applies to new APIs that are newer than Function.bind. // Without it, APIs such as getGamepads() break. if (CordovaNavigator.bind) { for (var key in origNavigator) { if (typeof origNavigator[key] == 'function') { newNavigator[key] = origNavigator[key].bind(origNavigator); } else { (function(k) { utils.defineGetterSetter(newNavigator,key,function() { return origNavigator[k]; }); })(key); } } } return newNavigator; } if (window.navigator) { window.navigator = replaceNavigator(window.navigator); } if (!window.console) { window.console = { log: function(){} }; } if (!window.console.warn) { window.console.warn = function(msg) { this.log("warn: " + msg); }; } // Register pause, resume and deviceready channels as events on document. channel.onPause = cordova.addDocumentEventHandler('pause'); channel.onResume = cordova.addDocumentEventHandler('resume'); channel.onActivated = cordova.addDocumentEventHandler('activated'); channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready'); // Listen for DOMContentLoaded and notify our channel subscribers. if (document.readyState == 'complete' || document.readyState == 'interactive') { channel.onDOMContentLoaded.fire(); } else { document.addEventListener('DOMContentLoaded', function() { channel.onDOMContentLoaded.fire(); }, false); } // _nativeReady is global variable that the native side can set // to signify that the native code is ready. It is a global since // it may be called before any cordova JS is ready. if (window._nativeReady) { channel.onNativeReady.fire(); } modulemapper.clobbers('cordova', 'cordova'); modulemapper.clobbers('cordova/exec', 'cordova.exec'); modulemapper.clobbers('cordova/exec', 'Cordova.exec'); // Call the platform-specific initialization. platform.bootstrap && platform.bootstrap(); // Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js. // The delay allows the attached modules to be defined before the plugin loader looks for them. setTimeout(function() { pluginloader.load(function() { channel.onPluginsReady.fire(); }); }, 0); /** * Create all cordova objects once native side is ready. */ channel.join(function() { modulemapper.mapModules(window); platform.initialize && platform.initialize(); // Fire event to notify that all objects are created channel.onCordovaReady.fire(); // Fire onDeviceReady event once page has fully loaded, all // constructors have run and cordova info has been received from native // side. channel.join(function() { require('cordova').fireDocumentEvent('deviceready'); }, channel.deviceReadyChannelsArray); }, platformInitChannelsArray); }); // file: src/common/init_b.js define("cordova/init_b", function(require, exports, module) { var channel = require('cordova/channel'); var cordova = require('cordova'); var modulemapper = require('cordova/modulemapper'); var platform = require('cordova/platform'); var pluginloader = require('cordova/pluginloader'); var utils = require('cordova/utils'); var platformInitChannelsArray = [channel.onDOMContentLoaded, channel.onNativeReady, channel.onPluginsReady]; // setting exec cordova.exec = require('cordova/exec'); function logUnfiredChannels(arr) { for (var i = 0; i < arr.length; ++i) { if (arr[i].state != 2) { console.log('Channel not fired: ' + arr[i].type); } } } window.setTimeout(function() { if (channel.onDeviceReady.state != 2) { console.log('deviceready has not fired after 5 seconds.'); logUnfiredChannels(platformInitChannelsArray); logUnfiredChannels(channel.deviceReadyChannelsArray); } }, 5000); // Replace navigator before any modules are required(), to ensure it happens as soon as possible. // We replace it so that properties that can't be clobbered can instead be overridden. function replaceNavigator(origNavigator) { var CordovaNavigator = function() {}; CordovaNavigator.prototype = origNavigator; var newNavigator = new CordovaNavigator(); // This work-around really only applies to new APIs that are newer than Function.bind. // Without it, APIs such as getGamepads() break. if (CordovaNavigator.bind) { for (var key in origNavigator) { if (typeof origNavigator[key] == 'function') { newNavigator[key] = origNavigator[key].bind(origNavigator); } else { (function(k) { utils.defineGetterSetter(newNavigator,key,function() { return origNavigator[k]; }); })(key); } } } return newNavigator; } if (window.navigator) { window.navigator = replaceNavigator(window.navigator); } if (!window.console) { window.console = { log: function(){} }; } if (!window.console.warn) { window.console.warn = function(msg) { this.log("warn: " + msg); }; } // Register pause, resume and deviceready channels as events on document. channel.onPause = cordova.addDocumentEventHandler('pause'); channel.onResume = cordova.addDocumentEventHandler('resume'); channel.onActivated = cordova.addDocumentEventHandler('activated'); channel.onDeviceReady = cordova.addStickyDocumentEventHandler('deviceready'); // Listen for DOMContentLoaded and notify our channel subscribers. if (document.readyState == 'complete' || document.readyState == 'interactive') { channel.onDOMContentLoaded.fire(); } else { document.addEventListener('DOMContentLoaded', function() { channel.onDOMContentLoaded.fire(); }, false); } // _nativeReady is global variable that the native side can set // to signify that the native code is ready. It is a global since // it may be called before any cordova JS is ready. if (window._nativeReady) { channel.onNativeReady.fire(); } // Call the platform-specific initialization. platform.bootstrap && platform.bootstrap(); // Wrap in a setTimeout to support the use-case of having plugin JS appended to cordova.js. // The delay allows the attached modules to be defined before the plugin loader looks for them. setTimeout(function() { pluginloader.load(function() { channel.onPluginsReady.fire(); }); }, 0); /** * Create all cordova objects once native side is ready. */ channel.join(function() { modulemapper.mapModules(window); platform.initialize && platform.initialize(); // Fire event to notify that all objects are created channel.onCordovaReady.fire(); // Fire onDeviceReady event once page has fully loaded, all // constructors have run and cordova info has been received from native // side. channel.join(function() { require('cordova').fireDocumentEvent('deviceready'); }, channel.deviceReadyChannelsArray); }, platformInitChannelsArray); }); // file: src/common/modulemapper.js define("cordova/modulemapper", function(require, exports, module) { var builder = require('cordova/builder'), moduleMap = define.moduleMap, symbolList, deprecationMap; exports.reset = function() { symbolList = []; deprecationMap = {}; }; function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) { if (!(moduleName in moduleMap)) { throw new Error('Module ' + moduleName + ' does not exist.'); } symbolList.push(strategy, moduleName, symbolPath); if (opt_deprecationMessage) { deprecationMap[symbolPath] = opt_deprecationMessage; } } // Note: Android 2.3 does have Function.bind(). exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('c', moduleName, symbolPath, opt_deprecationMessage); }; exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('m', moduleName, symbolPath, opt_deprecationMessage); }; exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('d', moduleName, symbolPath, opt_deprecationMessage); }; exports.runs = function(moduleName) { addEntry('r', moduleName, null); }; function prepareNamespace(symbolPath, context) { if (!symbolPath) { return context; } var parts = symbolPath.split('.'); var cur = context; for (var i = 0, part; part = parts[i]; ++i) { cur = cur[part] = cur[part] || {}; } return cur; } exports.mapModules = function(context) { var origSymbols = {}; context.CDV_origSymbols = origSymbols; for (var i = 0, len = symbolList.length; i < len; i += 3) { var strategy = symbolList[i]; var moduleName = symbolList[i + 1]; var module = require(moduleName); // <runs/> if (strategy == 'r') { continue; } var symbolPath = symbolList[i + 2]; var lastDot = symbolPath.lastIndexOf('.'); var namespace = symbolPath.substr(0, lastDot); var lastName = symbolPath.substr(lastDot + 1); var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null; var parentObj = prepareNamespace(namespace, context); var target = parentObj[lastName]; if (strategy == 'm' && target) { builder.recursiveMerge(target, module); } else if ((strategy == 'd' && !target) || (strategy != 'd')) { if (!(symbolPath in origSymbols)) { origSymbols[symbolPath] = target; } builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg); } } }; exports.getOriginalSymbol = function(context, symbolPath) { var origSymbols = context.CDV_origSymbols; if (origSymbols && (symbolPath in origSymbols)) { return origSymbols[symbolPath]; } var parts = symbolPath.split('.'); var obj = context; for (var i = 0; i < parts.length; ++i) { obj = obj && obj[parts[i]]; } return obj; }; exports.reset(); }); // file: src/common/modulemapper_b.js define("cordova/modulemapper_b", function(require, exports, module) { var builder = require('cordova/builder'), symbolList = [], deprecationMap; exports.reset = function() { symbolList = []; deprecationMap = {}; }; function addEntry(strategy, moduleName, symbolPath, opt_deprecationMessage) { symbolList.push(strategy, moduleName, symbolPath); if (opt_deprecationMessage) { deprecationMap[symbolPath] = opt_deprecationMessage; } } // Note: Android 2.3 does have Function.bind(). exports.clobbers = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('c', moduleName, symbolPath, opt_deprecationMessage); }; exports.merges = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('m', moduleName, symbolPath, opt_deprecationMessage); }; exports.defaults = function(moduleName, symbolPath, opt_deprecationMessage) { addEntry('d', moduleName, symbolPath, opt_deprecationMessage); }; exports.runs = function(moduleName) { addEntry('r', moduleName, null); }; function prepareNamespace(symbolPath, context) { if (!symbolPath) { return context; } var parts = symbolPath.split('.'); var cur = context; for (var i = 0, part; part = parts[i]; ++i) { cur = cur[part] = cur[part] || {}; } return cur; } exports.mapModules = function(context) { var origSymbols = {}; context.CDV_origSymbols = origSymbols; for (var i = 0, len = symbolList.length; i < len; i += 3) { var strategy = symbolList[i]; var moduleName = symbolList[i + 1]; var module = require(moduleName); // <runs/> if (strategy == 'r') { continue; } var symbolPath = symbolList[i + 2]; var lastDot = symbolPath.lastIndexOf('.'); var namespace = symbolPath.substr(0, lastDot); var lastName = symbolPath.substr(lastDot + 1); var deprecationMsg = symbolPath in deprecationMap ? 'Access made to deprecated symbol: ' + symbolPath + '. ' + deprecationMsg : null; var parentObj = prepareNamespace(namespace, context); var target = parentObj[lastName]; if (strategy == 'm' && target) { builder.recursiveMerge(target, module); } else if ((strategy == 'd' && !target) || (strategy != 'd')) { if (!(symbolPath in origSymbols)) { origSymbols[symbolPath] = target; } builder.assignOrWrapInDeprecateGetter(parentObj, lastName, module, deprecationMsg); } } }; exports.getOriginalSymbol = function(context, symbolPath) { var origSymbols = context.CDV_origSymbols; if (origSymbols && (symbolPath in origSymbols)) { return origSymbols[symbolPath]; } var parts = symbolPath.split('.'); var obj = context; for (var i = 0; i < parts.length; ++i) { obj = obj && obj[parts[i]]; } return obj; }; exports.reset(); }); // file: e:/cordova/cordova-browser/cordova-js-src/platform.js define("cordova/platform", function(require, exports, module) { module.exports = { id: 'browser', cordovaVersion: '3.4.0', bootstrap: function() { var modulemapper = require('cordova/modulemapper'); var channel = require('cordova/channel'); modulemapper.clobbers('cordova/exec/proxy', 'cordova.commandProxy'); channel.onNativeReady.fire(); // FIXME is this the right place to clobber pause/resume? I am guessing not // FIXME pause/resume should be deprecated IN CORDOVA for pagevisiblity api document.addEventListener('webkitvisibilitychange', function() { if (document.webkitHidden) { channel.onPause.fire(); } else { channel.onResume.fire(); } }, false); // End of bootstrap } }; }); // file: src/common/pluginloader.js define("cordova/pluginloader", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); var urlutil = require('cordova/urlutil'); // Helper function to inject a <script> tag. // Exported for testing. exports.injectScript = function(url, onload, onerror) { var script = document.createElement("script"); // onload fires even when script fails loads with an error. script.onload = onload; // onerror fires for malformed URLs. script.onerror = onerror; script.src = url; document.head.appendChild(script); }; function injectIfNecessary(id, url, onload, onerror) { onerror = onerror || onload; if (id in define.moduleMap) { onload(); } else { exports.injectScript(url, function() { if (id in define.moduleMap) { onload(); } else { onerror(); } }, onerror); } } function onScriptLoadingComplete(moduleList, finishPluginLoading) { // Loop through all the plugins and then through their clobbers and merges. for (var i = 0, module; module = moduleList[i]; i++) { if (module.clobbers && module.clobbers.length) { for (var j = 0; j < module.clobbers.length; j++) { modulemapper.clobbers(module.id, module.clobbers[j]); } } if (module.merges && module.merges.length) { for (var k = 0; k < module.merges.length; k++) { modulemapper.merges(module.id, module.merges[k]); } } // Finally, if runs is truthy we want to simply require() the module. if (module.runs) { modulemapper.runs(module.id); } } finishPluginLoading(); } // Handler for the cordova_plugins.js content. // See plugman's plugin_loader.js for the details of this object. // This function is only called if the really is a plugins array that isn't empty. // Otherwise the onerror response handler will just call finishPluginLoading(). function handlePluginsObject(path, moduleList, finishPluginLoading) { // Now inject the scripts. var scriptCounter = moduleList.length; if (!scriptCounter) { finishPluginLoading(); return; } function scriptLoadedCallback() { if (!--scriptCounter) { onScriptLoadingComplete(moduleList, finishPluginLoading); } } for (var i = 0; i < moduleList.length; i++) { injectIfNecessary(moduleList[i].id, path + moduleList[i].file, scriptLoadedCallback); } } function findCordovaPath() { var path = null; var scripts = document.getElementsByTagName('script'); var term = '/cordova.js'; for (var n = scripts.length-1; n>-1; n--) { var src = scripts[n].src.replace(/\?.*$/, ''); // Strip any query param (CB-6007). if (src.indexOf(term) == (src.length - term.length)) { path = src.substring(0, src.length - term.length) + '/'; break; } } return path; } // Tries to load all plugins' js-modules. // This is an async process, but onDeviceReady is blocked on onPluginsReady. // onPluginsReady is fired when there are no plugins to load, or they are all done. exports.load = function(callback) { var pathPrefix = findCordovaPath(); if (pathPrefix === null) { console.log('Could not find cordova.js script tag. Plugin loading may fail.'); pathPrefix = ''; } injectIfNecessary('cordova/plugin_list', pathPrefix + 'cordova_plugins.js', function() { var moduleList = require("cordova/plugin_list"); handlePluginsObject(pathPrefix, moduleList, callback); }, callback); }; }); // file: src/common/pluginloader_b.js define("cordova/pluginloader_b", function(require, exports, module) { var modulemapper = require('cordova/modulemapper'); // Handler for the cordova_plugins.js content. // See plugman's plugin_loader.js for the details of this object. function handlePluginsObject(moduleList) { // if moduleList is not defined or empty, we've nothing to do if (!moduleList || !moduleList.length) { return; } // Loop through all the modules and then through their clobbers and merges. for (var i = 0, module; module = moduleList[i]; i++) { if (module.clobbers && module.clobbers.length) { for (var j = 0; j < module.clobbers.length; j++) { modulemapper.clobbers(module.id, module.clobbers[j]); } } if (module.merges && module.merges.length) { for (var k = 0; k < module.merges.length; k++) { modulemapper.merges(module.id, module.merges[k]); } } // Finally, if runs is truthy we want to simply require() the module. if (module.runs) { modulemapper.runs(module.id); } } } // Loads all plugins' js-modules. Plugin loading is syncronous in browserified bundle // but the method accepts callback to be compatible with non-browserify flow. // onDeviceReady is blocked on onPluginsReady. onPluginsReady is fired when there are // no plugins to load, or they are all done. exports.load = function(callback) { var moduleList = require("cordova/plugin_list"); handlePluginsObject(moduleList); callback(); }; }); // file: src/common/urlutil.js define("cordova/urlutil", function(require, exports, module) { /** * For already absolute URLs, returns what is passed in. * For relative URLs, converts them to absolute ones. */ exports.makeAbsolute = function makeAbsolute(url) { var anchorEl = document.createElement('a'); anchorEl.href = url; return anchorEl.href; }; }); // file: src/common/utils.js define("cordova/utils", function(require, exports, module) { var utils = exports; /** * Defines a property getter / setter for obj[key]. */ utils.defineGetterSetter = function(obj, key, getFunc, opt_setFunc) { if (Object.defineProperty) { var desc = { get: getFunc, configurable: true }; if (opt_setFunc) { desc.set = opt_setFunc; } Object.defineProperty(obj, key, desc); } else { obj.__defineGetter__(key, getFunc); if (opt_setFunc) { obj.__defineSetter__(key, opt_setFunc); } } }; /** * Defines a property getter for obj[key]. */ utils.defineGetter = utils.defineGetterSetter; utils.arrayIndexOf = function(a, item) { if (a.indexOf) { return a.indexOf(item); } var len = a.length; for (var i = 0; i < len; ++i) { if (a[i] == item) { return i; } } return -1; }; /** * Returns whether the item was found in the array. */ utils.arrayRemove = function(a, item) { var index = utils.arrayIndexOf(a, item); if (index != -1) { a.splice(index, 1); } return index != -1; }; utils.typeName = function(val) { return Object.prototype.toString.call(val).slice(8, -1); }; /** * Returns an indication of whether the argument is an array or not */ utils.isArray = Array.isArray || function(a) {return utils.typeName(a) == 'Array';}; /** * Returns an indication of whether the argument is a Date or not */ utils.isDate = function(d) { return (d instanceof Date); }; /** * Does a deep clone of the object. */ utils.clone = function(obj) { if(!obj || typeof obj == 'function' || utils.isDate(obj) || typeof obj != 'object') { return obj; } var retVal, i; if(utils.isArray(obj)){ retVal = []; for(i = 0; i < obj.length; ++i){ retVal.push(utils.clone(obj[i])); } return retVal; } retVal = {}; for(i in obj){ if(!(i in retVal) || retVal[i] != obj[i]) { retVal[i] = utils.clone(obj[i]); } } return retVal; }; /** * Returns a wrapped version of the function */ utils.close = function(context, func, params) { return function() { var args = params || arguments; return func.apply(context, args); }; }; //------------------------------------------------------------------------------ function UUIDcreatePart(length) { var uuidpart = ""; for (var i=0; i<length; i++) { var uuidchar = parseInt((Math.random() * 256), 10).toString(16); if (uuidchar.length == 1) { uuidchar = "0" + uuidchar; } uuidpart += uuidchar; } return uuidpart; } /** * Create a UUID */ utils.createUUID = function() { return UUIDcreatePart(4) + '-' + UUIDcreatePart(2) + '-' + UUIDcreatePart(2) + '-' + UUIDcreatePart(2) + '-' + UUIDcreatePart(6); }; /** * Extends a child object from a parent object using classical inheritance * pattern. */ utils.extend = (function() { // proxy used to establish prototype chain var F = function() {}; // extend Child from Parent return function(Child, Parent) { F.prototype = Parent.prototype; Child.prototype = new F(); Child.__super__ = Parent.prototype; Child.prototype.constructor = Child; }; }()); /** * Alerts a message in any available way: alert or console.log. */ utils.alert = function(msg) { if (window.alert) { window.alert(msg); } else if (console && console.log) { console.log(msg); } }; }); window.cordova = require('cordova'); // file: src/scripts/bootstrap.js require('cordova/init'); })();
yogawarisman/materi
platforms/browser/www/cordova.js
JavaScript
apache-2.0
59,083
// Copyright (c) 2012, 2013 Ugorji Nwoke. All rights reserved. // Use of this source code is governed by a BSD-style license found in the LICENSE file. package codec // All non-std package dependencies live in this file, // so porting to different environment is easy (just update functions). import ( "errors" "fmt" "math" "reflect" ) var ( raisePanicAfterRecover = false debugging = true ) func panicValToErr(panicVal interface{}, err *error) { switch xerr := panicVal.(type) { case error: *err = xerr case string: *err = errors.New(xerr) default: *err = fmt.Errorf("%v", panicVal) } if raisePanicAfterRecover { panic(panicVal) } return } func isEmptyValueDeref(v reflect.Value, deref bool) bool { switch v.Kind() { case reflect.Array, reflect.Map, reflect.Slice, reflect.String: return v.Len() == 0 case reflect.Bool: return !v.Bool() case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: return v.Int() == 0 case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: return v.Uint() == 0 case reflect.Float32, reflect.Float64: return v.Float() == 0 case reflect.Interface, reflect.Ptr: if deref { if v.IsNil() { return true } return isEmptyValueDeref(v.Elem(), deref) } else { return v.IsNil() } case reflect.Struct: // return true if all fields are empty. else return false. // we cannot use equality check, because some fields may be maps/slices/etc // and consequently the structs are not comparable. // return v.Interface() == reflect.Zero(v.Type()).Interface() for i, n := 0, v.NumField(); i < n; i++ { if !isEmptyValueDeref(v.Field(i), deref) { return false } } return true } return false } func isEmptyValue(v reflect.Value) bool { return isEmptyValueDeref(v, true) } func debugf(format string, args ...interface{}) { if debugging { if len(format) == 0 || format[len(format)-1] != '\n' { format = format + "\n" } fmt.Printf(format, args...) } } func pruneSignExt(v []byte, pos bool) (n int) { if len(v) < 2 { } else if pos && v[0] == 0 { for ; v[n] == 0 && n+1 < len(v) && (v[n+1]&(1<<7) == 0); n++ { } } else if !pos && v[0] == 0xff { for ; v[n] == 0xff && n+1 < len(v) && (v[n+1]&(1<<7) != 0); n++ { } } return } func implementsIntf(typ, iTyp reflect.Type) (success bool, indir int8) { if typ == nil { return } rt := typ // The type might be a pointer and we need to keep // dereferencing to the base type until we find an implementation. for { if rt.Implements(iTyp) { return true, indir } if p := rt; p.Kind() == reflect.Ptr { indir++ if indir >= math.MaxInt8 { // insane number of indirections return false, 0 } rt = p.Elem() continue } break } // No luck yet, but if this is a base type (non-pointer), the pointer might satisfy. if typ.Kind() != reflect.Ptr { // Not a pointer, but does the pointer work? if reflect.PtrTo(typ).Implements(iTyp) { return true, -1 } } return false, 0 }
endocode/docker
vendor/src/github.com/hashicorp/go-msgpack/codec/helper_internal.go
GO
apache-2.0
3,055
/** * Copyright 2010 Mark Wyszomierski */ package com.joelapenna.foursquared; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.error.FoursquareException; import com.joelapenna.foursquare.types.Settings; import com.joelapenna.foursquare.types.User; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.Window; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; /** * Lets the user set pings on/off for a given friend. * * @date September 25, 2010 * @author Mark Wyszomierski (markww@gmail.com) * */ public class UserDetailsPingsActivity extends Activity { private static final String TAG = "UserDetailsPingsActivity"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; public static final String EXTRA_USER_PARCEL = Foursquared.PACKAGE_NAME + ".UserDetailsPingsActivity.EXTRA_USER_PARCEL"; public static final String EXTRA_USER_RETURNED = Foursquared.PACKAGE_NAME + ".UserDetailsPingsActivity.EXTRA_USER_RETURNED"; private StateHolder mStateHolder; private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (DEBUG) Log.d(TAG, "onReceive: " + intent); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.user_details_pings_activity); registerReceiver(mLoggedOutReceiver, new IntentFilter(Foursquared.INTENT_ACTION_LOGGED_OUT)); Object retained = getLastNonConfigurationInstance(); if (retained != null && retained instanceof StateHolder) { mStateHolder = (StateHolder) retained; mStateHolder.setActivity(this); setPreparedResultIntent(); } else { mStateHolder = new StateHolder(); if (getIntent().getExtras() != null) { if (getIntent().hasExtra(EXTRA_USER_PARCEL)) { User user = getIntent().getExtras().getParcelable(EXTRA_USER_PARCEL); mStateHolder.setUser(user); } else { Log.e(TAG, TAG + " requires a user pareclable in its intent extras."); finish(); return; } } else { Log.e(TAG, "TipActivity requires a tip pareclable in its intent extras."); finish(); return; } } ensureUi(); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(mLoggedOutReceiver); } @Override public Object onRetainNonConfigurationInstance() { mStateHolder.setActivity(null); return mStateHolder; } private void ensureUi() { User user = mStateHolder.getUser(); TextView tv = (TextView)findViewById(R.id.userDetailsPingsActivityDescription); Button btn = (Button)findViewById(R.id.userDetailsPingsActivityButton); if (user.getSettings().getGetPings()) { tv.setText(getString(R.string.user_details_pings_activity_description_on, user.getFirstname())); btn.setText(getString(R.string.user_details_pings_activity_pings_off, user.getFirstname())); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); setProgressBarIndeterminateVisibility(true); mStateHolder.startPingsTask(UserDetailsPingsActivity.this, false); } }); } else { tv.setText(getString(R.string.user_details_pings_activity_description_off, user.getFirstname())); btn.setText(getString(R.string.user_details_pings_activity_pings_on, user.getFirstname())); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { v.setEnabled(false); setProgressBarIndeterminateVisibility(true); mStateHolder.startPingsTask(UserDetailsPingsActivity.this, true); } }); } if (mStateHolder.getIsRunningTaskPings()) { btn.setEnabled(false); setProgressBarIndeterminateVisibility(true); } else { btn.setEnabled(true); setProgressBarIndeterminateVisibility(false); } } private void setPreparedResultIntent() { if (mStateHolder.getPreparedResult() != null) { setResult(Activity.RESULT_OK, mStateHolder.getPreparedResult()); } } private void prepareResultIntent() { Intent intent = new Intent(); intent.putExtra(EXTRA_USER_RETURNED, mStateHolder.getUser()); mStateHolder.setPreparedResult(intent); setPreparedResultIntent(); } private void onTaskPingsComplete(Settings settings, String userId, boolean on, Exception ex) { mStateHolder.setIsRunningTaskPings(false); // The api is returning pings = false for all cases, so manually overwrite, // assume a non-null settings object is success. if (settings != null) { settings.setGetPings(on); mStateHolder.setSettingsResult(settings); prepareResultIntent(); } else { Toast.makeText(this, ex.toString(), Toast.LENGTH_LONG).show(); } ensureUi(); } private static class TaskPings extends AsyncTask<Void, Void, Settings> { private UserDetailsPingsActivity mActivity; private String mUserId; private boolean mOn; private Exception mReason; public TaskPings(UserDetailsPingsActivity activity, String userId, boolean on) { mActivity = activity; mUserId = userId; mOn = on; } public void setActivity(UserDetailsPingsActivity activity) { mActivity = activity; } @Override protected void onPreExecute() { mActivity.ensureUi(); } @Override protected Settings doInBackground(Void... params) { try { Foursquared foursquared = (Foursquared) mActivity.getApplication(); Foursquare foursquare = foursquared.getFoursquare(); return foursquare.setpings(mUserId, mOn); } catch (Exception e) { if (DEBUG) Log.d(TAG, "TipTask: Exception performing tip task.", e); mReason = e; } return null; } @Override protected void onPostExecute(Settings settings) { if (mActivity != null) { mActivity.onTaskPingsComplete(settings, mUserId, mOn, mReason); } } @Override protected void onCancelled() { if (mActivity != null) { mActivity.onTaskPingsComplete(null, mUserId, mOn, new FoursquareException("Tip task cancelled.")); } } } private static class StateHolder { private User mUser; private boolean mIsRunningTask; private Intent mPreparedResult; private TaskPings mTaskPings; public StateHolder() { mPreparedResult = null; mIsRunningTask = false; } public User getUser() { return mUser; } public void setUser(User user) { mUser = user; } public void setSettingsResult(Settings settings) { mUser.getSettings().setGetPings(settings.getGetPings()); } public void startPingsTask(UserDetailsPingsActivity activity, boolean on) { if (!mIsRunningTask) { mIsRunningTask = true; mTaskPings = new TaskPings(activity, mUser.getId(), on); mTaskPings.execute(); } } public void setActivity(UserDetailsPingsActivity activity) { if (mTaskPings != null) { mTaskPings.setActivity(activity); } } public void setIsRunningTaskPings(boolean isRunning) { mIsRunningTask = isRunning; } public boolean getIsRunningTaskPings() { return mIsRunningTask; } public Intent getPreparedResult() { return mPreparedResult; } public void setPreparedResult(Intent intent) { mPreparedResult = intent; } } }
akhilesh9205/foursquared
main/src/com/joelapenna/foursquared/UserDetailsPingsActivity.java
Java
apache-2.0
9,363
/* 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 fake import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" labels "k8s.io/apimachinery/pkg/labels" schema "k8s.io/apimachinery/pkg/runtime/schema" types "k8s.io/apimachinery/pkg/types" watch "k8s.io/apimachinery/pkg/watch" testing "k8s.io/client-go/testing" v1beta1 "k8s.io/kubernetes/pkg/apis/storage/v1beta1" ) // FakeStorageClasses implements StorageClassInterface type FakeStorageClasses struct { Fake *FakeStorageV1beta1 } var storageclassesResource = schema.GroupVersionResource{Group: "storage.k8s.io", Version: "v1beta1", Resource: "storageclasses"} func (c *FakeStorageClasses) Create(storageClass *v1beta1.StorageClass) (result *v1beta1.StorageClass, err error) { obj, err := c.Fake. Invokes(testing.NewRootCreateAction(storageclassesResource, storageClass), &v1beta1.StorageClass{}) if obj == nil { return nil, err } return obj.(*v1beta1.StorageClass), err } func (c *FakeStorageClasses) Update(storageClass *v1beta1.StorageClass) (result *v1beta1.StorageClass, err error) { obj, err := c.Fake. Invokes(testing.NewRootUpdateAction(storageclassesResource, storageClass), &v1beta1.StorageClass{}) if obj == nil { return nil, err } return obj.(*v1beta1.StorageClass), err } func (c *FakeStorageClasses) Delete(name string, options *v1.DeleteOptions) error { _, err := c.Fake. Invokes(testing.NewRootDeleteAction(storageclassesResource, name), &v1beta1.StorageClass{}) return err } func (c *FakeStorageClasses) DeleteCollection(options *v1.DeleteOptions, listOptions v1.ListOptions) error { action := testing.NewRootDeleteCollectionAction(storageclassesResource, listOptions) _, err := c.Fake.Invokes(action, &v1beta1.StorageClassList{}) return err } func (c *FakeStorageClasses) Get(name string, options v1.GetOptions) (result *v1beta1.StorageClass, err error) { obj, err := c.Fake. Invokes(testing.NewRootGetAction(storageclassesResource, name), &v1beta1.StorageClass{}) if obj == nil { return nil, err } return obj.(*v1beta1.StorageClass), err } func (c *FakeStorageClasses) List(opts v1.ListOptions) (result *v1beta1.StorageClassList, err error) { obj, err := c.Fake. Invokes(testing.NewRootListAction(storageclassesResource, opts), &v1beta1.StorageClassList{}) if obj == nil { return nil, err } label, _, _ := testing.ExtractFromListOptions(opts) if label == nil { label = labels.Everything() } list := &v1beta1.StorageClassList{} for _, item := range obj.(*v1beta1.StorageClassList).Items { if label.Matches(labels.Set(item.Labels)) { list.Items = append(list.Items, item) } } return list, err } // Watch returns a watch.Interface that watches the requested storageClasses. func (c *FakeStorageClasses) Watch(opts v1.ListOptions) (watch.Interface, error) { return c.Fake. InvokesWatch(testing.NewRootWatchAction(storageclassesResource, opts)) } // Patch applies the patch and returns the patched storageClass. func (c *FakeStorageClasses) Patch(name string, pt types.PatchType, data []byte, subresources ...string) (result *v1beta1.StorageClass, err error) { obj, err := c.Fake. Invokes(testing.NewRootPatchSubresourceAction(storageclassesResource, name, data, subresources...), &v1beta1.StorageClass{}) if obj == nil { return nil, err } return obj.(*v1beta1.StorageClass), err }
stevekuznetsov/origin
vendor/k8s.io/kubernetes/pkg/client/clientset_generated/clientset/typed/storage/v1beta1/fake/fake_storageclass.go
GO
apache-2.0
3,855
/* * 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.registry.client.types; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.classification.InterfaceStability; /** * Enum of address types -as integers. * Why integers and not enums? Cross platform serialization as JSON */ @InterfaceAudience.Public @InterfaceStability.Evolving public interface AddressTypes { /** * hostname/FQDN and port pair: {@value}. * The host/domain name and port are set as separate strings in the address * list, e.g. * <pre> * ["namenode.example.org", "50070"] * </pre> */ public static final String ADDRESS_HOSTNAME_AND_PORT = "host/port"; public static final String ADDRESS_HOSTNAME_FIELD = "host"; public static final String ADDRESS_PORT_FIELD = "port"; /** * Path <code>/a/b/c</code> style: {@value}. * The entire path is encoded in a single entry * * <pre> * ["/users/example/dataset"] * </pre> */ public static final String ADDRESS_PATH = "path"; /** * URI entries: {@value}. * <pre> * ["http://example.org"] * </pre> */ public static final String ADDRESS_URI = "uri"; /** * Zookeeper addresses as a triple : {@value}. * <p> * These are provide as a 3 element tuple of: hostname, port * and optionally path (depending on the application) * <p> * A single element would be * <pre> * ["zk1","2181","/registry"] * </pre> * An endpoint with multiple elements would list them as * <pre> * [ * ["zk1","2181","/registry"] * ["zk2","1600","/registry"] * ] * </pre> * * the third element in each entry , the path, MUST be the same in each entry. * A client reading the addresses of an endpoint is free to pick any * of the set, so they must be the same. * */ public static final String ADDRESS_ZOOKEEPER = "zktriple"; /** * Any other address: {@value}. */ public static final String ADDRESS_OTHER = ""; }
malli3131/hadoop-1
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-registry/src/main/java/org/apache/hadoop/registry/client/types/AddressTypes.java
Java
apache-2.0
2,779
// Copyright ©2014 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gonum import ( "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/internal/asm/f64" ) var _ blas.Float64Level2 = Implementation{} // Dger performs the rank-one operation // A += alpha * x * yᵀ // where A is an m×n dense matrix, x and y are vectors, and alpha is a scalar. func (Implementation) Dger(m, n int, alpha float64, x []float64, incX int, y []float64, incY int, a []float64, lda int) { if m < 0 { panic(mLT0) } if n < 0 { panic(nLT0) } if lda < max(1, n) { panic(badLdA) } if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } // Quick return if possible. if m == 0 || n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if (incX > 0 && len(x) <= (m-1)*incX) || (incX < 0 && len(x) <= (1-m)*incX) { panic(shortX) } if (incY > 0 && len(y) <= (n-1)*incY) || (incY < 0 && len(y) <= (1-n)*incY) { panic(shortY) } if len(a) < lda*(m-1)+n { panic(shortA) } // Quick return if possible. if alpha == 0 { return } f64.Ger(uintptr(m), uintptr(n), alpha, x, uintptr(incX), y, uintptr(incY), a, uintptr(lda)) } // Dgbmv performs one of the matrix-vector operations // y = alpha * A * x + beta * y if tA == blas.NoTrans // y = alpha * Aᵀ * x + beta * y if tA == blas.Trans or blas.ConjTrans // where A is an m×n band matrix with kL sub-diagonals and kU super-diagonals, // x and y are vectors, and alpha and beta are scalars. func (Implementation) Dgbmv(tA blas.Transpose, m, n, kL, kU int, alpha float64, a []float64, lda int, x []float64, incX int, beta float64, y []float64, incY int) { if tA != blas.NoTrans && tA != blas.Trans && tA != blas.ConjTrans { panic(badTranspose) } if m < 0 { panic(mLT0) } if n < 0 { panic(nLT0) } if kL < 0 { panic(kLLT0) } if kU < 0 { panic(kULT0) } if lda < kL+kU+1 { panic(badLdA) } if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } // Quick return if possible. if m == 0 || n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(a) < lda*(min(m, n+kL)-1)+kL+kU+1 { panic(shortA) } lenX := m lenY := n if tA == blas.NoTrans { lenX = n lenY = m } if (incX > 0 && len(x) <= (lenX-1)*incX) || (incX < 0 && len(x) <= (1-lenX)*incX) { panic(shortX) } if (incY > 0 && len(y) <= (lenY-1)*incY) || (incY < 0 && len(y) <= (1-lenY)*incY) { panic(shortY) } // Quick return if possible. if alpha == 0 && beta == 1 { return } var kx, ky int if incX < 0 { kx = -(lenX - 1) * incX } if incY < 0 { ky = -(lenY - 1) * incY } // Form y = beta * y. if beta != 1 { if incY == 1 { if beta == 0 { for i := range y[:lenY] { y[i] = 0 } } else { f64.ScalUnitary(beta, y[:lenY]) } } else { iy := ky if beta == 0 { for i := 0; i < lenY; i++ { y[iy] = 0 iy += incY } } else { if incY > 0 { f64.ScalInc(beta, y, uintptr(lenY), uintptr(incY)) } else { f64.ScalInc(beta, y, uintptr(lenY), uintptr(-incY)) } } } } if alpha == 0 { return } // i and j are indices of the compacted banded matrix. // off is the offset into the dense matrix (off + j = densej) nCol := kU + 1 + kL if tA == blas.NoTrans { iy := ky if incX == 1 { for i := 0; i < min(m, n+kL); i++ { l := max(0, kL-i) u := min(nCol, n+kL-i) off := max(0, i-kL) atmp := a[i*lda+l : i*lda+u] xtmp := x[off : off+u-l] var sum float64 for j, v := range atmp { sum += xtmp[j] * v } y[iy] += sum * alpha iy += incY } return } for i := 0; i < min(m, n+kL); i++ { l := max(0, kL-i) u := min(nCol, n+kL-i) off := max(0, i-kL) atmp := a[i*lda+l : i*lda+u] jx := kx var sum float64 for _, v := range atmp { sum += x[off*incX+jx] * v jx += incX } y[iy] += sum * alpha iy += incY } return } if incX == 1 { for i := 0; i < min(m, n+kL); i++ { l := max(0, kL-i) u := min(nCol, n+kL-i) off := max(0, i-kL) atmp := a[i*lda+l : i*lda+u] tmp := alpha * x[i] jy := ky for _, v := range atmp { y[jy+off*incY] += tmp * v jy += incY } } return } ix := kx for i := 0; i < min(m, n+kL); i++ { l := max(0, kL-i) u := min(nCol, n+kL-i) off := max(0, i-kL) atmp := a[i*lda+l : i*lda+u] tmp := alpha * x[ix] jy := ky for _, v := range atmp { y[jy+off*incY] += tmp * v jy += incY } ix += incX } } // Dtrmv performs one of the matrix-vector operations // x = A * x if tA == blas.NoTrans // x = Aᵀ * x if tA == blas.Trans or blas.ConjTrans // where A is an n×n triangular matrix, and x is a vector. func (Implementation) Dtrmv(ul blas.Uplo, tA blas.Transpose, d blas.Diag, n int, a []float64, lda int, x []float64, incX int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if tA != blas.NoTrans && tA != blas.Trans && tA != blas.ConjTrans { panic(badTranspose) } if d != blas.NonUnit && d != blas.Unit { panic(badDiag) } if n < 0 { panic(nLT0) } if lda < max(1, n) { panic(badLdA) } if incX == 0 { panic(zeroIncX) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(a) < lda*(n-1)+n { panic(shortA) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } nonUnit := d != blas.Unit if n == 1 { if nonUnit { x[0] *= a[0] } return } var kx int if incX <= 0 { kx = -(n - 1) * incX } if tA == blas.NoTrans { if ul == blas.Upper { if incX == 1 { for i := 0; i < n; i++ { ilda := i * lda var tmp float64 if nonUnit { tmp = a[ilda+i] * x[i] } else { tmp = x[i] } x[i] = tmp + f64.DotUnitary(a[ilda+i+1:ilda+n], x[i+1:n]) } return } ix := kx for i := 0; i < n; i++ { ilda := i * lda var tmp float64 if nonUnit { tmp = a[ilda+i] * x[ix] } else { tmp = x[ix] } x[ix] = tmp + f64.DotInc(x, a[ilda+i+1:ilda+n], uintptr(n-i-1), uintptr(incX), 1, uintptr(ix+incX), 0) ix += incX } return } if incX == 1 { for i := n - 1; i >= 0; i-- { ilda := i * lda var tmp float64 if nonUnit { tmp += a[ilda+i] * x[i] } else { tmp = x[i] } x[i] = tmp + f64.DotUnitary(a[ilda:ilda+i], x[:i]) } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { ilda := i * lda var tmp float64 if nonUnit { tmp = a[ilda+i] * x[ix] } else { tmp = x[ix] } x[ix] = tmp + f64.DotInc(x, a[ilda:ilda+i], uintptr(i), uintptr(incX), 1, uintptr(kx), 0) ix -= incX } return } // Cases where a is transposed. if ul == blas.Upper { if incX == 1 { for i := n - 1; i >= 0; i-- { ilda := i * lda xi := x[i] f64.AxpyUnitary(xi, a[ilda+i+1:ilda+n], x[i+1:n]) if nonUnit { x[i] *= a[ilda+i] } } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { ilda := i * lda xi := x[ix] f64.AxpyInc(xi, a[ilda+i+1:ilda+n], x, uintptr(n-i-1), 1, uintptr(incX), 0, uintptr(kx+(i+1)*incX)) if nonUnit { x[ix] *= a[ilda+i] } ix -= incX } return } if incX == 1 { for i := 0; i < n; i++ { ilda := i * lda xi := x[i] f64.AxpyUnitary(xi, a[ilda:ilda+i], x[:i]) if nonUnit { x[i] *= a[i*lda+i] } } return } ix := kx for i := 0; i < n; i++ { ilda := i * lda xi := x[ix] f64.AxpyInc(xi, a[ilda:ilda+i], x, uintptr(i), 1, uintptr(incX), 0, uintptr(kx)) if nonUnit { x[ix] *= a[ilda+i] } ix += incX } } // Dtrsv solves one of the systems of equations // A * x = b if tA == blas.NoTrans // Aᵀ * x = b if tA == blas.Trans or blas.ConjTrans // where A is an n×n triangular matrix, and x and b are vectors. // // At entry to the function, x contains the values of b, and the result is // stored in-place into x. // // No test for singularity or near-singularity is included in this // routine. Such tests must be performed before calling this routine. func (Implementation) Dtrsv(ul blas.Uplo, tA blas.Transpose, d blas.Diag, n int, a []float64, lda int, x []float64, incX int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if tA != blas.NoTrans && tA != blas.Trans && tA != blas.ConjTrans { panic(badTranspose) } if d != blas.NonUnit && d != blas.Unit { panic(badDiag) } if n < 0 { panic(nLT0) } if lda < max(1, n) { panic(badLdA) } if incX == 0 { panic(zeroIncX) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(a) < lda*(n-1)+n { panic(shortA) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } if n == 1 { if d == blas.NonUnit { x[0] /= a[0] } return } var kx int if incX < 0 { kx = -(n - 1) * incX } nonUnit := d == blas.NonUnit if tA == blas.NoTrans { if ul == blas.Upper { if incX == 1 { for i := n - 1; i >= 0; i-- { var sum float64 atmp := a[i*lda+i+1 : i*lda+n] for j, v := range atmp { jv := i + j + 1 sum += x[jv] * v } x[i] -= sum if nonUnit { x[i] /= a[i*lda+i] } } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { var sum float64 jx := ix + incX atmp := a[i*lda+i+1 : i*lda+n] for _, v := range atmp { sum += x[jx] * v jx += incX } x[ix] -= sum if nonUnit { x[ix] /= a[i*lda+i] } ix -= incX } return } if incX == 1 { for i := 0; i < n; i++ { var sum float64 atmp := a[i*lda : i*lda+i] for j, v := range atmp { sum += x[j] * v } x[i] -= sum if nonUnit { x[i] /= a[i*lda+i] } } return } ix := kx for i := 0; i < n; i++ { jx := kx var sum float64 atmp := a[i*lda : i*lda+i] for _, v := range atmp { sum += x[jx] * v jx += incX } x[ix] -= sum if nonUnit { x[ix] /= a[i*lda+i] } ix += incX } return } // Cases where a is transposed. if ul == blas.Upper { if incX == 1 { for i := 0; i < n; i++ { if nonUnit { x[i] /= a[i*lda+i] } xi := x[i] atmp := a[i*lda+i+1 : i*lda+n] for j, v := range atmp { jv := j + i + 1 x[jv] -= v * xi } } return } ix := kx for i := 0; i < n; i++ { if nonUnit { x[ix] /= a[i*lda+i] } xi := x[ix] jx := kx + (i+1)*incX atmp := a[i*lda+i+1 : i*lda+n] for _, v := range atmp { x[jx] -= v * xi jx += incX } ix += incX } return } if incX == 1 { for i := n - 1; i >= 0; i-- { if nonUnit { x[i] /= a[i*lda+i] } xi := x[i] atmp := a[i*lda : i*lda+i] for j, v := range atmp { x[j] -= v * xi } } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { if nonUnit { x[ix] /= a[i*lda+i] } xi := x[ix] jx := kx atmp := a[i*lda : i*lda+i] for _, v := range atmp { x[jx] -= v * xi jx += incX } ix -= incX } } // Dsymv performs the matrix-vector operation // y = alpha * A * x + beta * y // where A is an n×n symmetric matrix, x and y are vectors, and alpha and // beta are scalars. func (Implementation) Dsymv(ul blas.Uplo, n int, alpha float64, a []float64, lda int, x []float64, incX int, beta float64, y []float64, incY int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if n < 0 { panic(nLT0) } if lda < max(1, n) { panic(badLdA) } if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(a) < lda*(n-1)+n { panic(shortA) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } if (incY > 0 && len(y) <= (n-1)*incY) || (incY < 0 && len(y) <= (1-n)*incY) { panic(shortY) } // Quick return if possible. if alpha == 0 && beta == 1 { return } // Set up start points var kx, ky int if incX < 0 { kx = -(n - 1) * incX } if incY < 0 { ky = -(n - 1) * incY } // Form y = beta * y if beta != 1 { if incY == 1 { if beta == 0 { for i := range y[:n] { y[i] = 0 } } else { f64.ScalUnitary(beta, y[:n]) } } else { iy := ky if beta == 0 { for i := 0; i < n; i++ { y[iy] = 0 iy += incY } } else { if incY > 0 { f64.ScalInc(beta, y, uintptr(n), uintptr(incY)) } else { f64.ScalInc(beta, y, uintptr(n), uintptr(-incY)) } } } } if alpha == 0 { return } if n == 1 { y[0] += alpha * a[0] * x[0] return } if ul == blas.Upper { if incX == 1 { iy := ky for i := 0; i < n; i++ { xv := x[i] * alpha sum := x[i] * a[i*lda+i] jy := ky + (i+1)*incY atmp := a[i*lda+i+1 : i*lda+n] for j, v := range atmp { jp := j + i + 1 sum += x[jp] * v y[jy] += xv * v jy += incY } y[iy] += alpha * sum iy += incY } return } ix := kx iy := ky for i := 0; i < n; i++ { xv := x[ix] * alpha sum := x[ix] * a[i*lda+i] jx := kx + (i+1)*incX jy := ky + (i+1)*incY atmp := a[i*lda+i+1 : i*lda+n] for _, v := range atmp { sum += x[jx] * v y[jy] += xv * v jx += incX jy += incY } y[iy] += alpha * sum ix += incX iy += incY } return } // Cases where a is lower triangular. if incX == 1 { iy := ky for i := 0; i < n; i++ { jy := ky xv := alpha * x[i] atmp := a[i*lda : i*lda+i] var sum float64 for j, v := range atmp { sum += x[j] * v y[jy] += xv * v jy += incY } sum += x[i] * a[i*lda+i] sum *= alpha y[iy] += sum iy += incY } return } ix := kx iy := ky for i := 0; i < n; i++ { jx := kx jy := ky xv := alpha * x[ix] atmp := a[i*lda : i*lda+i] var sum float64 for _, v := range atmp { sum += x[jx] * v y[jy] += xv * v jx += incX jy += incY } sum += x[ix] * a[i*lda+i] sum *= alpha y[iy] += sum ix += incX iy += incY } } // Dtbmv performs one of the matrix-vector operations // x = A * x if tA == blas.NoTrans // x = Aᵀ * x if tA == blas.Trans or blas.ConjTrans // where A is an n×n triangular band matrix with k+1 diagonals, and x is a vector. func (Implementation) Dtbmv(ul blas.Uplo, tA blas.Transpose, d blas.Diag, n, k int, a []float64, lda int, x []float64, incX int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if tA != blas.NoTrans && tA != blas.Trans && tA != blas.ConjTrans { panic(badTranspose) } if d != blas.NonUnit && d != blas.Unit { panic(badDiag) } if n < 0 { panic(nLT0) } if k < 0 { panic(kLT0) } if lda < k+1 { panic(badLdA) } if incX == 0 { panic(zeroIncX) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(a) < lda*(n-1)+k+1 { panic(shortA) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } var kx int if incX < 0 { kx = -(n - 1) * incX } nonunit := d != blas.Unit if tA == blas.NoTrans { if ul == blas.Upper { if incX == 1 { for i := 0; i < n; i++ { u := min(1+k, n-i) var sum float64 atmp := a[i*lda:] xtmp := x[i:] for j := 1; j < u; j++ { sum += xtmp[j] * atmp[j] } if nonunit { sum += xtmp[0] * atmp[0] } else { sum += xtmp[0] } x[i] = sum } return } ix := kx for i := 0; i < n; i++ { u := min(1+k, n-i) var sum float64 atmp := a[i*lda:] jx := incX for j := 1; j < u; j++ { sum += x[ix+jx] * atmp[j] jx += incX } if nonunit { sum += x[ix] * atmp[0] } else { sum += x[ix] } x[ix] = sum ix += incX } return } if incX == 1 { for i := n - 1; i >= 0; i-- { l := max(0, k-i) atmp := a[i*lda:] var sum float64 for j := l; j < k; j++ { sum += x[i-k+j] * atmp[j] } if nonunit { sum += x[i] * atmp[k] } else { sum += x[i] } x[i] = sum } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { l := max(0, k-i) atmp := a[i*lda:] var sum float64 jx := l * incX for j := l; j < k; j++ { sum += x[ix-k*incX+jx] * atmp[j] jx += incX } if nonunit { sum += x[ix] * atmp[k] } else { sum += x[ix] } x[ix] = sum ix -= incX } return } if ul == blas.Upper { if incX == 1 { for i := n - 1; i >= 0; i-- { u := k + 1 if i < u { u = i + 1 } var sum float64 for j := 1; j < u; j++ { sum += x[i-j] * a[(i-j)*lda+j] } if nonunit { sum += x[i] * a[i*lda] } else { sum += x[i] } x[i] = sum } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { u := k + 1 if i < u { u = i + 1 } var sum float64 jx := incX for j := 1; j < u; j++ { sum += x[ix-jx] * a[(i-j)*lda+j] jx += incX } if nonunit { sum += x[ix] * a[i*lda] } else { sum += x[ix] } x[ix] = sum ix -= incX } return } if incX == 1 { for i := 0; i < n; i++ { u := k if i+k >= n { u = n - i - 1 } var sum float64 for j := 0; j < u; j++ { sum += x[i+j+1] * a[(i+j+1)*lda+k-j-1] } if nonunit { sum += x[i] * a[i*lda+k] } else { sum += x[i] } x[i] = sum } return } ix := kx for i := 0; i < n; i++ { u := k if i+k >= n { u = n - i - 1 } var ( sum float64 jx int ) for j := 0; j < u; j++ { sum += x[ix+jx+incX] * a[(i+j+1)*lda+k-j-1] jx += incX } if nonunit { sum += x[ix] * a[i*lda+k] } else { sum += x[ix] } x[ix] = sum ix += incX } } // Dtpmv performs one of the matrix-vector operations // x = A * x if tA == blas.NoTrans // x = Aᵀ * x if tA == blas.Trans or blas.ConjTrans // where A is an n×n triangular matrix in packed format, and x is a vector. func (Implementation) Dtpmv(ul blas.Uplo, tA blas.Transpose, d blas.Diag, n int, ap []float64, x []float64, incX int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if tA != blas.NoTrans && tA != blas.Trans && tA != blas.ConjTrans { panic(badTranspose) } if d != blas.NonUnit && d != blas.Unit { panic(badDiag) } if n < 0 { panic(nLT0) } if incX == 0 { panic(zeroIncX) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(ap) < n*(n+1)/2 { panic(shortAP) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } var kx int if incX < 0 { kx = -(n - 1) * incX } nonUnit := d == blas.NonUnit var offset int // Offset is the index of (i,i) if tA == blas.NoTrans { if ul == blas.Upper { if incX == 1 { for i := 0; i < n; i++ { xi := x[i] if nonUnit { xi *= ap[offset] } atmp := ap[offset+1 : offset+n-i] xtmp := x[i+1:] for j, v := range atmp { xi += v * xtmp[j] } x[i] = xi offset += n - i } return } ix := kx for i := 0; i < n; i++ { xix := x[ix] if nonUnit { xix *= ap[offset] } atmp := ap[offset+1 : offset+n-i] jx := kx + (i+1)*incX for _, v := range atmp { xix += v * x[jx] jx += incX } x[ix] = xix offset += n - i ix += incX } return } if incX == 1 { offset = n*(n+1)/2 - 1 for i := n - 1; i >= 0; i-- { xi := x[i] if nonUnit { xi *= ap[offset] } atmp := ap[offset-i : offset] for j, v := range atmp { xi += v * x[j] } x[i] = xi offset -= i + 1 } return } ix := kx + (n-1)*incX offset = n*(n+1)/2 - 1 for i := n - 1; i >= 0; i-- { xix := x[ix] if nonUnit { xix *= ap[offset] } atmp := ap[offset-i : offset] jx := kx for _, v := range atmp { xix += v * x[jx] jx += incX } x[ix] = xix offset -= i + 1 ix -= incX } return } // Cases where ap is transposed. if ul == blas.Upper { if incX == 1 { offset = n*(n+1)/2 - 1 for i := n - 1; i >= 0; i-- { xi := x[i] atmp := ap[offset+1 : offset+n-i] xtmp := x[i+1:] for j, v := range atmp { xtmp[j] += v * xi } if nonUnit { x[i] *= ap[offset] } offset -= n - i + 1 } return } ix := kx + (n-1)*incX offset = n*(n+1)/2 - 1 for i := n - 1; i >= 0; i-- { xix := x[ix] jx := kx + (i+1)*incX atmp := ap[offset+1 : offset+n-i] for _, v := range atmp { x[jx] += v * xix jx += incX } if nonUnit { x[ix] *= ap[offset] } offset -= n - i + 1 ix -= incX } return } if incX == 1 { for i := 0; i < n; i++ { xi := x[i] atmp := ap[offset-i : offset] for j, v := range atmp { x[j] += v * xi } if nonUnit { x[i] *= ap[offset] } offset += i + 2 } return } ix := kx for i := 0; i < n; i++ { xix := x[ix] jx := kx atmp := ap[offset-i : offset] for _, v := range atmp { x[jx] += v * xix jx += incX } if nonUnit { x[ix] *= ap[offset] } ix += incX offset += i + 2 } } // Dtbsv solves one of the systems of equations // A * x = b if tA == blas.NoTrans // Aᵀ * x = b if tA == blas.Trans or tA == blas.ConjTrans // where A is an n×n triangular band matrix with k+1 diagonals, // and x and b are vectors. // // At entry to the function, x contains the values of b, and the result is // stored in-place into x. // // No test for singularity or near-singularity is included in this // routine. Such tests must be performed before calling this routine. func (Implementation) Dtbsv(ul blas.Uplo, tA blas.Transpose, d blas.Diag, n, k int, a []float64, lda int, x []float64, incX int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if tA != blas.NoTrans && tA != blas.Trans && tA != blas.ConjTrans { panic(badTranspose) } if d != blas.NonUnit && d != blas.Unit { panic(badDiag) } if n < 0 { panic(nLT0) } if k < 0 { panic(kLT0) } if lda < k+1 { panic(badLdA) } if incX == 0 { panic(zeroIncX) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(a) < lda*(n-1)+k+1 { panic(shortA) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } var kx int if incX < 0 { kx = -(n - 1) * incX } nonUnit := d == blas.NonUnit // Form x = A^-1 x. // Several cases below use subslices for speed improvement. // The incX != 1 cases usually do not because incX may be negative. if tA == blas.NoTrans { if ul == blas.Upper { if incX == 1 { for i := n - 1; i >= 0; i-- { bands := k if i+bands >= n { bands = n - i - 1 } atmp := a[i*lda+1:] xtmp := x[i+1 : i+bands+1] var sum float64 for j, v := range xtmp { sum += v * atmp[j] } x[i] -= sum if nonUnit { x[i] /= a[i*lda] } } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { max := k + 1 if i+max > n { max = n - i } atmp := a[i*lda:] var ( jx int sum float64 ) for j := 1; j < max; j++ { jx += incX sum += x[ix+jx] * atmp[j] } x[ix] -= sum if nonUnit { x[ix] /= atmp[0] } ix -= incX } return } if incX == 1 { for i := 0; i < n; i++ { bands := k if i-k < 0 { bands = i } atmp := a[i*lda+k-bands:] xtmp := x[i-bands : i] var sum float64 for j, v := range xtmp { sum += v * atmp[j] } x[i] -= sum if nonUnit { x[i] /= atmp[bands] } } return } ix := kx for i := 0; i < n; i++ { bands := k if i-k < 0 { bands = i } atmp := a[i*lda+k-bands:] var ( sum float64 jx int ) for j := 0; j < bands; j++ { sum += x[ix-bands*incX+jx] * atmp[j] jx += incX } x[ix] -= sum if nonUnit { x[ix] /= atmp[bands] } ix += incX } return } // Cases where a is transposed. if ul == blas.Upper { if incX == 1 { for i := 0; i < n; i++ { bands := k if i-k < 0 { bands = i } var sum float64 for j := 0; j < bands; j++ { sum += x[i-bands+j] * a[(i-bands+j)*lda+bands-j] } x[i] -= sum if nonUnit { x[i] /= a[i*lda] } } return } ix := kx for i := 0; i < n; i++ { bands := k if i-k < 0 { bands = i } var ( sum float64 jx int ) for j := 0; j < bands; j++ { sum += x[ix-bands*incX+jx] * a[(i-bands+j)*lda+bands-j] jx += incX } x[ix] -= sum if nonUnit { x[ix] /= a[i*lda] } ix += incX } return } if incX == 1 { for i := n - 1; i >= 0; i-- { bands := k if i+bands >= n { bands = n - i - 1 } var sum float64 xtmp := x[i+1 : i+1+bands] for j, v := range xtmp { sum += v * a[(i+j+1)*lda+k-j-1] } x[i] -= sum if nonUnit { x[i] /= a[i*lda+k] } } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { bands := k if i+bands >= n { bands = n - i - 1 } var ( sum float64 jx int ) for j := 0; j < bands; j++ { sum += x[ix+jx+incX] * a[(i+j+1)*lda+k-j-1] jx += incX } x[ix] -= sum if nonUnit { x[ix] /= a[i*lda+k] } ix -= incX } } // Dsbmv performs the matrix-vector operation // y = alpha * A * x + beta * y // where A is an n×n symmetric band matrix with k super-diagonals, x and y are // vectors, and alpha and beta are scalars. func (Implementation) Dsbmv(ul blas.Uplo, n, k int, alpha float64, a []float64, lda int, x []float64, incX int, beta float64, y []float64, incY int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if n < 0 { panic(nLT0) } if k < 0 { panic(kLT0) } if lda < k+1 { panic(badLdA) } if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(a) < lda*(n-1)+k+1 { panic(shortA) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } if (incY > 0 && len(y) <= (n-1)*incY) || (incY < 0 && len(y) <= (1-n)*incY) { panic(shortY) } // Quick return if possible. if alpha == 0 && beta == 1 { return } // Set up indexes lenX := n lenY := n var kx, ky int if incX < 0 { kx = -(lenX - 1) * incX } if incY < 0 { ky = -(lenY - 1) * incY } // Form y = beta * y. if beta != 1 { if incY == 1 { if beta == 0 { for i := range y[:n] { y[i] = 0 } } else { f64.ScalUnitary(beta, y[:n]) } } else { iy := ky if beta == 0 { for i := 0; i < n; i++ { y[iy] = 0 iy += incY } } else { if incY > 0 { f64.ScalInc(beta, y, uintptr(n), uintptr(incY)) } else { f64.ScalInc(beta, y, uintptr(n), uintptr(-incY)) } } } } if alpha == 0 { return } if ul == blas.Upper { if incX == 1 { iy := ky for i := 0; i < n; i++ { atmp := a[i*lda:] tmp := alpha * x[i] sum := tmp * atmp[0] u := min(k, n-i-1) jy := incY for j := 1; j <= u; j++ { v := atmp[j] sum += alpha * x[i+j] * v y[iy+jy] += tmp * v jy += incY } y[iy] += sum iy += incY } return } ix := kx iy := ky for i := 0; i < n; i++ { atmp := a[i*lda:] tmp := alpha * x[ix] sum := tmp * atmp[0] u := min(k, n-i-1) jx := incX jy := incY for j := 1; j <= u; j++ { v := atmp[j] sum += alpha * x[ix+jx] * v y[iy+jy] += tmp * v jx += incX jy += incY } y[iy] += sum ix += incX iy += incY } return } // Casses where a has bands below the diagonal. if incX == 1 { iy := ky for i := 0; i < n; i++ { l := max(0, k-i) tmp := alpha * x[i] jy := l * incY atmp := a[i*lda:] for j := l; j < k; j++ { v := atmp[j] y[iy] += alpha * v * x[i-k+j] y[iy-k*incY+jy] += tmp * v jy += incY } y[iy] += tmp * atmp[k] iy += incY } return } ix := kx iy := ky for i := 0; i < n; i++ { l := max(0, k-i) tmp := alpha * x[ix] jx := l * incX jy := l * incY atmp := a[i*lda:] for j := l; j < k; j++ { v := atmp[j] y[iy] += alpha * v * x[ix-k*incX+jx] y[iy-k*incY+jy] += tmp * v jx += incX jy += incY } y[iy] += tmp * atmp[k] ix += incX iy += incY } } // Dsyr performs the symmetric rank-one update // A += alpha * x * xᵀ // where A is an n×n symmetric matrix, and x is a vector. func (Implementation) Dsyr(ul blas.Uplo, n int, alpha float64, x []float64, incX int, a []float64, lda int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if n < 0 { panic(nLT0) } if lda < max(1, n) { panic(badLdA) } if incX == 0 { panic(zeroIncX) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } if len(a) < lda*(n-1)+n { panic(shortA) } // Quick return if possible. if alpha == 0 { return } lenX := n var kx int if incX < 0 { kx = -(lenX - 1) * incX } if ul == blas.Upper { if incX == 1 { for i := 0; i < n; i++ { tmp := x[i] * alpha if tmp != 0 { atmp := a[i*lda+i : i*lda+n] xtmp := x[i:n] for j, v := range xtmp { atmp[j] += v * tmp } } } return } ix := kx for i := 0; i < n; i++ { tmp := x[ix] * alpha if tmp != 0 { jx := ix atmp := a[i*lda:] for j := i; j < n; j++ { atmp[j] += x[jx] * tmp jx += incX } } ix += incX } return } // Cases where a is lower triangular. if incX == 1 { for i := 0; i < n; i++ { tmp := x[i] * alpha if tmp != 0 { atmp := a[i*lda:] xtmp := x[:i+1] for j, v := range xtmp { atmp[j] += tmp * v } } } return } ix := kx for i := 0; i < n; i++ { tmp := x[ix] * alpha if tmp != 0 { atmp := a[i*lda:] jx := kx for j := 0; j < i+1; j++ { atmp[j] += tmp * x[jx] jx += incX } } ix += incX } } // Dsyr2 performs the symmetric rank-two update // A += alpha * x * yᵀ + alpha * y * xᵀ // where A is an n×n symmetric matrix, x and y are vectors, and alpha is a scalar. func (Implementation) Dsyr2(ul blas.Uplo, n int, alpha float64, x []float64, incX int, y []float64, incY int, a []float64, lda int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if n < 0 { panic(nLT0) } if lda < max(1, n) { panic(badLdA) } if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } if (incY > 0 && len(y) <= (n-1)*incY) || (incY < 0 && len(y) <= (1-n)*incY) { panic(shortY) } if len(a) < lda*(n-1)+n { panic(shortA) } // Quick return if possible. if alpha == 0 { return } var ky, kx int if incY < 0 { ky = -(n - 1) * incY } if incX < 0 { kx = -(n - 1) * incX } if ul == blas.Upper { if incX == 1 && incY == 1 { for i := 0; i < n; i++ { xi := x[i] yi := y[i] atmp := a[i*lda:] for j := i; j < n; j++ { atmp[j] += alpha * (xi*y[j] + x[j]*yi) } } return } ix := kx iy := ky for i := 0; i < n; i++ { jx := kx + i*incX jy := ky + i*incY xi := x[ix] yi := y[iy] atmp := a[i*lda:] for j := i; j < n; j++ { atmp[j] += alpha * (xi*y[jy] + x[jx]*yi) jx += incX jy += incY } ix += incX iy += incY } return } if incX == 1 && incY == 1 { for i := 0; i < n; i++ { xi := x[i] yi := y[i] atmp := a[i*lda:] for j := 0; j <= i; j++ { atmp[j] += alpha * (xi*y[j] + x[j]*yi) } } return } ix := kx iy := ky for i := 0; i < n; i++ { jx := kx jy := ky xi := x[ix] yi := y[iy] atmp := a[i*lda:] for j := 0; j <= i; j++ { atmp[j] += alpha * (xi*y[jy] + x[jx]*yi) jx += incX jy += incY } ix += incX iy += incY } } // Dtpsv solves one of the systems of equations // A * x = b if tA == blas.NoTrans // Aᵀ * x = b if tA == blas.Trans or blas.ConjTrans // where A is an n×n triangular matrix in packed format, and x and b are vectors. // // At entry to the function, x contains the values of b, and the result is // stored in-place into x. // // No test for singularity or near-singularity is included in this // routine. Such tests must be performed before calling this routine. func (Implementation) Dtpsv(ul blas.Uplo, tA blas.Transpose, d blas.Diag, n int, ap []float64, x []float64, incX int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if tA != blas.NoTrans && tA != blas.Trans && tA != blas.ConjTrans { panic(badTranspose) } if d != blas.NonUnit && d != blas.Unit { panic(badDiag) } if n < 0 { panic(nLT0) } if incX == 0 { panic(zeroIncX) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(ap) < n*(n+1)/2 { panic(shortAP) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } var kx int if incX < 0 { kx = -(n - 1) * incX } nonUnit := d == blas.NonUnit var offset int // Offset is the index of (i,i) if tA == blas.NoTrans { if ul == blas.Upper { offset = n*(n+1)/2 - 1 if incX == 1 { for i := n - 1; i >= 0; i-- { atmp := ap[offset+1 : offset+n-i] xtmp := x[i+1:] var sum float64 for j, v := range atmp { sum += v * xtmp[j] } x[i] -= sum if nonUnit { x[i] /= ap[offset] } offset -= n - i + 1 } return } ix := kx + (n-1)*incX for i := n - 1; i >= 0; i-- { atmp := ap[offset+1 : offset+n-i] jx := kx + (i+1)*incX var sum float64 for _, v := range atmp { sum += v * x[jx] jx += incX } x[ix] -= sum if nonUnit { x[ix] /= ap[offset] } ix -= incX offset -= n - i + 1 } return } if incX == 1 { for i := 0; i < n; i++ { atmp := ap[offset-i : offset] var sum float64 for j, v := range atmp { sum += v * x[j] } x[i] -= sum if nonUnit { x[i] /= ap[offset] } offset += i + 2 } return } ix := kx for i := 0; i < n; i++ { jx := kx atmp := ap[offset-i : offset] var sum float64 for _, v := range atmp { sum += v * x[jx] jx += incX } x[ix] -= sum if nonUnit { x[ix] /= ap[offset] } ix += incX offset += i + 2 } return } // Cases where ap is transposed. if ul == blas.Upper { if incX == 1 { for i := 0; i < n; i++ { if nonUnit { x[i] /= ap[offset] } xi := x[i] atmp := ap[offset+1 : offset+n-i] xtmp := x[i+1:] for j, v := range atmp { xtmp[j] -= v * xi } offset += n - i } return } ix := kx for i := 0; i < n; i++ { if nonUnit { x[ix] /= ap[offset] } xix := x[ix] atmp := ap[offset+1 : offset+n-i] jx := kx + (i+1)*incX for _, v := range atmp { x[jx] -= v * xix jx += incX } ix += incX offset += n - i } return } if incX == 1 { offset = n*(n+1)/2 - 1 for i := n - 1; i >= 0; i-- { if nonUnit { x[i] /= ap[offset] } xi := x[i] atmp := ap[offset-i : offset] for j, v := range atmp { x[j] -= v * xi } offset -= i + 1 } return } ix := kx + (n-1)*incX offset = n*(n+1)/2 - 1 for i := n - 1; i >= 0; i-- { if nonUnit { x[ix] /= ap[offset] } xix := x[ix] atmp := ap[offset-i : offset] jx := kx for _, v := range atmp { x[jx] -= v * xix jx += incX } ix -= incX offset -= i + 1 } } // Dspmv performs the matrix-vector operation // y = alpha * A * x + beta * y // where A is an n×n symmetric matrix in packed format, x and y are vectors, // and alpha and beta are scalars. func (Implementation) Dspmv(ul blas.Uplo, n int, alpha float64, ap []float64, x []float64, incX int, beta float64, y []float64, incY int) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if n < 0 { panic(nLT0) } if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if len(ap) < n*(n+1)/2 { panic(shortAP) } if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } if (incY > 0 && len(y) <= (n-1)*incY) || (incY < 0 && len(y) <= (1-n)*incY) { panic(shortY) } // Quick return if possible. if alpha == 0 && beta == 1 { return } // Set up start points var kx, ky int if incX < 0 { kx = -(n - 1) * incX } if incY < 0 { ky = -(n - 1) * incY } // Form y = beta * y. if beta != 1 { if incY == 1 { if beta == 0 { for i := range y[:n] { y[i] = 0 } } else { f64.ScalUnitary(beta, y[:n]) } } else { iy := ky if beta == 0 { for i := 0; i < n; i++ { y[iy] = 0 iy += incY } } else { if incY > 0 { f64.ScalInc(beta, y, uintptr(n), uintptr(incY)) } else { f64.ScalInc(beta, y, uintptr(n), uintptr(-incY)) } } } } if alpha == 0 { return } if n == 1 { y[0] += alpha * ap[0] * x[0] return } var offset int // Offset is the index of (i,i). if ul == blas.Upper { if incX == 1 { iy := ky for i := 0; i < n; i++ { xv := x[i] * alpha sum := ap[offset] * x[i] atmp := ap[offset+1 : offset+n-i] xtmp := x[i+1:] jy := ky + (i+1)*incY for j, v := range atmp { sum += v * xtmp[j] y[jy] += v * xv jy += incY } y[iy] += alpha * sum iy += incY offset += n - i } return } ix := kx iy := ky for i := 0; i < n; i++ { xv := x[ix] * alpha sum := ap[offset] * x[ix] atmp := ap[offset+1 : offset+n-i] jx := kx + (i+1)*incX jy := ky + (i+1)*incY for _, v := range atmp { sum += v * x[jx] y[jy] += v * xv jx += incX jy += incY } y[iy] += alpha * sum ix += incX iy += incY offset += n - i } return } if incX == 1 { iy := ky for i := 0; i < n; i++ { xv := x[i] * alpha atmp := ap[offset-i : offset] jy := ky var sum float64 for j, v := range atmp { sum += v * x[j] y[jy] += v * xv jy += incY } sum += ap[offset] * x[i] y[iy] += alpha * sum iy += incY offset += i + 2 } return } ix := kx iy := ky for i := 0; i < n; i++ { xv := x[ix] * alpha atmp := ap[offset-i : offset] jx := kx jy := ky var sum float64 for _, v := range atmp { sum += v * x[jx] y[jy] += v * xv jx += incX jy += incY } sum += ap[offset] * x[ix] y[iy] += alpha * sum ix += incX iy += incY offset += i + 2 } } // Dspr performs the symmetric rank-one operation // A += alpha * x * xᵀ // where A is an n×n symmetric matrix in packed format, x is a vector, and // alpha is a scalar. func (Implementation) Dspr(ul blas.Uplo, n int, alpha float64, x []float64, incX int, ap []float64) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if n < 0 { panic(nLT0) } if incX == 0 { panic(zeroIncX) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } if len(ap) < n*(n+1)/2 { panic(shortAP) } // Quick return if possible. if alpha == 0 { return } lenX := n var kx int if incX < 0 { kx = -(lenX - 1) * incX } var offset int // Offset is the index of (i,i). if ul == blas.Upper { if incX == 1 { for i := 0; i < n; i++ { atmp := ap[offset:] xv := alpha * x[i] xtmp := x[i:n] for j, v := range xtmp { atmp[j] += xv * v } offset += n - i } return } ix := kx for i := 0; i < n; i++ { jx := kx + i*incX atmp := ap[offset:] xv := alpha * x[ix] for j := 0; j < n-i; j++ { atmp[j] += xv * x[jx] jx += incX } ix += incX offset += n - i } return } if incX == 1 { for i := 0; i < n; i++ { atmp := ap[offset-i:] xv := alpha * x[i] xtmp := x[:i+1] for j, v := range xtmp { atmp[j] += xv * v } offset += i + 2 } return } ix := kx for i := 0; i < n; i++ { jx := kx atmp := ap[offset-i:] xv := alpha * x[ix] for j := 0; j <= i; j++ { atmp[j] += xv * x[jx] jx += incX } ix += incX offset += i + 2 } } // Dspr2 performs the symmetric rank-2 update // A += alpha * x * yᵀ + alpha * y * xᵀ // where A is an n×n symmetric matrix in packed format, x and y are vectors, // and alpha is a scalar. func (Implementation) Dspr2(ul blas.Uplo, n int, alpha float64, x []float64, incX int, y []float64, incY int, ap []float64) { if ul != blas.Lower && ul != blas.Upper { panic(badUplo) } if n < 0 { panic(nLT0) } if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } // Quick return if possible. if n == 0 { return } // For zero matrix size the following slice length checks are trivially satisfied. if (incX > 0 && len(x) <= (n-1)*incX) || (incX < 0 && len(x) <= (1-n)*incX) { panic(shortX) } if (incY > 0 && len(y) <= (n-1)*incY) || (incY < 0 && len(y) <= (1-n)*incY) { panic(shortY) } if len(ap) < n*(n+1)/2 { panic(shortAP) } // Quick return if possible. if alpha == 0 { return } var ky, kx int if incY < 0 { ky = -(n - 1) * incY } if incX < 0 { kx = -(n - 1) * incX } var offset int // Offset is the index of (i,i). if ul == blas.Upper { if incX == 1 && incY == 1 { for i := 0; i < n; i++ { atmp := ap[offset:] xi := x[i] yi := y[i] xtmp := x[i:n] ytmp := y[i:n] for j, v := range xtmp { atmp[j] += alpha * (xi*ytmp[j] + v*yi) } offset += n - i } return } ix := kx iy := ky for i := 0; i < n; i++ { jx := kx + i*incX jy := ky + i*incY atmp := ap[offset:] xi := x[ix] yi := y[iy] for j := 0; j < n-i; j++ { atmp[j] += alpha * (xi*y[jy] + x[jx]*yi) jx += incX jy += incY } ix += incX iy += incY offset += n - i } return } if incX == 1 && incY == 1 { for i := 0; i < n; i++ { atmp := ap[offset-i:] xi := x[i] yi := y[i] xtmp := x[:i+1] for j, v := range xtmp { atmp[j] += alpha * (xi*y[j] + v*yi) } offset += i + 2 } return } ix := kx iy := ky for i := 0; i < n; i++ { jx := kx jy := ky atmp := ap[offset-i:] for j := 0; j <= i; j++ { atmp[j] += alpha * (x[ix]*y[jy] + x[jx]*y[iy]) jx += incX jy += incY } ix += incX iy += incY offset += i + 2 } }
erwinvaneyk/kubernetes
vendor/gonum.org/v1/gonum/blas/gonum/level2float64.go
GO
apache-2.0
43,259
/************************************************************* * * MathJax/jax/output/HTML-CSS/fonts/TeX/Main/Bold/CombDiactForSymbols.js * * Copyright (c) 2009-2015 The MathJax Consortium * * 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. * */ MathJax.Hub.Insert( MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['MathJax_Main-bold'], { 0x20D7: [723,-513,0,-542,-33] // COMBINING RIGHT ARROW ABOVE } ); MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/Main/Bold/CombDiactForSymbols.js");
smmribeiro/intellij-community
python/helpers/MathJax/jax/output/HTML-CSS/fonts/TeX/Main/Bold/CombDiactForSymbols.js
JavaScript
apache-2.0
1,044
/** * Copyright 2008 Joe LaPenna */ package com.joelapenna.foursquared.widget; import com.joelapenna.foursquare.Foursquare; import com.joelapenna.foursquare.types.Group; import com.joelapenna.foursquare.types.Mayor; import com.joelapenna.foursquare.types.User; import com.joelapenna.foursquared.FoursquaredSettings; import com.joelapenna.foursquared.R; import com.joelapenna.foursquared.util.RemoteResourceManager; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import java.io.IOException; import java.util.Observable; import java.util.Observer; /** * @author Joe LaPenna (joe@joelapenna.com) */ public class MayorListAdapter extends BaseMayorAdapter implements ObservableAdapter { private static final String TAG = "MayorListAdapter"; private static final boolean DEBUG = FoursquaredSettings.DEBUG; private LayoutInflater mInflater; private RemoteResourceManager mRrm; private Handler mHandler = new Handler(); private RemoteResourceManagerObserver mResourcesObserver; public MayorListAdapter(Context context, RemoteResourceManager rrm) { super(context); mInflater = LayoutInflater.from(context); mRrm = rrm; mResourcesObserver = new RemoteResourceManagerObserver(); mRrm.addObserver(mResourcesObserver); } public void removeObserver() { mRrm.deleteObserver(mResourcesObserver); } @Override public View getView(int position, View convertView, ViewGroup parent) { // A ViewHolder keeps references to children views to avoid unnecessary // calls to findViewById() on each row. final ViewHolder holder; // When convertView is not null, we can reuse it directly, there is no // need to re-inflate it. We only inflate a new View when the // convertView supplied by ListView is null. if (convertView == null) { convertView = mInflater.inflate(R.layout.mayor_list_item, null); // Creates a ViewHolder and store references to the two children // views we want to bind data to. holder = new ViewHolder(); holder.photo = (ImageView)convertView.findViewById(R.id.photo); holder.firstLine = (TextView)convertView.findViewById(R.id.firstLine); holder.secondLine = (TextView)convertView.findViewById(R.id.mayorMessageTextView); convertView.setTag(holder); } else { // Get the ViewHolder back to get fast access to the TextView // and the ImageView. holder = (ViewHolder)convertView.getTag(); } Mayor mayor = (Mayor)getItem(position); final User user = mayor.getUser(); final Uri photoUri = Uri.parse(user.getPhoto()); try { Bitmap bitmap = BitmapFactory.decodeStream(mRrm.getInputStream(photoUri)); holder.photo.setImageBitmap(bitmap); } catch (IOException e) { if (Foursquare.MALE.equals(user.getGender())) { holder.photo.setImageResource(R.drawable.blank_boy); } else { holder.photo.setImageResource(R.drawable.blank_girl); } } holder.firstLine.setText(mayor.getUser().getFirstname()); holder.secondLine.setText(mayor.getMessage()); return convertView; } @Override public void setGroup(Group<Mayor> g) { super.setGroup(g); for (int i = 0; i < g.size(); i++) { Uri photoUri = Uri.parse((g.get(i)).getUser().getPhoto()); if (!mRrm.exists(photoUri)) { mRrm.request(photoUri); } } } private class RemoteResourceManagerObserver implements Observer { @Override public void update(Observable observable, Object data) { if (DEBUG) Log.d(TAG, "Fetcher got: " + data); mHandler.post(new Runnable() { @Override public void run() { notifyDataSetChanged(); } }); } } private static class ViewHolder { ImageView photo; TextView firstLine; TextView secondLine; } }
hejie/foursquared
main/src/com/joelapenna/foursquared/widget/MayorListAdapter.java
Java
apache-2.0
4,478
/* * Copyright (C) 2013 ZXing 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.zxing.client.android; import java.net.URI; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.Collection; import android.app.AlertDialog; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.CheckBoxPreference; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.PreferenceFragment; import android.preference.PreferenceScreen; public final class PreferencesFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener { private CheckBoxPreference[] checkBoxPrefs; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); addPreferencesFromResource(R.xml.preferences); PreferenceScreen preferences = getPreferenceScreen(); preferences.getSharedPreferences().registerOnSharedPreferenceChangeListener(this); checkBoxPrefs = findDecodePrefs(preferences, PreferencesActivity.KEY_DECODE_1D_PRODUCT, PreferencesActivity.KEY_DECODE_1D_INDUSTRIAL, PreferencesActivity.KEY_DECODE_QR, PreferencesActivity.KEY_DECODE_DATA_MATRIX, PreferencesActivity.KEY_DECODE_AZTEC, PreferencesActivity.KEY_DECODE_PDF417); disableLastCheckedPref(); EditTextPreference customProductSearch = (EditTextPreference) preferences.findPreference(PreferencesActivity.KEY_CUSTOM_PRODUCT_SEARCH); customProductSearch.setOnPreferenceChangeListener(new CustomSearchURLValidator()); } private static CheckBoxPreference[] findDecodePrefs(PreferenceScreen preferences, String... keys) { CheckBoxPreference[] prefs = new CheckBoxPreference[keys.length]; for (int i = 0; i < keys.length; i++) { prefs[i] = (CheckBoxPreference) preferences.findPreference(keys[i]); } return prefs; } @Override public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { disableLastCheckedPref(); } private void disableLastCheckedPref() { Collection<CheckBoxPreference> checked = new ArrayList<>(checkBoxPrefs.length); for (CheckBoxPreference pref : checkBoxPrefs) { if (pref.isChecked()) { checked.add(pref); } } boolean disable = checked.size() <= 1; for (CheckBoxPreference pref : checkBoxPrefs) { pref.setEnabled(!(disable && checked.contains(pref))); } } private class CustomSearchURLValidator implements Preference.OnPreferenceChangeListener { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { if (!isValid(newValue)) { AlertDialog.Builder builder = new AlertDialog.Builder(PreferencesFragment.this.getActivity()); builder.setTitle(R.string.msg_error); builder.setMessage(R.string.msg_invalid_value); builder.setCancelable(true); builder.show(); return false; } return true; } private boolean isValid(Object newValue) { // Allow empty/null value if (newValue == null) { return true; } String valueString = newValue.toString(); if (valueString.isEmpty()) { return true; } // Before validating, remove custom placeholders, which will not // be considered valid parts of the URL in some locations: // Blank %t and %s: valueString = valueString.replaceAll("%[st]", ""); // Blank %f but not if followed by digit or a-f as it may be a hex sequence valueString = valueString.replaceAll("%f(?![0-9a-f])", ""); // Require a scheme otherwise: try { URI uri = new URI(valueString); return uri.getScheme() != null; } catch (URISyntaxException use) { return false; } } } }
zhangyihao/zxing
android/src/com/google/zxing/client/android/PreferencesFragment.java
Java
apache-2.0
4,593
/* 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 upgrade import ( "fmt" "net/http" "os" apps "k8s.io/api/apps/v1" "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/util/sets" clientset "k8s.io/client-go/kubernetes" "k8s.io/kubernetes/cmd/kubeadm/app/constants" "k8s.io/kubernetes/cmd/kubeadm/app/preflight" ) // healthCheck is a helper struct for easily performing healthchecks against the cluster and printing the output type healthCheck struct { name string client clientset.Interface // f is invoked with a k8s client passed to it. Should return an optional error f func(clientset.Interface) error } // Check is part of the preflight.Checker interface func (c *healthCheck) Check() (warnings, errors []error) { if err := c.f(c.client); err != nil { return nil, []error{err} } return nil, nil } // Name is part of the preflight.Checker interface func (c *healthCheck) Name() string { return c.name } // CheckClusterHealth makes sure: // - the API /healthz endpoint is healthy // - all master Nodes are Ready // - (if self-hosted) that there are DaemonSets with at least one Pod for all control plane components // - (if static pod-hosted) that all required Static Pod manifests exist on disk func CheckClusterHealth(client clientset.Interface, ignoreChecksErrors sets.String) error { fmt.Println("[upgrade] Making sure the cluster is healthy:") healthChecks := []preflight.Checker{ &healthCheck{ name: "APIServerHealth", client: client, f: apiServerHealthy, }, &healthCheck{ name: "MasterNodesReady", client: client, f: masterNodesReady, }, // TODO: Add a check for ComponentStatuses here? } // Run slightly different health checks depending on control plane hosting type if IsControlPlaneSelfHosted(client) { healthChecks = append(healthChecks, &healthCheck{ name: "ControlPlaneHealth", client: client, f: controlPlaneHealth, }) } else { healthChecks = append(healthChecks, &healthCheck{ name: "StaticPodManifest", client: client, f: staticPodManifestHealth, }) } return preflight.RunChecks(healthChecks, os.Stderr, ignoreChecksErrors) } // apiServerHealthy checks whether the API server's /healthz endpoint is healthy func apiServerHealthy(client clientset.Interface) error { healthStatus := 0 // If client.Discovery().RESTClient() is nil, the fake client is used, and that means we are dry-running. Just proceed if client.Discovery().RESTClient() == nil { return nil } client.Discovery().RESTClient().Get().AbsPath("/healthz").Do().StatusCode(&healthStatus) if healthStatus != http.StatusOK { return fmt.Errorf("the API Server is unhealthy; /healthz didn't return %q", "ok") } return nil } // masterNodesReady checks whether all master Nodes in the cluster are in the Running state func masterNodesReady(client clientset.Interface) error { selector := labels.SelectorFromSet(labels.Set(map[string]string{ constants.LabelNodeRoleMaster: "", })) masters, err := client.CoreV1().Nodes().List(metav1.ListOptions{ LabelSelector: selector.String(), }) if err != nil { return fmt.Errorf("couldn't list masters in cluster: %v", err) } if len(masters.Items) == 0 { return fmt.Errorf("failed to find any nodes with master role") } notReadyMasters := getNotReadyNodes(masters.Items) if len(notReadyMasters) != 0 { return fmt.Errorf("there are NotReady masters in the cluster: %v", notReadyMasters) } return nil } // controlPlaneHealth ensures all control plane DaemonSets are healthy func controlPlaneHealth(client clientset.Interface) error { notReadyDaemonSets, err := getNotReadyDaemonSets(client) if err != nil { return err } if len(notReadyDaemonSets) != 0 { return fmt.Errorf("there are control plane DaemonSets in the cluster that are not ready: %v", notReadyDaemonSets) } return nil } // staticPodManifestHealth makes sure the required static pods are presents func staticPodManifestHealth(_ clientset.Interface) error { nonExistentManifests := []string{} for _, component := range constants.MasterComponents { manifestFile := constants.GetStaticPodFilepath(component, constants.GetStaticPodDirectory()) if _, err := os.Stat(manifestFile); os.IsNotExist(err) { nonExistentManifests = append(nonExistentManifests, manifestFile) } } if len(nonExistentManifests) == 0 { return nil } return fmt.Errorf("The control plane seems to be Static Pod-hosted, but some of the manifests don't seem to exist on disk. This probably means you're running 'kubeadm upgrade' on a remote machine, which is not supported for a Static Pod-hosted cluster. Manifest files not found: %v", nonExistentManifests) } // IsControlPlaneSelfHosted returns whether the control plane is self hosted or not func IsControlPlaneSelfHosted(client clientset.Interface) bool { notReadyDaemonSets, err := getNotReadyDaemonSets(client) if err != nil { return false } // If there are no NotReady DaemonSets, we are using self-hosting return len(notReadyDaemonSets) == 0 } // getNotReadyDaemonSets gets the amount of Ready control plane DaemonSets func getNotReadyDaemonSets(client clientset.Interface) ([]error, error) { notReadyDaemonSets := []error{} for _, component := range constants.MasterComponents { dsName := constants.AddSelfHostedPrefix(component) ds, err := client.AppsV1().DaemonSets(metav1.NamespaceSystem).Get(dsName, metav1.GetOptions{}) if err != nil { return nil, fmt.Errorf("couldn't get daemonset %q in the %s namespace", dsName, metav1.NamespaceSystem) } if err := daemonSetHealth(&ds.Status); err != nil { notReadyDaemonSets = append(notReadyDaemonSets, fmt.Errorf("DaemonSet %q not healthy: %v", dsName, err)) } } return notReadyDaemonSets, nil } // daemonSetHealth is a helper function for getting the health of a DaemonSet's status func daemonSetHealth(dsStatus *apps.DaemonSetStatus) error { if dsStatus.CurrentNumberScheduled != dsStatus.DesiredNumberScheduled { return fmt.Errorf("current number of scheduled Pods ('%d') doesn't match the amount of desired Pods ('%d')", dsStatus.CurrentNumberScheduled, dsStatus.DesiredNumberScheduled) } if dsStatus.NumberAvailable == 0 { return fmt.Errorf("no available Pods for DaemonSet") } if dsStatus.NumberReady == 0 { return fmt.Errorf("no ready Pods for DaemonSet") } return nil } // getNotReadyNodes returns a string slice of nodes in the cluster that are NotReady func getNotReadyNodes(nodes []v1.Node) []string { notReadyNodes := []string{} for _, node := range nodes { for _, condition := range node.Status.Conditions { if condition.Type == v1.NodeReady && condition.Status != v1.ConditionTrue { notReadyNodes = append(notReadyNodes, node.ObjectMeta.Name) } } } return notReadyNodes }
adityakali/kubernetes
cmd/kubeadm/app/phases/upgrade/health.go
GO
apache-2.0
7,381
/* Copyright 2014 The Kubernetes 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. */ package meta import ( "reflect" "testing" "github.com/GoogleCloudPlatform/kubernetes/pkg/runtime" "github.com/GoogleCloudPlatform/kubernetes/pkg/util" ) func TestGenericTypeMeta(t *testing.T) { type TypeMeta struct { Kind string `json:"kind,omitempty"` Namespace string `json:"namespace,omitempty"` Name string `json:"name,omitempty"` GenerateName string `json:"generateName,omitempty"` UID string `json:"uid,omitempty"` CreationTimestamp util.Time `json:"creationTimestamp,omitempty"` SelfLink string `json:"selfLink,omitempty"` ResourceVersion string `json:"resourceVersion,omitempty"` APIVersion string `json:"apiVersion,omitempty"` Labels map[string]string `json:"labels,omitempty"` Annotations map[string]string `json:"annotations,omitempty"` } type Object struct { TypeMeta `json:",inline"` } j := Object{ TypeMeta{ Namespace: "bar", Name: "foo", GenerateName: "prefix", UID: "uid", APIVersion: "a", Kind: "b", ResourceVersion: "1", SelfLink: "some/place/only/we/know", Labels: map[string]string{"foo": "bar"}, Annotations: map[string]string{"x": "y"}, }, } accessor, err := Accessor(&j) if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := "bar", accessor.Namespace(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "foo", accessor.Name(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "prefix", accessor.GenerateName(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "uid", string(accessor.UID()); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "a", accessor.APIVersion(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "b", accessor.Kind(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "1", accessor.ResourceVersion(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "some/place/only/we/know", accessor.SelfLink(); e != a { t.Errorf("expected %v, got %v", e, a) } typeAccessor, err := TypeAccessor(&j) if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := "a", accessor.APIVersion(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "b", accessor.Kind(); e != a { t.Errorf("expected %v, got %v", e, a) } accessor.SetNamespace("baz") accessor.SetName("bar") accessor.SetGenerateName("generate") accessor.SetUID("other") accessor.SetAPIVersion("c") accessor.SetKind("d") accessor.SetResourceVersion("2") accessor.SetSelfLink("google.com") // Prove that accessor changes the original object. if e, a := "baz", j.Namespace; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "bar", j.Name; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "generate", j.GenerateName; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "other", j.UID; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "c", j.APIVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "d", j.Kind; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "2", j.ResourceVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "google.com", j.SelfLink; e != a { t.Errorf("expected %v, got %v", e, a) } typeAccessor.SetAPIVersion("d") typeAccessor.SetKind("e") if e, a := "d", j.APIVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "e", j.Kind; e != a { t.Errorf("expected %v, got %v", e, a) } } type InternalTypeMeta struct { Kind string `json:"kind,omitempty"` Namespace string `json:"namespace,omitempty"` Name string `json:"name,omitempty"` GenerateName string `json:"generateName,omitempty"` UID string `json:"uid,omitempty"` CreationTimestamp util.Time `json:"creationTimestamp,omitempty"` SelfLink string `json:"selfLink,omitempty"` ResourceVersion string `json:"resourceVersion,omitempty"` APIVersion string `json:"apiVersion,omitempty"` Labels map[string]string `json:"labels,omitempty"` Annotations map[string]string `json:"annotations,omitempty"` } type InternalObject struct { TypeMeta InternalTypeMeta `json:",inline"` } func (*InternalObject) IsAnAPIObject() {} func TestGenericTypeMetaAccessor(t *testing.T) { j := &InternalObject{ InternalTypeMeta{ Namespace: "bar", Name: "foo", GenerateName: "prefix", UID: "uid", APIVersion: "a", Kind: "b", ResourceVersion: "1", SelfLink: "some/place/only/we/know", Labels: map[string]string{"foo": "bar"}, Annotations: map[string]string{"x": "y"}, }, } accessor := NewAccessor() namespace, err := accessor.Namespace(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := "bar", namespace; e != a { t.Errorf("expected %v, got %v", e, a) } name, err := accessor.Name(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := "foo", name; e != a { t.Errorf("expected %v, got %v", e, a) } generateName, err := accessor.GenerateName(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := "prefix", generateName; e != a { t.Errorf("expected %v, got %v", e, a) } uid, err := accessor.UID(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := "uid", string(uid); e != a { t.Errorf("expected %v, got %v", e, a) } apiVersion, err := accessor.APIVersion(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := "a", apiVersion; e != a { t.Errorf("expected %v, got %v", e, a) } kind, err := accessor.Kind(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := "b", kind; e != a { t.Errorf("expected %v, got %v", e, a) } rv, err := accessor.ResourceVersion(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := "1", rv; e != a { t.Errorf("expected %v, got %v", e, a) } selfLink, err := accessor.SelfLink(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := "some/place/only/we/know", selfLink; e != a { t.Errorf("expected %v, got %v", e, a) } labels, err := accessor.Labels(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := 1, len(labels); e != a { t.Errorf("expected %v, got %v", e, a) } annotations, err := accessor.Annotations(j) if err != nil { t.Errorf("unexpected error: %v", err) } if e, a := 1, len(annotations); e != a { t.Errorf("expected %v, got %v", e, a) } if err := accessor.SetNamespace(j, "baz"); err != nil { t.Errorf("unexpected error: %v", err) } if err := accessor.SetName(j, "bar"); err != nil { t.Errorf("unexpected error: %v", err) } if err := accessor.SetGenerateName(j, "generate"); err != nil { t.Errorf("unexpected error: %v", err) } if err := accessor.SetUID(j, "other"); err != nil { t.Errorf("unexpected error: %v", err) } if err := accessor.SetAPIVersion(j, "c"); err != nil { t.Errorf("unexpected error: %v", err) } if err := accessor.SetKind(j, "d"); err != nil { t.Errorf("unexpected error: %v", err) } if err := accessor.SetResourceVersion(j, "2"); err != nil { t.Errorf("unexpected error: %v", err) } if err := accessor.SetSelfLink(j, "google.com"); err != nil { t.Errorf("unexpected error: %v", err) } if err := accessor.SetLabels(j, map[string]string{}); err != nil { t.Errorf("unexpected error: %v", err) } var nilMap map[string]string if err := accessor.SetAnnotations(j, nilMap); err != nil { t.Errorf("unexpected error: %v", err) } // Prove that accessor changes the original object. if e, a := "baz", j.TypeMeta.Namespace; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "bar", j.TypeMeta.Name; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "generate", j.TypeMeta.GenerateName; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "other", j.TypeMeta.UID; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "c", j.TypeMeta.APIVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "d", j.TypeMeta.Kind; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "2", j.TypeMeta.ResourceVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "google.com", j.TypeMeta.SelfLink; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := map[string]string{}, j.TypeMeta.Labels; !reflect.DeepEqual(e, a) { t.Errorf("expected %#v, got %#v", e, a) } if e, a := nilMap, j.TypeMeta.Annotations; !reflect.DeepEqual(e, a) { t.Errorf("expected %#v, got %#v", e, a) } } func TestGenericObjectMeta(t *testing.T) { type TypeMeta struct { Kind string `json:"kind,omitempty"` APIVersion string `json:"apiVersion,omitempty"` } type ObjectMeta struct { Namespace string `json:"namespace,omitempty"` Name string `json:"name,omitempty"` GenerateName string `json:"generateName,omitempty"` UID string `json:"uid,omitempty"` CreationTimestamp util.Time `json:"creationTimestamp,omitempty"` SelfLink string `json:"selfLink,omitempty"` ResourceVersion string `json:"resourceVersion,omitempty"` Labels map[string]string `json:"labels,omitempty"` Annotations map[string]string `json:"annotations,omitempty"` } type Object struct { TypeMeta `json:",inline"` ObjectMeta `json:"metadata"` } j := Object{ TypeMeta{ APIVersion: "a", Kind: "b", }, ObjectMeta{ Namespace: "bar", Name: "foo", GenerateName: "prefix", UID: "uid", ResourceVersion: "1", SelfLink: "some/place/only/we/know", Labels: map[string]string{"foo": "bar"}, Annotations: map[string]string{"a": "b"}, }, } accessor, err := Accessor(&j) if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := "bar", accessor.Namespace(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "foo", accessor.Name(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "prefix", accessor.GenerateName(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "uid", string(accessor.UID()); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "a", accessor.APIVersion(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "b", accessor.Kind(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "1", accessor.ResourceVersion(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "some/place/only/we/know", accessor.SelfLink(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := 1, len(accessor.Labels()); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := 1, len(accessor.Annotations()); e != a { t.Errorf("expected %v, got %v", e, a) } accessor.SetNamespace("baz") accessor.SetName("bar") accessor.SetGenerateName("generate") accessor.SetUID("other") accessor.SetAPIVersion("c") accessor.SetKind("d") accessor.SetResourceVersion("2") accessor.SetSelfLink("google.com") accessor.SetLabels(map[string]string{"other": "label"}) accessor.SetAnnotations(map[string]string{"c": "d"}) // Prove that accessor changes the original object. if e, a := "baz", j.Namespace; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "bar", j.Name; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "generate", j.GenerateName; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "other", j.UID; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "c", j.APIVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "d", j.Kind; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "2", j.ResourceVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "google.com", j.SelfLink; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := map[string]string{"other": "label"}, j.Labels; !reflect.DeepEqual(e, a) { t.Errorf("expected %#v, got %#v", e, a) } if e, a := map[string]string{"c": "d"}, j.Annotations; !reflect.DeepEqual(e, a) { t.Errorf("expected %#v, got %#v", e, a) } } func TestGenericListMeta(t *testing.T) { type TypeMeta struct { Kind string `json:"kind,omitempty"` APIVersion string `json:"apiVersion,omitempty"` } type ListMeta struct { SelfLink string `json:"selfLink,omitempty"` ResourceVersion string `json:"resourceVersion,omitempty"` } type Object struct { TypeMeta `json:",inline"` ListMeta `json:"metadata"` } j := Object{ TypeMeta{ APIVersion: "a", Kind: "b", }, ListMeta{ ResourceVersion: "1", SelfLink: "some/place/only/we/know", }, } accessor, err := Accessor(&j) if err != nil { t.Fatalf("unexpected error: %v", err) } if e, a := "", accessor.Name(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "", string(accessor.UID()); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "a", accessor.APIVersion(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "b", accessor.Kind(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "1", accessor.ResourceVersion(); e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "some/place/only/we/know", accessor.SelfLink(); e != a { t.Errorf("expected %v, got %v", e, a) } accessor.SetName("bar") accessor.SetUID("other") accessor.SetAPIVersion("c") accessor.SetKind("d") accessor.SetResourceVersion("2") accessor.SetSelfLink("google.com") // Prove that accessor changes the original object. if e, a := "c", j.APIVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "d", j.Kind; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "2", j.ResourceVersion; e != a { t.Errorf("expected %v, got %v", e, a) } if e, a := "google.com", j.SelfLink; e != a { t.Errorf("expected %v, got %v", e, a) } } type MyAPIObject struct { TypeMeta InternalTypeMeta `json:",inline"` } func (*MyAPIObject) IsAnAPIObject() {} type MyIncorrectlyMarkedAsAPIObject struct { } func (*MyIncorrectlyMarkedAsAPIObject) IsAnAPIObject() {} func TestResourceVersionerOfAPI(t *testing.T) { type T struct { runtime.Object Expected string } testCases := map[string]T{ "empty api object": {&MyAPIObject{}, ""}, "api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"}, "pointer to api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"}, } versioning := NewAccessor() for key, testCase := range testCases { actual, err := versioning.ResourceVersion(testCase.Object) if err != nil { t.Errorf("%s: unexpected error %#v", key, err) } if actual != testCase.Expected { t.Errorf("%s: expected %v, got %v", key, testCase.Expected, actual) } } failingCases := map[string]struct { runtime.Object Expected string }{ "not a valid object to try": {&MyIncorrectlyMarkedAsAPIObject{}, "1"}, } for key, testCase := range failingCases { _, err := versioning.ResourceVersion(testCase.Object) if err == nil { t.Errorf("%s: expected error, got nil", key) } } setCases := map[string]struct { runtime.Object Expected string }{ "pointer to api object with version": {&MyAPIObject{TypeMeta: InternalTypeMeta{ResourceVersion: "1"}}, "1"}, } for key, testCase := range setCases { if err := versioning.SetResourceVersion(testCase.Object, "5"); err != nil { t.Errorf("%s: unexpected error %#v", key, err) } actual, err := versioning.ResourceVersion(testCase.Object) if err != nil { t.Errorf("%s: unexpected error %#v", key, err) } if actual != "5" { t.Errorf("%s: expected %v, got %v", key, "5", actual) } } } func TestTypeMetaSelfLinker(t *testing.T) { table := map[string]struct { obj runtime.Object expect string try string succeed bool }{ "normal": { obj: &MyAPIObject{TypeMeta: InternalTypeMeta{SelfLink: "foobar"}}, expect: "foobar", try: "newbar", succeed: true, }, "fail": { obj: &MyIncorrectlyMarkedAsAPIObject{}, succeed: false, }, } linker := runtime.SelfLinker(NewAccessor()) for name, item := range table { got, err := linker.SelfLink(item.obj) if e, a := item.succeed, err == nil; e != a { t.Errorf("%v: expected %v, got %v", name, e, a) } if e, a := item.expect, got; item.succeed && e != a { t.Errorf("%v: expected %v, got %v", name, e, a) } err = linker.SetSelfLink(item.obj, item.try) if e, a := item.succeed, err == nil; e != a { t.Errorf("%v: expected %v, got %v", name, e, a) } if item.succeed { got, err := linker.SelfLink(item.obj) if err != nil { t.Errorf("%v: expected no err, got %v", name, err) } if e, a := item.try, got; e != a { t.Errorf("%v: expected %v, got %v", name, e, a) } } } }
ycaihua/kubernetes
pkg/api/meta/meta_test.go
GO
apache-2.0
17,932
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Oracle Utility Class * * @category Database * @author ExpressionEngine Dev Team * @link http://codeigniter.com/user_guide/database/ */ class CI_DB_oci8_utility extends CI_DB_utility { /** * List databases * * @access private * @return bool */ function _list_databases() { return FALSE; } // -------------------------------------------------------------------- /** * Optimize table query * * Generates a platform-specific query so that a table can be optimized * * @access private * @param string the table name * @return object */ function _optimize_table($table) { return FALSE; // Is this supported in Oracle? } // -------------------------------------------------------------------- /** * Repair table query * * Generates a platform-specific query so that a table can be repaired * * @access private * @param string the table name * @return object */ function _repair_table($table) { return FALSE; // Is this supported in Oracle? } // -------------------------------------------------------------------- /** * Oracle Export * * @access private * @param array Preferences * @return mixed */ function _backup($params = array()) { // Currently unsupported return $this->db->display_error('db_unsuported_feature'); } } /* End of file oci8_utility.php */ /* Location: ./system/database/drivers/oci8/oci8_utility.php */
amx15/liquor-database
system/database/drivers/oci8/oci8_utility.php
PHP
apache-2.0
1,929
package cache import ( "context" "github.com/docker/distribution" prometheus "github.com/docker/distribution/metrics" "github.com/opencontainers/go-digest" ) // Metrics is used to hold metric counters // related to the number of times a cache was // hit or missed. type Metrics struct { Requests uint64 Hits uint64 Misses uint64 } // Logger can be provided on the MetricsTracker to log errors. // // Usually, this is just a proxy to dcontext.GetLogger. type Logger interface { Errorf(format string, args ...interface{}) } // MetricsTracker represents a metric tracker // which simply counts the number of hits and misses. type MetricsTracker interface { Hit() Miss() Metrics() Metrics Logger(context.Context) Logger } type cachedBlobStatter struct { cache distribution.BlobDescriptorService backend distribution.BlobDescriptorService tracker MetricsTracker } var ( // cacheCount is the number of total cache request received/hits/misses cacheCount = prometheus.StorageNamespace.NewLabeledCounter("cache", "The number of cache request received", "type") ) // NewCachedBlobStatter creates a new statter which prefers a cache and // falls back to a backend. func NewCachedBlobStatter(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService) distribution.BlobDescriptorService { return &cachedBlobStatter{ cache: cache, backend: backend, } } // NewCachedBlobStatterWithMetrics creates a new statter which prefers a cache and // falls back to a backend. Hits and misses will send to the tracker. func NewCachedBlobStatterWithMetrics(cache distribution.BlobDescriptorService, backend distribution.BlobDescriptorService, tracker MetricsTracker) distribution.BlobStatter { return &cachedBlobStatter{ cache: cache, backend: backend, tracker: tracker, } } func (cbds *cachedBlobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) { cacheCount.WithValues("Request").Inc(1) desc, err := cbds.cache.Stat(ctx, dgst) if err != nil { if err != distribution.ErrBlobUnknown { logErrorf(ctx, cbds.tracker, "error retrieving descriptor from cache: %v", err) } goto fallback } cacheCount.WithValues("Hit").Inc(1) if cbds.tracker != nil { cbds.tracker.Hit() } return desc, nil fallback: cacheCount.WithValues("Miss").Inc(1) if cbds.tracker != nil { cbds.tracker.Miss() } desc, err = cbds.backend.Stat(ctx, dgst) if err != nil { return desc, err } if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil { logErrorf(ctx, cbds.tracker, "error adding descriptor %v to cache: %v", desc.Digest, err) } return desc, err } func (cbds *cachedBlobStatter) Clear(ctx context.Context, dgst digest.Digest) error { err := cbds.cache.Clear(ctx, dgst) if err != nil { return err } err = cbds.backend.Clear(ctx, dgst) if err != nil { return err } return nil } func (cbds *cachedBlobStatter) SetDescriptor(ctx context.Context, dgst digest.Digest, desc distribution.Descriptor) error { if err := cbds.cache.SetDescriptor(ctx, dgst, desc); err != nil { logErrorf(ctx, cbds.tracker, "error adding descriptor %v to cache: %v", desc.Digest, err) } return nil } func logErrorf(ctx context.Context, tracker MetricsTracker, format string, args ...interface{}) { if tracker == nil { return } logger := tracker.Logger(ctx) if logger == nil { return } logger.Errorf(format, args...) }
coreydaley/source-to-image
vendor/github.com/docker/distribution/registry/storage/cache/cachedblobdescriptorstore.go
GO
apache-2.0
3,430
<?php /** * PHPExcel * * Copyright (c) 2006 - 2011 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Worksheet * @copyright Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version 1.7.6, 2011-02-27 */ /** * PHPExcel_Worksheet_PageSetup * * <code> * Paper size taken from Office Open XML Part 4 - Markup Language Reference, page 1988: * * 1 = Letter paper (8.5 in. by 11 in.) * 2 = Letter small paper (8.5 in. by 11 in.) * 3 = Tabloid paper (11 in. by 17 in.) * 4 = Ledger paper (17 in. by 11 in.) * 5 = Legal paper (8.5 in. by 14 in.) * 6 = Statement paper (5.5 in. by 8.5 in.) * 7 = Executive paper (7.25 in. by 10.5 in.) * 8 = A3 paper (297 mm by 420 mm) * 9 = A4 paper (210 mm by 297 mm) * 10 = A4 small paper (210 mm by 297 mm) * 11 = A5 paper (148 mm by 210 mm) * 12 = B4 paper (250 mm by 353 mm) * 13 = B5 paper (176 mm by 250 mm) * 14 = Folio paper (8.5 in. by 13 in.) * 15 = Quarto paper (215 mm by 275 mm) * 16 = Standard paper (10 in. by 14 in.) * 17 = Standard paper (11 in. by 17 in.) * 18 = Note paper (8.5 in. by 11 in.) * 19 = #9 envelope (3.875 in. by 8.875 in.) * 20 = #10 envelope (4.125 in. by 9.5 in.) * 21 = #11 envelope (4.5 in. by 10.375 in.) * 22 = #12 envelope (4.75 in. by 11 in.) * 23 = #14 envelope (5 in. by 11.5 in.) * 24 = C paper (17 in. by 22 in.) * 25 = D paper (22 in. by 34 in.) * 26 = E paper (34 in. by 44 in.) * 27 = DL envelope (110 mm by 220 mm) * 28 = C5 envelope (162 mm by 229 mm) * 29 = C3 envelope (324 mm by 458 mm) * 30 = C4 envelope (229 mm by 324 mm) * 31 = C6 envelope (114 mm by 162 mm) * 32 = C65 envelope (114 mm by 229 mm) * 33 = B4 envelope (250 mm by 353 mm) * 34 = B5 envelope (176 mm by 250 mm) * 35 = B6 envelope (176 mm by 125 mm) * 36 = Italy envelope (110 mm by 230 mm) * 37 = Monarch envelope (3.875 in. by 7.5 in.). * 38 = 6 3/4 envelope (3.625 in. by 6.5 in.) * 39 = US standard fanfold (14.875 in. by 11 in.) * 40 = German standard fanfold (8.5 in. by 12 in.) * 41 = German legal fanfold (8.5 in. by 13 in.) * 42 = ISO B4 (250 mm by 353 mm) * 43 = Japanese double postcard (200 mm by 148 mm) * 44 = Standard paper (9 in. by 11 in.) * 45 = Standard paper (10 in. by 11 in.) * 46 = Standard paper (15 in. by 11 in.) * 47 = Invite envelope (220 mm by 220 mm) * 50 = Letter extra paper (9.275 in. by 12 in.) * 51 = Legal extra paper (9.275 in. by 15 in.) * 52 = Tabloid extra paper (11.69 in. by 18 in.) * 53 = A4 extra paper (236 mm by 322 mm) * 54 = Letter transverse paper (8.275 in. by 11 in.) * 55 = A4 transverse paper (210 mm by 297 mm) * 56 = Letter extra transverse paper (9.275 in. by 12 in.) * 57 = SuperA/SuperA/A4 paper (227 mm by 356 mm) * 58 = SuperB/SuperB/A3 paper (305 mm by 487 mm) * 59 = Letter plus paper (8.5 in. by 12.69 in.) * 60 = A4 plus paper (210 mm by 330 mm) * 61 = A5 transverse paper (148 mm by 210 mm) * 62 = JIS B5 transverse paper (182 mm by 257 mm) * 63 = A3 extra paper (322 mm by 445 mm) * 64 = A5 extra paper (174 mm by 235 mm) * 65 = ISO B5 extra paper (201 mm by 276 mm) * 66 = A2 paper (420 mm by 594 mm) * 67 = A3 transverse paper (297 mm by 420 mm) * 68 = A3 extra transverse paper (322 mm by 445 mm) * </code> * * @category PHPExcel * @package PHPExcel_Worksheet * @copyright Copyright (c) 2006 - 2011 PHPExcel (http://www.codeplex.com/PHPExcel) */ class PHPExcel_Worksheet_PageSetup { /* Paper size */ const PAPERSIZE_LETTER = 1; const PAPERSIZE_LETTER_SMALL = 2; const PAPERSIZE_TABLOID = 3; const PAPERSIZE_LEDGER = 4; const PAPERSIZE_LEGAL = 5; const PAPERSIZE_STATEMENT = 6; const PAPERSIZE_EXECUTIVE = 7; const PAPERSIZE_A3 = 8; const PAPERSIZE_A4 = 9; const PAPERSIZE_A4_SMALL = 10; const PAPERSIZE_A5 = 11; const PAPERSIZE_B4 = 12; const PAPERSIZE_B5 = 13; const PAPERSIZE_FOLIO = 14; const PAPERSIZE_QUARTO = 15; const PAPERSIZE_STANDARD_1 = 16; const PAPERSIZE_STANDARD_2 = 17; const PAPERSIZE_NOTE = 18; const PAPERSIZE_NO9_ENVELOPE = 19; const PAPERSIZE_NO10_ENVELOPE = 20; const PAPERSIZE_NO11_ENVELOPE = 21; const PAPERSIZE_NO12_ENVELOPE = 22; const PAPERSIZE_NO14_ENVELOPE = 23; const PAPERSIZE_C = 24; const PAPERSIZE_D = 25; const PAPERSIZE_E = 26; const PAPERSIZE_DL_ENVELOPE = 27; const PAPERSIZE_C5_ENVELOPE = 28; const PAPERSIZE_C3_ENVELOPE = 29; const PAPERSIZE_C4_ENVELOPE = 30; const PAPERSIZE_C6_ENVELOPE = 31; const PAPERSIZE_C65_ENVELOPE = 32; const PAPERSIZE_B4_ENVELOPE = 33; const PAPERSIZE_B5_ENVELOPE = 34; const PAPERSIZE_B6_ENVELOPE = 35; const PAPERSIZE_ITALY_ENVELOPE = 36; const PAPERSIZE_MONARCH_ENVELOPE = 37; const PAPERSIZE_6_3_4_ENVELOPE = 38; const PAPERSIZE_US_STANDARD_FANFOLD = 39; const PAPERSIZE_GERMAN_STANDARD_FANFOLD = 40; const PAPERSIZE_GERMAN_LEGAL_FANFOLD = 41; const PAPERSIZE_ISO_B4 = 42; const PAPERSIZE_JAPANESE_DOUBLE_POSTCARD = 43; const PAPERSIZE_STANDARD_PAPER_1 = 44; const PAPERSIZE_STANDARD_PAPER_2 = 45; const PAPERSIZE_STANDARD_PAPER_3 = 46; const PAPERSIZE_INVITE_ENVELOPE = 47; const PAPERSIZE_LETTER_EXTRA_PAPER = 48; const PAPERSIZE_LEGAL_EXTRA_PAPER = 49; const PAPERSIZE_TABLOID_EXTRA_PAPER = 50; const PAPERSIZE_A4_EXTRA_PAPER = 51; const PAPERSIZE_LETTER_TRANSVERSE_PAPER = 52; const PAPERSIZE_A4_TRANSVERSE_PAPER = 53; const PAPERSIZE_LETTER_EXTRA_TRANSVERSE_PAPER = 54; const PAPERSIZE_SUPERA_SUPERA_A4_PAPER = 55; const PAPERSIZE_SUPERB_SUPERB_A3_PAPER = 56; const PAPERSIZE_LETTER_PLUS_PAPER = 57; const PAPERSIZE_A4_PLUS_PAPER = 58; const PAPERSIZE_A5_TRANSVERSE_PAPER = 59; const PAPERSIZE_JIS_B5_TRANSVERSE_PAPER = 60; const PAPERSIZE_A3_EXTRA_PAPER = 61; const PAPERSIZE_A5_EXTRA_PAPER = 62; const PAPERSIZE_ISO_B5_EXTRA_PAPER = 63; const PAPERSIZE_A2_PAPER = 64; const PAPERSIZE_A3_TRANSVERSE_PAPER = 65; const PAPERSIZE_A3_EXTRA_TRANSVERSE_PAPER = 66; /* Page orientation */ const ORIENTATION_DEFAULT = 'default'; const ORIENTATION_LANDSCAPE = 'landscape'; const ORIENTATION_PORTRAIT = 'portrait'; /* Print Range Set Method */ const SETPRINTRANGE_OVERWRITE = 'O'; const SETPRINTRANGE_INSERT = 'I'; /** * Paper size * * @var int */ private $_paperSize = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER; /** * Orientation * * @var string */ private $_orientation = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT; /** * Scale (Print Scale) * * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use * * @var int? */ private $_scale = 100; /** * Fit To Page * Whether scale or fitToWith / fitToHeight applies * * @var boolean */ private $_fitToPage = false; /** * Fit To Height * Number of vertical pages to fit on * * @var int? */ private $_fitToHeight = 1; /** * Fit To Width * Number of horizontal pages to fit on * * @var int? */ private $_fitToWidth = 1; /** * Columns to repeat at left * * @var array Containing start column and end column, empty array if option unset */ private $_columnsToRepeatAtLeft = array('', ''); /** * Rows to repeat at top * * @var array Containing start row number and end row number, empty array if option unset */ private $_rowsToRepeatAtTop = array(0, 0); /** * Center page horizontally * * @var boolean */ private $_horizontalCentered = false; /** * Center page vertically * * @var boolean */ private $_verticalCentered = false; /** * Print area * * @var string */ private $_printArea = null; /** * First page number * * @var int */ private $_firstPageNumber = null; /** * Create a new PHPExcel_Worksheet_PageSetup */ public function __construct() { } /** * Get Paper Size * * @return int */ public function getPaperSize() { return $this->_paperSize; } /** * Set Paper Size * * @param int $pValue * @return PHPExcel_Worksheet_PageSetup */ public function setPaperSize($pValue = PHPExcel_Worksheet_PageSetup::PAPERSIZE_LETTER) { $this->_paperSize = $pValue; return $this; } /** * Get Orientation * * @return string */ public function getOrientation() { return $this->_orientation; } /** * Set Orientation * * @param string $pValue * @return PHPExcel_Worksheet_PageSetup */ public function setOrientation($pValue = PHPExcel_Worksheet_PageSetup::ORIENTATION_DEFAULT) { $this->_orientation = $pValue; return $this; } /** * Get Scale * * @return int? */ public function getScale() { return $this->_scale; } /** * Set Scale * * Print scaling. Valid values range from 10 to 400 * This setting is overridden when fitToWidth and/or fitToHeight are in use * * @param int? $pValue * @param boolean $pUpdate Update fitToPage so scaling applies rather than fitToHeight / fitToWidth * @throws Exception * @return PHPExcel_Worksheet_PageSetup */ public function setScale($pValue = 100, $pUpdate = true) { // Microsoft Office Excel 2007 only allows setting a scale between 10 and 400 via the user interface, // but it is apparently still able to handle any scale >= 0, where 0 results in 100 if (($pValue >= 0) || is_null($pValue)) { $this->_scale = $pValue; if ($pUpdate) { $this->_fitToPage = false; } } else { throw new Exception("Scale must not be negative"); } return $this; } /** * Get Fit To Page * * @return boolean */ public function getFitToPage() { return $this->_fitToPage; } /** * Set Fit To Page * * @param boolean $pValue * @return PHPExcel_Worksheet_PageSetup */ public function setFitToPage($pValue = true) { $this->_fitToPage = $pValue; return $this; } /** * Get Fit To Height * * @return int? */ public function getFitToHeight() { return $this->_fitToHeight; } /** * Set Fit To Height * * @param int? $pValue * @param boolean $pUpdate Update fitToPage so it applies rather than scaling * @return PHPExcel_Worksheet_PageSetup */ public function setFitToHeight($pValue = 1, $pUpdate = true) { $this->_fitToHeight = $pValue; if ($pUpdate) { $this->_fitToPage = true; } return $this; } /** * Get Fit To Width * * @return int? */ public function getFitToWidth() { return $this->_fitToWidth; } /** * Set Fit To Width * * @param int? $pValue * @param boolean $pUpdate Update fitToPage so it applies rather than scaling * @return PHPExcel_Worksheet_PageSetup */ public function setFitToWidth($pValue = 1, $pUpdate = true) { $this->_fitToWidth = $pValue; if ($pUpdate) { $this->_fitToPage = true; } return $this; } /** * Is Columns to repeat at left set? * * @return boolean */ public function isColumnsToRepeatAtLeftSet() { if (is_array($this->_columnsToRepeatAtLeft)) { if ($this->_columnsToRepeatAtLeft[0] != '' && $this->_columnsToRepeatAtLeft[1] != '') { return true; } } return false; } /** * Get Columns to repeat at left * * @return array Containing start column and end column, empty array if option unset */ public function getColumnsToRepeatAtLeft() { return $this->_columnsToRepeatAtLeft; } /** * Set Columns to repeat at left * * @param array $pValue Containing start column and end column, empty array if option unset * @return PHPExcel_Worksheet_PageSetup */ public function setColumnsToRepeatAtLeft($pValue = null) { if (is_array($pValue)) { $this->_columnsToRepeatAtLeft = $pValue; } return $this; } /** * Set Columns to repeat at left by start and end * * @param string $pStart * @param string $pEnd * @return PHPExcel_Worksheet_PageSetup */ public function setColumnsToRepeatAtLeftByStartAndEnd($pStart = 'A', $pEnd = 'A') { $this->_columnsToRepeatAtLeft = array($pStart, $pEnd); return $this; } /** * Is Rows to repeat at top set? * * @return boolean */ public function isRowsToRepeatAtTopSet() { if (is_array($this->_rowsToRepeatAtTop)) { if ($this->_rowsToRepeatAtTop[0] != 0 && $this->_rowsToRepeatAtTop[1] != 0) { return true; } } return false; } /** * Get Rows to repeat at top * * @return array Containing start column and end column, empty array if option unset */ public function getRowsToRepeatAtTop() { return $this->_rowsToRepeatAtTop; } /** * Set Rows to repeat at top * * @param array $pValue Containing start column and end column, empty array if option unset * @return PHPExcel_Worksheet_PageSetup */ public function setRowsToRepeatAtTop($pValue = null) { if (is_array($pValue)) { $this->_rowsToRepeatAtTop = $pValue; } return $this; } /** * Set Rows to repeat at top by start and end * * @param int $pStart * @param int $pEnd * @return PHPExcel_Worksheet_PageSetup */ public function setRowsToRepeatAtTopByStartAndEnd($pStart = 1, $pEnd = 1) { $this->_rowsToRepeatAtTop = array($pStart, $pEnd); return $this; } /** * Get center page horizontally * * @return bool */ public function getHorizontalCentered() { return $this->_horizontalCentered; } /** * Set center page horizontally * * @param bool $value * @return PHPExcel_Worksheet_PageSetup */ public function setHorizontalCentered($value = false) { $this->_horizontalCentered = $value; return $this; } /** * Get center page vertically * * @return bool */ public function getVerticalCentered() { return $this->_verticalCentered; } /** * Set center page vertically * * @param bool $value * @return PHPExcel_Worksheet_PageSetup */ public function setVerticalCentered($value = false) { $this->_verticalCentered = $value; return $this; } /** * Get print area * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or a index value of 0, will return all ranges as a comma-separated string * Otherwise, the specific range identified by the value of $index will be returned * Print areas are numbered from 1 * @throws Exception * @return string */ public function getPrintArea($index = 0) { if ($index == 0) { return $this->_printArea; } $printAreas = explode(',',$this->_printArea); if (isset($printAreas[$index-1])) { return $printAreas[$index-1]; } throw new Exception("Requested Print Area does not exist"); } /** * Is print area set? * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or an index value of 0, will identify whether any print range is set * Otherwise, existence of the range identified by the value of $index will be returned * Print areas are numbered from 1 * @return boolean */ public function isPrintAreaSet($index = 0) { if ($index == 0) { return !is_null($this->_printArea); } $printAreas = explode(',',$this->_printArea); return isset($printAreas[$index-1]); } /** * Clear a print area * * @param int $index Identifier for a specific print area range if several ranges have been set * Default behaviour, or an index value of 0, will clear all print ranges that are set * Otherwise, the range identified by the value of $index will be removed from the series * Print areas are numbered from 1 * @return PHPExcel_Worksheet_PageSetup */ public function clearPrintArea($index = 0) { if ($index == 0) { $this->_printArea = NULL; } else { $printAreas = explode(',',$this->_printArea); if (isset($printAreas[$index-1])) { unset($printAreas[$index-1]); $this->_printArea = implode(',',$printAreas); } } return $this; } /** * Set print area. e.g. 'A1:D10' or 'A1:D10,G5:M20' * * @param string $value * @param int $index Identifier for a specific print area range allowing several ranges to be set * When the method is "O"verwrite, then a positive integer index will overwrite that indexed * entry in the print areas list; a negative index value will identify which entry to * overwrite working bacward through the print area to the list, with the last entry as -1. * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. * When the method is "I"nsert, then a positive index will insert after that indexed entry in * the print areas list, while a negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * @throws Exception * @return PHPExcel_Worksheet_PageSetup */ public function setPrintArea($value, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { if (strpos($value,'!') !== false) { throw new Exception('Cell coordinate must not specify a worksheet.'); } elseif (strpos($value,':') === false) { throw new Exception('Cell coordinate must be a range of cells.'); } elseif (strpos($value,'$') !== false) { throw new Exception('Cell coordinate must not be absolute.'); } $value = strtoupper($value); if ($method == self::SETPRINTRANGE_OVERWRITE) { if ($index == 0) { $this->_printArea = $value; } else { $printAreas = explode(',',$this->_printArea); if($index < 0) { $index = count($printAreas) - abs($index) + 1; } if (($index <= 0) || ($index > count($printAreas))) { throw new Exception('Invalid index for setting print range.'); } $printAreas[$index-1] = $value; $this->_printArea = implode(',',$printAreas); } } elseif($method == self::SETPRINTRANGE_INSERT) { if ($index == 0) { $this->_printArea .= ($this->_printArea == '') ? $value : ','.$value; } else { $printAreas = explode(',',$this->_printArea); if($index < 0) { $index = abs($index) - 1; } if ($index > count($printAreas)) { throw new Exception('Invalid index for setting print range.'); } $printAreas = array_merge(array_slice($printAreas,0,$index),array($value),array_slice($printAreas,$index)); $this->_printArea = implode(',',$printAreas); } } else { throw new Exception('Invalid method for setting print range.'); } return $this; } /** * Add a new print area (e.g. 'A1:D10' or 'A1:D10,G5:M20') to the list of print areas * * @param string $value * @param int $index Identifier for a specific print area range allowing several ranges to be set * A positive index will insert after that indexed entry in the print areas list, while a * negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @throws Exception * @return PHPExcel_Worksheet_PageSetup */ public function addPrintArea($value, $index = -1) { return $this->setPrintArea($value, $index, self::SETPRINTRANGE_INSERT); } /** * Set print area * * @param int $column1 Column 1 * @param int $row1 Row 1 * @param int $column2 Column 2 * @param int $row2 Row 2 * @param int $index Identifier for a specific print area range allowing several ranges to be set * When the method is "O"verwrite, then a positive integer index will overwrite that indexed * entry in the print areas list; a negative index value will identify which entry to * overwrite working bacward through the print area to the list, with the last entry as -1. * Specifying an index value of 0, will overwrite <b>all</b> existing print ranges. * When the method is "I"nsert, then a positive index will insert after that indexed entry in * the print areas list, while a negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @param string $method Determines the method used when setting multiple print areas * Default behaviour, or the "O" method, overwrites existing print area * The "I" method, inserts the new print area before any specified index, or at the end of the list * @throws Exception * @return PHPExcel_Worksheet_PageSetup */ public function setPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = 0, $method = self::SETPRINTRANGE_OVERWRITE) { return $this->setPrintArea(PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2, $index, $method); } /** * Add a new print area to the list of print areas * * @param int $column1 Column 1 * @param int $row1 Row 1 * @param int $column2 Column 2 * @param int $row2 Row 2 * @param int $index Identifier for a specific print area range allowing several ranges to be set * A positive index will insert after that indexed entry in the print areas list, while a * negative index will insert before the indexed entry. * Specifying an index value of 0, will always append the new print range at the end of the * list. * Print areas are numbered from 1 * @throws Exception * @return PHPExcel_Worksheet_PageSetup */ public function addPrintAreaByColumnAndRow($column1, $row1, $column2, $row2, $index = -1) { return $this->setPrintArea(PHPExcel_Cell::stringFromColumnIndex($column1) . $row1 . ':' . PHPExcel_Cell::stringFromColumnIndex($column2) . $row2, $index, self::SETPRINTRANGE_INSERT); } /** * Get first page number * * @return int */ public function getFirstPageNumber() { return $this->_firstPageNumber; } /** * Set first page number * * @param int $value * @return PHPExcel_Worksheet_HeaderFooter */ public function setFirstPageNumber($value = null) { $this->_firstPageNumber = $value; return $this; } /** * Reset first page number * * @return PHPExcel_Worksheet_HeaderFooter */ public function resetFirstPageNumber() { return $this->setFirstPageNumber(null); } /** * Implement PHP __clone to create a deep clone, not just a shallow copy. */ public function __clone() { $vars = get_object_vars($this); foreach ($vars as $key => $value) { if (is_object($value)) { $this->$key = clone $value; } else { $this->$key = $value; } } } }
codingoneapp/codingone
YYUC.NET/plugin/PHPExcel/Worksheet/PageSetup.php
PHP
apache-2.0
24,008
var floating_recipient_bar = (function () { var exports = {}; var is_floating_recipient_bar_showing = false; function show_floating_recipient_bar() { if (!is_floating_recipient_bar_showing) { $("#floating_recipient_bar").css('visibility', 'visible'); is_floating_recipient_bar_showing = true; } } var old_label; function replace_floating_recipient_bar(desired_label) { var new_label, other_label, header; if (desired_label !== old_label) { if (desired_label.children(".message_header_stream").length !== 0) { new_label = $("#current_label_stream"); other_label = $("#current_label_private_message"); header = desired_label.children(".message_header_stream"); } else { new_label = $("#current_label_private_message"); other_label = $("#current_label_stream"); header = desired_label.children(".message_header_private_message"); } new_label.find(".message_header").replaceWith(header.clone()); other_label.css('display', 'none'); new_label.css('display', 'block'); new_label.attr("zid", rows.id(rows.first_message_in_group(desired_label))); new_label.toggleClass('faded', desired_label.hasClass('faded')); old_label = desired_label; } show_floating_recipient_bar(); } exports.hide = function () { if (is_floating_recipient_bar_showing) { $("#floating_recipient_bar").css('visibility', 'hidden'); is_floating_recipient_bar_showing = false; } }; exports.update = function () { var floating_recipient_bar = $("#floating_recipient_bar"); var floating_recipient_bar_top = floating_recipient_bar.offset().top; var floating_recipient_bar_bottom = floating_recipient_bar_top + floating_recipient_bar.outerHeight(); // Find the last message where the top of the recipient // row is at least partially occluded by our box. // Start with the pointer's current location. var selected_row = current_msg_list.selected_row(); if (selected_row === undefined || selected_row.length === 0) { return; } var candidate = rows.get_message_recipient_row(selected_row); if (candidate === undefined) { return; } while (true) { if (candidate.length === 0) { // We're at the top of the page and no labels are above us. exports.hide(); return; } if (candidate.is(".recipient_row")) { if (candidate.offset().top < floating_recipient_bar_bottom) { break; } } candidate = candidate.prev(); } var current_label = candidate; // We now know what the floating stream/subject bar should say. // Do we show it? // Hide if the bottom of our floating stream/subject label is not // lower than the bottom of current_label (since that means we're // covering up a label that already exists). var header_height = $(current_label).find('.message_header').outerHeight(); if (floating_recipient_bar_bottom <= (current_label.offset().top + header_height)) { exports.hide(); return; } replace_floating_recipient_bar(current_label); }; return exports; }());
KJin99/zulip
static/js/floating_recipient_bar.js
JavaScript
apache-2.0
3,284
/* Copyright 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. */ // Code generated by lister-gen. DO NOT EDIT. package v1 import ( "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" v1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1" ) // APIServiceLister helps list APIServices. // All objects returned here must be treated as read-only. type APIServiceLister interface { // List lists all APIServices in the indexer. // Objects returned here must be treated as read-only. List(selector labels.Selector) (ret []*v1.APIService, err error) // Get retrieves the APIService from the index for a given name. // Objects returned here must be treated as read-only. Get(name string) (*v1.APIService, error) APIServiceListerExpansion } // aPIServiceLister implements the APIServiceLister interface. type aPIServiceLister struct { indexer cache.Indexer } // NewAPIServiceLister returns a new APIServiceLister. func NewAPIServiceLister(indexer cache.Indexer) APIServiceLister { return &aPIServiceLister{indexer: indexer} } // List lists all APIServices in the indexer. func (s *aPIServiceLister) List(selector labels.Selector) (ret []*v1.APIService, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1.APIService)) }) return ret, err } // Get retrieves the APIService from the index for a given name. func (s *aPIServiceLister) Get(name string) (*v1.APIService, error) { obj, exists, err := s.indexer.GetByKey(name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1.Resource("apiservice"), name) } return obj.(*v1.APIService), nil }
fabriziopandini/kubernetes
staging/src/k8s.io/kube-aggregator/pkg/client/listers/apiregistration/v1/apiservice.go
GO
apache-2.0
2,193
// Copyright 2012 The Gorilla Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package context import ( "net/http" "testing" ) type keyType int const ( key1 keyType = iota key2 ) func TestContext(t *testing.T) { assertEqual := func(val interface{}, exp interface{}) { if val != exp { t.Errorf("Expected %v, got %v.", exp, val) } } r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) emptyR, _ := http.NewRequest("GET", "http://localhost:8080/", nil) // Get() assertEqual(Get(r, key1), nil) // Set() Set(r, key1, "1") assertEqual(Get(r, key1), "1") assertEqual(len(data[r]), 1) Set(r, key2, "2") assertEqual(Get(r, key2), "2") assertEqual(len(data[r]), 2) //GetOk value, ok := GetOk(r, key1) assertEqual(value, "1") assertEqual(ok, true) value, ok = GetOk(r, "not exists") assertEqual(value, nil) assertEqual(ok, false) Set(r, "nil value", nil) value, ok = GetOk(r, "nil value") assertEqual(value, nil) assertEqual(ok, true) // GetAll() values := GetAll(r) assertEqual(len(values), 3) // GetAll() for empty request values = GetAll(emptyR) if values != nil { t.Error("GetAll didn't return nil value for invalid request") } // GetAllOk() values, ok = GetAllOk(r) assertEqual(len(values), 3) assertEqual(ok, true) // GetAllOk() for empty request values, ok = GetAllOk(emptyR) assertEqual(value, nil) assertEqual(ok, false) // Delete() Delete(r, key1) assertEqual(Get(r, key1), nil) assertEqual(len(data[r]), 2) Delete(r, key2) assertEqual(Get(r, key2), nil) assertEqual(len(data[r]), 1) // Clear() Clear(r) assertEqual(len(data), 0) } func parallelReader(r *http.Request, key string, iterations int, wait, done chan struct{}) { <-wait for i := 0; i < iterations; i++ { Get(r, key) } done <- struct{}{} } func parallelWriter(r *http.Request, key, value string, iterations int, wait, done chan struct{}) { <-wait for i := 0; i < iterations; i++ { Get(r, key) } done <- struct{}{} } func benchmarkMutex(b *testing.B, numReaders, numWriters, iterations int) { b.StopTimer() r, _ := http.NewRequest("GET", "http://localhost:8080/", nil) done := make(chan struct{}) b.StartTimer() for i := 0; i < b.N; i++ { wait := make(chan struct{}) for i := 0; i < numReaders; i++ { go parallelReader(r, "test", iterations, wait, done) } for i := 0; i < numWriters; i++ { go parallelWriter(r, "test", "123", iterations, wait, done) } close(wait) for i := 0; i < numReaders+numWriters; i++ { <-done } } } func BenchmarkMutexSameReadWrite1(b *testing.B) { benchmarkMutex(b, 1, 1, 32) } func BenchmarkMutexSameReadWrite2(b *testing.B) { benchmarkMutex(b, 2, 2, 32) } func BenchmarkMutexSameReadWrite4(b *testing.B) { benchmarkMutex(b, 4, 4, 32) } func BenchmarkMutex1(b *testing.B) { benchmarkMutex(b, 2, 8, 32) } func BenchmarkMutex2(b *testing.B) { benchmarkMutex(b, 16, 4, 64) } func BenchmarkMutex3(b *testing.B) { benchmarkMutex(b, 1, 2, 128) } func BenchmarkMutex4(b *testing.B) { benchmarkMutex(b, 128, 32, 256) } func BenchmarkMutex5(b *testing.B) { benchmarkMutex(b, 1024, 2048, 64) } func BenchmarkMutex6(b *testing.B) { benchmarkMutex(b, 2048, 1024, 512) }
bxy09/distribution
Godeps/_workspace/src/github.com/gorilla/context/context_test.go
GO
apache-2.0
3,284
// Code generated by "go generate gonum.org/v1/gonum/blas/gonum”; DO NOT EDIT. // Copyright ©2017 The Gonum Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package gonum import ( math "gonum.org/v1/gonum/internal/math32" "gonum.org/v1/gonum/blas" "gonum.org/v1/gonum/internal/asm/c64" ) var _ blas.Complex64Level1 = Implementation{} // Scasum returns the sum of the absolute values of the elements of x // \sum_i |Re(x[i])| + |Im(x[i])| // Scasum returns 0 if incX is negative. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Scasum(n int, x []complex64, incX int) float32 { if n < 0 { panic(nLT0) } if incX < 1 { if incX == 0 { panic(zeroIncX) } return 0 } var sum float32 if incX == 1 { if len(x) < n { panic(shortX) } for _, v := range x[:n] { sum += scabs1(v) } return sum } if (n-1)*incX >= len(x) { panic(shortX) } for i := 0; i < n; i++ { v := x[i*incX] sum += scabs1(v) } return sum } // Scnrm2 computes the Euclidean norm of the complex vector x, // ‖x‖_2 = sqrt(\sum_i x[i] * conj(x[i])). // This function returns 0 if incX is negative. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Scnrm2(n int, x []complex64, incX int) float32 { if incX < 1 { if incX == 0 { panic(zeroIncX) } return 0 } if n < 1 { if n == 0 { return 0 } panic(nLT0) } if (n-1)*incX >= len(x) { panic(shortX) } var ( scale float32 ssq float32 = 1 ) if incX == 1 { for _, v := range x[:n] { re, im := math.Abs(real(v)), math.Abs(imag(v)) if re != 0 { if re > scale { ssq = 1 + ssq*(scale/re)*(scale/re) scale = re } else { ssq += (re / scale) * (re / scale) } } if im != 0 { if im > scale { ssq = 1 + ssq*(scale/im)*(scale/im) scale = im } else { ssq += (im / scale) * (im / scale) } } } if math.IsInf(scale, 1) { return math.Inf(1) } return scale * math.Sqrt(ssq) } for ix := 0; ix < n*incX; ix += incX { re, im := math.Abs(real(x[ix])), math.Abs(imag(x[ix])) if re != 0 { if re > scale { ssq = 1 + ssq*(scale/re)*(scale/re) scale = re } else { ssq += (re / scale) * (re / scale) } } if im != 0 { if im > scale { ssq = 1 + ssq*(scale/im)*(scale/im) scale = im } else { ssq += (im / scale) * (im / scale) } } } if math.IsInf(scale, 1) { return math.Inf(1) } return scale * math.Sqrt(ssq) } // Icamax returns the index of the first element of x having largest |Re(·)|+|Im(·)|. // Icamax returns -1 if n is 0 or incX is negative. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Icamax(n int, x []complex64, incX int) int { if incX < 1 { if incX == 0 { panic(zeroIncX) } // Return invalid index. return -1 } if n < 1 { if n == 0 { // Return invalid index. return -1 } panic(nLT0) } if len(x) <= (n-1)*incX { panic(shortX) } idx := 0 max := scabs1(x[0]) if incX == 1 { for i, v := range x[1:n] { absV := scabs1(v) if absV > max { max = absV idx = i + 1 } } return idx } ix := incX for i := 1; i < n; i++ { absV := scabs1(x[ix]) if absV > max { max = absV idx = i } ix += incX } return idx } // Caxpy adds alpha times x to y: // y[i] += alpha * x[i] for all i // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Caxpy(n int, alpha complex64, x []complex64, incX int, y []complex64, incY int) { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n < 1 { if n == 0 { return } panic(nLT0) } if (incX > 0 && (n-1)*incX >= len(x)) || (incX < 0 && (1-n)*incX >= len(x)) { panic(shortX) } if (incY > 0 && (n-1)*incY >= len(y)) || (incY < 0 && (1-n)*incY >= len(y)) { panic(shortY) } if alpha == 0 { return } if incX == 1 && incY == 1 { c64.AxpyUnitary(alpha, x[:n], y[:n]) return } var ix, iy int if incX < 0 { ix = (1 - n) * incX } if incY < 0 { iy = (1 - n) * incY } c64.AxpyInc(alpha, x, y, uintptr(n), uintptr(incX), uintptr(incY), uintptr(ix), uintptr(iy)) } // Ccopy copies the vector x to vector y. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Ccopy(n int, x []complex64, incX int, y []complex64, incY int) { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n < 1 { if n == 0 { return } panic(nLT0) } if (incX > 0 && (n-1)*incX >= len(x)) || (incX < 0 && (1-n)*incX >= len(x)) { panic(shortX) } if (incY > 0 && (n-1)*incY >= len(y)) || (incY < 0 && (1-n)*incY >= len(y)) { panic(shortY) } if incX == 1 && incY == 1 { copy(y[:n], x[:n]) return } var ix, iy int if incX < 0 { ix = (-n + 1) * incX } if incY < 0 { iy = (-n + 1) * incY } for i := 0; i < n; i++ { y[iy] = x[ix] ix += incX iy += incY } } // Cdotc computes the dot product // xᴴ · y // of two complex vectors x and y. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Cdotc(n int, x []complex64, incX int, y []complex64, incY int) complex64 { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n <= 0 { if n == 0 { return 0 } panic(nLT0) } if incX == 1 && incY == 1 { if len(x) < n { panic(shortX) } if len(y) < n { panic(shortY) } return c64.DotcUnitary(x[:n], y[:n]) } var ix, iy int if incX < 0 { ix = (-n + 1) * incX } if incY < 0 { iy = (-n + 1) * incY } if ix >= len(x) || (n-1)*incX >= len(x) { panic(shortX) } if iy >= len(y) || (n-1)*incY >= len(y) { panic(shortY) } return c64.DotcInc(x, y, uintptr(n), uintptr(incX), uintptr(incY), uintptr(ix), uintptr(iy)) } // Cdotu computes the dot product // xᵀ · y // of two complex vectors x and y. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Cdotu(n int, x []complex64, incX int, y []complex64, incY int) complex64 { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n <= 0 { if n == 0 { return 0 } panic(nLT0) } if incX == 1 && incY == 1 { if len(x) < n { panic(shortX) } if len(y) < n { panic(shortY) } return c64.DotuUnitary(x[:n], y[:n]) } var ix, iy int if incX < 0 { ix = (-n + 1) * incX } if incY < 0 { iy = (-n + 1) * incY } if ix >= len(x) || (n-1)*incX >= len(x) { panic(shortX) } if iy >= len(y) || (n-1)*incY >= len(y) { panic(shortY) } return c64.DotuInc(x, y, uintptr(n), uintptr(incX), uintptr(incY), uintptr(ix), uintptr(iy)) } // Csscal scales the vector x by a real scalar alpha. // Csscal has no effect if incX < 0. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Csscal(n int, alpha float32, x []complex64, incX int) { if incX < 1 { if incX == 0 { panic(zeroIncX) } return } if (n-1)*incX >= len(x) { panic(shortX) } if n < 1 { if n == 0 { return } panic(nLT0) } if alpha == 0 { if incX == 1 { x = x[:n] for i := range x { x[i] = 0 } return } for ix := 0; ix < n*incX; ix += incX { x[ix] = 0 } return } if incX == 1 { x = x[:n] for i, v := range x { x[i] = complex(alpha*real(v), alpha*imag(v)) } return } for ix := 0; ix < n*incX; ix += incX { v := x[ix] x[ix] = complex(alpha*real(v), alpha*imag(v)) } } // Cscal scales the vector x by a complex scalar alpha. // Cscal has no effect if incX < 0. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Cscal(n int, alpha complex64, x []complex64, incX int) { if incX < 1 { if incX == 0 { panic(zeroIncX) } return } if (n-1)*incX >= len(x) { panic(shortX) } if n < 1 { if n == 0 { return } panic(nLT0) } if alpha == 0 { if incX == 1 { x = x[:n] for i := range x { x[i] = 0 } return } for ix := 0; ix < n*incX; ix += incX { x[ix] = 0 } return } if incX == 1 { c64.ScalUnitary(alpha, x[:n]) return } c64.ScalInc(alpha, x, uintptr(n), uintptr(incX)) } // Cswap exchanges the elements of two complex vectors x and y. // // Complex64 implementations are autogenerated and not directly tested. func (Implementation) Cswap(n int, x []complex64, incX int, y []complex64, incY int) { if incX == 0 { panic(zeroIncX) } if incY == 0 { panic(zeroIncY) } if n < 1 { if n == 0 { return } panic(nLT0) } if (incX > 0 && (n-1)*incX >= len(x)) || (incX < 0 && (1-n)*incX >= len(x)) { panic(shortX) } if (incY > 0 && (n-1)*incY >= len(y)) || (incY < 0 && (1-n)*incY >= len(y)) { panic(shortY) } if incX == 1 && incY == 1 { x = x[:n] for i, v := range x { x[i], y[i] = y[i], v } return } var ix, iy int if incX < 0 { ix = (-n + 1) * incX } if incY < 0 { iy = (-n + 1) * incY } for i := 0; i < n; i++ { x[ix], y[iy] = y[iy], x[ix] ix += incX iy += incY } }
mahak/kubernetes
vendor/gonum.org/v1/gonum/blas/gonum/level1cmplx64.go
GO
apache-2.0
9,128
// Copyright © 2013 Steve Francia <spf@spf13.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 cobra is a commander providing a simple interface to create powerful modern CLI interfaces. //In addition to providing an interface, Cobra simultaneously provides a controller to organize your application code. package cobra import ( "bytes" "fmt" "io" "os" "path/filepath" "sort" "strings" flag "github.com/spf13/pflag" ) // Command is just that, a command for your application. // eg. 'go run' ... 'run' is the command. Cobra requires // you to define the usage and description as part of your command // definition to ensure usability. type Command struct { // Name is the command name, usually the executable's name. name string // The one-line usage message. Use string // An array of aliases that can be used instead of the first word in Use. Aliases []string // An array of command names for which this command will be suggested - similar to aliases but only suggests. SuggestFor []string // The short description shown in the 'help' output. Short string // The long message shown in the 'help <this-command>' output. Long string // Examples of how to use the command Example string // List of all valid non-flag arguments that are accepted in bash completions ValidArgs []string // List of aliases for ValidArgs. These are not suggested to the user in the bash // completion, but accepted if entered manually. ArgAliases []string // Expected arguments Args PositionalArgs // Custom functions used by the bash autocompletion generator BashCompletionFunction string // Is this command deprecated and should print this string when used? Deprecated string // Is this command hidden and should NOT show up in the list of available commands? Hidden bool // Tags are key/value pairs that can be used by applications to identify or // group commands Tags map[string]string // Full set of flags flags *flag.FlagSet // Set of flags childrens of this command will inherit pflags *flag.FlagSet // Flags that are declared specifically by this command (not inherited). lflags *flag.FlagSet // SilenceErrors is an option to quiet errors down stream SilenceErrors bool // Silence Usage is an option to silence usage when an error occurs. SilenceUsage bool // The *Run functions are executed in the following order: // * PersistentPreRun() // * PreRun() // * Run() // * PostRun() // * PersistentPostRun() // All functions get the same args, the arguments after the command name // PersistentPreRun: children of this command will inherit and execute PersistentPreRun func(cmd *Command, args []string) // PersistentPreRunE: PersistentPreRun but returns an error PersistentPreRunE func(cmd *Command, args []string) error // PreRun: children of this command will not inherit. PreRun func(cmd *Command, args []string) // PreRunE: PreRun but returns an error PreRunE func(cmd *Command, args []string) error // Run: Typically the actual work function. Most commands will only implement this Run func(cmd *Command, args []string) // RunE: Run but returns an error RunE func(cmd *Command, args []string) error // PostRun: run after the Run command. PostRun func(cmd *Command, args []string) // PostRunE: PostRun but returns an error PostRunE func(cmd *Command, args []string) error // PersistentPostRun: children of this command will inherit and execute after PostRun PersistentPostRun func(cmd *Command, args []string) // PersistentPostRunE: PersistentPostRun but returns an error PersistentPostRunE func(cmd *Command, args []string) error // DisableAutoGenTag remove DisableAutoGenTag bool // Commands is the list of commands supported by this program. commands []*Command // Parent Command for this command parent *Command // max lengths of commands' string lengths for use in padding commandsMaxUseLen int commandsMaxCommandPathLen int commandsMaxNameLen int // is commands slice are sorted or not commandsAreSorted bool flagErrorBuf *bytes.Buffer args []string // actual args parsed from flags output *io.Writer // nil means stderr; use Out() method instead usageFunc func(*Command) error // Usage can be defined by application usageTemplate string // Can be defined by Application flagErrorFunc func(*Command, error) error helpTemplate string // Can be defined by Application helpFunc func(*Command, []string) // Help can be defined by application helpCommand *Command // The help command // The global normalization function that we can use on every pFlag set and children commands globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName // Disable the suggestions based on Levenshtein distance that go along with 'unknown command' messages DisableSuggestions bool // If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0 SuggestionsMinimumDistance int // Disable the flag parsing. If this is true all flags will be passed to the command as arguments. DisableFlagParsing bool // TraverseChildren parses flags on all parents before executing child command TraverseChildren bool } // os.Args[1:] by default, if desired, can be overridden // particularly useful when testing. func (c *Command) SetArgs(a []string) { c.args = a } func (c *Command) getOut(def io.Writer) io.Writer { if c.output != nil { return *c.output } if c.HasParent() { return c.parent.Out() } return def } func (c *Command) Out() io.Writer { return c.getOut(os.Stderr) } func (c *Command) getOutOrStdout() io.Writer { return c.getOut(os.Stdout) } // SetOutput sets the destination for usage and error messages. // If output is nil, os.Stderr is used. func (c *Command) SetOutput(output io.Writer) { c.output = &output } // Usage can be defined by application func (c *Command) SetUsageFunc(f func(*Command) error) { c.usageFunc = f } // Can be defined by Application func (c *Command) SetUsageTemplate(s string) { c.usageTemplate = s } // SetFlagErrorFunc sets a function to generate an error when flag parsing // fails func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) { c.flagErrorFunc = f } // Can be defined by Application func (c *Command) SetHelpFunc(f func(*Command, []string)) { c.helpFunc = f } func (c *Command) SetHelpCommand(cmd *Command) { c.helpCommand = cmd } // Can be defined by Application func (c *Command) SetHelpTemplate(s string) { c.helpTemplate = s } // SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. // The user should not have a cyclic dependency on commands. func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) { c.Flags().SetNormalizeFunc(n) c.PersistentFlags().SetNormalizeFunc(n) c.globNormFunc = n for _, command := range c.commands { command.SetGlobalNormalizationFunc(n) } } func (c *Command) UsageFunc() (f func(*Command) error) { if c.usageFunc != nil { return c.usageFunc } if c.HasParent() { return c.parent.UsageFunc() } return func(c *Command) error { err := tmpl(c.Out(), c.UsageTemplate(), c) if err != nil { fmt.Print(err) } return err } } // HelpFunc returns either the function set by SetHelpFunc for this command // or a parent, or it returns a function which calls c.Help() func (c *Command) HelpFunc() func(*Command, []string) { cmd := c for cmd != nil { if cmd.helpFunc != nil { return cmd.helpFunc } cmd = cmd.parent } return func(*Command, []string) { err := c.Help() if err != nil { c.Println(err) } } } // FlagErrorFunc returns either the function set by SetFlagErrorFunc for this // command or a parent, or it returns a function which returns the original // error. func (c *Command) FlagErrorFunc() (f func(*Command, error) error) { if c.flagErrorFunc != nil { return c.flagErrorFunc } if c.HasParent() { return c.parent.FlagErrorFunc() } return func(c *Command, err error) error { return err } } var minUsagePadding = 25 func (c *Command) UsagePadding() int { if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen { return minUsagePadding } return c.parent.commandsMaxUseLen } var minCommandPathPadding = 11 // func (c *Command) CommandPathPadding() int { if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen { return minCommandPathPadding } return c.parent.commandsMaxCommandPathLen } var minNamePadding = 11 func (c *Command) NamePadding() int { if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen { return minNamePadding } return c.parent.commandsMaxNameLen } func (c *Command) UsageTemplate() string { if c.usageTemplate != "" { return c.usageTemplate } if c.HasParent() { return c.parent.UsageTemplate() } return `Usage:{{if .Runnable}} {{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}} {{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}} Aliases: {{.NameAndAliases}} {{end}}{{if .HasExample}} Examples: {{ .Example }}{{end}}{{ if .HasAvailableSubCommands}} Available Commands:{{range .Commands}}{{if .IsAvailableCommand}} {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableLocalFlags}} Flags: {{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasAvailableInheritedFlags}} Global Flags: {{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}} Additional help topics:{{range .Commands}}{{if .IsHelpCommand}} {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasAvailableSubCommands }} Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}} ` } func (c *Command) HelpTemplate() string { if c.helpTemplate != "" { return c.helpTemplate } if c.HasParent() { return c.parent.HelpTemplate() } return `{{with or .Long .Short }}{{. | trim}} {{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}` } // Really only used when casting a command to a commander func (c *Command) resetChildrensParents() { for _, x := range c.commands { x.parent = c } } // Test if the named flag is a boolean flag. func isBooleanFlag(name string, f *flag.FlagSet) bool { flag := f.Lookup(name) if flag == nil { return false } return flag.Value.Type() == "bool" } // Test if the named flag is a boolean flag. func isBooleanShortFlag(name string, f *flag.FlagSet) bool { result := false f.VisitAll(func(f *flag.Flag) { if f.Shorthand == name && f.Value.Type() == "bool" { result = true } }) return result } func stripFlags(args []string, c *Command) []string { if len(args) < 1 { return args } c.mergePersistentFlags() commands := []string{} inQuote := false inFlag := false for _, y := range args { if !inQuote { switch { case strings.HasPrefix(y, "\""): inQuote = true case strings.Contains(y, "=\""): inQuote = true case strings.HasPrefix(y, "--") && !strings.Contains(y, "="): // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' inFlag = !isBooleanFlag(y[2:], c.Flags()) case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()): inFlag = true case inFlag: inFlag = false case y == "": // strip empty commands, as the go tests expect this to be ok.... case !strings.HasPrefix(y, "-"): commands = append(commands, y) inFlag = false } } if strings.HasSuffix(y, "\"") && !strings.HasSuffix(y, "\\\"") { inQuote = false } } return commands } // argsMinusFirstX removes only the first x from args. Otherwise, commands that look like // openshift admin policy add-role-to-user admin my-user, lose the admin argument (arg[4]). func argsMinusFirstX(args []string, x string) []string { for i, y := range args { if x == y { ret := []string{} ret = append(ret, args[:i]...) ret = append(ret, args[i+1:]...) return ret } } return args } func isFlagArg(arg string) bool { return ((len(arg) >= 3 && arg[1] == '-') || (len(arg) >= 2 && arg[0] == '-' && arg[1] != '-')) } // Find the target command given the args and command tree // Meant to be run on the highest node. Only searches down. func (c *Command) Find(args []string) (*Command, []string, error) { var innerfind func(*Command, []string) (*Command, []string) innerfind = func(c *Command, innerArgs []string) (*Command, []string) { argsWOflags := stripFlags(innerArgs, c) if len(argsWOflags) == 0 { return c, innerArgs } nextSubCmd := argsWOflags[0] cmd := c.findNext(nextSubCmd) if cmd != nil { return innerfind(cmd, argsMinusFirstX(innerArgs, nextSubCmd)) } return c, innerArgs } commandFound, a := innerfind(c, args) if commandFound.Args == nil { return commandFound, a, legacyArgs(commandFound, stripFlags(a, commandFound)) } return commandFound, a, nil } func (c *Command) findNext(next string) *Command { matches := make([]*Command, 0) for _, cmd := range c.commands { if cmd.Name() == next || cmd.HasAlias(next) { return cmd } if EnablePrefixMatching && cmd.HasNameOrAliasPrefix(next) { matches = append(matches, cmd) } } if len(matches) == 1 { return matches[0] } return nil } // Traverse the command tree to find the command, and parse args for // each parent. func (c *Command) Traverse(args []string) (*Command, []string, error) { flags := []string{} inFlag := false for i, arg := range args { switch { // A long flag with a space separated value case strings.HasPrefix(arg, "--") && !strings.Contains(arg, "="): // TODO: this isn't quite right, we should really check ahead for 'true' or 'false' inFlag = !isBooleanFlag(arg[2:], c.Flags()) flags = append(flags, arg) continue // A short flag with a space separated value case strings.HasPrefix(arg, "-") && !strings.Contains(arg, "=") && len(arg) == 2 && !isBooleanShortFlag(arg[1:], c.Flags()): inFlag = true flags = append(flags, arg) continue // The value for a flag case inFlag: inFlag = false flags = append(flags, arg) continue // A flag without a value, or with an `=` separated value case isFlagArg(arg): flags = append(flags, arg) continue } cmd := c.findNext(arg) if cmd == nil { return c, args, nil } if err := c.ParseFlags(flags); err != nil { return nil, args, err } return cmd.Traverse(args[i+1:]) } return c, args, nil } func (c *Command) findSuggestions(arg string) string { if c.DisableSuggestions { return "" } if c.SuggestionsMinimumDistance <= 0 { c.SuggestionsMinimumDistance = 2 } suggestionsString := "" if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 { suggestionsString += "\n\nDid you mean this?\n" for _, s := range suggestions { suggestionsString += fmt.Sprintf("\t%v\n", s) } } return suggestionsString } func (c *Command) SuggestionsFor(typedName string) []string { suggestions := []string{} for _, cmd := range c.commands { if cmd.IsAvailableCommand() { levenshteinDistance := ld(typedName, cmd.Name(), true) suggestByLevenshtein := levenshteinDistance <= c.SuggestionsMinimumDistance suggestByPrefix := strings.HasPrefix(strings.ToLower(cmd.Name()), strings.ToLower(typedName)) if suggestByLevenshtein || suggestByPrefix { suggestions = append(suggestions, cmd.Name()) } for _, explicitSuggestion := range cmd.SuggestFor { if strings.EqualFold(typedName, explicitSuggestion) { suggestions = append(suggestions, cmd.Name()) } } } } return suggestions } func (c *Command) VisitParents(fn func(*Command)) { var traverse func(*Command) *Command traverse = func(x *Command) *Command { if x != c { fn(x) } if x.HasParent() { return traverse(x.parent) } return x } traverse(c) } func (c *Command) Root() *Command { var findRoot func(*Command) *Command findRoot = func(x *Command) *Command { if x.HasParent() { return findRoot(x.parent) } return x } return findRoot(c) } // ArgsLenAtDash will return the length of f.Args at the moment when a -- was // found during arg parsing. This allows your program to know which args were // before the -- and which came after. (Description from // https://godoc.org/github.com/spf13/pflag#FlagSet.ArgsLenAtDash). func (c *Command) ArgsLenAtDash() int { return c.Flags().ArgsLenAtDash() } func (c *Command) execute(a []string) (err error) { if c == nil { return fmt.Errorf("Called Execute() on a nil Command") } if len(c.Deprecated) > 0 { c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) } // initialize help flag as the last point possible to allow for user // overriding c.initHelpFlag() err = c.ParseFlags(a) if err != nil { return c.FlagErrorFunc()(c, err) } // If help is called, regardless of other flags, return we want help // Also say we need help if the command isn't runnable. helpVal, err := c.Flags().GetBool("help") if err != nil { // should be impossible to get here as we always declare a help // flag in initHelpFlag() c.Println("\"help\" flag declared as non-bool. Please correct your code") return err } if helpVal || !c.Runnable() { return flag.ErrHelp } c.preRun() argWoFlags := c.Flags().Args() if c.DisableFlagParsing { argWoFlags = a } if err := c.ValidateArgs(argWoFlags); err != nil { return err } for p := c; p != nil; p = p.Parent() { if p.PersistentPreRunE != nil { if err := p.PersistentPreRunE(c, argWoFlags); err != nil { return err } break } else if p.PersistentPreRun != nil { p.PersistentPreRun(c, argWoFlags) break } } if c.PreRunE != nil { if err := c.PreRunE(c, argWoFlags); err != nil { return err } } else if c.PreRun != nil { c.PreRun(c, argWoFlags) } if c.RunE != nil { if err := c.RunE(c, argWoFlags); err != nil { return err } } else { c.Run(c, argWoFlags) } if c.PostRunE != nil { if err := c.PostRunE(c, argWoFlags); err != nil { return err } } else if c.PostRun != nil { c.PostRun(c, argWoFlags) } for p := c; p != nil; p = p.Parent() { if p.PersistentPostRunE != nil { if err := p.PersistentPostRunE(c, argWoFlags); err != nil { return err } break } else if p.PersistentPostRun != nil { p.PersistentPostRun(c, argWoFlags) break } } return nil } func (c *Command) preRun() { for _, x := range initializers { x() } } func (c *Command) errorMsgFromParse() string { s := c.flagErrorBuf.String() x := strings.Split(s, "\n") if len(x) > 0 { return x[0] } return "" } // Call execute to use the args (os.Args[1:] by default) // and run through the command tree finding appropriate matches // for commands and then corresponding flags. func (c *Command) Execute() error { _, err := c.ExecuteC() return err } func (c *Command) ExecuteC() (cmd *Command, err error) { // Regardless of what command execute is called on, run on Root only if c.HasParent() { return c.Root().ExecuteC() } // windows hook if preExecHookFn != nil { preExecHookFn(c) } // initialize help as the last point possible to allow for user // overriding c.initHelpCmd() var args []string // Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155 if c.args == nil && filepath.Base(os.Args[0]) != "cobra.test" { args = os.Args[1:] } else { args = c.args } var flags []string if c.TraverseChildren { cmd, flags, err = c.Traverse(args) } else { cmd, flags, err = c.Find(args) } if err != nil { // If found parse to a subcommand and then failed, talk about the subcommand if cmd != nil { c = cmd } if !c.SilenceErrors { c.Println("Error:", err.Error()) c.Printf("Run '%v --help' for usage.\n", c.CommandPath()) } return c, err } err = cmd.execute(flags) if err != nil { // Always show help if requested, even if SilenceErrors is in // effect if err == flag.ErrHelp { cmd.HelpFunc()(cmd, args) return cmd, nil } // If root command has SilentErrors flagged, // all subcommands should respect it if !cmd.SilenceErrors && !c.SilenceErrors { c.Println("Error:", err.Error()) } // If root command has SilentUsage flagged, // all subcommands should respect it if !cmd.SilenceUsage && !c.SilenceUsage { c.Println(cmd.UsageString()) } return cmd, err } return cmd, nil } func (c *Command) ValidateArgs(args []string) error { if c.Args == nil { return nil } return c.Args(c, args) } func (c *Command) initHelpFlag() { c.mergePersistentFlags() if c.Flags().Lookup("help") == nil { c.Flags().BoolP("help", "h", false, "help for "+c.Name()) } } func (c *Command) initHelpCmd() { if c.helpCommand == nil { if !c.HasSubCommands() { return } c.helpCommand = &Command{ Use: "help [command]", Short: "Help about any command", Long: `Help provides help for any command in the application. Simply type ` + c.Name() + ` help [path to command] for full details.`, PersistentPreRun: func(cmd *Command, args []string) {}, PersistentPostRun: func(cmd *Command, args []string) {}, Run: func(c *Command, args []string) { cmd, _, e := c.Root().Find(args) if cmd == nil || e != nil { c.Printf("Unknown help topic %#q.", args) c.Root().Usage() } else { helpFunc := cmd.HelpFunc() helpFunc(cmd, args) } }, } } c.AddCommand(c.helpCommand) } // Used for testing func (c *Command) ResetCommands() { c.commands = nil c.helpCommand = nil } // Sorts commands by their names type commandSorterByName []*Command func (c commandSorterByName) Len() int { return len(c) } func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] } func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() } // Commands returns a sorted slice of child commands. func (c *Command) Commands() []*Command { // do not sort commands if it already sorted or sorting was disabled if EnableCommandSorting && !c.commandsAreSorted { sort.Sort(commandSorterByName(c.commands)) c.commandsAreSorted = true } return c.commands } // AddCommand adds one or more commands to this parent command. func (c *Command) AddCommand(cmds ...*Command) { for i, x := range cmds { if cmds[i] == c { panic("Command can't be a child of itself") } cmds[i].parent = c // update max lengths usageLen := len(x.Use) if usageLen > c.commandsMaxUseLen { c.commandsMaxUseLen = usageLen } commandPathLen := len(x.CommandPath()) if commandPathLen > c.commandsMaxCommandPathLen { c.commandsMaxCommandPathLen = commandPathLen } nameLen := len(x.Name()) if nameLen > c.commandsMaxNameLen { c.commandsMaxNameLen = nameLen } // If global normalization function exists, update all children if c.globNormFunc != nil { x.SetGlobalNormalizationFunc(c.globNormFunc) } c.commands = append(c.commands, x) c.commandsAreSorted = false } } // RemoveCommand removes one or more commands from a parent command. func (c *Command) RemoveCommand(cmds ...*Command) { commands := []*Command{} main: for _, command := range c.commands { for _, cmd := range cmds { if command == cmd { command.parent = nil continue main } } commands = append(commands, command) } c.commands = commands // recompute all lengths c.commandsMaxUseLen = 0 c.commandsMaxCommandPathLen = 0 c.commandsMaxNameLen = 0 for _, command := range c.commands { usageLen := len(command.Use) if usageLen > c.commandsMaxUseLen { c.commandsMaxUseLen = usageLen } commandPathLen := len(command.CommandPath()) if commandPathLen > c.commandsMaxCommandPathLen { c.commandsMaxCommandPathLen = commandPathLen } nameLen := len(command.Name()) if nameLen > c.commandsMaxNameLen { c.commandsMaxNameLen = nameLen } } } // Print is a convenience method to Print to the defined output func (c *Command) Print(i ...interface{}) { fmt.Fprint(c.Out(), i...) } // Println is a convenience method to Println to the defined output func (c *Command) Println(i ...interface{}) { str := fmt.Sprintln(i...) c.Print(str) } // Printf is a convenience method to Printf to the defined output func (c *Command) Printf(format string, i ...interface{}) { str := fmt.Sprintf(format, i...) c.Print(str) } // Output the usage for the command // Used when a user provides invalid input // Can be defined by user by overriding UsageFunc func (c *Command) Usage() error { c.mergePersistentFlags() err := c.UsageFunc()(c) return err } // Output the help for the command // Used when a user calls help [command] // by the default HelpFunc in the commander func (c *Command) Help() error { c.mergePersistentFlags() err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c) return err } func (c *Command) UsageString() string { tmpOutput := c.output bb := new(bytes.Buffer) c.SetOutput(bb) c.Usage() c.output = tmpOutput return bb.String() } // CommandPath returns the full path to this command. func (c *Command) CommandPath() string { str := c.Name() x := c for x.HasParent() { str = x.parent.Name() + " " + str x = x.parent } return str } //The full usage for a given command (including parents) func (c *Command) UseLine() string { str := "" if c.HasParent() { str = c.parent.CommandPath() + " " } return str + c.Use } // For use in determining which flags have been assigned to which commands // and which persist func (c *Command) DebugFlags() { c.Println("DebugFlags called on", c.Name()) var debugflags func(*Command) debugflags = func(x *Command) { if x.HasFlags() || x.HasPersistentFlags() { c.Println(x.Name()) } if x.HasFlags() { x.flags.VisitAll(func(f *flag.Flag) { if x.HasPersistentFlags() { if x.persistentFlag(f.Name) == nil { c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") } else { c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [LP]") } } else { c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [L]") } }) } if x.HasPersistentFlags() { x.pflags.VisitAll(func(f *flag.Flag) { if x.HasFlags() { if x.flags.Lookup(f.Name) == nil { c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") } } else { c.Println(" -"+f.Shorthand+",", "--"+f.Name, "["+f.DefValue+"]", "", f.Value, " [P]") } }) } c.Println(x.flagErrorBuf) if x.HasSubCommands() { for _, y := range x.commands { debugflags(y) } } } debugflags(c) } // Name returns the command's name: the first word in the use line. func (c *Command) Name() string { if c.name != "" { return c.name } name := c.Use i := strings.Index(name, " ") if i >= 0 { name = name[:i] } return name } // HasAlias determines if a given string is an alias of the command. func (c *Command) HasAlias(s string) bool { for _, a := range c.Aliases { if a == s { return true } } return false } // HasNameOrAliasPrefix returns true if the Name or any of aliases start // with prefix func (c *Command) HasNameOrAliasPrefix(prefix string) bool { if strings.HasPrefix(c.Name(), prefix) { return true } for _, alias := range c.Aliases { if strings.HasPrefix(alias, prefix) { return true } } return false } func (c *Command) NameAndAliases() string { return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ") } func (c *Command) HasExample() bool { return len(c.Example) > 0 } // Runnable determines if the command is itself runnable func (c *Command) Runnable() bool { return c.Run != nil || c.RunE != nil } // HasSubCommands determines if the command has children commands func (c *Command) HasSubCommands() bool { return len(c.commands) > 0 } // IsAvailableCommand determines if a command is available as a non-help command // (this includes all non deprecated/hidden commands) func (c *Command) IsAvailableCommand() bool { if len(c.Deprecated) != 0 || c.Hidden { return false } if c.HasParent() && c.Parent().helpCommand == c { return false } if c.Runnable() || c.HasAvailableSubCommands() { return true } return false } // IsHelpCommand determines if a command is a 'help' command; a help command is // determined by the fact that it is NOT runnable/hidden/deprecated, and has no // sub commands that are runnable/hidden/deprecated func (c *Command) IsHelpCommand() bool { // if a command is runnable, deprecated, or hidden it is not a 'help' command if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden { return false } // if any non-help sub commands are found, the command is not a 'help' command for _, sub := range c.commands { if !sub.IsHelpCommand() { return false } } // the command either has no sub commands, or no non-help sub commands return true } // HasHelpSubCommands determines if a command has any avilable 'help' sub commands // that need to be shown in the usage/help default template under 'additional help // topics' func (c *Command) HasHelpSubCommands() bool { // return true on the first found available 'help' sub command for _, sub := range c.commands { if sub.IsHelpCommand() { return true } } // the command either has no sub commands, or no available 'help' sub commands return false } // HasAvailableSubCommands determines if a command has available sub commands that // need to be shown in the usage/help default template under 'available commands' func (c *Command) HasAvailableSubCommands() bool { // return true on the first found available (non deprecated/help/hidden) // sub command for _, sub := range c.commands { if sub.IsAvailableCommand() { return true } } // the command either has no sub comamnds, or no available (non deprecated/help/hidden) // sub commands return false } // Determine if the command is a child command func (c *Command) HasParent() bool { return c.parent != nil } // GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName { return c.globNormFunc } // Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents) func (c *Command) Flags() *flag.FlagSet { if c.flags == nil { c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } c.flags.SetOutput(c.flagErrorBuf) } return c.flags } // LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands func (c *Command) LocalNonPersistentFlags() *flag.FlagSet { persistentFlags := c.PersistentFlags() out := flag.NewFlagSet(c.Name(), flag.ContinueOnError) c.LocalFlags().VisitAll(func(f *flag.Flag) { if persistentFlags.Lookup(f.Name) == nil { out.AddFlag(f) } }) return out } // Get the local FlagSet specifically set in the current command func (c *Command) LocalFlags() *flag.FlagSet { c.mergePersistentFlags() local := flag.NewFlagSet(c.Name(), flag.ContinueOnError) c.lflags.VisitAll(func(f *flag.Flag) { local.AddFlag(f) }) if !c.HasParent() { flag.CommandLine.VisitAll(func(f *flag.Flag) { if local.Lookup(f.Name) == nil { local.AddFlag(f) } }) } return local } // All Flags which were inherited from parents commands func (c *Command) InheritedFlags() *flag.FlagSet { c.mergePersistentFlags() inherited := flag.NewFlagSet(c.Name(), flag.ContinueOnError) local := c.LocalFlags() var rmerge func(x *Command) rmerge = func(x *Command) { if x.HasPersistentFlags() { x.PersistentFlags().VisitAll(func(f *flag.Flag) { if inherited.Lookup(f.Name) == nil && local.Lookup(f.Name) == nil { inherited.AddFlag(f) } }) } if x.HasParent() { rmerge(x.parent) } } if c.HasParent() { rmerge(c.parent) } return inherited } // All Flags which were not inherited from parent commands func (c *Command) NonInheritedFlags() *flag.FlagSet { return c.LocalFlags() } // Get the Persistent FlagSet specifically set in the current command func (c *Command) PersistentFlags() *flag.FlagSet { if c.pflags == nil { c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } c.pflags.SetOutput(c.flagErrorBuf) } return c.pflags } // For use in testing func (c *Command) ResetFlags() { c.flagErrorBuf = new(bytes.Buffer) c.flagErrorBuf.Reset() c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) c.flags.SetOutput(c.flagErrorBuf) c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) c.pflags.SetOutput(c.flagErrorBuf) } // Does the command contain any flags (local plus persistent from the entire structure) func (c *Command) HasFlags() bool { return c.Flags().HasFlags() } // Does the command contain persistent flags func (c *Command) HasPersistentFlags() bool { return c.PersistentFlags().HasFlags() } // Does the command has flags specifically declared locally func (c *Command) HasLocalFlags() bool { return c.LocalFlags().HasFlags() } // Does the command have flags inherited from its parent command func (c *Command) HasInheritedFlags() bool { return c.InheritedFlags().HasFlags() } // Does the command contain any flags (local plus persistent from the entire // structure) which are not hidden or deprecated func (c *Command) HasAvailableFlags() bool { return c.Flags().HasAvailableFlags() } // Does the command contain persistent flags which are not hidden or deprecated func (c *Command) HasAvailablePersistentFlags() bool { return c.PersistentFlags().HasAvailableFlags() } // Does the command has flags specifically declared locally which are not hidden // or deprecated func (c *Command) HasAvailableLocalFlags() bool { return c.LocalFlags().HasAvailableFlags() } // Does the command have flags inherited from its parent command which are // not hidden or deprecated func (c *Command) HasAvailableInheritedFlags() bool { return c.InheritedFlags().HasAvailableFlags() } // Flag climbs up the command tree looking for matching flag func (c *Command) Flag(name string) (flag *flag.Flag) { flag = c.Flags().Lookup(name) if flag == nil { flag = c.persistentFlag(name) } return } // recursively find matching persistent flag func (c *Command) persistentFlag(name string) (flag *flag.Flag) { if c.HasPersistentFlags() { flag = c.PersistentFlags().Lookup(name) } if flag == nil && c.HasParent() { flag = c.parent.persistentFlag(name) } return } // ParseFlags parses persistent flag tree & local flags func (c *Command) ParseFlags(args []string) (err error) { if c.DisableFlagParsing { return nil } c.mergePersistentFlags() err = c.Flags().Parse(args) return } // Parent returns a commands parent command func (c *Command) Parent() *Command { return c.parent } func (c *Command) mergePersistentFlags() { var rmerge func(x *Command) // Save the set of local flags if c.lflags == nil { c.lflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError) if c.flagErrorBuf == nil { c.flagErrorBuf = new(bytes.Buffer) } c.lflags.SetOutput(c.flagErrorBuf) addtolocal := func(f *flag.Flag) { c.lflags.AddFlag(f) } c.Flags().VisitAll(addtolocal) c.PersistentFlags().VisitAll(addtolocal) } rmerge = func(x *Command) { if !x.HasParent() { flag.CommandLine.VisitAll(func(f *flag.Flag) { if x.PersistentFlags().Lookup(f.Name) == nil { x.PersistentFlags().AddFlag(f) } }) } if x.HasPersistentFlags() { x.PersistentFlags().VisitAll(func(f *flag.Flag) { if c.Flags().Lookup(f.Name) == nil { c.Flags().AddFlag(f) } }) } if x.HasParent() { rmerge(x.parent) } } rmerge(c) }
PatrickLang/moby
vendor/github.com/spf13/cobra/command.go
GO
apache-2.0
36,518
/* 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 v1beta1 import ( metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // GroupName is the group name for this API. const GroupName = "admission.k8s.io" // SchemeGroupVersion is group version used to register these objects var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1beta1"} // Resource takes an unqualified resource and returns a Group qualified GroupResource func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() } var ( // TODO: move SchemeBuilder with zz_generated.deepcopy.go to k8s.io/api. // localSchemeBuilder and AddToScheme will stay in k8s.io/kubernetes. SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) localSchemeBuilder = &SchemeBuilder AddToScheme = localSchemeBuilder.AddToScheme ) // Adds the list of known types to the given scheme. func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &AdmissionReview{}, ) metav1.AddToGroupVersion(scheme, SchemeGroupVersion) return nil }
juanvallejo/kubernetes
staging/src/k8s.io/api/admission/v1beta1/register.go
GO
apache-2.0
1,715
# $Id$ # # Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org) # # Licensed under The MIT License # For full copyright and license information, please see the LICENSE.txt # Redistributions of files must retain the above copyright notice. # MIT License (http://www.opensource.org/licenses/mit-license.php) CREATE TABLE acos ( id INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT, parent_id INTEGER(10) DEFAULT NULL, model VARCHAR(255) DEFAULT '', foreign_key INTEGER(10) UNSIGNED DEFAULT NULL, alias VARCHAR(255) DEFAULT '', lft INTEGER(10) DEFAULT NULL, rght INTEGER(10) DEFAULT NULL, PRIMARY KEY (id) ); CREATE TABLE aros_acos ( id INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT, aro_id INTEGER(10) UNSIGNED NOT NULL, aco_id INTEGER(10) UNSIGNED NOT NULL, _create CHAR(2) NOT NULL DEFAULT 0, _read CHAR(2) NOT NULL DEFAULT 0, _update CHAR(2) NOT NULL DEFAULT 0, _delete CHAR(2) NOT NULL DEFAULT 0, PRIMARY KEY(id) ); CREATE TABLE aros ( id INTEGER(10) UNSIGNED NOT NULL AUTO_INCREMENT, parent_id INTEGER(10) DEFAULT NULL, model VARCHAR(255) DEFAULT '', foreign_key INTEGER(10) UNSIGNED DEFAULT NULL, alias VARCHAR(255) DEFAULT '', lft INTEGER(10) DEFAULT NULL, rght INTEGER(10) DEFAULT NULL, PRIMARY KEY (id) ); /* this indexes will improve acl perfomance */ CREATE INDEX idx_acos_lft_rght ON `acos` (`lft`, `rght`); CREATE INDEX idx_acos_alias ON `acos` (`alias`); CREATE INDEX idx_aros_lft_rght ON `aros` (`lft`, `rght`); CREATE INDEX idx_aros_alias ON `aros` (`alias`); CREATE INDEX idx_aco_id ON `aros_acos` (`aco_id`);
katedoloverio/PCInventory
app/Config/Schema/db_acl.sql
SQL
apache-2.0
1,597
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp","si",{title:"ළඟා වියහැකි ",contents:"උදව් සඳහා අන්තර්ගතය.නික්මයෙමට ESC බොත්තම ඔබන්න",legend:[{name:"පොදු කරුණු",items:[{name:"සංස්කරණ මෙවලම් ",legend:"ඔබන්න ${මෙවලම් තීරු අවධානය} මෙවලම් තීරුවේ එහා මෙහා යෑමට.ඉදිරියට යෑමට හා ආපසු යෑමට මෙවලම් තීරුකාණ්ඩය හා TAB හා SHIFT-TAB .ඉදිරියට යෑමට හා ආපසු යෑමට මෙවලම් තීරු බොත්තම සමග RIGHT ARROW හෝ LEFT ARROW.මෙවලම් තීරු බොත්තම සක්‍රිය කර ගැනීමට SPACE හෝ ENTER බොත්තම ඔබන්න."},{name:"සංස්කරණ ",legend:"දෙබසක් තුළ, ඊළඟ දෙබස් පෙදෙසට යෑමට TAB බොත්තම ඔබන්න, කලින් පෙදෙසට යෑමට SHIFT + TAB බොත්තම ද, දෙබස් ඉදිරිපත් කිරීමට ENTER බොත්තම ද, දෙබස් නැවතීමට ESCබොත්තම ද, දෙබස් සහිත ගොනු, පිටු වැඩි සංක්‍යයාවක් ලබා ගෙනිමට,ගොනු තුළ එහාමෙහා යෑමට ALT + F10 බොත්තම් ද, ඊළඟ ගොනුවට යෑමට TAB හෝ RIGTH ARROW බොත්තම ඔබන්න. පෙර ගොනුවට යෑමට SHIFT + TAB හෝ LEFT ARROW බොත්තම් ද ,ගොනු පිටු තේරීමට SPACE හෝ ENTER බොත්තම් ද ඔබන්න."}, {name:"සංස්කරණ අඩංගුවට ",legend:"ඔබන්න ${අන්තර්ගත මෙනුව} හෝ APPLICATION KEY අන්තර්ගත-මෙනුව විවුරතකිරීමට. ඊළඟ මෙනුව-ව්කල්පයන්ට යෑමට TAB හෝ DOWN ARROW බොත්තම ද, පෙර විකල්පයන්ටයෑමට SHIFT+TAB හෝ UP ARROW බොත්තම ද, මෙනුව-ව්කල්පයන් තේරීමට SPACE හෝ ENTER බොත්තම ද, දැනට විවුර්තව ඇති උප-මෙනුවක වීකල්ප තේරීමට SPACE හෝ ENTER හෝ RIGHT ARROW ද, නැවත පෙර ප්‍රධාන මෙනුවට යෑමට ESC හෝ LEFT ARROW බොත්තම ද. අන්තර්ගත-මෙනුව වැසීමට ESC බොත්තම ද ඔබන්න."},{name:"සංස්කරණ තේරුම් ",legend:"තේරුම් කොටුව තුළ , ඊළඟ අයිතමයට යෑමට TAB හෝ DOWN ARROW , පෙර අයිතමයට යෑමට SHIFT + TAB හෝ UP ARROW . අයිතම විකල්පයන් තේරීමට SPACE හෝ ENTER ,තේරුම් කොටුව වැසීමට ESC බොත්තම් ද ඔබන්න."}, {name:"සංස්කරණ අංග සහිත ",legend:"ඔබන්න ${මෙවලම් තීරු අවධානය} මෙවලම් තීරුවේ එහා මෙහා යෑමට.ඉදිරියට යෑමට හා ආපසු යෑමට මෙවලම් තීරුකාණ්ඩය හා TAB හා SHIFT-TAB .ඉදිරියට යෑමට හා ආපසු යෑමට මෙවලම් තීරු බොත්තම සමග RIGHT ARROW හෝ LEFT ARROW.මෙවලම් තීරු බොත්තම සක්‍රිය කර ගැනීමට SPACE හෝ ENTER බොත්තම ඔබන්න."}]},{name:"විධාන",items:[{name:"විධානය වෙනස් ",legend:"ඔබන්න ${වෙනස් කිරීම}"},{name:"විධාන නැවත් පෙර පරිදිම වෙනස්කර ගැනීම.",legend:"ඔබන්න ${නැවත් පෙර පරිදිම වෙනස්කර ගැනීම}"},{name:"තද අකුරින් විධාන",legend:"ඔබන්න ${තද }"}, {name:"බැධී අකුරු විධාන",legend:"ඔබන්න ${බැධී අකුරු }"},{name:"යටින් ඉරි ඇද ඇති විධාන.",legend:"ඔබන්න ${යටින් ඉරි ඇද ඇති}"},{name:"සම්බන්ධිත විධාන",legend:"ඔබන්න ${සම්බන්ධ }"},{name:"මෙවලම් තීරු හැකුලුම් විධාන",legend:"ඔබන්න ${මෙවලම් තීරු හැකුලුම් }"},{name:"යොමුවීමට පෙර වැදගත් විධාන",legend:"ඔබන්න ${යොමුවීමට ඊළඟ }"},{name:"යොමුවීමට ඊළග වැදගත් විධාන",legend:"ඔබන්න ${යොමුවීමට ඊළඟ }"},{name:"ප්‍රවේශ ",legend:"ඔබන්න ${a11y }"}]}],backspace:"Backspace",tab:"Tab",enter:"Enter",shift:"Shift",ctrl:"Ctrl", alt:"Alt",pause:"Pause",capslock:"Caps Lock",escape:"Escape",pageUp:"Page Up",pageDown:"Page Down",end:"End",home:"Home",leftArrow:"Left Arrow",upArrow:"Up Arrow",rightArrow:"Right Arrow",downArrow:"Down Arrow",insert:"Insert","delete":"Delete",leftWindowKey:"Left Windows key",rightWindowKey:"Right Windows key",selectKey:"Select key",numpad0:"Numpad 0",numpad1:"Numpad 1",numpad2:"Numpad 2",numpad3:"Numpad 3",numpad4:"Numpad 4",numpad5:"Numpad 5",numpad6:"Numpad 6",numpad7:"Numpad 7",numpad8:"Numpad 8", numpad9:"Numpad 9",multiply:"Multiply",add:"Add",subtract:"Subtract",decimalPoint:"Decimal Point",divide:"Divide",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Semicolon",equalSign:"Equal Sign",comma:"Comma",dash:"Dash",period:"Period",forwardSlash:"Forward Slash",graveAccent:"Grave Accent",openBracket:"Open Bracket",backSlash:"Backslash",closeBracket:"Close Bracket",singleQuote:"Single Quote"});
huanggang/hyd
modules/ckeditor/ckeditor/plugins/a11yhelp/dialogs/lang/si.js
JavaScript
apache-2.0
6,497
// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE (function(mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS mod(require("../../lib/codemirror"), require("../fold/xml-fold")); else if (typeof define == "function" && define.amd) // AMD define(["../../lib/codemirror", "../fold/xml-fold"], mod); else // Plain browser env mod(CodeMirror); })(function(CodeMirror) { "use strict"; CodeMirror.defineOption("matchTags", false, function(cm, val, old) { if (old && old != CodeMirror.Init) { cm.off("cursorActivity", doMatchTags); cm.off("viewportChange", maybeUpdateMatch); clear(cm); } if (val) { cm.state.matchBothTags = typeof val == "object" && val.bothTags; cm.on("cursorActivity", doMatchTags); cm.on("viewportChange", maybeUpdateMatch); doMatchTags(cm); } }); function clear(cm) { if (cm.state.tagHit) cm.state.tagHit.clear(); if (cm.state.tagOther) cm.state.tagOther.clear(); cm.state.tagHit = cm.state.tagOther = null; } function doMatchTags(cm) { cm.state.failedTagMatch = false; cm.operation(function() { clear(cm); if (cm.somethingSelected()) return; var cur = cm.getCursor(), range = cm.getViewport(); range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to); var match = CodeMirror.findMatchingTag(cm, cur, range); if (!match) return; if (cm.state.matchBothTags) { var hit = match.at == "open" ? match.open : match.close; if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: "CodeMirror-matchingtag"}); } var other = match.at == "close" ? match.open : match.close; if (other) cm.state.tagOther = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"}); else cm.state.failedTagMatch = true; }); } function maybeUpdateMatch(cm) { if (cm.state.failedTagMatch) doMatchTags(cm); } CodeMirror.commands.toMatchingTag = function(cm) { var found = CodeMirror.findMatchingTag(cm, cm.getCursor()); if (found) { var other = found.at == "close" ? found.open : found.close; if (other) cm.extendSelection(other.to, other.from); } }; });
torch2424/CECS-300-Wordpress-Site
wp-content/plugins/types/embedded/toolset/toolset-common/visual-editor/res/js/codemirror/addon/edit/matchtags.js
JavaScript
apache-2.0
2,355
package signed import ( "encoding/json" "errors" "strings" "time" "github.com/Sirupsen/logrus" "github.com/endophage/gotuf/data" "github.com/endophage/gotuf/keys" "github.com/tent/canonical-json-go" ) var ( ErrMissingKey = errors.New("tuf: missing key") ErrNoSignatures = errors.New("tuf: data has no signatures") ErrInvalid = errors.New("tuf: signature verification failed") ErrWrongMethod = errors.New("tuf: invalid signature type") ErrUnknownRole = errors.New("tuf: unknown role") ErrWrongType = errors.New("tuf: meta file has wrong type") ) type signedMeta struct { Type string `json:"_type"` Expires time.Time `json:"expires"` Version int `json:"version"` } // VerifyRoot checks if a given root file is valid against a known set of keys. // Threshold is always assumed to be 1 func VerifyRoot(s *data.Signed, minVersion int, keys map[string]data.PublicKey) error { if len(s.Signatures) == 0 { return ErrNoSignatures } var decoded map[string]interface{} if err := json.Unmarshal(s.Signed, &decoded); err != nil { return err } msg, err := cjson.Marshal(decoded) if err != nil { return err } for _, sig := range s.Signatures { // method lookup is consistent due to Unmarshal JSON doing lower case for us. method := sig.Method verifier, ok := Verifiers[method] if !ok { logrus.Debugf("continuing b/c signing method is not supported for verify root: %s\n", sig.Method) continue } key, ok := keys[sig.KeyID] if !ok { logrus.Debugf("continuing b/c signing key isn't present in keys: %s\n", sig.KeyID) continue } if err := verifier.Verify(key, sig.Signature, msg); err != nil { logrus.Debugf("continuing b/c signature was invalid\n") continue } // threshold of 1 so return on first success return verifyMeta(s, "root", minVersion) } return ErrRoleThreshold{} } func Verify(s *data.Signed, role string, minVersion int, db *keys.KeyDB) error { if err := VerifySignatures(s, role, db); err != nil { return err } return verifyMeta(s, role, minVersion) } func verifyMeta(s *data.Signed, role string, minVersion int) error { sm := &signedMeta{} if err := json.Unmarshal(s.Signed, sm); err != nil { return err } if !data.ValidTUFType(sm.Type, role) { return ErrWrongType } if IsExpired(sm.Expires) { logrus.Errorf("Metadata for %s expired", role) return ErrExpired{Role: role, Expired: sm.Expires.Format("Mon Jan 2 15:04:05 MST 2006")} } if sm.Version < minVersion { return ErrLowVersion{sm.Version, minVersion} } return nil } var IsExpired = func(t time.Time) bool { return t.Before(time.Now()) } func VerifySignatures(s *data.Signed, role string, db *keys.KeyDB) error { if len(s.Signatures) == 0 { return ErrNoSignatures } roleData := db.GetRole(role) if roleData == nil { return ErrUnknownRole } if roleData.Threshold < 1 { return ErrRoleThreshold{} } logrus.Debugf("%s role has key IDs: %s", role, strings.Join(roleData.KeyIDs, ",")) var decoded map[string]interface{} if err := json.Unmarshal(s.Signed, &decoded); err != nil { return err } msg, err := cjson.Marshal(decoded) if err != nil { return err } valid := make(map[string]struct{}) for _, sig := range s.Signatures { logrus.Debug("verifying signature for key ID: ", sig.KeyID) if !roleData.ValidKey(sig.KeyID) { logrus.Debugf("continuing b/c keyid was invalid: %s for roledata %s\n", sig.KeyID, roleData) continue } key := db.GetKey(sig.KeyID) if key == nil { logrus.Debugf("continuing b/c keyid lookup was nil: %s\n", sig.KeyID) continue } // method lookup is consistent due to Unmarshal JSON doing lower case for us. method := sig.Method verifier, ok := Verifiers[method] if !ok { logrus.Debugf("continuing b/c signing method is not supported: %s\n", sig.Method) continue } if err := verifier.Verify(key, sig.Signature, msg); err != nil { logrus.Debugf("continuing b/c signature was invalid\n") continue } valid[sig.KeyID] = struct{}{} } if len(valid) < roleData.Threshold { return ErrRoleThreshold{} } return nil } func Unmarshal(b []byte, v interface{}, role string, minVersion int, db *keys.KeyDB) error { s := &data.Signed{} if err := json.Unmarshal(b, s); err != nil { return err } if err := Verify(s, role, minVersion, db); err != nil { return err } return json.Unmarshal(s.Signed, v) } func UnmarshalTrusted(b []byte, v interface{}, role string, db *keys.KeyDB) error { s := &data.Signed{} if err := json.Unmarshal(b, s); err != nil { return err } if err := VerifySignatures(s, role, db); err != nil { return err } return json.Unmarshal(s.Signed, v) }
nf/docker
vendor/src/github.com/endophage/gotuf/signed/verify.go
GO
apache-2.0
4,667
/* The following code was generated by JFlex 1.4.2 */ package org.json.simple.parser; class Yylex { /** This character denotes the end of file */ public static final int YYEOF = -1; /** initial size of the lookahead buffer */ private static final int ZZ_BUFFERSIZE = 16384; /** lexical states */ public static final int YYINITIAL = 0; public static final int STRING_BEGIN = 2; /** * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l * at the beginning of a line * l is of the form l = 2*k, k a non negative integer */ private static final int ZZ_LEXSTATE[] = { 0, 0, 1, 1 }; /** * Translates characters to character classes */ private static final String ZZ_CMAP_PACKED = "\11\0\1\7\1\7\2\0\1\7\22\0\1\7\1\0\1\11\10\0"+ "\1\6\1\31\1\2\1\4\1\12\12\3\1\32\6\0\4\1\1\5"+ "\1\1\24\0\1\27\1\10\1\30\3\0\1\22\1\13\2\1\1\21"+ "\1\14\5\0\1\23\1\0\1\15\3\0\1\16\1\24\1\17\1\20"+ "\5\0\1\25\1\0\1\26\uff82\0"; /** * Translates characters to character classes */ private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); /** * Translates DFA states to action switch labels. */ private static final int [] ZZ_ACTION = zzUnpackAction(); private static final String ZZ_ACTION_PACKED_0 = "\2\0\2\1\1\2\1\3\1\4\3\1\1\5\1\6"+ "\1\7\1\10\1\11\1\12\1\13\1\14\1\15\5\0"+ "\1\14\1\16\1\17\1\20\1\21\1\22\1\23\1\24"+ "\1\0\1\25\1\0\1\25\4\0\1\26\1\27\2\0"+ "\1\30"; private static int [] zzUnpackAction() { int [] result = new int[45]; int offset = 0; offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); return result; } private static int zzUnpackAction(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** * Translates a state to a row index in the transition table */ private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); private static final String ZZ_ROWMAP_PACKED_0 = "\0\0\0\33\0\66\0\121\0\154\0\207\0\66\0\242"+ "\0\275\0\330\0\66\0\66\0\66\0\66\0\66\0\66"+ "\0\363\0\u010e\0\66\0\u0129\0\u0144\0\u015f\0\u017a\0\u0195"+ "\0\66\0\66\0\66\0\66\0\66\0\66\0\66\0\66"+ "\0\u01b0\0\u01cb\0\u01e6\0\u01e6\0\u0201\0\u021c\0\u0237\0\u0252"+ "\0\66\0\66\0\u026d\0\u0288\0\66"; private static int [] zzUnpackRowMap() { int [] result = new int[45]; int offset = 0; offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); return result; } private static int zzUnpackRowMap(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int high = packed.charAt(i++) << 16; result[j++] = high | packed.charAt(i++); } return j; } /** * The transition table of the DFA */ private static final int ZZ_TRANS [] = { 2, 2, 3, 4, 2, 2, 2, 5, 2, 6, 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, 2, 10, 11, 12, 13, 14, 15, 16, 16, 16, 16, 16, 16, 16, 16, 17, 18, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 19, 20, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 16, 16, 16, 16, 16, 16, 16, 16, -1, -1, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, -1, -1, 24, 25, 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 33, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 34, 35, -1, -1, 34, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 37, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 38, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 39, -1, 39, -1, 39, -1, -1, -1, -1, -1, 39, 39, -1, -1, -1, -1, 39, 39, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 33, -1, 20, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 35, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 38, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 40, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 41, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 42, -1, 42, -1, 42, -1, -1, -1, -1, -1, 42, 42, -1, -1, -1, -1, 42, 42, -1, -1, -1, -1, -1, -1, -1, -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, -1, -1, 43, 43, -1, -1, -1, -1, 43, 43, -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, -1, 44, -1, 44, -1, -1, -1, -1, -1, 44, 44, -1, -1, -1, -1, 44, 44, -1, -1, -1, -1, -1, -1, -1, -1, }; /* error codes */ private static final int ZZ_UNKNOWN_ERROR = 0; private static final int ZZ_NO_MATCH = 1; private static final int ZZ_PUSHBACK_2BIG = 2; /* error messages for the codes above */ private static final String ZZ_ERROR_MSG[] = { "Unkown internal scanner error", "Error: could not match input", "Error: pushback value was too large" }; /** * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> */ private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); private static final String ZZ_ATTRIBUTE_PACKED_0 = "\2\0\1\11\3\1\1\11\3\1\6\11\2\1\1\11"+ "\5\0\10\11\1\0\1\1\1\0\1\1\4\0\2\11"+ "\2\0\1\11"; private static int [] zzUnpackAttribute() { int [] result = new int[45]; int offset = 0; offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); return result; } private static int zzUnpackAttribute(String packed, int offset, int [] result) { int i = 0; /* index in packed string */ int j = offset; /* index in unpacked array */ int l = packed.length(); while (i < l) { int count = packed.charAt(i++); int value = packed.charAt(i++); do result[j++] = value; while (--count > 0); } return j; } /** the input device */ private java.io.Reader zzReader; /** the current state of the DFA */ private int zzState; /** the current lexical state */ private int zzLexicalState = YYINITIAL; /** this buffer contains the current text to be matched and is the source of the yytext() string */ private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; /** the textposition at the last accepting state */ private int zzMarkedPos; /** the current text position in the buffer */ private int zzCurrentPos; /** startRead marks the beginning of the yytext() string in the buffer */ private int zzStartRead; /** endRead marks the last character in the buffer, that has been read from input */ private int zzEndRead; /** number of newlines encountered up to the start of the matched text */ private int yyline; /** the number of characters up to the start of the matched text */ private int yychar; /** * the number of characters from the last newline up to the start of the * matched text */ private int yycolumn; /** * zzAtBOL == true <=> the scanner is currently at the beginning of a line */ private boolean zzAtBOL = true; /** zzAtEOF == true <=> the scanner is at the EOF */ private boolean zzAtEOF; /* user code: */ private StringBuffer sb=new StringBuffer(); int getPosition(){ return yychar; } /** * Creates a new scanner * There is also a java.io.InputStream version of this constructor. * * @param in the java.io.Reader to read input from. */ Yylex(java.io.Reader in) { this.zzReader = in; } /** * Creates a new scanner. * There is also java.io.Reader version of this constructor. * * @param in the java.io.Inputstream to read input from. */ Yylex(java.io.InputStream in) { this(new java.io.InputStreamReader(in)); } /** * Unpacks the compressed character translation table. * * @param packed the packed character translation table * @return the unpacked character translation table */ private static char [] zzUnpackCMap(String packed) { char [] map = new char[0x10000]; int i = 0; /* index in packed string */ int j = 0; /* index in unpacked array */ while (i < 90) { int count = packed.charAt(i++); char value = packed.charAt(i++); do map[j++] = value; while (--count > 0); } return map; } /** * Refills the input buffer. * * @return <code>false</code>, iff there was new input. * * @exception java.io.IOException if any I/O-Error occurs */ private boolean zzRefill() throws java.io.IOException { /* first: make room (if you can) */ if (zzStartRead > 0) { System.arraycopy(zzBuffer, zzStartRead, zzBuffer, 0, zzEndRead-zzStartRead); /* translate stored positions */ zzEndRead-= zzStartRead; zzCurrentPos-= zzStartRead; zzMarkedPos-= zzStartRead; zzStartRead = 0; } /* is the buffer big enough? */ if (zzCurrentPos >= zzBuffer.length) { /* if not: blow it up */ char newBuffer[] = new char[zzCurrentPos*2]; System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); zzBuffer = newBuffer; } /* finally: fill the buffer with new input */ int numRead = zzReader.read(zzBuffer, zzEndRead, zzBuffer.length-zzEndRead); if (numRead > 0) { zzEndRead+= numRead; return false; } // unlikely but not impossible: read 0 characters, but not at end of stream if (numRead == 0) { int c = zzReader.read(); if (c == -1) { return true; } else { zzBuffer[zzEndRead++] = (char) c; return false; } } // numRead < 0 return true; } /** * Closes the input stream. */ public final void yyclose() throws java.io.IOException { zzAtEOF = true; /* indicate end of file */ zzEndRead = zzStartRead; /* invalidate buffer */ if (zzReader != null) zzReader.close(); } /** * Resets the scanner to read from a new input stream. * Does not close the old reader. * * All internal variables are reset, the old input stream * <b>cannot</b> be reused (internal buffer is discarded and lost). * Lexical state is set to <tt>ZZ_INITIAL</tt>. * * @param reader the new input stream */ public final void yyreset(java.io.Reader reader) { zzReader = reader; zzAtBOL = true; zzAtEOF = false; zzEndRead = zzStartRead = 0; zzCurrentPos = zzMarkedPos = 0; yyline = yychar = yycolumn = 0; zzLexicalState = YYINITIAL; } /** * Returns the current lexical state. */ public final int yystate() { return zzLexicalState; } /** * Enters a new lexical state * * @param newState the new lexical state */ public final void yybegin(int newState) { zzLexicalState = newState; } /** * Returns the text matched by the current regular expression. */ public final String yytext() { return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); } /** * Returns the character at position <tt>pos</tt> from the * matched text. * * It is equivalent to yytext().charAt(pos), but faster * * @param pos the position of the character to fetch. * A value from 0 to yylength()-1. * * @return the character at position pos */ public final char yycharat(int pos) { return zzBuffer[zzStartRead+pos]; } /** * Returns the length of the matched text region. */ public final int yylength() { return zzMarkedPos-zzStartRead; } /** * Reports an error that occured while scanning. * * In a wellformed scanner (no or only correct usage of * yypushback(int) and a match-all fallback rule) this method * will only be called with things that "Can't Possibly Happen". * If this method is called, something is seriously wrong * (e.g. a JFlex bug producing a faulty scanner etc.). * * Usual syntax/scanner level error handling should be done * in error fallback rules. * * @param errorCode the code of the errormessage to display */ private void zzScanError(int errorCode) { String message; try { message = ZZ_ERROR_MSG[errorCode]; } catch (ArrayIndexOutOfBoundsException e) { message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; } throw new Error(message); } /** * Pushes the specified amount of characters back into the input stream. * * They will be read again by then next call of the scanning method * * @param number the number of characters to be read again. * This number must not be greater than yylength()! */ public void yypushback(int number) { if ( number > yylength() ) zzScanError(ZZ_PUSHBACK_2BIG); zzMarkedPos -= number; } /** * Resumes scanning until the next regular expression is matched, * the end of input is encountered or an I/O-Error occurs. * * @return the next token * @exception java.io.IOException if any I/O-Error occurs */ public Yytoken yylex() throws java.io.IOException, ParseException { int zzInput; int zzAction; // cached fields: int zzCurrentPosL; int zzMarkedPosL; int zzEndReadL = zzEndRead; char [] zzBufferL = zzBuffer; char [] zzCMapL = ZZ_CMAP; int [] zzTransL = ZZ_TRANS; int [] zzRowMapL = ZZ_ROWMAP; int [] zzAttrL = ZZ_ATTRIBUTE; while (true) { zzMarkedPosL = zzMarkedPos; yychar+= zzMarkedPosL-zzStartRead; zzAction = -1; zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; zzState = ZZ_LEXSTATE[zzLexicalState]; zzForAction: { while (true) { if (zzCurrentPosL < zzEndReadL) zzInput = zzBufferL[zzCurrentPosL++]; else if (zzAtEOF) { zzInput = YYEOF; break zzForAction; } else { // store back cached positions zzCurrentPos = zzCurrentPosL; zzMarkedPos = zzMarkedPosL; boolean eof = zzRefill(); // get translated positions and possibly new buffer zzCurrentPosL = zzCurrentPos; zzMarkedPosL = zzMarkedPos; zzBufferL = zzBuffer; zzEndReadL = zzEndRead; if (eof) { zzInput = YYEOF; break zzForAction; } else { zzInput = zzBufferL[zzCurrentPosL++]; } } int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; if (zzNext == -1) break zzForAction; zzState = zzNext; int zzAttributes = zzAttrL[zzState]; if ( (zzAttributes & 1) == 1 ) { zzAction = zzState; zzMarkedPosL = zzCurrentPosL; if ( (zzAttributes & 8) == 8 ) break zzForAction; } } } // store back cached position zzMarkedPos = zzMarkedPosL; switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { case 11: { sb.append(yytext()); } case 25: break; case 4: { sb = null; sb = new StringBuffer(); yybegin(STRING_BEGIN); } case 26: break; case 16: { sb.append('\b'); } case 27: break; case 6: { return new Yytoken(Yytoken.TYPE_RIGHT_BRACE,null); } case 28: break; case 23: { Boolean val=Boolean.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); } case 29: break; case 22: { return new Yytoken(Yytoken.TYPE_VALUE, null); } case 30: break; case 13: { yybegin(YYINITIAL);return new Yytoken(Yytoken.TYPE_VALUE, sb.toString()); } case 31: break; case 12: { sb.append('\\'); } case 32: break; case 21: { Double val=Double.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); } case 33: break; case 1: { throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, new Character(yycharat(0))); } case 34: break; case 8: { return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE,null); } case 35: break; case 19: { sb.append('\r'); } case 36: break; case 15: { sb.append('/'); } case 37: break; case 10: { return new Yytoken(Yytoken.TYPE_COLON,null); } case 38: break; case 14: { sb.append('"'); } case 39: break; case 5: { return new Yytoken(Yytoken.TYPE_LEFT_BRACE,null); } case 40: break; case 17: { sb.append('\f'); } case 41: break; case 24: { try{ int ch=Integer.parseInt(yytext().substring(2),16); sb.append((char)ch); } catch(Exception e){ throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e); } } case 42: break; case 20: { sb.append('\t'); } case 43: break; case 7: { return new Yytoken(Yytoken.TYPE_LEFT_SQUARE,null); } case 44: break; case 2: { Long val=Long.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); } case 45: break; case 18: { sb.append('\n'); } case 46: break; case 9: { return new Yytoken(Yytoken.TYPE_COMMA,null); } case 47: break; case 3: { } case 48: break; default: if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { zzAtEOF = true; return null; } else { zzScanError(ZZ_NO_MATCH); } } } } }
gpalla/json-simple
src/main/java/org/json/simple/parser/Yylex.java
Java
apache-2.0
20,556
function setupClicker() { // when hovering over arrow, add highlight (only if inactive) $("i.methodToggle").hover(function () { if (!$("i.methodToggle").hasClass('active')) $(this).addClass("methodToggleHover"); }, function () { $(this).removeClass("methodToggleHover"); } ); function handleClick(e, linkHref) { //if (linkHref.indexOf("nav=api&api=") >= 0) // return; if (linkHref == "api") return; e.preventDefault(); var dstElem; if (linkHref) { dstElem = $("article[id='" + linkHref + "']"); } var $article = (dstElem || $(this)).closest('.article'), $arrow = $('i.methodClicker', $article); if (!$article.hasClass('methodToggleOpen') || this.force) { $article.addClass('methodToggleOpen'); $arrow.removeClass('inactive').addClass('active'); if (!$arrow[0]) return; var data = $arrow[0].id.replace(/^js_/, ""); //var state = {}; //state.section = data; //$.bbq.pushState(state); scrollTo(null, data); } else { $article.removeClass('methodToggleOpen'); $arrow.removeClass('active').addClass('inactive'); } } function transformHash(e) { // some bs to figure out link hash var hashId = (e.srcElement ? e.srcElement.href : (e.hash || e.target.href)) || e.currentTarget.hash; handleClick(e, hashId.substring(hashId.indexOf("#") + 1)); } // for the arrow $("i.methodToggle").click(handleClick); // for the signature $('.member-name').click(handleClick); // for the top dropdown $('li.memberLink a').click(transformHash); //$('a[href^="#"]').click(transformHash); $('.related-to', '.metaInfo').click(function(){ location.hash = $(this).find('a').attr('href').split('#')[1]; }); }
schematical/nde
public/bower_components/ace/doc/template/resources/javascripts/clicker.js
JavaScript
apache-2.0
1,941
// +build acceptance package v2 import ( "crypto/rand" "crypto/rsa" "testing" "github.com/rackspace/gophercloud/acceptance/tools" "github.com/rackspace/gophercloud/openstack/compute/v2/extensions/keypairs" "github.com/rackspace/gophercloud/openstack/compute/v2/servers" th "github.com/rackspace/gophercloud/testhelper" "golang.org/x/crypto/ssh" ) const keyName = "gophercloud_test_key_pair" func TestCreateServerWithKeyPair(t *testing.T) { client, err := newClient() th.AssertNoErr(t, err) if testing.Short() { t.Skip("Skipping test that requires server creation in short mode.") } privateKey, err := rsa.GenerateKey(rand.Reader, 2048) publicKey := privateKey.PublicKey pub, err := ssh.NewPublicKey(&publicKey) th.AssertNoErr(t, err) pubBytes := ssh.MarshalAuthorizedKey(pub) pk := string(pubBytes) kp, err := keypairs.Create(client, keypairs.CreateOpts{ Name: keyName, PublicKey: pk, }).Extract() th.AssertNoErr(t, err) t.Logf("Created key pair: %s\n", kp) choices, err := ComputeChoicesFromEnv() th.AssertNoErr(t, err) name := tools.RandomString("Gophercloud-", 8) t.Logf("Creating server [%s] with key pair.", name) serverCreateOpts := servers.CreateOpts{ Name: name, FlavorRef: choices.FlavorID, ImageRef: choices.ImageID, } server, err := servers.Create(client, keypairs.CreateOptsExt{ serverCreateOpts, keyName, }).Extract() th.AssertNoErr(t, err) defer servers.Delete(client, server.ID) if err = waitForStatus(client, server, "ACTIVE"); err != nil { t.Fatalf("Unable to wait for server: %v", err) } server, err = servers.Get(client, server.ID).Extract() t.Logf("Created server: %+v\n", server) th.AssertNoErr(t, err) th.AssertEquals(t, server.KeyName, keyName) t.Logf("Deleting key pair [%s]...", kp.Name) err = keypairs.Delete(client, keyName).ExtractErr() th.AssertNoErr(t, err) t.Logf("Deleting server [%s]...", name) }
spohnan/origin
Godeps/_workspace/src/github.com/rackspace/gophercloud/acceptance/openstack/compute/v2/keypairs_test.go
GO
apache-2.0
1,917
/* Flot plugin that adds some extra symbols for plotting points. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. The symbols are accessed as strings through the standard symbol options: series: { points: { symbol: "square" // or "diamond", "triangle", "cross" } } */ (function ($) { function processRawData(plot, series, datapoints) { // we normalize the area of each symbol so it is approximately the // same as a circle of the given radius var handlers = { square: function (ctx, x, y, radius, shadow) { // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 var size = radius * Math.sqrt(Math.PI) / 2; ctx.rect(x - size, y - size, size + size, size + size); }, diamond: function (ctx, x, y, radius, shadow) { // pi * r^2 = 2s^2 => s = r * sqrt(pi/2) var size = radius * Math.sqrt(Math.PI / 2); ctx.moveTo(x - size, y); ctx.lineTo(x, y - size); ctx.lineTo(x + size, y); ctx.lineTo(x, y + size); ctx.lineTo(x - size, y); }, triangle: function (ctx, x, y, radius, shadow) { // pi * r^2 = 1/2 * s^2 * sin (pi / 3) => s = r * sqrt(2 * pi / sin(pi / 3)) var size = radius * Math.sqrt(2 * Math.PI / Math.sin(Math.PI / 3)); var height = size * Math.sin(Math.PI / 3); ctx.moveTo(x - size/2, y + height/2); ctx.lineTo(x + size/2, y + height/2); if (!shadow) { ctx.lineTo(x, y - height/2); ctx.lineTo(x - size/2, y + height/2); } }, cross: function (ctx, x, y, radius, shadow) { // pi * r^2 = (2s)^2 => s = r * sqrt(pi)/2 var size = radius * Math.sqrt(Math.PI) / 2; ctx.moveTo(x - size, y - size); ctx.lineTo(x + size, y + size); ctx.moveTo(x - size, y + size); ctx.lineTo(x + size, y - size); } }; var s = series.points.symbol; if (handlers[s]) series.points.symbol = handlers[s]; } function init(plot) { plot.hooks.processDatapoints.push(processRawData); } $.plot.plugins.push({ init: init, name: 'symbols', version: '1.0' }); })(jQuery);
fanybook/demo
public/vendor/adminlte/plugins/flot/jquery.flot.symbol.js
JavaScript
apache-2.0
2,505
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.5"/> <title>GLM: GLM_GTC_constants</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">GLM &#160;<span id="projectnumber">0.9.5</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.5 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="namespaces.html"><span>Namespaces</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#func-members">Functions</a> </div> <div class="headertitle"> <div class="title">GLM_GTC_constants<div class="ingroups"><a class="el" href="a00164.html">GTC Extensions (Stable)</a></div></div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a> Functions</h2></td></tr> <tr class="memitem:gab83fb6de0f05d6c0d11bdf0479f8319e"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gab83fb6de0f05d6c0d11bdf0479f8319e"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gab83fb6de0f05d6c0d11bdf0479f8319e">e</a> ()</td></tr> <tr class="separator:gab83fb6de0f05d6c0d11bdf0479f8319e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gacb41049b8d22c8aa90e362b96c524feb"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gacb41049b8d22c8aa90e362b96c524feb"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gacb41049b8d22c8aa90e362b96c524feb">epsilon</a> ()</td></tr> <tr class="separator:gacb41049b8d22c8aa90e362b96c524feb"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga6f14b46653b7ead1edcbd0fc6c9c5289"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga6f14b46653b7ead1edcbd0fc6c9c5289"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga6f14b46653b7ead1edcbd0fc6c9c5289">euler</a> ()</td></tr> <tr class="separator:ga6f14b46653b7ead1edcbd0fc6c9c5289"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gafd53093ef2d756333865d774bea3cdf9"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gafd53093ef2d756333865d774bea3cdf9"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gafd53093ef2d756333865d774bea3cdf9">golden_ratio</a> ()</td></tr> <tr class="separator:gafd53093ef2d756333865d774bea3cdf9"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga7f7a1050729f3b03b1873a06ba4a472f"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga7f7a1050729f3b03b1873a06ba4a472f"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga7f7a1050729f3b03b1873a06ba4a472f">half_pi</a> ()</td></tr> <tr class="separator:ga7f7a1050729f3b03b1873a06ba4a472f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga650774609debe4a90bcac449b574de2c"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga650774609debe4a90bcac449b574de2c"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga650774609debe4a90bcac449b574de2c">ln_ln_two</a> ()</td></tr> <tr class="separator:ga650774609debe4a90bcac449b574de2c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga48addf0cb0980277d208a71a1c59c073"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga48addf0cb0980277d208a71a1c59c073"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga48addf0cb0980277d208a71a1c59c073">ln_ten</a> ()</td></tr> <tr class="separator:ga48addf0cb0980277d208a71a1c59c073"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga22fae798430edc3022766af4fd83e8a4"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga22fae798430edc3022766af4fd83e8a4"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga22fae798430edc3022766af4fd83e8a4">ln_two</a> ()</td></tr> <tr class="separator:ga22fae798430edc3022766af4fd83e8a4"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga8186ec2c330457d41d9686c47cd3b2d1"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga8186ec2c330457d41d9686c47cd3b2d1"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga8186ec2c330457d41d9686c47cd3b2d1">one</a> ()</td></tr> <tr class="separator:ga8186ec2c330457d41d9686c47cd3b2d1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9ba09a027db6d4f4e259b01cf5d6c178"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga9ba09a027db6d4f4e259b01cf5d6c178"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga9ba09a027db6d4f4e259b01cf5d6c178">one_over_pi</a> ()</td></tr> <tr class="separator:ga9ba09a027db6d4f4e259b01cf5d6c178"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gac1a9b3248357fd9e9b740bed90e0b1b7"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gac1a9b3248357fd9e9b740bed90e0b1b7"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gac1a9b3248357fd9e9b740bed90e0b1b7">one_over_root_two</a> ()</td></tr> <tr class="separator:gac1a9b3248357fd9e9b740bed90e0b1b7"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae671930537266a9a650ccb4b88757692"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gae671930537266a9a650ccb4b88757692"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gae671930537266a9a650ccb4b88757692">pi</a> ()</td></tr> <tr class="separator:gae671930537266a9a650ccb4b88757692"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga0148d757b4bfda4d86251b8d1ea1dad3"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga0148d757b4bfda4d86251b8d1ea1dad3"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga0148d757b4bfda4d86251b8d1ea1dad3">quarter_pi</a> ()</td></tr> <tr class="separator:ga0148d757b4bfda4d86251b8d1ea1dad3"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gace2b8dfed1ab9fabbb67dde08e7e5b58"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gace2b8dfed1ab9fabbb67dde08e7e5b58"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gace2b8dfed1ab9fabbb67dde08e7e5b58">root_five</a> ()</td></tr> <tr class="separator:gace2b8dfed1ab9fabbb67dde08e7e5b58"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gaec5af85e2148c118aad7e797430fdeb0"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gaec5af85e2148c118aad7e797430fdeb0"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gaec5af85e2148c118aad7e797430fdeb0">root_half_pi</a> ()</td></tr> <tr class="separator:gaec5af85e2148c118aad7e797430fdeb0"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga9cae3fad9314e34c1d3aab71fcdef05f"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga9cae3fad9314e34c1d3aab71fcdef05f"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga9cae3fad9314e34c1d3aab71fcdef05f">root_ln_four</a> ()</td></tr> <tr class="separator:ga9cae3fad9314e34c1d3aab71fcdef05f"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga1cfeb345f34f72697d14f4db8d5d4c6c"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga1cfeb345f34f72697d14f4db8d5d4c6c"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga1cfeb345f34f72697d14f4db8d5d4c6c">root_pi</a> ()</td></tr> <tr class="separator:ga1cfeb345f34f72697d14f4db8d5d4c6c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gab3183635ac615473e2f95852f491be83"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gab3183635ac615473e2f95852f491be83"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gab3183635ac615473e2f95852f491be83">root_three</a> ()</td></tr> <tr class="separator:gab3183635ac615473e2f95852f491be83"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gab91b7799f88f9f2be33e385dec11b9c2"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gab91b7799f88f9f2be33e385dec11b9c2"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gab91b7799f88f9f2be33e385dec11b9c2">root_two</a> ()</td></tr> <tr class="separator:gab91b7799f88f9f2be33e385dec11b9c2"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gae991b4d39c57b57990054eec3677597c"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gae991b4d39c57b57990054eec3677597c"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gae991b4d39c57b57990054eec3677597c">root_two_pi</a> ()</td></tr> <tr class="separator:gae991b4d39c57b57990054eec3677597c"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gabf280496105e0ad070287417f840ebd8"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gabf280496105e0ad070287417f840ebd8"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gabf280496105e0ad070287417f840ebd8">third</a> ()</td></tr> <tr class="separator:gabf280496105e0ad070287417f840ebd8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga85729d38c47351686e8659f80447a7ea"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga85729d38c47351686e8659f80447a7ea"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga85729d38c47351686e8659f80447a7ea">two_over_pi</a> ()</td></tr> <tr class="separator:ga85729d38c47351686e8659f80447a7ea"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga767e539c20585bf60aa63595b0f0b259"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga767e539c20585bf60aa63595b0f0b259"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga767e539c20585bf60aa63595b0f0b259">two_over_root_pi</a> ()</td></tr> <tr class="separator:ga767e539c20585bf60aa63595b0f0b259"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:gadde7f2efce3b14c8b26944fbafed4a10"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:gadde7f2efce3b14c8b26944fbafed4a10"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#gadde7f2efce3b14c8b26944fbafed4a10">two_thirds</a> ()</td></tr> <tr class="separator:gadde7f2efce3b14c8b26944fbafed4a10"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ga5cc97dd01d37fc199264ff6030578435"><td class="memTemplParams" colspan="2">template&lt;typename genType &gt; </td></tr> <tr class="memitem:ga5cc97dd01d37fc199264ff6030578435"><td class="memTemplItemLeft" align="right" valign="top">GLM_FUNC_DECL genType&#160;</td><td class="memTemplItemRight" valign="bottom"><a class="el" href="a00171.html#ga5cc97dd01d37fc199264ff6030578435">zero</a> ()</td></tr> <tr class="separator:ga5cc97dd01d37fc199264ff6030578435"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <p>Allow to perform bit operations on integer values. </p> <p>&lt;<a class="el" href="a00019.html" title="OpenGL Mathematics (glm.g-truc.net) ">glm/gtc/constants.hpp</a>&gt; need to be included to use these features. </p> <h2 class="groupheader">Function Documentation</h2> <a class="anchor" id="gab83fb6de0f05d6c0d11bdf0479f8319e"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::e </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return e constant. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gacb41049b8d22c8aa90e362b96c524feb"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::epsilon </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return the epsilon constant for floating point types. </p> <dl class="todo"><dt><b><a class="el" href="a00239.html#_todo000004">Todo:</a></b></dt><dd>Implement epsilon for half-precision floating point type. </dd></dl> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga6f14b46653b7ead1edcbd0fc6c9c5289"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::euler </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return Euler's constant. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gafd53093ef2d756333865d774bea3cdf9"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::golden_ratio </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return the golden ratio constant. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga7f7a1050729f3b03b1873a06ba4a472f"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::half_pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return pi / 2. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga650774609debe4a90bcac449b574de2c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::ln_ln_two </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return ln(ln(2)). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga48addf0cb0980277d208a71a1c59c073"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::ln_ten </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return ln(10). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga22fae798430edc3022766af4fd83e8a4"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::ln_two </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return ln(2). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga8186ec2c330457d41d9686c47cd3b2d1"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::one </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return 1. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga9ba09a027db6d4f4e259b01cf5d6c178"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::one_over_pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return 1 / pi. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gac1a9b3248357fd9e9b740bed90e0b1b7"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::one_over_root_two </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return 1 / sqrt(2). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gae671930537266a9a650ccb4b88757692"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return the pi constant. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga0148d757b4bfda4d86251b8d1ea1dad3"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::quarter_pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return pi / 4. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gace2b8dfed1ab9fabbb67dde08e7e5b58"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::root_five </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return sqrt(5). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gaec5af85e2148c118aad7e797430fdeb0"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::root_half_pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return sqrt(pi / 2). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga9cae3fad9314e34c1d3aab71fcdef05f"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::root_ln_four </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return sqrt(ln(4)). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga1cfeb345f34f72697d14f4db8d5d4c6c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::root_pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return square root of pi. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gab3183635ac615473e2f95852f491be83"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::root_three </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return sqrt(3). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gab91b7799f88f9f2be33e385dec11b9c2"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::root_two </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return sqrt(2). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gae991b4d39c57b57990054eec3677597c"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::root_two_pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return sqrt(2 * pi). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gabf280496105e0ad070287417f840ebd8"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::third </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return 1 / 3. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga85729d38c47351686e8659f80447a7ea"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::two_over_pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return 2 / pi. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga767e539c20585bf60aa63595b0f0b259"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::two_over_root_pi </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return 2 / sqrt(pi). </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="gadde7f2efce3b14c8b26944fbafed4a10"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::two_thirds </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return 2 / 3. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> <a class="anchor" id="ga5cc97dd01d37fc199264ff6030578435"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">GLM_FUNC_DECL genType glm::zero </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> <p>Return 0. </p> <dl class="section see"><dt>See Also</dt><dd><a class="el" href="a00171.html" title="Allow to perform bit operations on integer values. ">GLM_GTC_constants</a> </dd></dl> </div> </div> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.5 </small></address> </body> </html>
simon247/omim
3party/glm/doc/api/a00171.html
HTML
apache-2.0
30,602
package testblas import ( "testing" "github.com/gonum/blas" ) type Dsyrer interface { Dsyr(ul blas.Uplo, n int, alpha float64, x []float64, incX int, a []float64, lda int) } func DsyrTest(t *testing.T, blasser Dsyrer) { for i, test := range []struct { ul blas.Uplo n int a [][]float64 x []float64 alpha float64 ans [][]float64 }{ { ul: blas.Upper, n: 4, a: [][]float64{ {10, 2, 0, 1}, {0, 1, 2, 3}, {0, 0, 9, 15}, {0, 0, 0, -6}, }, x: []float64{1, 2, 0, 5}, alpha: 8, ans: [][]float64{ {18, 18, 0, 41}, {0, 33, 2, 83}, {0, 0, 9, 15}, {0, 0, 0, 194}, }, }, { ul: blas.Lower, n: 3, a: [][]float64{ {10, 2, 0}, {4, 1, 2}, {2, 7, 9}, }, x: []float64{3, 0, 5}, alpha: 8, ans: [][]float64{ {82, 2, 0}, {4, 1, 2}, {122, 7, 209}, }, }, } { incTest := func(incX, extra int) { xnew := makeIncremented(test.x, incX, extra) aFlat := flatten(test.a) ans := flatten(test.ans) lda := test.n blasser.Dsyr(test.ul, test.n, test.alpha, xnew, incX, aFlat, lda) if !dSliceTolEqual(aFlat, ans) { t.Errorf("Case %v, idx %v: Want %v, got %v.", i, incX, ans, aFlat) } } incTest(1, 3) incTest(1, 0) incTest(3, 2) incTest(-2, 2) } }
smunilla/origin
Godeps/_workspace/src/github.com/gonum/blas/testblas/dsyr.go
GO
apache-2.0
1,306
/* 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. */ // This file was automatically generated by lister-gen package v1beta2 import ( v1beta2 "k8s.io/api/apps/v1beta2" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/labels" "k8s.io/client-go/tools/cache" ) // ControllerRevisionLister helps list ControllerRevisions. type ControllerRevisionLister interface { // List lists all ControllerRevisions in the indexer. List(selector labels.Selector) (ret []*v1beta2.ControllerRevision, err error) // ControllerRevisions returns an object that can list and get ControllerRevisions. ControllerRevisions(namespace string) ControllerRevisionNamespaceLister ControllerRevisionListerExpansion } // controllerRevisionLister implements the ControllerRevisionLister interface. type controllerRevisionLister struct { indexer cache.Indexer } // NewControllerRevisionLister returns a new ControllerRevisionLister. func NewControllerRevisionLister(indexer cache.Indexer) ControllerRevisionLister { return &controllerRevisionLister{indexer: indexer} } // List lists all ControllerRevisions in the indexer. func (s *controllerRevisionLister) List(selector labels.Selector) (ret []*v1beta2.ControllerRevision, err error) { err = cache.ListAll(s.indexer, selector, func(m interface{}) { ret = append(ret, m.(*v1beta2.ControllerRevision)) }) return ret, err } // ControllerRevisions returns an object that can list and get ControllerRevisions. func (s *controllerRevisionLister) ControllerRevisions(namespace string) ControllerRevisionNamespaceLister { return controllerRevisionNamespaceLister{indexer: s.indexer, namespace: namespace} } // ControllerRevisionNamespaceLister helps list and get ControllerRevisions. type ControllerRevisionNamespaceLister interface { // List lists all ControllerRevisions in the indexer for a given namespace. List(selector labels.Selector) (ret []*v1beta2.ControllerRevision, err error) // Get retrieves the ControllerRevision from the indexer for a given namespace and name. Get(name string) (*v1beta2.ControllerRevision, error) ControllerRevisionNamespaceListerExpansion } // controllerRevisionNamespaceLister implements the ControllerRevisionNamespaceLister // interface. type controllerRevisionNamespaceLister struct { indexer cache.Indexer namespace string } // List lists all ControllerRevisions in the indexer for a given namespace. func (s controllerRevisionNamespaceLister) List(selector labels.Selector) (ret []*v1beta2.ControllerRevision, err error) { err = cache.ListAllByNamespace(s.indexer, s.namespace, selector, func(m interface{}) { ret = append(ret, m.(*v1beta2.ControllerRevision)) }) return ret, err } // Get retrieves the ControllerRevision from the indexer for a given namespace and name. func (s controllerRevisionNamespaceLister) Get(name string) (*v1beta2.ControllerRevision, error) { obj, exists, err := s.indexer.GetByKey(s.namespace + "/" + name) if err != nil { return nil, err } if !exists { return nil, errors.NewNotFound(v1beta2.Resource("controllerrevision"), name) } return obj.(*v1beta2.ControllerRevision), nil }
martinivanov/kubernetes
staging/src/k8s.io/client-go/listers/apps/v1beta2/controllerrevision.go
GO
apache-2.0
3,641
# Copyright (C) 2002-2006 Python Software Foundation # Contact: email-sig@python.org # email package unit tests for (optional) Asian codecs import unittest from test.test_support import TestSkipped, run_unittest from email.test.test_email import TestEmailBase from email.Charset import Charset from email.Header import Header, decode_header from email.Message import Message # We're compatible with Python 2.3, but it doesn't have the built-in Asian # codecs, so we have to skip all these tests. try: unicode('foo', 'euc-jp') except LookupError: raise TestSkipped class TestEmailAsianCodecs(TestEmailBase): def test_japanese_codecs(self): eq = self.ndiffAssertEqual j = Charset("euc-jp") g = Charset("iso-8859-1") h = Header("Hello World!") jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa' ghello = 'Gr\xfc\xdf Gott!' h.append(jhello, j) h.append(ghello, g) # BAW: This used to -- and maybe should -- fold the two iso-8859-1 # chunks into a single encoded word. However it doesn't violate the # standard to have them as two encoded chunks and maybe it's # reasonable <wink> for each .append() call to result in a separate # encoded word. eq(h.encode(), """\ Hello World! =?iso-2022-jp?b?GyRCJU8lbSE8JW8hPCVrJUkhKhsoQg==?= =?iso-8859-1?q?Gr=FC=DF?= =?iso-8859-1?q?_Gott!?=""") eq(decode_header(h.encode()), [('Hello World!', None), ('\x1b$B%O%m!<%o!<%k%I!*\x1b(B', 'iso-2022-jp'), ('Gr\xfc\xdf Gott!', 'iso-8859-1')]) long = 'test-ja \xa4\xd8\xc5\xea\xb9\xc6\xa4\xb5\xa4\xec\xa4\xbf\xa5\xe1\xa1\xbc\xa5\xeb\xa4\xcf\xbb\xca\xb2\xf1\xbc\xd4\xa4\xce\xbe\xb5\xc7\xa7\xa4\xf2\xc2\xd4\xa4\xc3\xa4\xc6\xa4\xa4\xa4\xde\xa4\xb9' h = Header(long, j, header_name="Subject") # test a very long header enc = h.encode() # TK: splitting point may differ by codec design and/or Header encoding eq(enc , """\ =?iso-2022-jp?b?dGVzdC1qYSAbJEIkWEVqOUYkNSRsJD8lYSE8JWskTztKGyhC?= =?iso-2022-jp?b?GyRCMnE8VCROPjVHJyRyQlQkQyRGJCQkXiQ5GyhC?=""") # TK: full decode comparison eq(h.__unicode__().encode('euc-jp'), long) def test_payload_encoding(self): jhello = '\xa5\xcf\xa5\xed\xa1\xbc\xa5\xef\xa1\xbc\xa5\xeb\xa5\xc9\xa1\xaa' jcode = 'euc-jp' msg = Message() msg.set_payload(jhello, jcode) ustr = unicode(msg.get_payload(), msg.get_content_charset()) self.assertEqual(jhello, ustr.encode(jcode)) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestEmailAsianCodecs)) return suite def test_main(): run_unittest(TestEmailAsianCodecs) if __name__ == '__main__': unittest.main(defaultTest='suite')
wreckJ/intellij-community
python/lib/Lib/email/test/test_email_codecs.py
Python
apache-2.0
2,849
/* * Copyright (c) 2015, Freescale Semiconductor, Inc. * Copyright 2016-2017 NXP * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * o Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * o 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. * * o Neither the name of the copyright holder 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. */ #include "fsl_flexbus.h" /******************************************************************************* * Prototypes ******************************************************************************/ /*! * @brief Gets the instance from the base address * * @param base FLEXBUS peripheral base address * * @return The FLEXBUS instance */ static uint32_t FLEXBUS_GetInstance(FB_Type *base); /******************************************************************************* * Variables ******************************************************************************/ /*! @brief Pointers to FLEXBUS bases for each instance. */ static FB_Type *const s_flexbusBases[] = FB_BASE_PTRS; #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) /*! @brief Pointers to FLEXBUS clocks for each instance. */ static const clock_ip_name_t s_flexbusClocks[] = FLEXBUS_CLOCKS; #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ /******************************************************************************* * Code ******************************************************************************/ static uint32_t FLEXBUS_GetInstance(FB_Type *base) { uint32_t instance; /* Find the instance index from base address mappings. */ for (instance = 0; instance < ARRAY_SIZE(s_flexbusBases); instance++) { if (s_flexbusBases[instance] == base) { break; } } assert(instance < ARRAY_SIZE(s_flexbusBases)); return instance; } void FLEXBUS_Init(FB_Type *base, const flexbus_config_t *config) { assert(config != NULL); assert(config->chip < FB_CSAR_COUNT); assert(config->waitStates <= 0x3FU); uint32_t chip = 0; uint32_t reg_value = 0; #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) /* Ungate clock for FLEXBUS */ CLOCK_EnableClock(s_flexbusClocks[FLEXBUS_GetInstance(base)]); #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ /* Reset all the register to default state */ for (chip = 0; chip < FB_CSAR_COUNT; chip++) { /* Reset CSMR register, all chips not valid (disabled) */ base->CS[chip].CSMR = 0x0000U; /* Set default base address */ base->CS[chip].CSAR &= (~FB_CSAR_BA_MASK); /* Reset FB_CSCRx register */ base->CS[chip].CSCR = 0x0000U; } /* Set FB_CSPMCR register */ /* FlexBus signal group 1 multiplex control */ reg_value |= kFLEXBUS_MultiplexGroup1_FB_ALE << FB_CSPMCR_GROUP1_SHIFT; /* FlexBus signal group 2 multiplex control */ reg_value |= kFLEXBUS_MultiplexGroup2_FB_CS4 << FB_CSPMCR_GROUP2_SHIFT; /* FlexBus signal group 3 multiplex control */ reg_value |= kFLEXBUS_MultiplexGroup3_FB_CS5 << FB_CSPMCR_GROUP3_SHIFT; /* FlexBus signal group 4 multiplex control */ reg_value |= kFLEXBUS_MultiplexGroup4_FB_TBST << FB_CSPMCR_GROUP4_SHIFT; /* FlexBus signal group 5 multiplex control */ reg_value |= kFLEXBUS_MultiplexGroup5_FB_TA << FB_CSPMCR_GROUP5_SHIFT; /* Write to CSPMCR register */ base->CSPMCR = reg_value; /* Update chip value */ chip = config->chip; /* Base address */ reg_value = config->chipBaseAddress; /* Write to CSAR register */ base->CS[chip].CSAR = reg_value; /* Chip-select validation */ reg_value = 0x1U << FB_CSMR_V_SHIFT; /* Write protect */ reg_value |= (uint32_t)(config->writeProtect) << FB_CSMR_WP_SHIFT; /* Base address mask */ reg_value |= config->chipBaseAddressMask << FB_CSMR_BAM_SHIFT; /* Write to CSMR register */ base->CS[chip].CSMR = reg_value; /* Burst write */ reg_value = (uint32_t)(config->burstWrite) << FB_CSCR_BSTW_SHIFT; /* Burst read */ reg_value |= (uint32_t)(config->burstRead) << FB_CSCR_BSTR_SHIFT; /* Byte-enable mode */ reg_value |= (uint32_t)(config->byteEnableMode) << FB_CSCR_BEM_SHIFT; /* Port size */ reg_value |= (uint32_t)config->portSize << FB_CSCR_PS_SHIFT; /* The internal transfer acknowledge for accesses */ reg_value |= (uint32_t)(config->autoAcknowledge) << FB_CSCR_AA_SHIFT; /* Byte-Lane shift */ reg_value |= (uint32_t)config->byteLaneShift << FB_CSCR_BLS_SHIFT; /* The number of wait states */ reg_value |= (uint32_t)config->waitStates << FB_CSCR_WS_SHIFT; /* Write address hold or deselect */ reg_value |= (uint32_t)config->writeAddressHold << FB_CSCR_WRAH_SHIFT; /* Read address hold or deselect */ reg_value |= (uint32_t)config->readAddressHold << FB_CSCR_RDAH_SHIFT; /* Address setup */ reg_value |= (uint32_t)config->addressSetup << FB_CSCR_ASET_SHIFT; /* Extended transfer start/extended address latch */ reg_value |= (uint32_t)(config->extendTransferAddress) << FB_CSCR_EXTS_SHIFT; /* Secondary wait state */ reg_value |= (uint32_t)(config->secondaryWaitStates) << FB_CSCR_SWSEN_SHIFT; /* Write to CSCR register */ base->CS[chip].CSCR = reg_value; /* FlexBus signal group 1 multiplex control */ reg_value = (uint32_t)config->group1MultiplexControl << FB_CSPMCR_GROUP1_SHIFT; /* FlexBus signal group 2 multiplex control */ reg_value |= (uint32_t)config->group2MultiplexControl << FB_CSPMCR_GROUP2_SHIFT; /* FlexBus signal group 3 multiplex control */ reg_value |= (uint32_t)config->group3MultiplexControl << FB_CSPMCR_GROUP3_SHIFT; /* FlexBus signal group 4 multiplex control */ reg_value |= (uint32_t)config->group4MultiplexControl << FB_CSPMCR_GROUP4_SHIFT; /* FlexBus signal group 5 multiplex control */ reg_value |= (uint32_t)config->group5MultiplexControl << FB_CSPMCR_GROUP5_SHIFT; /* Write to CSPMCR register */ base->CSPMCR = reg_value; } void FLEXBUS_Deinit(FB_Type *base) { #if !(defined(FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) && FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL) /* Gate clock for FLEXBUS */ CLOCK_DisableClock(s_flexbusClocks[FLEXBUS_GetInstance(base)]); #endif /* FSL_SDK_DISABLE_DRIVER_CLOCK_CONTROL */ } void FLEXBUS_GetDefaultConfig(flexbus_config_t *config) { config->chip = 0; /* Chip 0 FlexBus for validation */ config->writeProtect = 0; /* Write accesses are allowed */ config->burstWrite = 0; /* Burst-Write disable */ config->burstRead = 0; /* Burst-Read disable */ config->byteEnableMode = 0; /* Byte-Enable mode is asserted for data write only */ config->autoAcknowledge = true; /* Auto-Acknowledge enable */ config->extendTransferAddress = 0; /* Extend transfer start/extend address latch disable */ config->secondaryWaitStates = 0; /* Secondary wait state disable */ config->byteLaneShift = kFLEXBUS_NotShifted; /* Byte-Lane shift disable */ config->writeAddressHold = kFLEXBUS_Hold1Cycle; /* Write address hold 1 cycles */ config->readAddressHold = kFLEXBUS_Hold1Or0Cycles; /* Read address hold 0 cycles */ config->addressSetup = kFLEXBUS_FirstRisingEdge; /* Assert ~FB_CSn on the first rising clock edge after the address is asserted */ config->portSize = kFLEXBUS_1Byte; /* 1 byte port size of transfer */ config->group1MultiplexControl = kFLEXBUS_MultiplexGroup1_FB_ALE; /* FB_ALE */ config->group2MultiplexControl = kFLEXBUS_MultiplexGroup2_FB_CS4; /* FB_CS4 */ config->group3MultiplexControl = kFLEXBUS_MultiplexGroup3_FB_CS5; /* FB_CS5 */ config->group4MultiplexControl = kFLEXBUS_MultiplexGroup4_FB_TBST; /* FB_TBST */ config->group5MultiplexControl = kFLEXBUS_MultiplexGroup5_FB_TA; /* FB_TA */ }
weety/rt-thread
bsp/frdm-k64f/device/MK64F12/fsl_flexbus.c
C
apache-2.0
9,305
#!/usr/bin/env node const user = process.env.SAUCE_USER , key = process.env.SAUCE_KEY , path = require('path') , brtapsauce = require('brtapsauce') , testFile = path.join(__dirname, 'basic-test.js') , capabilities = [ { browserName: 'chrome' , platform: 'Windows XP', version: '' } , { browserName: 'firefox' , platform: 'Windows 8' , version: '' } , { browserName: 'firefox' , platform: 'Windows XP', version: '4' } , { browserName: 'internet explorer' , platform: 'Windows 8' , version: '10' } , { browserName: 'internet explorer' , platform: 'Windows 7' , version: '9' } , { browserName: 'internet explorer' , platform: 'Windows 7' , version: '8' } , { browserName: 'internet explorer' , platform: 'Windows XP', version: '7' } , { browserName: 'internet explorer' , platform: 'Windows XP', version: '6' } , { browserName: 'safari' , platform: 'Windows 7' , version: '5' } , { browserName: 'safari' , platform: 'OS X 10.8' , version: '6' } , { browserName: 'opera' , platform: 'Windows 7' , version: '' } , { browserName: 'opera' , platform: 'Windows 7' , version: '11' } , { browserName: 'ipad' , platform: 'OS X 10.8' , version: '6' } , { browserName: 'android' , platform: 'Linux' , version: '4.0', 'device-type': 'tablet' } ] if (!user) throw new Error('Must set a SAUCE_USER env var') if (!key) throw new Error('Must set a SAUCE_KEY env var') brtapsauce({ name : 'Traversty' , user : user , key : key , brsrc : testFile , capabilities : capabilities , options : { timeout: 60 * 6 } })
sakib3/IMDB
node_modules/protractor/node_modules/request/node_modules/bl/test/sauce.js
JavaScript
apache-2.0
1,829
// 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. /* cbtemulator launches the in-memory Cloud Bigtable server on the given address. */ package main import ( "flag" "fmt" "log" "cloud.google.com/go/bigtable/bttest" ) var ( host = flag.String("host", "localhost", "the address to bind to on the local machine") port = flag.Int("port", 9000, "the port number to bind to on the local machine") ) func main() { flag.Parse() srv, err := bttest.NewServer(fmt.Sprintf("%s:%d", *host, *port)) if err != nil { log.Fatalf("failed to start emulator: %v", err) } fmt.Printf("Cloud Bigtable emulator running on %s\n", srv.Addr) select {} }
radanalyticsio/oshinko-cli
vendor/github.com/openshift/origin/cmd/cluster-capacity/go/src/github.com/kubernetes-incubator/cluster-capacity/vendor/cloud.google.com/go/bigtable/cmd/emulator/cbtemulator.go
GO
apache-2.0
1,206
// Copyright 2011 The Closure Library 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. /** * @fileoverview Unit tests for the abstract cryptographic hash interface. * */ goog.provide('goog.crypt.hashTester'); goog.require('goog.array'); goog.require('goog.crypt'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.testing.PerformanceTable'); goog.require('goog.testing.PseudoRandom'); goog.require('goog.testing.asserts'); goog.setTestOnly('hashTester'); /** * Runs basic tests. * * @param {!goog.crypt.Hash} hash A hash instance. */ goog.crypt.hashTester.runBasicTests = function(hash) { // Compute first hash. hash.update([97, 158]); var golden1 = hash.digest(); // Compute second hash. hash.reset(); hash.update('aB'); var golden2 = hash.digest(); assertTrue('Two different inputs resulted in a hash collision', !!goog.testing.asserts.findDifferences(golden1, golden2)); // Empty hash. hash.reset(); var empty = hash.digest(); assertTrue('Empty hash collided with a non-trivial one', !!goog.testing.asserts.findDifferences(golden1, empty) && !!goog.testing.asserts.findDifferences(golden2, empty)); // Zero-length array update. hash.reset(); hash.update([]); assertArrayEquals('Updating with an empty array did not give an empty hash', empty, hash.digest()); // Zero-length string update. hash.reset(); hash.update(''); assertArrayEquals('Updating with an empty string did not give an empty hash', empty, hash.digest()); // Recompute the first hash. hash.reset(); hash.update([97, 158]); assertArrayEquals('The reset did not produce the initial state', golden1, hash.digest()); // Check for a trivial collision. hash.reset(); hash.update([158, 97]); assertTrue('Swapping bytes resulted in a hash collision', !!goog.testing.asserts.findDifferences(golden1, hash.digest())); // Compare array and string input. hash.reset(); hash.update([97, 66]); assertArrayEquals('String and array inputs should give the same result', golden2, hash.digest()); // Compute in parts. hash.reset(); hash.update('a'); hash.update([158]); assertArrayEquals('Partial updates resulted in a different hash', golden1, hash.digest()); // Test update with specified length. hash.reset(); hash.update('aB', 0); hash.update([97, 158, 32], 2); assertArrayEquals('Updating with an explicit buffer length did not work', golden1, hash.digest()); }; /** * Runs block tests. * * @param {!goog.crypt.Hash} hash A hash instance. * @param {number} blockBytes Size of the hash block. */ goog.crypt.hashTester.runBlockTests = function(hash, blockBytes) { // Compute a message which is 1 byte shorter than hash block size. var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; var message = ''; for (var i = 0; i < blockBytes - 1; i++) { message += chars.charAt(i % chars.length); } // Compute golden hash for 1 block + 2 bytes. hash.update(message + '123'); var golden1 = hash.digest(); // Compute golden hash for 2 blocks + 1 byte. hash.reset(); hash.update(message + message + '123'); var golden2 = hash.digest(); // Almost fill a block, then overflow. hash.reset(); hash.update(message); hash.update('123'); assertArrayEquals(golden1, hash.digest()); // Fill a block. hash.reset(); hash.update(message + '1'); hash.update('23'); assertArrayEquals(golden1, hash.digest()); // Overflow a block. hash.reset(); hash.update(message + '12'); hash.update('3'); assertArrayEquals(golden1, hash.digest()); // Test single overflow with an array. hash.reset(); hash.update(goog.crypt.stringToByteArray(message + '123')); assertArrayEquals(golden1, hash.digest()); // Almost fill a block, then overflow this and the next block. hash.reset(); hash.update(message); hash.update(message + '123'); assertArrayEquals(golden2, hash.digest()); // Fill two blocks. hash.reset(); hash.update(message + message + '12'); hash.update('3'); assertArrayEquals(golden2, hash.digest()); // Test double overflow with an array. hash.reset(); hash.update(goog.crypt.stringToByteArray(message)); hash.update(goog.crypt.stringToByteArray(message + '123')); assertArrayEquals(golden2, hash.digest()); }; /** * Runs performance tests. * * @param {function():!goog.crypt.Hash} hashFactory A hash factory. * @param {string} hashName Name of the hashing function. */ goog.crypt.hashTester.runPerfTests = function(hashFactory, hashName) { var body = goog.dom.getDocument().body; var perfTable = goog.dom.createElement(goog.dom.TagName.DIV); goog.dom.appendChild(body, perfTable); var table = new goog.testing.PerformanceTable(perfTable); function runPerfTest(byteLength, updateCount) { var label = (hashName + ': ' + updateCount + ' update(s) of ' + byteLength + ' bytes'); function run(data, dataType) { table.run(function() { var hash = hashFactory(); for (var i = 0; i < updateCount; i++) { hash.update(data, byteLength); } var digest = hash.digest(); }, label + ' (' + dataType + ')'); } var byteArray = goog.crypt.hashTester.createRandomByteArray_(byteLength); var byteString = goog.crypt.hashTester.createByteString_(byteArray); run(byteArray, 'byte array'); run(byteString, 'byte string'); } var MESSAGE_LENGTH_LONG = 10000000; // 10 Mbytes var MESSAGE_LENGTH_SHORT = 10; // 10 bytes var MESSAGE_COUNT_SHORT = MESSAGE_LENGTH_LONG / MESSAGE_LENGTH_SHORT; runPerfTest(MESSAGE_LENGTH_LONG, 1); runPerfTest(MESSAGE_LENGTH_SHORT, MESSAGE_COUNT_SHORT); }; /** * Creates and returns a random byte array. * * @param {number} length Length of the byte array. * @return {!Array<number>} An array of bytes. * @private */ goog.crypt.hashTester.createRandomByteArray_ = function(length) { var random = new goog.testing.PseudoRandom(0); var bytes = []; for (var i = 0; i < length; ++i) { // Generates an integer from 0 to 255. var b = Math.floor(random.random() * 0x100); bytes.push(b); } return bytes; }; /** * Creates a string from an array of bytes. * * @param {!Array<number>} bytes An array of bytes. * @return {string} The string encoded by the bytes. * @private */ goog.crypt.hashTester.createByteString_ = function(bytes) { var str = ''; goog.array.forEach(bytes, function(b) { str += String.fromCharCode(b); }); return str; };
quoideneuf/selenium
third_party/closure/goog/crypt/hashtester.js
JavaScript
apache-2.0
7,110
/* * Copyright (C) 2009 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.testing; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.Map.Entry; import java.util.SortedMap; /** * Tests representing the contract of {@link SortedMap}. Concrete subclasses of * this base class test conformance of concrete {@link SortedMap} subclasses to * that contract. * * @author Jared Levy */ // TODO: Use this class to test classes besides ImmutableSortedMap. @GwtCompatible public abstract class SortedMapInterfaceTest<K, V> extends MapInterfaceTest<K, V> { protected SortedMapInterfaceTest(boolean allowsNullKeys, boolean allowsNullValues, boolean supportsPut, boolean supportsRemove, boolean supportsClear) { super(allowsNullKeys, allowsNullValues, supportsPut, supportsRemove, supportsClear); } @Override protected abstract SortedMap<K, V> makeEmptyMap() throws UnsupportedOperationException; @Override protected abstract SortedMap<K, V> makePopulatedMap() throws UnsupportedOperationException; @Override protected SortedMap<K, V> makeEitherMap() { try { return makePopulatedMap(); } catch (UnsupportedOperationException e) { return makeEmptyMap(); } } public void testTailMapWriteThrough() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } if (map.size() < 2 || !supportsPut) { return; } Iterator<Entry<K, V>> iterator = map.entrySet().iterator(); Entry<K, V> firstEntry = iterator.next(); Entry<K, V> secondEntry = iterator.next(); K key = secondEntry.getKey(); SortedMap<K, V> subMap = map.tailMap(key); V value = getValueNotInPopulatedMap(); subMap.put(key, value); assertEquals(secondEntry.getValue(), value); assertEquals(map.get(key), value); try { subMap.put(firstEntry.getKey(), value); fail("Expected IllegalArgumentException"); } catch (IllegalArgumentException expected) { } } public void testTailMapRemoveThrough() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } int oldSize = map.size(); if (map.size() < 2 || !supportsRemove) { return; } Iterator<Entry<K, V>> iterator = map.entrySet().iterator(); Entry<K, V> firstEntry = iterator.next(); Entry<K, V> secondEntry = iterator.next(); K key = secondEntry.getKey(); SortedMap<K, V> subMap = map.tailMap(key); subMap.remove(key); assertNull(subMap.remove(firstEntry.getKey())); assertEquals(map.size(), oldSize - 1); assertFalse(map.containsKey(key)); assertEquals(subMap.size(), oldSize - 2); } public void testTailMapClearThrough() { final SortedMap<K, V> map; try { map = makePopulatedMap(); } catch (UnsupportedOperationException e) { return; } int oldSize = map.size(); if (map.size() < 2 || !supportsClear) { return; } Iterator<Entry<K, V>> iterator = map.entrySet().iterator(); iterator.next(); // advance Entry<K, V> secondEntry = iterator.next(); K key = secondEntry.getKey(); SortedMap<K, V> subMap = map.tailMap(key); int subMapSize = subMap.size(); subMap.clear(); assertEquals(map.size(), oldSize - subMapSize); assertTrue(subMap.isEmpty()); } }
dongxingong/Guava
guava-testlib/src/com/google/common/collect/testing/SortedMapInterfaceTest.java
Java
apache-2.0
4,023
/* * Copyright (C) 2010 ZXing 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. */ /* * These authors would like to acknowledge the Spanish Ministry of Industry, * Tourism and Trade, for the support in the project TSI020301-2008-2 * "PIRAmIDE: Personalizable Interactions with Resources on AmI-enabled * Mobile Dynamic Environments", led by Treelogic * ( http://www.treelogic.com/ ): * * http://www.piramidepse.com/ */ package com.google.zxing.oned.rss.expanded.decoders; import com.google.zxing.NotFoundException; import com.google.zxing.common.BitArray; /** * @author Pablo Orduña, University of Deusto (pablo.orduna@deusto.es) * @author Eduardo Castillejo, University of Deusto (eduardo.castillejo@deusto.es) */ final class AI01AndOtherAIs extends AI01decoder { private static final int HEADER_SIZE = 1 + 1 + 2; //first bit encodes the linkage flag, //the second one is the encodation method, and the other two are for the variable length AI01AndOtherAIs(BitArray information) { super(information); } @Override public String parseInformation() throws NotFoundException { StringBuilder buff = new StringBuilder(); buff.append("(01)"); int initialGtinPosition = buff.length(); int firstGtinDigit = this.getGeneralDecoder().extractNumericValueFromBitArray(HEADER_SIZE, 4); buff.append(firstGtinDigit); this.encodeCompressedGtinWithoutAI(buff, HEADER_SIZE + 4, initialGtinPosition); return this.getGeneralDecoder().decodeAllCodes(buff, HEADER_SIZE + 44); } }
TonnyXu/Zxing
core/src/com/google/zxing/oned/rss/expanded/decoders/AI01AndOtherAIs.java
Java
apache-2.0
2,070
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <!-- Copyright 2011 Software Freedom Conservancy 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. --> <html> <head> <meta content="text/html; charset=ISO-8859-1" http-equiv="content-type"> <title>Test Run Failed Tests</title> </head> <body> <table cellpadding="1" cellspacing="1" border="1"> <tbody> <tr> <td rowspan="1" colspan="3">Test Run Failed Tests<br> </td> </tr> <tr> <td>setTimeout</td> <td>120000</td> <td>&nbsp;</td> </tr> <tr> <td>storeEval</td> <td>selenium.browserbot.baseUrl</td> <td>myBaseUrl</td> </tr> <tr> <td>echo</td> <td>${myBaseUrl}</td> <td>&nbsp;</td> </tr> <tr> <td>open</td> <td>../core/TestRunner.html?test=../tests/dogfood/aut/BaseUrl1TestSuite.html&baseUrl=${myBaseUrl}</td> <td>&nbsp;</td> </tr> <tr> <td>waitForEval</td> <td>window.htmlTestRunner.testCaseLoaded</td> <td>true</td> </tr> <tr> <td>click</td> <td>runSuite</td> <td>&nbsp;</td> </tr> <tr> <td>waitForText</td> <td>testRuns</td> <td>1</td> </tr> <tr> <td>verifyText</td> <td>commandPasses</td> <td>1</td> </tr> <tr> <td>open</td> <td>../core/TestRunner.html?test=../tests/dogfood/aut/BaseUrl2TestSuite.html&baseUrl=${myBaseUrl}/../html/</td> <td>&nbsp;</td> </tr> <tr> <td>waitForEval</td> <td>window.htmlTestRunner.testCaseLoaded</td> <td>true</td> </tr> <tr> <td>click</td> <td>runSuite</td> <td>&nbsp;</td> </tr> <tr> <td>waitForText</td> <td>testRuns</td> <td>1</td> </tr> <tr> <td>verifyText</td> <td>commandPasses</td> <td>1</td> </tr> </tbody> </table> </body> </html>
compstak/selenium
java/server/test/org/openqa/selenium/tests/dogfood/TestBaseUrl.html
HTML
apache-2.0
2,424
/* Copyright 2015 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 v1alpha1 import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" ) // GroupName is the group name use in this package const GroupName = "componentconfig" // SchemeGroupVersion is group version used to register these objects var SchemeGroupVersion = schema.GroupVersion{Group: GroupName, Version: "v1alpha1"} var ( SchemeBuilder = runtime.NewSchemeBuilder(addKnownTypes, addDefaultingFuncs) AddToScheme = SchemeBuilder.AddToScheme ) func addKnownTypes(scheme *runtime.Scheme) error { scheme.AddKnownTypes(SchemeGroupVersion, &KubeProxyConfiguration{}, &KubeSchedulerConfiguration{}, &KubeletConfiguration{}, ) return nil } func (obj *KubeProxyConfiguration) GetObjectKind() schema.ObjectKind { return &obj.TypeMeta } func (obj *KubeSchedulerConfiguration) GetObjectKind() schema.ObjectKind { return &obj.TypeMeta } func (obj *KubeletConfiguration) GetObjectKind() schema.ObjectKind { return &obj.TypeMeta }
eparis/origin
vendor/k8s.io/kubernetes/pkg/apis/componentconfig/v1alpha1/register.go
GO
apache-2.0
1,544
# line 1 "rake-tasks/crazy_fun/build_grammar.rl" class BuildFile # line 73 "rake-tasks/crazy_fun/build_grammar.rl" def parse(data) # line 12 "rake-tasks/crazy_fun/build_grammar.rb" class << self attr_accessor :_build_grammar_trans_keys private :_build_grammar_trans_keys, :_build_grammar_trans_keys= end self._build_grammar_trans_keys = [ 0, 0, 9, 122, 10, 13, 40, 122, 9, 122, 9, 122, 9, 122, 9, 61, 9, 91, 34, 34, 9, 44, 10, 13, 9, 123, 34, 34, 9, 93, 9, 123, 9, 44, 9, 34, 34, 34, 9, 58, 9, 34, 34, 34, 9, 125, 9, 125, 9, 93, 9, 122, 9, 122, 0 ] class << self attr_accessor :_build_grammar_key_spans private :_build_grammar_key_spans, :_build_grammar_key_spans= end self._build_grammar_key_spans = [ 0, 114, 4, 83, 114, 114, 114, 53, 83, 1, 36, 4, 115, 1, 85, 115, 36, 26, 1, 50, 26, 1, 117, 117, 85, 114, 114 ] class << self attr_accessor :_build_grammar_index_offsets private :_build_grammar_index_offsets, :_build_grammar_index_offsets= end self._build_grammar_index_offsets = [ 0, 0, 115, 120, 204, 319, 434, 549, 603, 687, 689, 726, 731, 847, 849, 935, 1051, 1088, 1115, 1117, 1168, 1195, 1197, 1315, 1433, 1519, 1634 ] class << self attr_accessor :_build_grammar_indicies private :_build_grammar_indicies, :_build_grammar_indicies= end self._build_grammar_indicies = [ 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0, 2, 2, 0, 2, 4, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 5, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 1, 6, 6, 6, 6, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 1, 8, 8, 8, 8, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 10, 10, 10, 10, 10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 10, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 1, 1, 1, 12, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 11, 1, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 1, 13, 13, 13, 13, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 13, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 14, 1, 14, 14, 14, 14, 14, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 14, 1, 15, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 16, 1, 18, 17, 19, 19, 19, 19, 19, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 19, 1, 1, 1, 1, 1, 1, 1, 1, 20, 1, 1, 4, 1, 22, 21, 21, 22, 21, 23, 23, 23, 23, 23, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 1, 24, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 25, 1, 27, 26, 28, 28, 28, 28, 28, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 28, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 29, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 30, 1, 29, 29, 29, 29, 29, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 29, 1, 24, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 30, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 25, 1, 18, 18, 18, 18, 18, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 18, 1, 1, 1, 1, 1, 1, 1, 1, 20, 1, 1, 4, 1, 31, 31, 31, 31, 31, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 31, 1, 32, 1, 34, 33, 35, 35, 35, 35, 35, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 35, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 36, 1, 36, 36, 36, 36, 36, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 36, 1, 37, 1, 39, 38, 40, 40, 40, 40, 40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 40, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 41, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 42, 1, 43, 43, 43, 43, 43, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 43, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 31, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 44, 1, 27, 27, 27, 27, 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 27, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 45, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 46, 1, 47, 47, 47, 47, 47, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 47, 1, 1, 48, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 49, 1, 22, 22, 22, 22, 22, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 22, 1, 1, 21, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 1, 0 ] class << self attr_accessor :_build_grammar_trans_targs private :_build_grammar_trans_targs, :_build_grammar_trans_targs= end self._build_grammar_trans_targs = [ 1, 0, 2, 3, 4, 3, 5, 6, 5, 6, 7, 6, 8, 7, 8, 9, 12, 9, 10, 10, 25, 11, 26, 12, 13, 17, 13, 14, 14, 15, 16, 17, 18, 18, 19, 19, 20, 21, 21, 22, 23, 17, 24, 23, 24, 15, 16, 26, 11, 3 ] class << self attr_accessor :_build_grammar_trans_actions private :_build_grammar_trans_actions, :_build_grammar_trans_actions= end self._build_grammar_trans_actions = [ 0, 0, 0, 1, 2, 3, 4, 5, 0, 6, 2, 3, 2, 0, 0, 7, 8, 3, 2, 0, 9, 0, 10, 0, 7, 11, 3, 2, 0, 0, 0, 0, 12, 3, 2, 0, 0, 7, 3, 2, 2, 2, 2, 0, 0, 2, 2, 9, 2, 13 ] class << self attr_accessor :_build_grammar_eof_actions private :_build_grammar_eof_actions, :_build_grammar_eof_actions= end self._build_grammar_eof_actions = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0 ] class << self attr_accessor :build_grammar_start end self.build_grammar_start = 1; class << self attr_accessor :build_grammar_first_final end self.build_grammar_first_final = 25; class << self attr_accessor :build_grammar_error end self.build_grammar_error = 0; class << self attr_accessor :build_grammar_en_main end self.build_grammar_en_main = 1; # line 77 "rake-tasks/crazy_fun/build_grammar.rl" @data = data @data = @data.unpack("c*") if @data.is_a?(String) # line 343 "rake-tasks/crazy_fun/build_grammar.rb" begin @p ||= 0 pe ||= @data.length cs = build_grammar_start end # line 82 "rake-tasks/crazy_fun/build_grammar.rl" begin # line 354 "rake-tasks/crazy_fun/build_grammar.rb" begin testEof = false _slen, _trans, _keys, _inds, _acts, _nacts = nil _goto_level = 0 _resume = 10 _eof_trans = 15 _again = 20 _test_eof = 30 _out = 40 while true if _goto_level <= 0 if @p == pe _goto_level = _test_eof next end if cs == 0 _goto_level = _out next end end if _goto_level <= _resume _keys = cs << 1 _inds = _build_grammar_index_offsets[cs] _slen = _build_grammar_key_spans[cs] _trans = if ( _slen > 0 && _build_grammar_trans_keys[_keys] <= @data[ @p] && @data[ @p] <= _build_grammar_trans_keys[_keys + 1] ) then _build_grammar_indicies[ _inds + @data[ @p] - _build_grammar_trans_keys[_keys] ] else _build_grammar_indicies[ _inds + _slen ] end cs = _build_grammar_trans_targs[_trans] if _build_grammar_trans_actions[_trans] != 0 case _build_grammar_trans_actions[_trans] when 4 then # line 10 "rake-tasks/crazy_fun/build_grammar.rl" begin # clear the stack while !@lhs[-1].is_a? OutputType leave end puts "Starting arg" if @debug @lhs.push ArgType.new end # line 10 "rake-tasks/crazy_fun/build_grammar.rl" when 8 then # line 23 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting array" if @debug @lhs.push ArrayType.new end # line 23 "rake-tasks/crazy_fun/build_grammar.rl" when 11 then # line 27 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting map" if @debug @lhs.push MapType.new end # line 27 "rake-tasks/crazy_fun/build_grammar.rl" when 7 then # line 35 "rake-tasks/crazy_fun/build_grammar.rl" begin if @data[@p + 1].chr == ':' puts "Starting symbol" if @debug @lhs.push SymbolType.new @p = @p + 1 else puts "Starting string" if @debug @lhs.push StringType.new end end # line 35 "rake-tasks/crazy_fun/build_grammar.rl" when 10 then # line 56 "rake-tasks/crazy_fun/build_grammar.rl" begin while (!@lhs.empty?) leave end end # line 56 "rake-tasks/crazy_fun/build_grammar.rl" when 3 then # line 67 "rake-tasks/crazy_fun/build_grammar.rl" begin @lhs[-1] << @data[@p].chr end # line 67 "rake-tasks/crazy_fun/build_grammar.rl" when 2 then # line 68 "rake-tasks/crazy_fun/build_grammar.rl" begin leave end # line 68 "rake-tasks/crazy_fun/build_grammar.rl" when 6 then # line 19 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting arg name" if @debug @lhs.push SymbolType.new end # line 19 "rake-tasks/crazy_fun/build_grammar.rl" # line 67 "rake-tasks/crazy_fun/build_grammar.rl" begin @lhs[-1] << @data[@p].chr end # line 67 "rake-tasks/crazy_fun/build_grammar.rl" when 12 then # line 31 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting map entry" if @debug @lhs.push MapEntry.new end # line 31 "rake-tasks/crazy_fun/build_grammar.rl" # line 35 "rake-tasks/crazy_fun/build_grammar.rl" begin if @data[@p + 1].chr == ':' puts "Starting symbol" if @debug @lhs.push SymbolType.new @p = @p + 1 else puts "Starting string" if @debug @lhs.push StringType.new end end # line 35 "rake-tasks/crazy_fun/build_grammar.rl" when 9 then # line 68 "rake-tasks/crazy_fun/build_grammar.rl" begin leave end # line 68 "rake-tasks/crazy_fun/build_grammar.rl" # line 56 "rake-tasks/crazy_fun/build_grammar.rl" begin while (!@lhs.empty?) leave end end # line 56 "rake-tasks/crazy_fun/build_grammar.rl" when 5 then # line 10 "rake-tasks/crazy_fun/build_grammar.rl" begin # clear the stack while !@lhs[-1].is_a? OutputType leave end puts "Starting arg" if @debug @lhs.push ArgType.new end # line 10 "rake-tasks/crazy_fun/build_grammar.rl" # line 19 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting arg name" if @debug @lhs.push SymbolType.new end # line 19 "rake-tasks/crazy_fun/build_grammar.rl" # line 67 "rake-tasks/crazy_fun/build_grammar.rl" begin @lhs[-1] << @data[@p].chr end # line 67 "rake-tasks/crazy_fun/build_grammar.rl" when 1 then # line 45 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting type" if @debug # Unwind the stack until the top is another OutputType (or it's empty) while (!@lhs.empty?) puts "Unwinding [#{@lhs}]" + @lhs.length.to_s leave end @lhs.push OutputType.new end # line 45 "rake-tasks/crazy_fun/build_grammar.rl" # line 62 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting type name" if @debug @lhs.push NameType.new end # line 62 "rake-tasks/crazy_fun/build_grammar.rl" # line 67 "rake-tasks/crazy_fun/build_grammar.rl" begin @lhs[-1] << @data[@p].chr end # line 67 "rake-tasks/crazy_fun/build_grammar.rl" when 13 then # line 68 "rake-tasks/crazy_fun/build_grammar.rl" begin leave end # line 68 "rake-tasks/crazy_fun/build_grammar.rl" # line 45 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting type" if @debug # Unwind the stack until the top is another OutputType (or it's empty) while (!@lhs.empty?) puts "Unwinding [#{@lhs}]" + @lhs.length.to_s leave end @lhs.push OutputType.new end # line 45 "rake-tasks/crazy_fun/build_grammar.rl" # line 62 "rake-tasks/crazy_fun/build_grammar.rl" begin puts "Starting type name" if @debug @lhs.push NameType.new end # line 62 "rake-tasks/crazy_fun/build_grammar.rl" # line 67 "rake-tasks/crazy_fun/build_grammar.rl" begin @lhs[-1] << @data[@p].chr end # line 67 "rake-tasks/crazy_fun/build_grammar.rl" # line 582 "rake-tasks/crazy_fun/build_grammar.rb" end end end if _goto_level <= _again if cs == 0 _goto_level = _out next end @p += 1 if @p != pe _goto_level = _resume next end end if _goto_level <= _test_eof if @p == @eof case _build_grammar_eof_actions[cs] when 2 then # line 68 "rake-tasks/crazy_fun/build_grammar.rl" begin leave end # line 68 "rake-tasks/crazy_fun/build_grammar.rl" # line 607 "rake-tasks/crazy_fun/build_grammar.rb" end end end if _goto_level <= _out break end end end # line 85 "rake-tasks/crazy_fun/build_grammar.rl" rescue puts show_bad_line throw $! end if cs == build_grammar_error throw show_bad_line end @types end end
SevInf/IEDriver
rake-tasks/crazy_fun/build_grammar.rb
Ruby
apache-2.0
15,555
/** * 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.mapred.join; import java.io.DataInput; import java.io.DataOutput; import java.io.IOException; import java.util.Iterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.extensions.TestSetup; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.MiniDFSCluster; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.SequenceFile; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.Writable; import org.apache.hadoop.io.WritableComparable; import org.apache.hadoop.mapred.FileOutputFormat; import org.apache.hadoop.mapred.InputFormat; import org.apache.hadoop.mapred.InputSplit; import org.apache.hadoop.mapred.JobClient; import org.apache.hadoop.mapred.JobConf; import org.apache.hadoop.mapred.JobConfigurable; import org.apache.hadoop.mapred.Mapper; import org.apache.hadoop.mapred.OutputCollector; import org.apache.hadoop.mapred.RecordReader; import org.apache.hadoop.mapred.Reducer; import org.apache.hadoop.mapred.Reporter; import org.apache.hadoop.mapred.SequenceFileInputFormat; import org.apache.hadoop.mapred.SequenceFileOutputFormat; import org.apache.hadoop.mapred.Utils; import org.apache.hadoop.mapred.lib.IdentityMapper; import org.apache.hadoop.mapred.lib.IdentityReducer; import org.apache.hadoop.util.ReflectionUtils; public class TestDatamerge extends TestCase { private static MiniDFSCluster cluster = null; public static Test suite() { TestSetup setup = new TestSetup(new TestSuite(TestDatamerge.class)) { protected void setUp() throws Exception { Configuration conf = new Configuration(); cluster = new MiniDFSCluster.Builder(conf).numDataNodes(2).build(); } protected void tearDown() throws Exception { if (cluster != null) { cluster.shutdown(); } } }; return setup; } private static SequenceFile.Writer[] createWriters(Path testdir, Configuration conf, int srcs, Path[] src) throws IOException { for (int i = 0; i < srcs; ++i) { src[i] = new Path(testdir, Integer.toString(i + 10, 36)); } SequenceFile.Writer out[] = new SequenceFile.Writer[srcs]; for (int i = 0; i < srcs; ++i) { out[i] = new SequenceFile.Writer(testdir.getFileSystem(conf), conf, src[i], IntWritable.class, IntWritable.class); } return out; } private static Path[] writeSimpleSrc(Path testdir, Configuration conf, int srcs) throws IOException { SequenceFile.Writer out[] = null; Path[] src = new Path[srcs]; try { out = createWriters(testdir, conf, srcs, src); final int capacity = srcs * 2 + 1; IntWritable key = new IntWritable(); IntWritable val = new IntWritable(); for (int k = 0; k < capacity; ++k) { for (int i = 0; i < srcs; ++i) { key.set(k % srcs == 0 ? k * srcs : k * srcs + i); val.set(10 * k + i); out[i].append(key, val); if (i == k) { // add duplicate key out[i].append(key, val); } } } } finally { if (out != null) { for (int i = 0; i < srcs; ++i) { if (out[i] != null) out[i].close(); } } } return src; } private static String stringify(IntWritable key, Writable val) { StringBuilder sb = new StringBuilder(); sb.append("(" + key); sb.append("," + val + ")"); return sb.toString(); } private static abstract class SimpleCheckerBase<V extends Writable> implements Mapper<IntWritable, V, IntWritable, IntWritable>, Reducer<IntWritable, IntWritable, Text, Text> { protected final static IntWritable one = new IntWritable(1); int srcs; public void close() { } public void configure(JobConf job) { srcs = job.getInt("testdatamerge.sources", 0); assertTrue("Invalid src count: " + srcs, srcs > 0); } public abstract void map(IntWritable key, V val, OutputCollector<IntWritable, IntWritable> out, Reporter reporter) throws IOException; public void reduce(IntWritable key, Iterator<IntWritable> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException { int seen = 0; while (values.hasNext()) { seen += values.next().get(); } assertTrue("Bad count for " + key.get(), verify(key.get(), seen)); } public abstract boolean verify(int key, int occ); } private static class InnerJoinChecker extends SimpleCheckerBase<TupleWritable> { public void map(IntWritable key, TupleWritable val, OutputCollector<IntWritable, IntWritable> out, Reporter reporter) throws IOException { int k = key.get(); final String kvstr = "Unexpected tuple: " + stringify(key, val); assertTrue(kvstr, 0 == k % (srcs * srcs)); for (int i = 0; i < val.size(); ++i) { final int vali = ((IntWritable)val.get(i)).get(); assertTrue(kvstr, (vali - i) * srcs == 10 * k); } out.collect(key, one); } public boolean verify(int key, int occ) { return (key == 0 && occ == 2) || (key != 0 && (key % (srcs * srcs) == 0) && occ == 1); } } private static class OuterJoinChecker extends SimpleCheckerBase<TupleWritable> { public void map(IntWritable key, TupleWritable val, OutputCollector<IntWritable, IntWritable> out, Reporter reporter) throws IOException { int k = key.get(); final String kvstr = "Unexpected tuple: " + stringify(key, val); if (0 == k % (srcs * srcs)) { for (int i = 0; i < val.size(); ++i) { assertTrue(kvstr, val.get(i) instanceof IntWritable); final int vali = ((IntWritable)val.get(i)).get(); assertTrue(kvstr, (vali - i) * srcs == 10 * k); } } else { for (int i = 0; i < val.size(); ++i) { if (i == k % srcs) { assertTrue(kvstr, val.get(i) instanceof IntWritable); final int vali = ((IntWritable)val.get(i)).get(); assertTrue(kvstr, srcs * (vali - i) == 10 * (k - i)); } else { assertTrue(kvstr, !val.has(i)); } } } out.collect(key, one); } public boolean verify(int key, int occ) { if (key < srcs * srcs && (key % (srcs + 1)) == 0) return 2 == occ; return 1 == occ; } } private static class OverrideChecker extends SimpleCheckerBase<IntWritable> { public void map(IntWritable key, IntWritable val, OutputCollector<IntWritable, IntWritable> out, Reporter reporter) throws IOException { int k = key.get(); final int vali = val.get(); final String kvstr = "Unexpected tuple: " + stringify(key, val); if (0 == k % (srcs * srcs)) { assertTrue(kvstr, vali == k * 10 / srcs + srcs - 1); } else { final int i = k % srcs; assertTrue(kvstr, srcs * (vali - i) == 10 * (k - i)); } out.collect(key, one); } public boolean verify(int key, int occ) { if (key < srcs * srcs && (key % (srcs + 1)) == 0 && key != 0) return 2 == occ; return 1 == occ; } } private static void joinAs(String jointype, Class<? extends SimpleCheckerBase> c) throws Exception { final int srcs = 4; Configuration conf = new Configuration(); JobConf job = new JobConf(conf, c); Path base = cluster.getFileSystem().makeQualified(new Path("/"+jointype)); Path[] src = writeSimpleSrc(base, conf, srcs); job.set("mapreduce.join.expr", CompositeInputFormat.compose(jointype, SequenceFileInputFormat.class, src)); job.setInt("testdatamerge.sources", srcs); job.setInputFormat(CompositeInputFormat.class); FileOutputFormat.setOutputPath(job, new Path(base, "out")); job.setMapperClass(c); job.setReducerClass(c); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(IntWritable.class); JobClient.runJob(job); base.getFileSystem(job).delete(base, true); } public void testSimpleInnerJoin() throws Exception { joinAs("inner", InnerJoinChecker.class); } public void testSimpleOuterJoin() throws Exception { joinAs("outer", OuterJoinChecker.class); } public void testSimpleOverride() throws Exception { joinAs("override", OverrideChecker.class); } public void testNestedJoin() throws Exception { // outer(inner(S1,...,Sn),outer(S1,...Sn)) final int SOURCES = 3; final int ITEMS = (SOURCES + 1) * (SOURCES + 1); JobConf job = new JobConf(); Path base = cluster.getFileSystem().makeQualified(new Path("/nested")); int[][] source = new int[SOURCES][]; for (int i = 0; i < SOURCES; ++i) { source[i] = new int[ITEMS]; for (int j = 0; j < ITEMS; ++j) { source[i][j] = (i + 2) * (j + 1); } } Path[] src = new Path[SOURCES]; SequenceFile.Writer out[] = createWriters(base, job, SOURCES, src); IntWritable k = new IntWritable(); for (int i = 0; i < SOURCES; ++i) { IntWritable v = new IntWritable(); v.set(i); for (int j = 0; j < ITEMS; ++j) { k.set(source[i][j]); out[i].append(k, v); } out[i].close(); } out = null; StringBuilder sb = new StringBuilder(); sb.append("outer(inner("); for (int i = 0; i < SOURCES; ++i) { sb.append( CompositeInputFormat.compose(SequenceFileInputFormat.class, src[i].toString())); if (i + 1 != SOURCES) sb.append(","); } sb.append("),outer("); sb.append(CompositeInputFormat.compose(Fake_IF.class,"foobar")); sb.append(","); for (int i = 0; i < SOURCES; ++i) { sb.append( CompositeInputFormat.compose(SequenceFileInputFormat.class, src[i].toString())); sb.append(","); } sb.append(CompositeInputFormat.compose(Fake_IF.class,"raboof") + "))"); job.set("mapreduce.join.expr", sb.toString()); job.setInputFormat(CompositeInputFormat.class); Path outf = new Path(base, "out"); FileOutputFormat.setOutputPath(job, outf); Fake_IF.setKeyClass(job, IntWritable.class); Fake_IF.setValClass(job, IntWritable.class); job.setMapperClass(IdentityMapper.class); job.setReducerClass(IdentityReducer.class); job.setNumReduceTasks(0); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(TupleWritable.class); job.setOutputFormat(SequenceFileOutputFormat.class); JobClient.runJob(job); FileStatus[] outlist = cluster.getFileSystem().listStatus(outf, new Utils.OutputFileUtils.OutputFilesFilter()); assertEquals(1, outlist.length); assertTrue(0 < outlist[0].getLen()); SequenceFile.Reader r = new SequenceFile.Reader(cluster.getFileSystem(), outlist[0].getPath(), job); TupleWritable v = new TupleWritable(); while (r.next(k, v)) { assertFalse(((TupleWritable)v.get(1)).has(0)); assertFalse(((TupleWritable)v.get(1)).has(SOURCES + 1)); boolean chk = true; int ki = k.get(); for (int i = 2; i < SOURCES + 2; ++i) { if ((ki % i) == 0 && ki <= i * ITEMS) { assertEquals(i - 2, ((IntWritable) ((TupleWritable)v.get(1)).get((i - 1))).get()); } else chk = false; } if (chk) { // present in all sources; chk inner assertTrue(v.has(0)); for (int i = 0; i < SOURCES; ++i) assertTrue(((TupleWritable)v.get(0)).has(i)); } else { // should not be present in inner join assertFalse(v.has(0)); } } r.close(); base.getFileSystem(job).delete(base, true); } public void testEmptyJoin() throws Exception { JobConf job = new JobConf(); Path base = cluster.getFileSystem().makeQualified(new Path("/empty")); Path[] src = { new Path(base,"i0"), new Path("i1"), new Path("i2") }; job.set("mapreduce.join.expr", CompositeInputFormat.compose("outer", Fake_IF.class, src)); job.setInputFormat(CompositeInputFormat.class); FileOutputFormat.setOutputPath(job, new Path(base, "out")); job.setMapperClass(IdentityMapper.class); job.setReducerClass(IdentityReducer.class); job.setOutputKeyClass(IncomparableKey.class); job.setOutputValueClass(NullWritable.class); JobClient.runJob(job); base.getFileSystem(job).delete(base, true); } public static class Fake_IF<K,V> implements InputFormat<K,V>, JobConfigurable { public static class FakeSplit implements InputSplit { public void write(DataOutput out) throws IOException { } public void readFields(DataInput in) throws IOException { } public long getLength() { return 0L; } public String[] getLocations() { return new String[0]; } } public static void setKeyClass(JobConf job, Class<?> k) { job.setClass("test.fakeif.keyclass", k, WritableComparable.class); } public static void setValClass(JobConf job, Class<?> v) { job.setClass("test.fakeif.valclass", v, Writable.class); } private Class<? extends K> keyclass; private Class<? extends V> valclass; @SuppressWarnings("unchecked") public void configure(JobConf job) { keyclass = (Class<? extends K>) job.getClass("test.fakeif.keyclass", IncomparableKey.class, WritableComparable.class); valclass = (Class<? extends V>) job.getClass("test.fakeif.valclass", NullWritable.class, WritableComparable.class); } public Fake_IF() { } public InputSplit[] getSplits(JobConf conf, int splits) { return new InputSplit[] { new FakeSplit() }; } public RecordReader<K,V> getRecordReader( InputSplit ignored, JobConf conf, Reporter reporter) { return new RecordReader<K,V>() { public boolean next(K key, V value) throws IOException { return false; } public K createKey() { return ReflectionUtils.newInstance(keyclass, null); } public V createValue() { return ReflectionUtils.newInstance(valclass, null); } public long getPos() throws IOException { return 0L; } public void close() throws IOException { } public float getProgress() throws IOException { return 0.0f; } }; } } }
frdeso/hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/join/TestDatamerge.java
Java
apache-2.0
15,338
.jh-key,.jh-root,.jh-root tr,.jh-type-array,.jh-type-object,.jh-value{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.jh-key,.jh-value{margin:0;padding:.2em}.jh-value{border-left:1px solid #ddd}.jh-type-bool,.jh-type-number{font-weight:700;text-align:center;color:#5286BC}.jh-type-string{font-style:italic;color:#839B00}.jh-array-key{font-style:italic;font-size:small;text-align:center}.jh-array-key,.jh-object-key{color:#444;vertical-align:top}.jh-type-array>tbody>tr:nth-child(odd),.jh-type-object>tbody>tr:nth-child(odd){background-color:#f5f5f5}.jh-type-array>tbody>tr:nth-child(even),.jh-type-object>tbody>tr:nth-child(even){background-color:#fff}.jh-type-array,.jh-type-object{width:100%;border-collapse:collapse}.jh-root{border:1px solid #ccc;margin:.2em}th.jh-key{text-align:left}.jh-type-array>tbody>tr,.jh-type-object>tbody>tr{border:1px solid #ddd;border-bottom:none}.jh-type-array>tbody>tr:last-child,.jh-type-object>tbody>tr:last-child{border-bottom:1px solid #ddd}.jh-type-array>tbody>tr:hover,.jh-type-object>tbody>tr:hover{border:1px solid #F99927}.jh-empty{font-style:italic;color:#999;font-size:small}
whitmo/kubernetes
www/app/vendor/angular-json-human/dist/angular-json-human.css
CSS
apache-2.0
1,151
/*! jQuery v3.1.0 | (c) jQuery Foundation | jquery.org/license */ !function(a,b){"use strict";"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){"use strict";var c=[],d=a.document,e=Object.getPrototypeOf,f=c.slice,g=c.concat,h=c.push,i=c.indexOf,j={},k=j.toString,l=j.hasOwnProperty,m=l.toString,n=m.call(Object),o={};function p(a,b){b=b||d;var c=b.createElement("script");c.text=a,b.head.appendChild(c).parentNode.removeChild(c)}var q="3.1.0",r=function(a,b){return new r.fn.init(a,b)},s=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,t=/^-ms-/,u=/-([a-z])/g,v=function(a,b){return b.toUpperCase()};r.fn=r.prototype={jquery:q,constructor:r,length:0,toArray:function(){return f.call(this)},get:function(a){return null!=a?a<0?this[a+this.length]:this[a]:f.call(this)},pushStack:function(a){var b=r.merge(this.constructor(),a);return b.prevObject=this,b},each:function(a){return r.each(this,a)},map:function(a){return this.pushStack(r.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(f.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(a<0?b:0);return this.pushStack(c>=0&&c<b?[this[c]]:[])},end:function(){return this.prevObject||this.constructor()},push:h,sort:c.sort,splice:c.splice},r.extend=r.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||r.isFunction(g)||(g={}),h===i&&(g=this,h--);h<i;h++)if(null!=(a=arguments[h]))for(b in a)c=g[b],d=a[b],g!==d&&(j&&d&&(r.isPlainObject(d)||(e=r.isArray(d)))?(e?(e=!1,f=c&&r.isArray(c)?c:[]):f=c&&r.isPlainObject(c)?c:{},g[b]=r.extend(j,f,d)):void 0!==d&&(g[b]=d));return g},r.extend({expando:"jQuery"+(q+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===r.type(a)},isArray:Array.isArray,isWindow:function(a){return null!=a&&a===a.window},isNumeric:function(a){var b=r.type(a);return("number"===b||"string"===b)&&!isNaN(a-parseFloat(a))},isPlainObject:function(a){var b,c;return!(!a||"[object Object]"!==k.call(a))&&(!(b=e(a))||(c=l.call(b,"constructor")&&b.constructor,"function"==typeof c&&m.call(c)===n))},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?j[k.call(a)]||"object":typeof a},globalEval:function(a){p(a)},camelCase:function(a){return a.replace(t,"ms-").replace(u,v)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b){var c,d=0;if(w(a)){for(c=a.length;d<c;d++)if(b.call(a[d],d,a[d])===!1)break}else for(d in a)if(b.call(a[d],d,a[d])===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(s,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(w(Object(a))?r.merge(c,"string"==typeof a?[a]:a):h.call(c,a)),c},inArray:function(a,b,c){return null==b?-1:i.call(b,a,c)},merge:function(a,b){for(var c=+b.length,d=0,e=a.length;d<c;d++)a[e++]=b[d];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;f<g;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,e,f=0,h=[];if(w(a))for(d=a.length;f<d;f++)e=b(a[f],f,c),null!=e&&h.push(e);else for(f in a)e=b(a[f],f,c),null!=e&&h.push(e);return g.apply([],h)},guid:1,proxy:function(a,b){var c,d,e;if("string"==typeof b&&(c=a[b],b=a,a=c),r.isFunction(a))return d=f.call(arguments,2),e=function(){return a.apply(b||this,d.concat(f.call(arguments)))},e.guid=a.guid=a.guid||r.guid++,e},now:Date.now,support:o}),"function"==typeof Symbol&&(r.fn[Symbol.iterator]=c[Symbol.iterator]),r.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(a,b){j["[object "+b+"]"]=b.toLowerCase()});function w(a){var b=!!a&&"length"in a&&a.length,c=r.type(a);return"function"!==c&&!r.isWindow(a)&&("array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a)}var x=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+1*new Date,v=a.document,w=0,x=0,y=ha(),z=ha(),A=ha(),B=function(a,b){return a===b&&(l=!0),0},C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=function(a,b){for(var c=0,d=a.length;c<d;c++)if(a[c]===b)return c;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",M="\\["+K+"*("+L+")(?:"+K+"*([*^$|!~]?=)"+K+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+L+"))|)"+K+"*\\]",N=":("+L+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+M+")*)|.*)\\)|)",O=new RegExp(K+"+","g"),P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(N),U=new RegExp("^"+L+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L+"|[*])"),ATTR:new RegExp("^"+M),PSEUDO:new RegExp("^"+N),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),aa=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:d<0?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)},ba=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g,ca=function(a,b){return b?"\0"===a?"\ufffd":a.slice(0,-1)+"\\"+a.charCodeAt(a.length-1).toString(16)+" ":"\\"+a},da=function(){m()},ea=ta(function(a){return a.disabled===!0},{dir:"parentNode",next:"legend"});try{G.apply(D=H.call(v.childNodes),v.childNodes),D[v.childNodes.length].nodeType}catch(fa){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function ga(a,b,d,e){var f,h,j,k,l,o,r,s=b&&b.ownerDocument,w=b?b.nodeType:9;if(d=d||[],"string"!=typeof a||!a||1!==w&&9!==w&&11!==w)return d;if(!e&&((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,p)){if(11!==w&&(l=Z.exec(a)))if(f=l[1]){if(9===w){if(!(j=b.getElementById(f)))return d;if(j.id===f)return d.push(j),d}else if(s&&(j=s.getElementById(f))&&t(b,j)&&j.id===f)return d.push(j),d}else{if(l[2])return G.apply(d,b.getElementsByTagName(a)),d;if((f=l[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(f)),d}if(c.qsa&&!A[a+" "]&&(!q||!q.test(a))){if(1!==w)s=b,r=a;else if("object"!==b.nodeName.toLowerCase()){(k=b.getAttribute("id"))?k=k.replace(ba,ca):b.setAttribute("id",k=u),o=g(a),h=o.length;while(h--)o[h]="#"+k+" "+sa(o[h]);r=o.join(","),s=$.test(a)&&qa(b.parentNode)||b}if(r)try{return G.apply(d,s.querySelectorAll(r)),d}catch(x){}finally{k===u&&b.removeAttribute("id")}}}return i(a.replace(P,"$1"),b,d,e)}function ha(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function ia(a){return a[u]=!0,a}function ja(a){var b=n.createElement("fieldset");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function ka(a,b){var c=a.split("|"),e=c.length;while(e--)d.attrHandle[c[e]]=b}function la(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&a.sourceIndex-b.sourceIndex;if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function ma(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function na(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function oa(a){return function(b){return"label"in b&&b.disabled===a||"form"in b&&b.disabled===a||"form"in b&&b.disabled===!1&&(b.isDisabled===a||b.isDisabled!==!a&&("label"in b||!ea(b))!==a)}}function pa(a){return ia(function(b){return b=+b,ia(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function qa(a){return a&&"undefined"!=typeof a.getElementsByTagName&&a}c=ga.support={},f=ga.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return!!b&&"HTML"!==b.nodeName},m=ga.setDocument=function(a){var b,e,g=a?a.ownerDocument||a:v;return g!==n&&9===g.nodeType&&g.documentElement?(n=g,o=n.documentElement,p=!f(n),v!==n&&(e=n.defaultView)&&e.top!==e&&(e.addEventListener?e.addEventListener("unload",da,!1):e.attachEvent&&e.attachEvent("onunload",da)),c.attributes=ja(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ja(function(a){return a.appendChild(n.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(n.getElementsByClassName),c.getById=ja(function(a){return o.appendChild(a).id=u,!n.getElementsByName||!n.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if("undefined"!=typeof b.getElementById&&p){var c=b.getElementById(a);return c?[c]:[]}},d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(_,aa);return function(a){var c="undefined"!=typeof a.getAttributeNode&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return"undefined"!=typeof b.getElementsByTagName?b.getElementsByTagName(a):c.qsa?b.querySelectorAll(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){if("undefined"!=typeof b.getElementsByClassName&&p)return b.getElementsByClassName(a)},r=[],q=[],(c.qsa=Y.test(n.querySelectorAll))&&(ja(function(a){o.appendChild(a).innerHTML="<a id='"+u+"'></a><select id='"+u+"-\r\\' msallowcapture=''><option selected=''></option></select>",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),ja(function(a){a.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var b=n.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+K+"*[*^$|!~]?="),2!==a.querySelectorAll(":enabled").length&&q.push(":enabled",":disabled"),o.appendChild(a).disabled=!0,2!==a.querySelectorAll(":disabled").length&&q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=Y.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ja(function(a){c.disconnectedMatch=s.call(a,"*"),s.call(a,"[s!='']:x"),r.push("!=",N)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=Y.test(o.compareDocumentPosition),t=b||Y.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===n||a.ownerDocument===v&&t(v,a)?-1:b===n||b.ownerDocument===v&&t(v,b)?1:k?I(k,a)-I(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,g=[a],h=[b];if(!e||!f)return a===n?-1:b===n?1:e?-1:f?1:k?I(k,a)-I(k,b):0;if(e===f)return la(a,b);c=a;while(c=c.parentNode)g.unshift(c);c=b;while(c=c.parentNode)h.unshift(c);while(g[d]===h[d])d++;return d?la(g[d],h[d]):g[d]===v?-1:h[d]===v?1:0},n):n},ga.matches=function(a,b){return ga(a,null,null,b)},ga.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(S,"='$1']"),c.matchesSelector&&p&&!A[b+" "]&&(!r||!r.test(b))&&(!q||!q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return ga(b,n,null,[a]).length>0},ga.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},ga.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},ga.escape=function(a){return(a+"").replace(ba,ca)},ga.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},ga.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=ga.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=ga.selectors={cacheLength:50,createPseudo:ia,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(_,aa),a[3]=(a[3]||a[4]||a[5]||"").replace(_,aa),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||ga.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&ga.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return V.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&T.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(_,aa).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=ga.attr(d,a);return null==e?"!="===b:!b||(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(O," ")+" ").indexOf(c)>-1:"|="===b&&(e===c||e.slice(0,c.length+1)===c+"-"))}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h,t=!1;if(q){if(f){while(p){m=b;while(m=m[p])if(h?m.nodeName.toLowerCase()===r:1===m.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){m=q,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n&&j[2],m=n&&q.childNodes[n];while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if(1===m.nodeType&&++t&&m===b){k[a]=[w,n,t];break}}else if(s&&(m=b,l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),j=k[a]||[],n=j[0]===w&&j[1],t=n),t===!1)while(m=++n&&m&&m[p]||(t=n=0)||o.pop())if((h?m.nodeName.toLowerCase()===r:1===m.nodeType)&&++t&&(s&&(l=m[u]||(m[u]={}),k=l[m.uniqueID]||(l[m.uniqueID]={}),k[a]=[w,t]),m===b))break;return t-=e,t===d||t%d===0&&t/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||ga.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ia(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ia(function(a){var b=[],c=[],d=h(a.replace(P,"$1"));return d[u]?ia(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ia(function(a){return function(b){return ga(a,b).length>0}}),contains:ia(function(a){return a=a.replace(_,aa),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ia(function(a){return U.test(a||"")||ga.error("unsupported lang: "+a),a=a.replace(_,aa).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:oa(!1),disabled:oa(!0),checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:pa(function(){return[0]}),last:pa(function(a,b){return[b-1]}),eq:pa(function(a,b,c){return[c<0?c+b:c]}),even:pa(function(a,b){for(var c=0;c<b;c+=2)a.push(c);return a}),odd:pa(function(a,b){for(var c=1;c<b;c+=2)a.push(c);return a}),lt:pa(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:pa(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=ma(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=na(b);function ra(){}ra.prototype=d.filters=d.pseudos,d.setFilters=new ra,g=ga.tokenize=function(a,b){var c,e,f,g,h,i,j,k=z[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){c&&!(e=Q.exec(h))||(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?ga.error(a):z(a,i).slice(0)};function sa(a){for(var b=0,c=a.length,d="";b<c;b++)d+=a[b].value;return d}function ta(a,b,c){var d=b.dir,e=b.next,f=e||d,g=c&&"parentNode"===f,h=x++;return b.first?function(b,c,e){while(b=b[d])if(1===b.nodeType||g)return a(b,c,e)}:function(b,c,i){var j,k,l,m=[w,h];if(i){while(b=b[d])if((1===b.nodeType||g)&&a(b,c,i))return!0}else while(b=b[d])if(1===b.nodeType||g)if(l=b[u]||(b[u]={}),k=l[b.uniqueID]||(l[b.uniqueID]={}),e&&e===b.nodeName.toLowerCase())b=b[d]||b;else{if((j=k[f])&&j[0]===w&&j[1]===h)return m[2]=j[2];if(k[f]=m,m[2]=a(b,c,i))return!0}}}function ua(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function va(a,b,c){for(var d=0,e=b.length;d<e;d++)ga(a,b[d],c);return c}function wa(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;h<i;h++)(f=a[h])&&(c&&!c(f,d,e)||(g.push(f),j&&b.push(h)));return g}function xa(a,b,c,d,e,f){return d&&!d[u]&&(d=xa(d)),e&&!e[u]&&(e=xa(e,f)),ia(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||va(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:wa(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=wa(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=wa(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ya(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=ta(function(a){return a===b},h,!0),l=ta(function(a){return I(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];i<f;i++)if(c=d.relative[a[i].type])m=[ta(ua(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;e<f;e++)if(d.relative[a[e].type])break;return xa(i>1&&ua(m),i>1&&sa(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(P,"$1"),c,i<e&&ya(a.slice(i,e)),e<f&&ya(a=a.slice(e)),e<f&&sa(a))}m.push(c)}return ua(m)}function za(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,o,q,r=0,s="0",t=f&&[],u=[],v=j,x=f||e&&d.find.TAG("*",k),y=w+=null==v?1:Math.random()||.1,z=x.length;for(k&&(j=g===n||g||k);s!==z&&null!=(l=x[s]);s++){if(e&&l){o=0,g||l.ownerDocument===n||(m(l),h=!p);while(q=a[o++])if(q(l,g||n,h)){i.push(l);break}k&&(w=y)}c&&((l=!q&&l)&&r--,f&&t.push(l))}if(r+=s,c&&s!==r){o=0;while(q=b[o++])q(t,u,g,h);if(f){if(r>0)while(s--)t[s]||u[s]||(u[s]=E.call(i));u=wa(u)}G.apply(i,u),k&&!f&&u.length>0&&r+b.length>1&&ga.uniqueSort(i)}return k&&(w=y,j=v),t};return c?ia(f):f}return h=ga.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=ya(b[c]),f[u]?d.push(f):e.push(f);f=A(a,za(e,d)),f.selector=a}return f},i=ga.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(_,aa),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=V.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(_,aa),$.test(j[0].type)&&qa(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&sa(j),!a)return G.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,!b||$.test(a)&&qa(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ja(function(a){return 1&a.compareDocumentPosition(n.createElement("fieldset"))}),ja(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||ka("type|href|height|width",function(a,b,c){if(!c)return a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ja(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||ka("value",function(a,b,c){if(!c&&"input"===a.nodeName.toLowerCase())return a.defaultValue}),ja(function(a){return null==a.getAttribute("disabled")})||ka(J,function(a,b,c){var d;if(!c)return a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),ga}(a);r.find=x,r.expr=x.selectors,r.expr[":"]=r.expr.pseudos,r.uniqueSort=r.unique=x.uniqueSort,r.text=x.getText,r.isXMLDoc=x.isXML,r.contains=x.contains,r.escapeSelector=x.escape;var y=function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&r(a).is(c))break;d.push(a)}return d},z=function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c},A=r.expr.match.needsContext,B=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,C=/^.[^:#\[\.,]*$/;function D(a,b,c){if(r.isFunction(b))return r.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return r.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(C.test(b))return r.filter(b,a,c);b=r.filter(b,a)}return r.grep(a,function(a){return i.call(b,a)>-1!==c&&1===a.nodeType})}r.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?r.find.matchesSelector(d,a)?[d]:[]:r.find.matches(a,r.grep(b,function(a){return 1===a.nodeType}))},r.fn.extend({find:function(a){var b,c,d=this.length,e=this;if("string"!=typeof a)return this.pushStack(r(a).filter(function(){for(b=0;b<d;b++)if(r.contains(e[b],this))return!0}));for(c=this.pushStack([]),b=0;b<d;b++)r.find(a,e[b],c);return d>1?r.uniqueSort(c):c},filter:function(a){return this.pushStack(D(this,a||[],!1))},not:function(a){return this.pushStack(D(this,a||[],!0))},is:function(a){return!!D(this,"string"==typeof a&&A.test(a)?r(a):a||[],!1).length}});var E,F=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,G=r.fn.init=function(a,b,c){var e,f;if(!a)return this;if(c=c||E,"string"==typeof a){if(e="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:F.exec(a),!e||!e[1]&&b)return!b||b.jquery?(b||c).find(a):this.constructor(b).find(a);if(e[1]){if(b=b instanceof r?b[0]:b,r.merge(this,r.parseHTML(e[1],b&&b.nodeType?b.ownerDocument||b:d,!0)),B.test(e[1])&&r.isPlainObject(b))for(e in b)r.isFunction(this[e])?this[e](b[e]):this.attr(e,b[e]);return this}return f=d.getElementById(e[2]),f&&(this[0]=f,this.length=1),this}return a.nodeType?(this[0]=a,this.length=1,this):r.isFunction(a)?void 0!==c.ready?c.ready(a):a(r):r.makeArray(a,this)};G.prototype=r.fn,E=r(d);var H=/^(?:parents|prev(?:Until|All))/,I={children:!0,contents:!0,next:!0,prev:!0};r.fn.extend({has:function(a){var b=r(a,this),c=b.length;return this.filter(function(){for(var a=0;a<c;a++)if(r.contains(this,b[a]))return!0})},closest:function(a,b){var c,d=0,e=this.length,f=[],g="string"!=typeof a&&r(a);if(!A.test(a))for(;d<e;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&r.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?r.uniqueSort(f):f)},index:function(a){return a?"string"==typeof a?i.call(r(a),this[0]):i.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(r.uniqueSort(r.merge(this.get(),r(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function J(a,b){while((a=a[b])&&1!==a.nodeType);return a}r.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return y(a,"parentNode")},parentsUntil:function(a,b,c){return y(a,"parentNode",c)},next:function(a){return J(a,"nextSibling")},prev:function(a){return J(a,"previousSibling")},nextAll:function(a){return y(a,"nextSibling")},prevAll:function(a){return y(a,"previousSibling")},nextUntil:function(a,b,c){return y(a,"nextSibling",c)},prevUntil:function(a,b,c){return y(a,"previousSibling",c)},siblings:function(a){return z((a.parentNode||{}).firstChild,a)},children:function(a){return z(a.firstChild)},contents:function(a){return a.contentDocument||r.merge([],a.childNodes)}},function(a,b){r.fn[a]=function(c,d){var e=r.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=r.filter(d,e)),this.length>1&&(I[a]||r.uniqueSort(e),H.test(a)&&e.reverse()),this.pushStack(e)}});var K=/\S+/g;function L(a){var b={};return r.each(a.match(K)||[],function(a,c){b[c]=!0}),b}r.Callbacks=function(a){a="string"==typeof a?L(a):r.extend({},a);var b,c,d,e,f=[],g=[],h=-1,i=function(){for(e=a.once,d=b=!0;g.length;h=-1){c=g.shift();while(++h<f.length)f[h].apply(c[0],c[1])===!1&&a.stopOnFalse&&(h=f.length,c=!1)}a.memory||(c=!1),b=!1,e&&(f=c?[]:"")},j={add:function(){return f&&(c&&!b&&(h=f.length-1,g.push(c)),function d(b){r.each(b,function(b,c){r.isFunction(c)?a.unique&&j.has(c)||f.push(c):c&&c.length&&"string"!==r.type(c)&&d(c)})}(arguments),c&&!b&&i()),this},remove:function(){return r.each(arguments,function(a,b){var c;while((c=r.inArray(b,f,c))>-1)f.splice(c,1),c<=h&&h--}),this},has:function(a){return a?r.inArray(a,f)>-1:f.length>0},empty:function(){return f&&(f=[]),this},disable:function(){return e=g=[],f=c="",this},disabled:function(){return!f},lock:function(){return e=g=[],c||b||(f=c=""),this},locked:function(){return!!e},fireWith:function(a,c){return e||(c=c||[],c=[a,c.slice?c.slice():c],g.push(c),b||i()),this},fire:function(){return j.fireWith(this,arguments),this},fired:function(){return!!d}};return j};function M(a){return a}function N(a){throw a}function O(a,b,c){var d;try{a&&r.isFunction(d=a.promise)?d.call(a).done(b).fail(c):a&&r.isFunction(d=a.then)?d.call(a,b,c):b.call(void 0,a)}catch(a){c.call(void 0,a)}}r.extend({Deferred:function(b){var c=[["notify","progress",r.Callbacks("memory"),r.Callbacks("memory"),2],["resolve","done",r.Callbacks("once memory"),r.Callbacks("once memory"),0,"resolved"],["reject","fail",r.Callbacks("once memory"),r.Callbacks("once memory"),1,"rejected"]],d="pending",e={state:function(){return d},always:function(){return f.done(arguments).fail(arguments),this},"catch":function(a){return e.then(null,a)},pipe:function(){var a=arguments;return r.Deferred(function(b){r.each(c,function(c,d){var e=r.isFunction(a[d[4]])&&a[d[4]];f[d[1]](function(){var a=e&&e.apply(this,arguments);a&&r.isFunction(a.promise)?a.promise().progress(b.notify).done(b.resolve).fail(b.reject):b[d[0]+"With"](this,e?[a]:arguments)})}),a=null}).promise()},then:function(b,d,e){var f=0;function g(b,c,d,e){return function(){var h=this,i=arguments,j=function(){var a,j;if(!(b<f)){if(a=d.apply(h,i),a===c.promise())throw new TypeError("Thenable self-resolution");j=a&&("object"==typeof a||"function"==typeof a)&&a.then,r.isFunction(j)?e?j.call(a,g(f,c,M,e),g(f,c,N,e)):(f++,j.call(a,g(f,c,M,e),g(f,c,N,e),g(f,c,M,c.notifyWith))):(d!==M&&(h=void 0,i=[a]),(e||c.resolveWith)(h,i))}},k=e?j:function(){try{j()}catch(a){r.Deferred.exceptionHook&&r.Deferred.exceptionHook(a,k.stackTrace),b+1>=f&&(d!==N&&(h=void 0,i=[a]),c.rejectWith(h,i))}};b?k():(r.Deferred.getStackHook&&(k.stackTrace=r.Deferred.getStackHook()),a.setTimeout(k))}}return r.Deferred(function(a){c[0][3].add(g(0,a,r.isFunction(e)?e:M,a.notifyWith)),c[1][3].add(g(0,a,r.isFunction(b)?b:M)),c[2][3].add(g(0,a,r.isFunction(d)?d:N))}).promise()},promise:function(a){return null!=a?r.extend(a,e):e}},f={};return r.each(c,function(a,b){var g=b[2],h=b[5];e[b[1]]=g.add,h&&g.add(function(){d=h},c[3-a][2].disable,c[0][2].lock),g.add(b[3].fire),f[b[0]]=function(){return f[b[0]+"With"](this===f?void 0:this,arguments),this},f[b[0]+"With"]=g.fireWith}),e.promise(f),b&&b.call(f,f),f},when:function(a){var b=arguments.length,c=b,d=Array(c),e=f.call(arguments),g=r.Deferred(),h=function(a){return function(c){d[a]=this,e[a]=arguments.length>1?f.call(arguments):c,--b||g.resolveWith(d,e)}};if(b<=1&&(O(a,g.done(h(c)).resolve,g.reject),"pending"===g.state()||r.isFunction(e[c]&&e[c].then)))return g.then();while(c--)O(e[c],h(c),g.reject);return g.promise()}});var P=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;r.Deferred.exceptionHook=function(b,c){a.console&&a.console.warn&&b&&P.test(b.name)&&a.console.warn("jQuery.Deferred exception: "+b.message,b.stack,c)},r.readyException=function(b){a.setTimeout(function(){throw b})};var Q=r.Deferred();r.fn.ready=function(a){return Q.then(a)["catch"](function(a){r.readyException(a)}),this},r.extend({isReady:!1,readyWait:1,holdReady:function(a){a?r.readyWait++:r.ready(!0)},ready:function(a){(a===!0?--r.readyWait:r.isReady)||(r.isReady=!0,a!==!0&&--r.readyWait>0||Q.resolveWith(d,[r]))}}),r.ready.then=Q.then;function R(){d.removeEventListener("DOMContentLoaded",R),a.removeEventListener("load",R),r.ready()}"complete"===d.readyState||"loading"!==d.readyState&&!d.documentElement.doScroll?a.setTimeout(r.ready):(d.addEventListener("DOMContentLoaded",R),a.addEventListener("load",R));var S=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===r.type(c)){e=!0;for(h in c)S(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0, r.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(r(a),c)})),b))for(;h<i;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},T=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function U(){this.expando=r.expando+U.uid++}U.uid=1,U.prototype={cache:function(a){var b=a[this.expando];return b||(b={},T(a)&&(a.nodeType?a[this.expando]=b:Object.defineProperty(a,this.expando,{value:b,configurable:!0}))),b},set:function(a,b,c){var d,e=this.cache(a);if("string"==typeof b)e[r.camelCase(b)]=c;else for(d in b)e[r.camelCase(d)]=b[d];return e},get:function(a,b){return void 0===b?this.cache(a):a[this.expando]&&a[this.expando][r.camelCase(b)]},access:function(a,b,c){return void 0===b||b&&"string"==typeof b&&void 0===c?this.get(a,b):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d=a[this.expando];if(void 0!==d){if(void 0!==b){r.isArray(b)?b=b.map(r.camelCase):(b=r.camelCase(b),b=b in d?[b]:b.match(K)||[]),c=b.length;while(c--)delete d[b[c]]}(void 0===b||r.isEmptyObject(d))&&(a.nodeType?a[this.expando]=void 0:delete a[this.expando])}},hasData:function(a){var b=a[this.expando];return void 0!==b&&!r.isEmptyObject(b)}};var V=new U,W=new U,X=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Y=/[A-Z]/g;function Z(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(Y,"-$&").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c||"false"!==c&&("null"===c?null:+c+""===c?+c:X.test(c)?JSON.parse(c):c)}catch(e){}W.set(a,b,c)}else c=void 0;return c}r.extend({hasData:function(a){return W.hasData(a)||V.hasData(a)},data:function(a,b,c){return W.access(a,b,c)},removeData:function(a,b){W.remove(a,b)},_data:function(a,b,c){return V.access(a,b,c)},_removeData:function(a,b){V.remove(a,b)}}),r.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=W.get(f),1===f.nodeType&&!V.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=r.camelCase(d.slice(5)),Z(f,d,e[d])));V.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){W.set(this,a)}):S(this,function(b){var c;if(f&&void 0===b){if(c=W.get(f,a),void 0!==c)return c;if(c=Z(f,a),void 0!==c)return c}else this.each(function(){W.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){W.remove(this,a)})}}),r.extend({queue:function(a,b,c){var d;if(a)return b=(b||"fx")+"queue",d=V.get(a,b),c&&(!d||r.isArray(c)?d=V.access(a,b,r.makeArray(c)):d.push(c)),d||[]},dequeue:function(a,b){b=b||"fx";var c=r.queue(a,b),d=c.length,e=c.shift(),f=r._queueHooks(a,b),g=function(){r.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return V.get(a,c)||V.access(a,c,{empty:r.Callbacks("once memory").add(function(){V.remove(a,[b+"queue",c])})})}}),r.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?r.queue(this[0],a):void 0===b?this:this.each(function(){var c=r.queue(this,a,b);r._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&r.dequeue(this,a)})},dequeue:function(a){return this.each(function(){r.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=r.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=V.get(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var $=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,_=new RegExp("^(?:([+-])=|)("+$+")([a-z%]*)$","i"),aa=["Top","Right","Bottom","Left"],ba=function(a,b){return a=b||a,"none"===a.style.display||""===a.style.display&&r.contains(a.ownerDocument,a)&&"none"===r.css(a,"display")},ca=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};function da(a,b,c,d){var e,f=1,g=20,h=d?function(){return d.cur()}:function(){return r.css(a,b,"")},i=h(),j=c&&c[3]||(r.cssNumber[b]?"":"px"),k=(r.cssNumber[b]||"px"!==j&&+i)&&_.exec(r.css(a,b));if(k&&k[3]!==j){j=j||k[3],c=c||[],k=+i||1;do f=f||".5",k/=f,r.style(a,b,k+j);while(f!==(f=h()/i)&&1!==f&&--g)}return c&&(k=+k||+i||0,e=c[1]?k+(c[1]+1)*c[2]:+c[2],d&&(d.unit=j,d.start=k,d.end=e)),e}var ea={};function fa(a){var b,c=a.ownerDocument,d=a.nodeName,e=ea[d];return e?e:(b=c.body.appendChild(c.createElement(d)),e=r.css(b,"display"),b.parentNode.removeChild(b),"none"===e&&(e="block"),ea[d]=e,e)}function ga(a,b){for(var c,d,e=[],f=0,g=a.length;f<g;f++)d=a[f],d.style&&(c=d.style.display,b?("none"===c&&(e[f]=V.get(d,"display")||null,e[f]||(d.style.display="")),""===d.style.display&&ba(d)&&(e[f]=fa(d))):"none"!==c&&(e[f]="none",V.set(d,"display",c)));for(f=0;f<g;f++)null!=e[f]&&(a[f].style.display=e[f]);return a}r.fn.extend({show:function(){return ga(this,!0)},hide:function(){return ga(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){ba(this)?r(this).show():r(this).hide()})}});var ha=/^(?:checkbox|radio)$/i,ia=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,ja=/^$|\/(?:java|ecma)script/i,ka={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};ka.optgroup=ka.option,ka.tbody=ka.tfoot=ka.colgroup=ka.caption=ka.thead,ka.th=ka.td;function la(a,b){var c="undefined"!=typeof a.getElementsByTagName?a.getElementsByTagName(b||"*"):"undefined"!=typeof a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&r.nodeName(a,b)?r.merge([a],c):c}function ma(a,b){for(var c=0,d=a.length;c<d;c++)V.set(a[c],"globalEval",!b||V.get(b[c],"globalEval"))}var na=/<|&#?\w+;/;function oa(a,b,c,d,e){for(var f,g,h,i,j,k,l=b.createDocumentFragment(),m=[],n=0,o=a.length;n<o;n++)if(f=a[n],f||0===f)if("object"===r.type(f))r.merge(m,f.nodeType?[f]:f);else if(na.test(f)){g=g||l.appendChild(b.createElement("div")),h=(ia.exec(f)||["",""])[1].toLowerCase(),i=ka[h]||ka._default,g.innerHTML=i[1]+r.htmlPrefilter(f)+i[2],k=i[0];while(k--)g=g.lastChild;r.merge(m,g.childNodes),g=l.firstChild,g.textContent=""}else m.push(b.createTextNode(f));l.textContent="",n=0;while(f=m[n++])if(d&&r.inArray(f,d)>-1)e&&e.push(f);else if(j=r.contains(f.ownerDocument,f),g=la(l.appendChild(f),"script"),j&&ma(g),c){k=0;while(f=g[k++])ja.test(f.type||"")&&c.push(f)}return l}!function(){var a=d.createDocumentFragment(),b=a.appendChild(d.createElement("div")),c=d.createElement("input");c.setAttribute("type","radio"),c.setAttribute("checked","checked"),c.setAttribute("name","t"),b.appendChild(c),o.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,b.innerHTML="<textarea>x</textarea>",o.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var pa=d.documentElement,qa=/^key/,ra=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,sa=/^([^.]*)(?:\.(.+)|)/;function ta(){return!0}function ua(){return!1}function va(){try{return d.activeElement}catch(a){}}function wa(a,b,c,d,e,f){var g,h;if("object"==typeof b){"string"!=typeof c&&(d=d||c,c=void 0);for(h in b)wa(a,h,c,d,b[h],f);return a}if(null==d&&null==e?(e=c,d=c=void 0):null==e&&("string"==typeof c?(e=d,d=void 0):(e=d,d=c,c=void 0)),e===!1)e=ua;else if(!e)return a;return 1===f&&(g=e,e=function(a){return r().off(a),g.apply(this,arguments)},e.guid=g.guid||(g.guid=r.guid++)),a.each(function(){r.event.add(this,b,e,d,c)})}r.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.get(a);if(q){c.handler&&(f=c,c=f.handler,e=f.selector),e&&r.find.matchesSelector(pa,e),c.guid||(c.guid=r.guid++),(i=q.events)||(i=q.events={}),(g=q.handle)||(g=q.handle=function(b){return"undefined"!=typeof r&&r.event.triggered!==b.type?r.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(K)||[""],j=b.length;while(j--)h=sa.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n&&(l=r.event.special[n]||{},n=(e?l.delegateType:l.bindType)||n,l=r.event.special[n]||{},k=r.extend({type:n,origType:p,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&r.expr.match.needsContext.test(e),namespace:o.join(".")},f),(m=i[n])||(m=i[n]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,o,g)!==!1||a.addEventListener&&a.addEventListener(n,g)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),r.event.global[n]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,n,o,p,q=V.hasData(a)&&V.get(a);if(q&&(i=q.events)){b=(b||"").match(K)||[""],j=b.length;while(j--)if(h=sa.exec(b[j])||[],n=p=h[1],o=(h[2]||"").split(".").sort(),n){l=r.event.special[n]||{},n=(d?l.delegateType:l.bindType)||n,m=i[n]||[],h=h[2]&&new RegExp("(^|\\.)"+o.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&p!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,o,q.handle)!==!1||r.removeEvent(a,n,q.handle),delete i[n])}else for(n in i)r.event.remove(a,n+b[j],c,d,!0);r.isEmptyObject(i)&&V.remove(a,"handle events")}},dispatch:function(a){var b=r.event.fix(a),c,d,e,f,g,h,i=new Array(arguments.length),j=(V.get(this,"events")||{})[b.type]||[],k=r.event.special[b.type]||{};for(i[0]=b,c=1;c<arguments.length;c++)i[c]=arguments[c];if(b.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,b)!==!1){h=r.event.handlers.call(this,b,j),c=0;while((f=h[c++])&&!b.isPropagationStopped()){b.currentTarget=f.elem,d=0;while((g=f.handlers[d++])&&!b.isImmediatePropagationStopped())b.rnamespace&&!b.rnamespace.test(g.namespace)||(b.handleObj=g,b.data=g.data,e=((r.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(b.result=e)===!1&&(b.preventDefault(),b.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,b),b.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&("click"!==a.type||isNaN(a.button)||a.button<1))for(;i!==this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(d=[],c=0;c<h;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?r(e,this).index(i)>-1:r.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},addProp:function(a,b){Object.defineProperty(r.Event.prototype,a,{enumerable:!0,configurable:!0,get:r.isFunction(b)?function(){if(this.originalEvent)return b(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[a]},set:function(b){Object.defineProperty(this,a,{enumerable:!0,configurable:!0,writable:!0,value:b})}})},fix:function(a){return a[r.expando]?a:new r.Event(a)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==va()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===va()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&r.nodeName(this,"input"))return this.click(),!1},_default:function(a){return r.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&a.originalEvent&&(a.originalEvent.returnValue=a.result)}}}},r.removeEvent=function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c)},r.Event=function(a,b){return this instanceof r.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&a.returnValue===!1?ta:ua,this.target=a.target&&3===a.target.nodeType?a.target.parentNode:a.target,this.currentTarget=a.currentTarget,this.relatedTarget=a.relatedTarget):this.type=a,b&&r.extend(this,b),this.timeStamp=a&&a.timeStamp||r.now(),void(this[r.expando]=!0)):new r.Event(a,b)},r.Event.prototype={constructor:r.Event,isDefaultPrevented:ua,isPropagationStopped:ua,isImmediatePropagationStopped:ua,isSimulated:!1,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=ta,a&&!this.isSimulated&&a.preventDefault()},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=ta,a&&!this.isSimulated&&a.stopPropagation()},stopImmediatePropagation:function(){var a=this.originalEvent;this.isImmediatePropagationStopped=ta,a&&!this.isSimulated&&a.stopImmediatePropagation(),this.stopPropagation()}},r.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,"char":!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(a){var b=a.button;return null==a.which&&qa.test(a.type)?null!=a.charCode?a.charCode:a.keyCode:!a.which&&void 0!==b&&ra.test(a.type)?1&b?1:2&b?3:4&b?2:0:a.which}},r.event.addProp),r.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(a,b){r.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return e&&(e===d||r.contains(d,e))||(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),r.fn.extend({on:function(a,b,c,d){return wa(this,a,b,c,d)},one:function(a,b,c,d){return wa(this,a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,r(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return b!==!1&&"function"!=typeof b||(c=b,b=void 0),c===!1&&(c=ua),this.each(function(){r.event.remove(this,a,c,b)})}});var xa=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,ya=/<script|<style|<link/i,za=/checked\s*(?:[^=]|=\s*.checked.)/i,Aa=/^true\/(.*)/,Ba=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;function Ca(a,b){return r.nodeName(a,"table")&&r.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a:a}function Da(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function Ea(a){var b=Aa.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Fa(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(V.hasData(a)&&(f=V.access(a),g=V.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;c<d;c++)r.event.add(b,e,j[e][c])}W.hasData(a)&&(h=W.access(a),i=r.extend({},h),W.set(b,i))}}function Ga(a,b){var c=b.nodeName.toLowerCase();"input"===c&&ha.test(a.type)?b.checked=a.checked:"input"!==c&&"textarea"!==c||(b.defaultValue=a.defaultValue)}function Ha(a,b,c,d){b=g.apply([],b);var e,f,h,i,j,k,l=0,m=a.length,n=m-1,q=b[0],s=r.isFunction(q);if(s||m>1&&"string"==typeof q&&!o.checkClone&&za.test(q))return a.each(function(e){var f=a.eq(e);s&&(b[0]=q.call(this,e,f.html())),Ha(f,b,c,d)});if(m&&(e=oa(b,a[0].ownerDocument,!1,a,d),f=e.firstChild,1===e.childNodes.length&&(e=f),f||d)){for(h=r.map(la(e,"script"),Da),i=h.length;l<m;l++)j=e,l!==n&&(j=r.clone(j,!0,!0),i&&r.merge(h,la(j,"script"))),c.call(a[l],j,l);if(i)for(k=h[h.length-1].ownerDocument,r.map(h,Ea),l=0;l<i;l++)j=h[l],ja.test(j.type||"")&&!V.access(j,"globalEval")&&r.contains(k,j)&&(j.src?r._evalUrl&&r._evalUrl(j.src):p(j.textContent.replace(Ba,""),k))}return a}function Ia(a,b,c){for(var d,e=b?r.filter(b,a):a,f=0;null!=(d=e[f]);f++)c||1!==d.nodeType||r.cleanData(la(d)),d.parentNode&&(c&&r.contains(d.ownerDocument,d)&&ma(la(d,"script")),d.parentNode.removeChild(d));return a}r.extend({htmlPrefilter:function(a){return a.replace(xa,"<$1></$2>")},clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=r.contains(a.ownerDocument,a);if(!(o.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||r.isXMLDoc(a)))for(g=la(h),f=la(a),d=0,e=f.length;d<e;d++)Ga(f[d],g[d]);if(b)if(c)for(f=f||la(a),g=g||la(h),d=0,e=f.length;d<e;d++)Fa(f[d],g[d]);else Fa(a,h);return g=la(h,"script"),g.length>0&&ma(g,!i&&la(a,"script")),h},cleanData:function(a){for(var b,c,d,e=r.event.special,f=0;void 0!==(c=a[f]);f++)if(T(c)){if(b=c[V.expando]){if(b.events)for(d in b.events)e[d]?r.event.remove(c,d):r.removeEvent(c,d,b.handle);c[V.expando]=void 0}c[W.expando]&&(c[W.expando]=void 0)}}}),r.fn.extend({detach:function(a){return Ia(this,a,!0)},remove:function(a){return Ia(this,a)},text:function(a){return S(this,function(a){return void 0===a?r.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=a)})},null,a,arguments.length)},append:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.appendChild(a)}})},prepend:function(){return Ha(this,arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=Ca(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return Ha(this,arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(r.cleanData(la(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null!=a&&a,b=null==b?a:b,this.map(function(){return r.clone(this,a,b)})},html:function(a){return S(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!ya.test(a)&&!ka[(ia.exec(a)||["",""])[1].toLowerCase()]){a=r.htmlPrefilter(a);try{for(;c<d;c++)b=this[c]||{},1===b.nodeType&&(r.cleanData(la(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=[];return Ha(this,arguments,function(b){var c=this.parentNode;r.inArray(this,a)<0&&(r.cleanData(la(this)),c&&c.replaceChild(b,this))},a)}}),r.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){r.fn[a]=function(a){for(var c,d=[],e=r(a),f=e.length-1,g=0;g<=f;g++)c=g===f?this:this.clone(!0),r(e[g])[b](c),h.apply(d,c.get());return this.pushStack(d)}});var Ja=/^margin/,Ka=new RegExp("^("+$+")(?!px)[a-z%]+$","i"),La=function(b){var c=b.ownerDocument.defaultView;return c&&c.opener||(c=a),c.getComputedStyle(b)};!function(){function b(){if(i){i.style.cssText="box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",i.innerHTML="",pa.appendChild(h);var b=a.getComputedStyle(i);c="1%"!==b.top,g="2px"===b.marginLeft,e="4px"===b.width,i.style.marginRight="50%",f="4px"===b.marginRight,pa.removeChild(h),i=null}}var c,e,f,g,h=d.createElement("div"),i=d.createElement("div");i.style&&(i.style.backgroundClip="content-box",i.cloneNode(!0).style.backgroundClip="",o.clearCloneStyle="content-box"===i.style.backgroundClip,h.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",h.appendChild(i),r.extend(o,{pixelPosition:function(){return b(),c},boxSizingReliable:function(){return b(),e},pixelMarginRight:function(){return b(),f},reliableMarginLeft:function(){return b(),g}}))}();function Ma(a,b,c){var d,e,f,g,h=a.style;return c=c||La(a),c&&(g=c.getPropertyValue(b)||c[b],""!==g||r.contains(a.ownerDocument,a)||(g=r.style(a,b)),!o.pixelMarginRight()&&Ka.test(g)&&Ja.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0!==g?g+"":g}function Na(a,b){return{get:function(){return a()?void delete this.get:(this.get=b).apply(this,arguments)}}}var Oa=/^(none|table(?!-c[ea]).+)/,Pa={position:"absolute",visibility:"hidden",display:"block"},Qa={letterSpacing:"0",fontWeight:"400"},Ra=["Webkit","Moz","ms"],Sa=d.createElement("div").style;function Ta(a){if(a in Sa)return a;var b=a[0].toUpperCase()+a.slice(1),c=Ra.length;while(c--)if(a=Ra[c]+b,a in Sa)return a}function Ua(a,b,c){var d=_.exec(b);return d?Math.max(0,d[2]-(c||0))+(d[3]||"px"):b}function Va(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;f<4;f+=2)"margin"===c&&(g+=r.css(a,c+aa[f],!0,e)),d?("content"===c&&(g-=r.css(a,"padding"+aa[f],!0,e)),"margin"!==c&&(g-=r.css(a,"border"+aa[f]+"Width",!0,e))):(g+=r.css(a,"padding"+aa[f],!0,e),"padding"!==c&&(g+=r.css(a,"border"+aa[f]+"Width",!0,e)));return g}function Wa(a,b,c){var d,e=!0,f=La(a),g="border-box"===r.css(a,"boxSizing",!1,f);if(a.getClientRects().length&&(d=a.getBoundingClientRect()[b]),d<=0||null==d){if(d=Ma(a,b,f),(d<0||null==d)&&(d=a.style[b]),Ka.test(d))return d;e=g&&(o.boxSizingReliable()||d===a.style[b]),d=parseFloat(d)||0}return d+Va(a,b,c||(g?"border":"content"),e,f)+"px"}r.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Ma(a,"opacity");return""===c?"1":c}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=r.camelCase(b),i=a.style;return b=r.cssProps[h]||(r.cssProps[h]=Ta(h)||h),g=r.cssHooks[b]||r.cssHooks[h],void 0===c?g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b]:(f=typeof c,"string"===f&&(e=_.exec(c))&&e[1]&&(c=da(a,b,e),f="number"),null!=c&&c===c&&("number"===f&&(c+=e&&e[3]||(r.cssNumber[h]?"":"px")),o.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),g&&"set"in g&&void 0===(c=g.set(a,c,d))||(i[b]=c)),void 0)}},css:function(a,b,c,d){var e,f,g,h=r.camelCase(b);return b=r.cssProps[h]||(r.cssProps[h]=Ta(h)||h),g=r.cssHooks[b]||r.cssHooks[h],g&&"get"in g&&(e=g.get(a,!0,c)),void 0===e&&(e=Ma(a,b,d)),"normal"===e&&b in Qa&&(e=Qa[b]),""===c||c?(f=parseFloat(e),c===!0||isFinite(f)?f||0:e):e}}),r.each(["height","width"],function(a,b){r.cssHooks[b]={get:function(a,c,d){if(c)return!Oa.test(r.css(a,"display"))||a.getClientRects().length&&a.getBoundingClientRect().width?Wa(a,b,d):ca(a,Pa,function(){return Wa(a,b,d)})},set:function(a,c,d){var e,f=d&&La(a),g=d&&Va(a,b,d,"border-box"===r.css(a,"boxSizing",!1,f),f);return g&&(e=_.exec(c))&&"px"!==(e[3]||"px")&&(a.style[b]=c,c=r.css(a,b)),Ua(a,c,g)}}}),r.cssHooks.marginLeft=Na(o.reliableMarginLeft,function(a,b){if(b)return(parseFloat(Ma(a,"marginLeft"))||a.getBoundingClientRect().left-ca(a,{marginLeft:0},function(){return a.getBoundingClientRect().left}))+"px"}),r.each({margin:"",padding:"",border:"Width"},function(a,b){r.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];d<4;d++)e[a+aa[d]+b]=f[d]||f[d-2]||f[0];return e}},Ja.test(a)||(r.cssHooks[a+b].set=Ua)}),r.fn.extend({css:function(a,b){return S(this,function(a,b,c){var d,e,f={},g=0;if(r.isArray(b)){for(d=La(a),e=b.length;g<e;g++)f[b[g]]=r.css(a,b[g],!1,d);return f}return void 0!==c?r.style(a,b,c):r.css(a,b)},a,b,arguments.length>1)}});function Xa(a,b,c,d,e){return new Xa.prototype.init(a,b,c,d,e)}r.Tween=Xa,Xa.prototype={constructor:Xa,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||r.easing._default,this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(r.cssNumber[c]?"":"px")},cur:function(){var a=Xa.propHooks[this.prop];return a&&a.get?a.get(this):Xa.propHooks._default.get(this)},run:function(a){var b,c=Xa.propHooks[this.prop];return this.options.duration?this.pos=b=r.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):this.pos=b=a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Xa.propHooks._default.set(this),this}},Xa.prototype.init.prototype=Xa.prototype,Xa.propHooks={_default:{get:function(a){var b;return 1!==a.elem.nodeType||null!=a.elem[a.prop]&&null==a.elem.style[a.prop]?a.elem[a.prop]:(b=r.css(a.elem,a.prop,""),b&&"auto"!==b?b:0)},set:function(a){r.fx.step[a.prop]?r.fx.step[a.prop](a):1!==a.elem.nodeType||null==a.elem.style[r.cssProps[a.prop]]&&!r.cssHooks[a.prop]?a.elem[a.prop]=a.now:r.style(a.elem,a.prop,a.now+a.unit)}}},Xa.propHooks.scrollTop=Xa.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},r.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2},_default:"swing"},r.fx=Xa.prototype.init,r.fx.step={};var Ya,Za,$a=/^(?:toggle|show|hide)$/,_a=/queueHooks$/;function ab(){Za&&(a.requestAnimationFrame(ab),r.fx.tick())}function bb(){return a.setTimeout(function(){Ya=void 0}),Ya=r.now()}function cb(a,b){var c,d=0,e={height:a};for(b=b?1:0;d<4;d+=2-b)c=aa[d],e["margin"+c]=e["padding"+c]=a;return b&&(e.opacity=e.width=a),e}function db(a,b,c){for(var d,e=(gb.tweeners[b]||[]).concat(gb.tweeners["*"]),f=0,g=e.length;f<g;f++)if(d=e[f].call(c,b,a))return d}function eb(a,b,c){var d,e,f,g,h,i,j,k,l="width"in b||"height"in b,m=this,n={},o=a.style,p=a.nodeType&&ba(a),q=V.get(a,"fxshow");c.queue||(g=r._queueHooks(a,"fx"),null==g.unqueued&&(g.unqueued=0,h=g.empty.fire,g.empty.fire=function(){g.unqueued||h()}),g.unqueued++,m.always(function(){m.always(function(){g.unqueued--,r.queue(a,"fx").length||g.empty.fire()})}));for(d in b)if(e=b[d],$a.test(e)){if(delete b[d],f=f||"toggle"===e,e===(p?"hide":"show")){if("show"!==e||!q||void 0===q[d])continue;p=!0}n[d]=q&&q[d]||r.style(a,d)}if(i=!r.isEmptyObject(b),i||!r.isEmptyObject(n)){l&&1===a.nodeType&&(c.overflow=[o.overflow,o.overflowX,o.overflowY],j=q&&q.display,null==j&&(j=V.get(a,"display")),k=r.css(a,"display"),"none"===k&&(j?k=j:(ga([a],!0),j=a.style.display||j,k=r.css(a,"display"),ga([a]))),("inline"===k||"inline-block"===k&&null!=j)&&"none"===r.css(a,"float")&&(i||(m.done(function(){o.display=j}),null==j&&(k=o.display,j="none"===k?"":k)),o.display="inline-block")),c.overflow&&(o.overflow="hidden",m.always(function(){o.overflow=c.overflow[0],o.overflowX=c.overflow[1],o.overflowY=c.overflow[2]})),i=!1;for(d in n)i||(q?"hidden"in q&&(p=q.hidden):q=V.access(a,"fxshow",{display:j}),f&&(q.hidden=!p),p&&ga([a],!0),m.done(function(){p||ga([a]),V.remove(a,"fxshow");for(d in n)r.style(a,d,n[d])})),i=db(p?q[d]:0,d,m),d in q||(q[d]=i.start,p&&(i.end=i.start,i.start=0))}}function fb(a,b){var c,d,e,f,g;for(c in a)if(d=r.camelCase(c),e=b[d],f=a[c],r.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=r.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function gb(a,b,c){var d,e,f=0,g=gb.prefilters.length,h=r.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=Ya||bb(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;g<i;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),f<1&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:r.extend({},b),opts:r.extend(!0,{specialEasing:{},easing:r.easing._default},c),originalProperties:b,originalOptions:c,startTime:Ya||bb(),duration:c.duration,tweens:[],createTween:function(b,c){var d=r.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;c<d;c++)j.tweens[c].run(1);return b?(h.notifyWith(a,[j,1,0]),h.resolveWith(a,[j,b])):h.rejectWith(a,[j,b]),this}}),k=j.props;for(fb(k,j.opts.specialEasing);f<g;f++)if(d=gb.prefilters[f].call(j,a,k,j.opts))return r.isFunction(d.stop)&&(r._queueHooks(j.elem,j.opts.queue).stop=r.proxy(d.stop,d)),d;return r.map(k,db,j),r.isFunction(j.opts.start)&&j.opts.start.call(a,j),r.fx.timer(r.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}r.Animation=r.extend(gb,{tweeners:{"*":[function(a,b){var c=this.createTween(a,b);return da(c.elem,a,_.exec(b),c),c}]},tweener:function(a,b){r.isFunction(a)?(b=a,a=["*"]):a=a.match(K);for(var c,d=0,e=a.length;d<e;d++)c=a[d],gb.tweeners[c]=gb.tweeners[c]||[],gb.tweeners[c].unshift(b)},prefilters:[eb],prefilter:function(a,b){b?gb.prefilters.unshift(a):gb.prefilters.push(a)}}),r.speed=function(a,b,c){var e=a&&"object"==typeof a?r.extend({},a):{complete:c||!c&&b||r.isFunction(a)&&a,duration:a,easing:c&&b||b&&!r.isFunction(b)&&b};return r.fx.off||d.hidden?e.duration=0:e.duration="number"==typeof e.duration?e.duration:e.duration in r.fx.speeds?r.fx.speeds[e.duration]:r.fx.speeds._default,null!=e.queue&&e.queue!==!0||(e.queue="fx"),e.old=e.complete,e.complete=function(){r.isFunction(e.old)&&e.old.call(this),e.queue&&r.dequeue(this,e.queue)},e},r.fn.extend({fadeTo:function(a,b,c,d){return this.filter(ba).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=r.isEmptyObject(a),f=r.speed(b,c,d),g=function(){var b=gb(this,r.extend({},a),f);(e||V.get(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=r.timers,g=V.get(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&_a.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));!b&&c||r.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=V.get(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=r.timers,g=d?d.length:0;for(c.finish=!0,r.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;b<g;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),r.each(["toggle","show","hide"],function(a,b){var c=r.fn[b];r.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(cb(b,!0),a,d,e)}}),r.each({slideDown:cb("show"),slideUp:cb("hide"),slideToggle:cb("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){r.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),r.timers=[],r.fx.tick=function(){var a,b=0,c=r.timers;for(Ya=r.now();b<c.length;b++)a=c[b],a()||c[b]!==a||c.splice(b--,1);c.length||r.fx.stop(),Ya=void 0},r.fx.timer=function(a){r.timers.push(a),a()?r.fx.start():r.timers.pop()},r.fx.interval=13,r.fx.start=function(){Za||(Za=a.requestAnimationFrame?a.requestAnimationFrame(ab):a.setInterval(r.fx.tick,r.fx.interval))},r.fx.stop=function(){a.cancelAnimationFrame?a.cancelAnimationFrame(Za):a.clearInterval(Za),Za=null},r.fx.speeds={slow:600,fast:200,_default:400},r.fn.delay=function(b,c){return b=r.fx?r.fx.speeds[b]||b:b,c=c||"fx",this.queue(c,function(c,d){var e=a.setTimeout(c,b);d.stop=function(){a.clearTimeout(e)}})},function(){var a=d.createElement("input"),b=d.createElement("select"),c=b.appendChild(d.createElement("option"));a.type="checkbox",o.checkOn=""!==a.value,o.optSelected=c.selected,a=d.createElement("input"),a.value="t",a.type="radio",o.radioValue="t"===a.value}();var hb,ib=r.expr.attrHandle;r.fn.extend({attr:function(a,b){return S(this,r.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){r.removeAttr(this,a)})}}),r.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return"undefined"==typeof a.getAttribute?r.prop(a,b,c):(1===f&&r.isXMLDoc(a)||(e=r.attrHooks[b.toLowerCase()]||(r.expr.match.bool.test(b)?hb:void 0)),void 0!==c?null===c?void r.removeAttr(a,b):e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:(a.setAttribute(b,c+""),c):e&&"get"in e&&null!==(d=e.get(a,b))?d:(d=r.find.attr(a,b),null==d?void 0:d))},attrHooks:{type:{set:function(a,b){if(!o.radioValue&&"radio"===b&&r.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}},removeAttr:function(a,b){var c,d=0,e=b&&b.match(K); if(e&&1===a.nodeType)while(c=e[d++])a.removeAttribute(c)}}),hb={set:function(a,b,c){return b===!1?r.removeAttr(a,c):a.setAttribute(c,c),c}},r.each(r.expr.match.bool.source.match(/\w+/g),function(a,b){var c=ib[b]||r.find.attr;ib[b]=function(a,b,d){var e,f,g=b.toLowerCase();return d||(f=ib[g],ib[g]=e,e=null!=c(a,b,d)?g:null,ib[g]=f),e}});var jb=/^(?:input|select|textarea|button)$/i,kb=/^(?:a|area)$/i;r.fn.extend({prop:function(a,b){return S(this,r.prop,a,b,arguments.length>1)},removeProp:function(a){return this.each(function(){delete this[r.propFix[a]||a]})}}),r.extend({prop:function(a,b,c){var d,e,f=a.nodeType;if(3!==f&&8!==f&&2!==f)return 1===f&&r.isXMLDoc(a)||(b=r.propFix[b]||b,e=r.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=r.find.attr(a,"tabindex");return b?parseInt(b,10):jb.test(a.nodeName)||kb.test(a.nodeName)&&a.href?0:-1}}},propFix:{"for":"htmlFor","class":"className"}}),o.optSelected||(r.propHooks.selected={get:function(a){var b=a.parentNode;return b&&b.parentNode&&b.parentNode.selectedIndex,null},set:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex)}}),r.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){r.propFix[this.toLowerCase()]=this});var lb=/[\t\r\n\f]/g;function mb(a){return a.getAttribute&&a.getAttribute("class")||""}r.fn.extend({addClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).addClass(a.call(this,b,mb(this)))});if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=mb(c),d=1===c.nodeType&&(" "+e+" ").replace(lb," ")){g=0;while(f=b[g++])d.indexOf(" "+f+" ")<0&&(d+=f+" ");h=r.trim(d),e!==h&&c.setAttribute("class",h)}}return this},removeClass:function(a){var b,c,d,e,f,g,h,i=0;if(r.isFunction(a))return this.each(function(b){r(this).removeClass(a.call(this,b,mb(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof a&&a){b=a.match(K)||[];while(c=this[i++])if(e=mb(c),d=1===c.nodeType&&(" "+e+" ").replace(lb," ")){g=0;while(f=b[g++])while(d.indexOf(" "+f+" ")>-1)d=d.replace(" "+f+" "," ");h=r.trim(d),e!==h&&c.setAttribute("class",h)}}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):r.isFunction(a)?this.each(function(c){r(this).toggleClass(a.call(this,c,mb(this),b),b)}):this.each(function(){var b,d,e,f;if("string"===c){d=0,e=r(this),f=a.match(K)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else void 0!==a&&"boolean"!==c||(b=mb(this),b&&V.set(this,"__className__",b),this.setAttribute&&this.setAttribute("class",b||a===!1?"":V.get(this,"__className__")||""))})},hasClass:function(a){var b,c,d=0;b=" "+a+" ";while(c=this[d++])if(1===c.nodeType&&(" "+mb(c)+" ").replace(lb," ").indexOf(b)>-1)return!0;return!1}});var nb=/\r/g,ob=/[\x20\t\r\n\f]+/g;r.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=r.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,r(this).val()):a,null==e?e="":"number"==typeof e?e+="":r.isArray(e)&&(e=r.map(e,function(a){return null==a?"":a+""})),b=r.valHooks[this.type]||r.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=r.valHooks[e.type]||r.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(nb,""):null==c?"":c)}}}),r.extend({valHooks:{option:{get:function(a){var b=r.find.attr(a,"value");return null!=b?b:r.trim(r.text(a)).replace(ob," ")}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type,g=f?null:[],h=f?e+1:d.length,i=e<0?h:f?e:0;i<h;i++)if(c=d[i],(c.selected||i===e)&&!c.disabled&&(!c.parentNode.disabled||!r.nodeName(c.parentNode,"optgroup"))){if(b=r(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=r.makeArray(b),g=e.length;while(g--)d=e[g],(d.selected=r.inArray(r.valHooks.option.get(d),f)>-1)&&(c=!0);return c||(a.selectedIndex=-1),f}}}}),r.each(["radio","checkbox"],function(){r.valHooks[this]={set:function(a,b){if(r.isArray(b))return a.checked=r.inArray(r(a).val(),b)>-1}},o.checkOn||(r.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var pb=/^(?:focusinfocus|focusoutblur)$/;r.extend(r.event,{trigger:function(b,c,e,f){var g,h,i,j,k,m,n,o=[e||d],p=l.call(b,"type")?b.type:b,q=l.call(b,"namespace")?b.namespace.split("."):[];if(h=i=e=e||d,3!==e.nodeType&&8!==e.nodeType&&!pb.test(p+r.event.triggered)&&(p.indexOf(".")>-1&&(q=p.split("."),p=q.shift(),q.sort()),k=p.indexOf(":")<0&&"on"+p,b=b[r.expando]?b:new r.Event(p,"object"==typeof b&&b),b.isTrigger=f?2:3,b.namespace=q.join("."),b.rnamespace=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=e),c=null==c?[b]:r.makeArray(c,[b]),n=r.event.special[p]||{},f||!n.trigger||n.trigger.apply(e,c)!==!1)){if(!f&&!n.noBubble&&!r.isWindow(e)){for(j=n.delegateType||p,pb.test(j+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),i=h;i===(e.ownerDocument||d)&&o.push(i.defaultView||i.parentWindow||a)}g=0;while((h=o[g++])&&!b.isPropagationStopped())b.type=g>1?j:n.bindType||p,m=(V.get(h,"events")||{})[b.type]&&V.get(h,"handle"),m&&m.apply(h,c),m=k&&h[k],m&&m.apply&&T(h)&&(b.result=m.apply(h,c),b.result===!1&&b.preventDefault());return b.type=p,f||b.isDefaultPrevented()||n._default&&n._default.apply(o.pop(),c)!==!1||!T(e)||k&&r.isFunction(e[p])&&!r.isWindow(e)&&(i=e[k],i&&(e[k]=null),r.event.triggered=p,e[p](),r.event.triggered=void 0,i&&(e[k]=i)),b.result}},simulate:function(a,b,c){var d=r.extend(new r.Event,c,{type:a,isSimulated:!0});r.event.trigger(d,null,b)}}),r.fn.extend({trigger:function(a,b){return this.each(function(){r.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];if(c)return r.event.trigger(a,b,c,!0)}}),r.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(a,b){r.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),r.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),o.focusin="onfocusin"in a,o.focusin||r.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){r.event.simulate(b,a.target,r.event.fix(a))};r.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=V.access(d,b);e||d.addEventListener(a,c,!0),V.access(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=V.access(d,b)-1;e?V.access(d,b,e):(d.removeEventListener(a,c,!0),V.remove(d,b))}}});var qb=a.location,rb=r.now(),sb=/\?/;r.parseXML=function(b){var c;if(!b||"string"!=typeof b)return null;try{c=(new a.DOMParser).parseFromString(b,"text/xml")}catch(d){c=void 0}return c&&!c.getElementsByTagName("parsererror").length||r.error("Invalid XML: "+b),c};var tb=/\[\]$/,ub=/\r?\n/g,vb=/^(?:submit|button|image|reset|file)$/i,wb=/^(?:input|select|textarea|keygen)/i;function xb(a,b,c,d){var e;if(r.isArray(b))r.each(b,function(b,e){c||tb.test(a)?d(a,e):xb(a+"["+("object"==typeof e&&null!=e?b:"")+"]",e,c,d)});else if(c||"object"!==r.type(b))d(a,b);else for(e in b)xb(a+"["+e+"]",b[e],c,d)}r.param=function(a,b){var c,d=[],e=function(a,b){var c=r.isFunction(b)?b():b;d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(null==c?"":c)};if(r.isArray(a)||a.jquery&&!r.isPlainObject(a))r.each(a,function(){e(this.name,this.value)});else for(c in a)xb(c,a[c],b,e);return d.join("&")},r.fn.extend({serialize:function(){return r.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=r.prop(this,"elements");return a?r.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!r(this).is(":disabled")&&wb.test(this.nodeName)&&!vb.test(a)&&(this.checked||!ha.test(a))}).map(function(a,b){var c=r(this).val();return null==c?null:r.isArray(c)?r.map(c,function(a){return{name:b.name,value:a.replace(ub,"\r\n")}}):{name:b.name,value:c.replace(ub,"\r\n")}}).get()}});var yb=/%20/g,zb=/#.*$/,Ab=/([?&])_=[^&]*/,Bb=/^(.*?):[ \t]*([^\r\n]*)$/gm,Cb=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Db=/^(?:GET|HEAD)$/,Eb=/^\/\//,Fb={},Gb={},Hb="*/".concat("*"),Ib=d.createElement("a");Ib.href=qb.href;function Jb(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(K)||[];if(r.isFunction(c))while(d=f[e++])"+"===d[0]?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Kb(a,b,c,d){var e={},f=a===Gb;function g(h){var i;return e[h]=!0,r.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Lb(a,b){var c,d,e=r.ajaxSettings.flatOptions||{};for(c in b)void 0!==b[c]&&((e[c]?a:d||(d={}))[c]=b[c]);return d&&r.extend(!0,a,d),a}function Mb(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===d&&(d=a.mimeType||b.getResponseHeader("Content-Type"));if(d)for(e in h)if(h[e]&&h[e].test(d)){i.unshift(e);break}if(i[0]in c)f=i[0];else{for(e in c){if(!i[0]||a.converters[e+" "+i[0]]){f=e;break}g||(g=e)}f=f||g}if(f)return f!==i[0]&&i.unshift(f),c[f]}function Nb(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}r.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:qb.href,type:"GET",isLocal:Cb.test(qb.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Hb,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":r.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Lb(Lb(a,r.ajaxSettings),b):Lb(r.ajaxSettings,a)},ajaxPrefilter:Jb(Fb),ajaxTransport:Jb(Gb),ajax:function(b,c){"object"==typeof b&&(c=b,b=void 0),c=c||{};var e,f,g,h,i,j,k,l,m,n,o=r.ajaxSetup({},c),p=o.context||o,q=o.context&&(p.nodeType||p.jquery)?r(p):r.event,s=r.Deferred(),t=r.Callbacks("once memory"),u=o.statusCode||{},v={},w={},x="canceled",y={readyState:0,getResponseHeader:function(a){var b;if(k){if(!h){h={};while(b=Bb.exec(g))h[b[1].toLowerCase()]=b[2]}b=h[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return k?g:null},setRequestHeader:function(a,b){return null==k&&(a=w[a.toLowerCase()]=w[a.toLowerCase()]||a,v[a]=b),this},overrideMimeType:function(a){return null==k&&(o.mimeType=a),this},statusCode:function(a){var b;if(a)if(k)y.always(a[y.status]);else for(b in a)u[b]=[u[b],a[b]];return this},abort:function(a){var b=a||x;return e&&e.abort(b),A(0,b),this}};if(s.promise(y),o.url=((b||o.url||qb.href)+"").replace(Eb,qb.protocol+"//"),o.type=c.method||c.type||o.method||o.type,o.dataTypes=(o.dataType||"*").toLowerCase().match(K)||[""],null==o.crossDomain){j=d.createElement("a");try{j.href=o.url,j.href=j.href,o.crossDomain=Ib.protocol+"//"+Ib.host!=j.protocol+"//"+j.host}catch(z){o.crossDomain=!0}}if(o.data&&o.processData&&"string"!=typeof o.data&&(o.data=r.param(o.data,o.traditional)),Kb(Fb,o,c,y),k)return y;l=r.event&&o.global,l&&0===r.active++&&r.event.trigger("ajaxStart"),o.type=o.type.toUpperCase(),o.hasContent=!Db.test(o.type),f=o.url.replace(zb,""),o.hasContent?o.data&&o.processData&&0===(o.contentType||"").indexOf("application/x-www-form-urlencoded")&&(o.data=o.data.replace(yb,"+")):(n=o.url.slice(f.length),o.data&&(f+=(sb.test(f)?"&":"?")+o.data,delete o.data),o.cache===!1&&(f=f.replace(Ab,""),n=(sb.test(f)?"&":"?")+"_="+rb++ +n),o.url=f+n),o.ifModified&&(r.lastModified[f]&&y.setRequestHeader("If-Modified-Since",r.lastModified[f]),r.etag[f]&&y.setRequestHeader("If-None-Match",r.etag[f])),(o.data&&o.hasContent&&o.contentType!==!1||c.contentType)&&y.setRequestHeader("Content-Type",o.contentType),y.setRequestHeader("Accept",o.dataTypes[0]&&o.accepts[o.dataTypes[0]]?o.accepts[o.dataTypes[0]]+("*"!==o.dataTypes[0]?", "+Hb+"; q=0.01":""):o.accepts["*"]);for(m in o.headers)y.setRequestHeader(m,o.headers[m]);if(o.beforeSend&&(o.beforeSend.call(p,y,o)===!1||k))return y.abort();if(x="abort",t.add(o.complete),y.done(o.success),y.fail(o.error),e=Kb(Gb,o,c,y)){if(y.readyState=1,l&&q.trigger("ajaxSend",[y,o]),k)return y;o.async&&o.timeout>0&&(i=a.setTimeout(function(){y.abort("timeout")},o.timeout));try{k=!1,e.send(v,A)}catch(z){if(k)throw z;A(-1,z)}}else A(-1,"No Transport");function A(b,c,d,h){var j,m,n,v,w,x=c;k||(k=!0,i&&a.clearTimeout(i),e=void 0,g=h||"",y.readyState=b>0?4:0,j=b>=200&&b<300||304===b,d&&(v=Mb(o,y,d)),v=Nb(o,v,y,j),j?(o.ifModified&&(w=y.getResponseHeader("Last-Modified"),w&&(r.lastModified[f]=w),w=y.getResponseHeader("etag"),w&&(r.etag[f]=w)),204===b||"HEAD"===o.type?x="nocontent":304===b?x="notmodified":(x=v.state,m=v.data,n=v.error,j=!n)):(n=x,!b&&x||(x="error",b<0&&(b=0))),y.status=b,y.statusText=(c||x)+"",j?s.resolveWith(p,[m,x,y]):s.rejectWith(p,[y,x,n]),y.statusCode(u),u=void 0,l&&q.trigger(j?"ajaxSuccess":"ajaxError",[y,o,j?m:n]),t.fireWith(p,[y,x]),l&&(q.trigger("ajaxComplete",[y,o]),--r.active||r.event.trigger("ajaxStop")))}return y},getJSON:function(a,b,c){return r.get(a,b,c,"json")},getScript:function(a,b){return r.get(a,void 0,b,"script")}}),r.each(["get","post"],function(a,b){r[b]=function(a,c,d,e){return r.isFunction(c)&&(e=e||d,d=c,c=void 0),r.ajax(r.extend({url:a,type:b,dataType:e,data:c,success:d},r.isPlainObject(a)&&a))}}),r._evalUrl=function(a){return r.ajax({url:a,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,"throws":!0})},r.fn.extend({wrapAll:function(a){var b;return this[0]&&(r.isFunction(a)&&(a=a.call(this[0])),b=r(a,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstElementChild)a=a.firstElementChild;return a}).append(this)),this},wrapInner:function(a){return r.isFunction(a)?this.each(function(b){r(this).wrapInner(a.call(this,b))}):this.each(function(){var b=r(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=r.isFunction(a);return this.each(function(c){r(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(a){return this.parent(a).not("body").each(function(){r(this).replaceWith(this.childNodes)}),this}}),r.expr.pseudos.hidden=function(a){return!r.expr.pseudos.visible(a)},r.expr.pseudos.visible=function(a){return!!(a.offsetWidth||a.offsetHeight||a.getClientRects().length)},r.ajaxSettings.xhr=function(){try{return new a.XMLHttpRequest}catch(b){}};var Ob={0:200,1223:204},Pb=r.ajaxSettings.xhr();o.cors=!!Pb&&"withCredentials"in Pb,o.ajax=Pb=!!Pb,r.ajaxTransport(function(b){var c,d;if(o.cors||Pb&&!b.crossDomain)return{send:function(e,f){var g,h=b.xhr();if(h.open(b.type,b.url,b.async,b.username,b.password),b.xhrFields)for(g in b.xhrFields)h[g]=b.xhrFields[g];b.mimeType&&h.overrideMimeType&&h.overrideMimeType(b.mimeType),b.crossDomain||e["X-Requested-With"]||(e["X-Requested-With"]="XMLHttpRequest");for(g in e)h.setRequestHeader(g,e[g]);c=function(a){return function(){c&&(c=d=h.onload=h.onerror=h.onabort=h.onreadystatechange=null,"abort"===a?h.abort():"error"===a?"number"!=typeof h.status?f(0,"error"):f(h.status,h.statusText):f(Ob[h.status]||h.status,h.statusText,"text"!==(h.responseType||"text")||"string"!=typeof h.responseText?{binary:h.response}:{text:h.responseText},h.getAllResponseHeaders()))}},h.onload=c(),d=h.onerror=c("error"),void 0!==h.onabort?h.onabort=d:h.onreadystatechange=function(){4===h.readyState&&a.setTimeout(function(){c&&d()})},c=c("abort");try{h.send(b.hasContent&&b.data||null)}catch(i){if(c)throw i}},abort:function(){c&&c()}}}),r.ajaxPrefilter(function(a){a.crossDomain&&(a.contents.script=!1)}),r.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(a){return r.globalEval(a),a}}}),r.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET")}),r.ajaxTransport("script",function(a){if(a.crossDomain){var b,c;return{send:function(e,f){b=r("<script>").prop({charset:a.scriptCharset,src:a.url}).on("load error",c=function(a){b.remove(),c=null,a&&f("error"===a.type?404:200,a.type)}),d.head.appendChild(b[0])},abort:function(){c&&c()}}}});var Qb=[],Rb=/(=)\?(?=&|$)|\?\?/;r.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=Qb.pop()||r.expando+"_"+rb++;return this[a]=!0,a}}),r.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(Rb.test(b.url)?"url":"string"==typeof b.data&&0===(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&Rb.test(b.data)&&"data");if(h||"jsonp"===b.dataTypes[0])return e=b.jsonpCallback=r.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(Rb,"$1"+e):b.jsonp!==!1&&(b.url+=(sb.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||r.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){void 0===f?r(a).removeProp(e):a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,Qb.push(e)),g&&r.isFunction(f)&&f(g[0]),g=f=void 0}),"script"}),o.createHTMLDocument=function(){var a=d.implementation.createHTMLDocument("").body;return a.innerHTML="<form></form><form></form>",2===a.childNodes.length}(),r.parseHTML=function(a,b,c){if("string"!=typeof a)return[];"boolean"==typeof b&&(c=b,b=!1);var e,f,g;return b||(o.createHTMLDocument?(b=d.implementation.createHTMLDocument(""),e=b.createElement("base"),e.href=d.location.href,b.head.appendChild(e)):b=d),f=B.exec(a),g=!c&&[],f?[b.createElement(f[1])]:(f=oa([a],b,g),g&&g.length&&r(g).remove(),r.merge([],f.childNodes))},r.fn.load=function(a,b,c){var d,e,f,g=this,h=a.indexOf(" ");return h>-1&&(d=r.trim(a.slice(h)),a=a.slice(0,h)),r.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(e="POST"),g.length>0&&r.ajax({url:a,type:e||"GET",dataType:"html",data:b}).done(function(a){f=arguments,g.html(d?r("<div>").append(r.parseHTML(a)).find(d):a)}).always(c&&function(a,b){g.each(function(){c.apply(this,f||[a.responseText,b,a])})}),this},r.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){r.fn[b]=function(a){return this.on(b,a)}}),r.expr.pseudos.animated=function(a){return r.grep(r.timers,function(b){return a===b.elem}).length};function Sb(a){return r.isWindow(a)?a:9===a.nodeType&&a.defaultView}r.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=r.css(a,"position"),l=r(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=r.css(a,"top"),i=r.css(a,"left"),j=("absolute"===k||"fixed"===k)&&(f+i).indexOf("auto")>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),r.isFunction(b)&&(b=b.call(a,c,r.extend({},h))),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},r.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){r.offset.setOffset(this,a,b)});var b,c,d,e,f=this[0];if(f)return f.getClientRects().length?(d=f.getBoundingClientRect(),d.width||d.height?(e=f.ownerDocument,c=Sb(e),b=e.documentElement,{top:d.top+c.pageYOffset-b.clientTop,left:d.left+c.pageXOffset-b.clientLeft}):d):{top:0,left:0}},position:function(){if(this[0]){var a,b,c=this[0],d={top:0,left:0};return"fixed"===r.css(c,"position")?b=c.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),r.nodeName(a[0],"html")||(d=a.offset()),d={top:d.top+r.css(a[0],"borderTopWidth",!0),left:d.left+r.css(a[0],"borderLeftWidth",!0)}),{top:b.top-d.top-r.css(c,"marginTop",!0),left:b.left-d.left-r.css(c,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent;while(a&&"static"===r.css(a,"position"))a=a.offsetParent;return a||pa})}}),r.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c="pageYOffset"===b;r.fn[a]=function(d){return S(this,function(a,d,e){var f=Sb(a);return void 0===e?f?f[b]:a[d]:void(f?f.scrollTo(c?f.pageXOffset:e,c?e:f.pageYOffset):a[d]=e)},a,d,arguments.length)}}),r.each(["top","left"],function(a,b){r.cssHooks[b]=Na(o.pixelPosition,function(a,c){if(c)return c=Ma(a,b),Ka.test(c)?r(a).position()[b]+"px":c})}),r.each({Height:"height",Width:"width"},function(a,b){r.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){r.fn[d]=function(e,f){var g=arguments.length&&(c||"boolean"!=typeof e),h=c||(e===!0||f===!0?"margin":"border");return S(this,function(b,c,e){var f;return r.isWindow(b)?0===d.indexOf("outer")?b["inner"+a]:b.document.documentElement["client"+a]:9===b.nodeType?(f=b.documentElement,Math.max(b.body["scroll"+a],f["scroll"+a],b.body["offset"+a],f["offset"+a],f["client"+a])):void 0===e?r.css(b,c,h):r.style(b,c,e,h)},b,g?e:void 0,g)}})}),r.fn.extend({bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}}),r.parseJSON=JSON.parse,"function"==typeof define&&define.amd&&define("jquery",[],function(){return r});var Tb=a.jQuery,Ub=a.$;return r.noConflict=function(b){return a.$===r&&(a.$=Ub),b&&a.jQuery===r&&(a.jQuery=Tb),r},b||(a.jQuery=a.$=r),r});
H5C3JS/hxsd
1606/三阶/week2/day03/js/jquery-3.1.0.min.js
JavaScript
apache-2.0
86,351