repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
PiotrDabkowski/Js2Py | tests/test_cases/language/keywords/S7.6.1.1_A1.13.js | 299 | // Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
info: The "in" token can not be used as identifier
es5id: 7.6.1.1_A1.13
description: Checking if execution of "in=1" fails
negative: SyntaxError
---*/
in = 1;
| mit |
eric-seekas/jquery-builder | dist/1.8.3/jquery-ajax-dimensions-effects.js | 217443 | /*!
* jQuery JavaScript Library v1.8.3 -ajax,-ajax/jsonp,-ajax/script,-ajax/xhr,-effects,-dimensions
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: Thu Feb 07 2013 15:58:11 GMT-0600 (CST)
*/
(function( window, undefined ) {
var
// A central reference to the root jQuery(document)
rootjQuery,
// The deferred used on DOM ready
readyList,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
location = window.location,
navigator = window.navigator,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Save a reference to some core methods
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
// Used for detecting and trimming whitespace
core_rnotwhite = /\S/,
core_rspace = /\s+/,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// The ready event handler and self cleanup method
DOMContentLoaded = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
} else if ( document.readyState === "complete" ) {
// we're here because readyState === "complete" in oldIE
// which is good enough for us to call the dom ready!
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
},
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context && context.nodeType ? context.ownerDocument || context : document );
// scripts is true for back-compat
selector = jQuery.parseHTML( match[1], doc, true );
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
this.attr.call( selector, context, true );
}
return jQuery.merge( this, selector );
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.8.3 -ajax,-ajax/jsonp,-ajax/script,-ajax/xhr,-effects,-dimensions",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ),
"slice", core_slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ core_toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// scripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, scripts ) {
var parsed;
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
scripts = context;
context = 0;
}
context = context || document;
// Single tag
if ( (parsed = rsingleTag.exec( data )) ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts ? null : [] );
return jQuery.merge( [],
(parsed.cacheable ? jQuery.clone( parsed.fragment ) : parsed.fragment).childNodes );
},
parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && core_rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var name,
i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction( obj );
if ( args ) {
if ( isObj ) {
for ( name in obj ) {
if ( callback.apply( obj[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( obj[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in obj ) {
if ( callback.call( obj[ name ], name, obj[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( obj[ i ], i, obj[ i++ ] ) === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var type,
ret = results || [];
if ( arr != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
type = jQuery.type( arr );
if ( arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( arr ) ) {
core_push.call( ret, arr );
} else {
jQuery.merge( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key,
ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready, 1 );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.split( core_rspace ), function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
return jQuery.inArray( fn, list ) > -1;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ]( jQuery.isFunction( fn ) ?
function() {
var returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
} :
newDefer[ action ]
);
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ] = list.fire
deferred[ tuple[0] ] = list.fire;
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
eventName,
i,
isSupported,
clickFn,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Support tests won't run in some limited or non-browser environments
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[ 0 ];
if ( !all || !a || !all.length ) {
return {};
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.5/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form (#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode
boxModel: ( document.compatMode === "CSS1Compat" ),
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", clickFn = function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent("onclick");
div.detachEvent( "onclick", clickFn );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
input.setAttribute( "checked", "checked" );
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
// Run tests that need a body at doc ready
jQuery(function() {
var container, div, tds, marginDiv,
divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = ( div.offsetWidth === 4 );
support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 );
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild( marginDiv );
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
container.style.zoom = 1;
}
// Null elements to avoid leaks in IE
body.removeChild( container );
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
fragment.removeChild( div );
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
// Remove at next major release (1.9/2.0)
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( !name.indexOf( "data-" ) ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery.removeData( elem, type + "queue", true );
jQuery.removeData( elem, key, true );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook, fixSpecified,
rclass = /[\t\r\n]/g,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea|)$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( setClass.indexOf( " " + classNames[ c ] + " " ) < 0 ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var removes, className, elem, c, cl, i, l;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
removes = ( value || "" ).split( core_rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
className = (" " + elem.className + " ").replace( rclass, " " );
// loop over each item in the removal list
for ( c = 0, cl = removes.length; c < cl; c++ ) {
// Remove until there is nothing to remove,
while ( className.indexOf(" " + removes[ c ] + " ") >= 0 ) {
className = className.replace( " " + removes[ c ] + " " , " " );
}
}
elem.className = value ? jQuery.trim( className ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( core_rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val,
self = jQuery(this);
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
// Unused in 1.8, left in so attrFn-stabbers won't die; remove in 1.9
attrFn: {},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && jQuery.isFunction( jQuery.fn[ name ] ) ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.split( core_rspace );
for ( ; i < attrNames.length; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.value !== "" : ret.specified ) ?
ret.value :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.value = value + "" );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*|)(?:\.(.+)|)$/,
rhoverHack = /(?:^|\s)hover(\.\S+|)\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var t, tns, type, origType, namespaces, origCount,
j, events, special, eventType, handleObj,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, "events", true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType,
type = event.type || event,
namespaces = [];
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
for ( old = elem; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old === (elem.ownerDocument || document) ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related,
handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call( arguments ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [];
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process clicks (ONLY) on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
selMatch = {};
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328; IE6/7/8)
event.metaKey = !!event.metaKey;
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === "undefined" ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "_submit_attached" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "_submit_attached", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "_change_attached" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "_change_attached", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2012 jQuery Foundation and other contributors
* Released under the MIT license
* http://sizzlejs.com/
*/
(function( window, undefined ) {
var i,
cachedruns,
Expr,
getText,
isXML,
compile,
hasDuplicate,
outermostContext,
// Local document vars
setDocument,
document,
docElem,
documentIsXML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
sortOrder,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
support = {},
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Array methods
arr = [],
pop = arr.pop,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rsibling = /[\x20\t\r\n\f]*[+~]/,
rnative = /\{\s*\[native code\]\s*\}/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,
funescape = function( _, escaped ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
return high !== high ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Use a stripped-down slice if we can't use a native one
try {
slice.call( docElem.childNodes, 0 )[0].nodeType;
} catch ( e ) {
slice = function( i ) {
var elem,
results = [];
for ( ; (elem = this[i]); i++ ) {
results.push( elem );
}
return results;
};
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var cache,
keys = [];
return (cache = function( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
});
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return fn( div );
} catch (e) {
return false;
} finally {
// release memory in IE
div = null;
}
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( !documentIsXML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) {
push.apply( results, slice.call(context.getElementsByClassName( m ), 0) );
return results;
}
}
// QSA path
if ( support.qsa && !rbuggyQSA.test(selector) ) {
old = true;
nid = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results, slice.call( newContext.querySelectorAll(
newSelector
), 0 ) );
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsXML = isXML( doc );
// Check if getElementsByTagName("*") returns only elements
support.tagNameNoComments = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if attributes should be retrieved by attribute nodes
support.attributes = assert(function( div ) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
// IE8 returns a string for some attributes even when not present
return type !== "boolean" && type !== "string";
});
// Check if getElementsByClassName can be trusted
support.getByClassName = assert(function( div ) {
// Opera can't find a second classname (in 9.6)
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) {
return false;
}
// Safari 3.2 caches class attributes and doesn't catch changes
div.lastChild.className = "e";
return div.getElementsByClassName("e").length === 2;
});
// Check if getElementById returns elements by name
// Check if getElementsByName privileges form controls or returns elements by ID
support.getByName = assert(function( div ) {
// Inject content
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore( div, docElem.firstChild );
// Test
var pass = doc.getElementsByName &&
// buggy browsers will return fewer than the correct 2
doc.getElementsByName( expando ).length === 2 +
// buggy browsers will return more than the correct 0
doc.getElementsByName( expando + 0 ).length;
support.getIdNotName = !doc.getElementById( expando );
// Cleanup
docElem.removeChild( div );
return pass;
});
// IE6/7 return modified attributes
Expr.attrHandle = assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined &&
div.firstChild.getAttribute("href") === "#";
}) ?
{} :
{
"href": function( elem ) {
return elem.getAttribute( "href", 2 );
},
"type": function( elem ) {
return elem.getAttribute("type");
}
};
// ID find and filter
if ( support.getIdNotName ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && !documentIsXML ) {
var m = context.getElementById( id );
return m ?
m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ?
[m] :
undefined :
[];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.tagNameNoComments ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Name
Expr.find["NAME"] = support.getByName && function( tag, context ) {
if ( typeof context.getElementsByName !== strundefined ) {
return context.getElementsByName( name );
}
};
// Class
Expr.find["CLASS"] = support.getByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) {
return context.getElementsByClassName( className );
}
};
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21),
// no need to also add to buggyMatches since matches checks buggyQSA
// A support test would require too much code (would include document ready)
rbuggyQSA = [ ":focus" ];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explictly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// IE8 - Some boolean attributes are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Opera 10-12/IE8 - ^= $= *= and empty values
// Should not select anything
div.innerHTML = "<input type='hidden' i=''/>";
if ( div.querySelectorAll("[i^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector ||
docElem.mozMatchesSelector ||
docElem.webkitMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = new RegExp( rbuggyMatches.join("|") );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
var compare;
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) {
if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) {
if ( a === doc || contains( preferredDoc, a ) ) {
return -1;
}
if ( b === doc || contains( preferredDoc, b ) ) {
return 1;
}
return 0;
}
return compare & 4 ? -1 : 1;
}
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return ( ~b.sourceIndex || MAX_NEGATIVE ) - ( contains( preferredDoc, a ) && ~a.sourceIndex || MAX_NEGATIVE );
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
// Always assume the presence of duplicates if sort doesn't
// pass them to our comparison function (as in Google Chrome).
hasDuplicate = false;
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
return document;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
// rbuggyQSA always contains :focus, so no need for an existence check
if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
var val;
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
if ( !documentIsXML ) {
name = name.toLowerCase();
}
if ( (val = Expr.attrHandle[ name ]) ) {
return val( elem );
}
if ( documentIsXML || support.attributes ) {
return elem.getAttribute( name );
}
return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ?
name :
val && val.specified ? val.value : null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
// Document sorting and removing duplicates
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
function siblingCheck( a, b ) {
var cur = a && b && a.nextSibling;
for ( ; cur; cur = cur.nextSibling ) {
if ( cur === b ) {
return -1;
}
}
return a ? 1 : -1;
}
// Returns a function to use in pseudos for input types
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
// Returns a function to use in pseudos for buttons
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
// Returns a function to use in pseudos for positionals
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[4] ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeName ) {
if ( nodeName === "*" ) {
return function() { return true; };
}
nodeName = nodeName.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.substr( result.length - check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.substr( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifider
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsXML ?
elem.getAttribute("xml:lang") || elem.getAttribute("lang") :
elem.lang) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push( {
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
} );
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push( {
value: matched,
type: type,
matches: match
} );
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Nested matchers should use non-integer dirruns
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
for ( j = 0; (matcher = elementMatchers[j]); j++ ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
// `i` starts as a string, so matchedCount would equal "00" if there are no elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
for ( j = 0; (matcher = setMatchers[j]); j++ ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
context.nodeType === 9 && !documentIsXML &&
Expr.relative[ tokens[1].type ] ) {
context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
for ( i = matchExpr["needsContext"].test( selector ) ? -1 : tokens.length - 1; i >= 0; i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, slice.call( seed, 0 ) );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
documentIsXML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
// Initialize with the default document
setDocument();
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i, l, length, n, r, ret,
self = this;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
ret = this.pushStack( "", "find", selector );
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
rneedsContext.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
cur = this[i];
while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( this.length > 1 && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, core_slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "X<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( set, this ), "before", this.selector );
}
},
after: function() {
if ( !isDisconnected( this[0] ) ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
}
if ( arguments.length ) {
var set = jQuery.clean( arguments );
return this.pushStack( jQuery.merge( this, set ), "after", this.selector );
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( !isDisconnected( this[0] ) ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
}
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
// Flatten any nested arrays
args = [].concat.apply( [], args );
var results, first, fragment, iNoClone,
i = 0,
value = args[0],
scripts = [],
l = this.length;
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call( this, i, table ? self.html() : undefined );
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
results = jQuery.buildFragment( args, this, scripts );
fragment = results.fragment;
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
// Fragments from the fragment cache must always be cloned and never used in place.
for ( iNoClone = results.cacheable || l - 1; i < l; i++ ) {
callback.call(
table && jQuery.nodeName( this[i], "table" ) ?
findOrAppend( this[i], "tbody" ) :
this[i],
i === iNoClone ?
fragment :
jQuery.clone( fragment, true, true )
);
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
if ( jQuery.ajax ) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function findOrAppend( elem, tag ) {
return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) );
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
if ( nodeName === "object" ) {
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML)) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
}
jQuery.buildFragment = function( args, context, scripts ) {
var fragment, cacheable, cachehit,
first = args[ 0 ];
// Set context from what may come in as undefined or a jQuery collection or a node
// Updated to fix #12266 where accessing context[0] could throw an exception in IE9/10 &
// also doubles as fix for #8950 where plain objects caused createDocumentFragment exception
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && context === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
// Mark cacheable and look for a hit
cacheable = true;
fragment = jQuery.fragments[ first ];
cachehit = fragment !== undefined;
}
if ( !fragment ) {
fragment = context.createDocumentFragment();
jQuery.clean( args, context, fragment, scripts );
// Update the cache, but only store false
// unless this is a second parsing of the same content
if ( cacheable ) {
jQuery.fragments[ first ] = cachehit && fragment;
}
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ( (parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( ; i < l; i++ ) {
elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
clone;
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags,
safe = context === document && safeFragment,
ret = [];
// Ensure that context is a document
if ( !context || typeof context.createDocumentFragment === "undefined" ) {
context = document;
}
// Use the already-created safe fragment if context permits
for ( i = 0; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Ensure a safe container in which to render the html
safe = safe || createSafeFragment( context );
div = context.createElement("div");
safe.appendChild( div );
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Go to html and back, then peel off extra wrappers
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Take out of fragment container (we need a fresh div each time)
div.parentNode.removeChild( div );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
jQuery.merge( ret, elem );
}
}
// Fix #11356: Clear elements from safeFragment
if ( div ) {
elem = div = safe = null;
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
for ( i = 0; (elem = ret[i]) != null; i++ ) {
if ( jQuery.nodeName( elem, "input" ) ) {
fixDefaultChecked( elem );
} else if ( typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
}
// Append elements to a provided document fragment
if ( fragment ) {
// Special handling of each script element
handleScript = function( elem ) {
// Check if we consider it executable
if ( !elem.type || rscriptType.test( elem.type ) ) {
// Detach the script and store it in the scripts array (if provided) or the fragment
// Return truthy to indicate that it has been handled
return scripts ?
scripts.push( elem.parentNode ? elem.parentNode.removeChild( elem ) : elem ) :
fragment.appendChild( elem );
}
};
for ( i = 0; (elem = ret[i]) != null; i++ ) {
// Check if we're done after handling an executable script
if ( !( jQuery.nodeName( elem, "script" ) && handleScript( elem ) ) ) {
// Append to fragment and handle embedded scripts
fragment.appendChild( elem );
if ( typeof elem.getElementsByTagName !== "undefined" ) {
// handleScript alters the DOM, so use jQuery.merge to ensure snapshot iteration
jsTags = jQuery.grep( jQuery.merge( [], elem.getElementsByTagName("script") ), handleScript );
// Splice the scripts into ret after their former ancestor and advance our index beyond them
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function( elems, /* internal */ acceptData ) {
var data, id, elem, type,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
jQuery.deletedIds.push( id );
}
}
}
}
}
});
// Limit scope pollution from any deprecated API
(function() {
var matched, browser;
// Use of jQuery.browser is frowned upon.
// More details: http://api.jquery.com/jQuery.browser
// jQuery.uaMatch maintained for back-compat
jQuery.uaMatch = function( ua ) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) ||
/(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) ||
[];
return {
browser: match[ 1 ] || "",
version: match[ 2 ] || "0"
};
};
matched = jQuery.uaMatch( navigator.userAgent );
browser = {};
if ( matched.browser ) {
browser[ matched.browser ] = true;
browser.version = matched.version;
}
// Chrome is Webkit, but Webkit is also Safari.
if ( browser.chrome ) {
browser.webkit = true;
} else if ( browser.webkit ) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.sub = function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
};
})();
var curCSS, iframe, iframeDoc,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// 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]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([-+])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ],
eventsToggle = jQuery.fn.toggle;
// 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.charAt(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 isHidden( elem, el ) {
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var elem, display,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && elem.style.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 ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
display = curCSS( elem, "display" );
if ( !values[ index ] && display !== "none" ) {
jQuery._data( elem, "olddisplay", 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.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
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, fn2 ) {
var bool = typeof state === "boolean";
if ( jQuery.isFunction( state ) && jQuery.isFunction( fn2 ) ) {
return eventsToggle.apply( this, arguments );
}
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
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;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": 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: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// 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
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= 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 NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// 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 ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} 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, numeric, extra ) {
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 ) );
// gets hook for the prefixed version
// followed by the unprefixed version
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 );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( numeric || extra !== undefined ) {
num = parseFloat( val );
return numeric || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// NOTE: To any future maintainer, we've window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
curCSS = function( elem, name ) {
var ret, width, minWidth, maxWidth,
computed = window.getComputedStyle( elem, null ),
style = elem.style;
if ( computed ) {
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed.getPropertyValue( name ) || computed[ name ];
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
curCSS = function( elem, name ) {
var left, rsLeft,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox ) {
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" ) {
// we use jQuery.css instead of curCSS here
// because of the reliableMarginRight CSS hook!
val += jQuery.css( elem, extra + cssExpand[ i ], true );
}
// From this point on we use curCSS for maximum performance (relevant in animations)
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
} else {
// at this point, extra isn't content, so add padding
val += parseFloat( curCSS( elem, "padding" + cssExpand[ i ] ) ) || 0;
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += parseFloat( curCSS( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "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 );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.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
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
if ( elemdisplay[ nodeName ] ) {
return elemdisplay[ nodeName ];
}
var elem = jQuery( "<" + nodeName + ">" ).appendTo( document.body ),
display = elem.css("display");
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// Use the already-created iframe if possible
iframe = document.body.appendChild(
iframe || jQuery.extend( document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
})
);
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild( iframeDoc.createElement(nodeName) );
display = curCSS( elem, "display" );
document.body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
return display;
}
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
// however, it must have a current display style that would benefit from this
if ( elem.offsetWidth === 0 && rdisplayswap.test( curCSS( elem, "display" ) ) ) {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
} else {
return getWidthOrHeight( elem, name, extra );
}
}
},
set: function( elem, value, extra ) {
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing" ) === "border-box"
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "marginRight" );
}
});
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
var ret = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( ret ) ? jQuery( elem ).position()[ prop ] + "px" : ret;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
return ( elem.offsetWidth === 0 && elem.offsetHeight === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// 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,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; 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;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
if ( (body = doc.body) === elem ) {
return jQuery.offset.bodyOffset( elem );
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== "undefined" ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || document.body;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
| mit |
xtrasmal/adaptive-speech | demo/js/controllers/todoCtrl.js | 5691 | /*global todomvc */
(function () {
'use strict';
/**
* The main controller for the app. The controller:
* - retrieves and persists the model via the todoStorage service
* - exposes the model to the template and provides event handlers
*/
todomvc.controller('TodoCtrl', function TodoCtrl($scope, $location, todoStorage, filterFilter, $speechRecognition) {
var todos = $scope.todos = todoStorage.get();
$scope.newTodo = '';
$scope.remainingCount = filterFilter(todos, {completed: false}).length;
$scope.editedTodo = null;
if ($location.path() === '') {
$location.path('/');
}
$scope.location = $location;
$scope.$watch('location.path()', function (path) {
$scope.statusFilter = (path === '/active') ?
{ completed: false } : (path === '/completed') ?
{ completed: true } : null;
});
$scope.$watch('remainingCount == 0', function (val) {
$scope.allChecked = val;
});
$scope.addTodo = function () {
var newTodo = $scope.newTodo.trim();
console.log(newTodo);
if (newTodo.length === 0) {
return;
}
todos.push({
title: newTodo,
completed: false
});
todoStorage.put(todos);
console.log(todos);
$scope.newTodo = '';
$scope.remainingCount++;
};
$scope.editTodo = function (todo) {
$scope.editedTodo = todo;
};
$scope.doneEditing = function (todo) {
$scope.editedTodo = null;
todo.title = todo.title.trim();
if (!todo.title) {
$scope.removeTodo(todo);
}
todoStorage.put(todos);
};
$scope.removeTodo = function (todo) {
$scope.remainingCount -= todo.completed ? 0 : 1;
todos.splice(todos.indexOf(todo), 1);
todoStorage.put(todos);
};
$scope.todoCompleted = function (todo) {
if (todo.completed) {
$scope.remainingCount--;
} else {
$scope.remainingCount++;
}
todoStorage.put(todos);
};
$scope.clearCompletedTodos = function () {
$scope.todos = todos = todos.filter(function (val) {
return !val.completed;
});
todoStorage.put(todos);
};
$scope.markAll = function (completed) {
todos.forEach(function (todo) {
todo.completed = completed;
});
$scope.remainingCount = completed ? 0 : todos.length;
todoStorage.put(todos);
};
/**
* Need to be added for speech recognition
*/
var findTodo = function(title){
for (var i=0; i<todos.length; i++){
if (todos[i].title === title) {
return todos[i];
}
}
return null;
};
var completeTodo = function(title){
for (var i=0; i<todos.length; i++){
if (todos[i].title === title) {
todos[i].completed = ! todos[i].completed;
$scope.todoCompleted(todos[i]);
$scope.$apply();
return true;
}
}
};
var LANG = 'en-US';
$speechRecognition.onstart(function(e){
$speechRecognition.speak('Yes? How can I help you?');
});
$speechRecognition.onerror(function(e){
var error = (e.error || '');
alert('An error occurred ' + error);
});
$speechRecognition.payAttention();
// $speechRecognition.setLang(LANG);
$speechRecognition.listen();
$scope.recognition = {};
$scope.recognition['en-US'] = {
'addToList': {
'regex': /^do .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
$scope.newTodo = parts.slice(1).join(' ');
$scope.addTodo();
$scope.$apply();
}
}
},
'show-all': {
'regex': /show.*all/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/');
$scope.$apply();
}
},
'show-active': {
'regex': /show.*active/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/active');
$scope.$apply();
}
},
'show-completed': {
'regex': /show.*complete/gi,
'lang': 'en-US',
'call': function(utterance){
$location.path('/completed');
$scope.$apply();
}
},
'mark-all': {
'regex': /^mark/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.markAll(1);
$scope.$apply();
}
},
'unmark-all': {
'regex': /^unmark/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.markAll(1);
$scope.$apply();
}
},
'clear-completed': {
'regex': /clear.*/gi,
'lang': 'en-US',
'call': function(utterance){
$scope.clearCompletedTodos();
$scope.$apply();
}
},
'listTasks': [{
'regex': /^complete .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
completeTodo(parts.slice(1).join(' '));
}
}
},{
'regex': /^remove .+/gi,
'lang': 'en-US',
'call': function(utterance){
var parts = utterance.split(' ');
if (parts.length > 1) {
var todo = findTodo(parts.slice(1).join(' '));
console.log(todo);
if (todo) {
$scope.removeTodo(todo);
$scope.$apply();
}
}
}
}]
};
var ignoreUtterance = {};
ignoreUtterance['addToList'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['addToList']);
ignoreUtterance['show-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-all']);
ignoreUtterance['show-active'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-active']);
ignoreUtterance['show-completed'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['show-completed']);
ignoreUtterance['mark-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['mark-all']);
ignoreUtterance['unmark-all'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['unmark-all']);
ignoreUtterance['clear-completed'] = $speechRecognition.listenUtterance($scope.recognition['en-US']['clear-completed']);
/*
to ignore listener call returned function
*/
// ignoreUtterance['addToList']();
});
}()); | mit |
Keno/TexExtensions.jl | LICENSE.md | 1167 | The TexExtensions.jl package is licensed under the MIT Expat License:
> Copyright (c) 2013: Keno Fischer.
>
> Permission is hereby granted, free of charge, to any person obtaining
> a copy of this software and associated documentation files (the
> "Software"), to deal in the Software without restriction, including
> without limitation the rights to use, copy, modify, merge, publish,
> distribute, sublicense, and/or sell copies of the Software, and to
> permit persons to whom the Software is furnished to do so, subject to
> the following conditions:
>
> The above copyright notice and this permission notice shall be
> included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
> EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
> MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
> IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
> CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
> TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
> SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| mit |
aspose-words/Aspose.Words-for-Java | Plugins/Aspose_Words_Java_for_Docx4j/src/main/java/com/aspose/words/examples/featurescomparison/documents/comments/Docx4jCommentsSample.java | 4780 | /*
* Copyright 2007-2008, Plutext Pty Ltd.
*
* This file is part of docx4j.
docx4j is 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.
NOTICE: ORIGINAL FILE MODIFIED
*/
package com.aspose.words.examples.featurescomparison.documents.comments;
import java.math.BigInteger;
import java.util.Calendar;
import org.docx4j.convert.out.flatOpcXml.FlatOpcXmlCreator;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.CommentsPart;
import org.docx4j.samples.AbstractSample;
import org.docx4j.wml.Comments;
import org.docx4j.wml.Comments.Comment;
import org.docx4j.wml.P;
import com.aspose.words.examples.Utils;
/**
* Creates a WordprocessingML document from scratch, and adds a comment.
*
* Note that only w:commentReference is required; this example doesn't add
* w:commentRangeStart or w:commentRangeEnd
*
* <w:p> <w:commentRangeStart w:id="0"/> <w:r> <w:t>hello</w:t> </w:r>
* <w:commentRangeEnd w:id="0"/> <w:r> <w:rPr> <w:rStyle
* w:val="CommentReference"/> </w:rPr> <w:commentReference w:id="0"/> </w:r>
* </w:p>
*
*
* @author Jason Harrop
*/
public class Docx4jCommentsSample extends AbstractSample
{
static org.docx4j.wml.ObjectFactory factory = Context.getWmlObjectFactory();
public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = Utils.getDataDir(Docx4jCommentsSample.class);
outputfilepath = dataDir + "Docx4j_CommentsSample.docx";
//boolean save = (outputfilepath == null ? false : true);
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage
.createPackage();
// Create and add a Comments Part
CommentsPart cp = new CommentsPart();
wordMLPackage.getMainDocumentPart().addTargetPart(cp);
// Part must have minimal contents
Comments comments = factory.createComments();
cp.setJaxbElement(comments);
// Add a comment to the comments part
java.math.BigInteger commentId = BigInteger.valueOf(0);
Comment theComment = createComment(commentId, "fred", null,
"my first comment");
comments.getComment().add(theComment);
// Add comment reference to document
P paraToCommentOn = wordMLPackage.getMainDocumentPart()
.addParagraphOfText("here is some content");
paraToCommentOn.getContent().add(createRunCommentReference(commentId));
// ++, for next comment ...
commentId = commentId.add(java.math.BigInteger.ONE);
wordMLPackage.save(new java.io.File(outputfilepath));
System.out.println("Saved " + outputfilepath);
System.out.println("Done.");
}
private static org.docx4j.wml.Comments.Comment createComment(
java.math.BigInteger commentId, String author, Calendar date,
String message)
{
org.docx4j.wml.Comments.Comment comment = factory
.createCommentsComment();
comment.setId(commentId);
if (author != null)
{
comment.setAuthor(author);
}
if (date != null)
{
// String dateString = RFC3339_FORMAT.format(date.getTime()) ;
// comment.setDate(value)
// TODO - at present this is XMLGregorianCalendar
}
org.docx4j.wml.P commentP = factory.createP();
comment.getEGBlockLevelElts().add(commentP);
org.docx4j.wml.R commentR = factory.createR();
commentP.getContent().add(commentR);
org.docx4j.wml.Text commentText = factory.createText();
commentR.getContent().add(commentText);
commentText.setValue(message);
return comment;
}
private static org.docx4j.wml.R createRunCommentReference(
java.math.BigInteger commentId)
{
org.docx4j.wml.R run = factory.createR();
org.docx4j.wml.R.CommentReference commentRef = factory
.createRCommentReference();
run.getContent().add(commentRef);
commentRef.setId(commentId);
return run;
}
} | mit |
plajjan/vrnetlab | nxos/README.md | 1181 | vrnetlab / Cisco Nexus NXOS
===========================
This is the vrnetlab docker image for Cisco Nexus NXOS Titanium emulator.
Building the docker image
-------------------------
Titanium doesn't appear to be exactly official but you can get it from the
Internet. VIRL is said to include it, so you may have luck in extracting it
from there.
Anyway, put the .qcow2 file in this directory and run `make docker-image` and
you should be good to go. The resulting image is called `vr-nxos`. You can tag
it with something else if you want, like `my-repo.example.com/vr-nxos` and then
push it to your repo. The tag is the same as the version of the NXOS image, so
if you have nxosv-7.2.0.D1.1.qcow2 your final docker image will be called
vr-nxos:7.2.0.D1.1
Usage
-----
```
docker run -d --privileged --name my-nxos-router vr-nxos
```
System requirements
-------------------
CPU: 1 core
RAM: 2GB
Disk: <500MB
FUAQ - Frequently or Unfrequently Asked Questions
-------------------------------------------------
##### Q: Has this been extensively tested?
A: Nope. I don't use Nexus myself (yet) so not much testing at all really.
Please do try it out and let me know if it works.
| mit |
andycmaj/cake | src/Cake.Common/Tools/MSBuild/MSBuildSettings.cs | 3061 | using System;
using System.Collections.Generic;
using Cake.Core.Diagnostics;
using Cake.Core.Tooling;
namespace Cake.Common.Tools.MSBuild
{
/// <summary>
/// Contains settings used by <see cref="MSBuildRunner"/>.
/// </summary>
public sealed class MSBuildSettings : ToolSettings
{
private readonly HashSet<string> _targets;
private readonly Dictionary<string, IList<string>> _properties;
/// <summary>
/// Gets the targets.
/// </summary>
/// <value>The targets.</value>
public ISet<string> Targets
{
get { return _targets; }
}
/// <summary>
/// Gets the properties.
/// </summary>
/// <value>The properties.</value>
public IDictionary<string, IList<string>> Properties
{
get { return _properties; }
}
/// <summary>
/// Gets or sets the platform target.
/// </summary>
/// <value>The platform target.</value>
public PlatformTarget? PlatformTarget { get; set; }
/// <summary>
/// Gets or sets the MSBuild platform.
/// </summary>
/// <value>The MSBuild platform.</value>
public MSBuildPlatform MSBuildPlatform { get; set; }
/// <summary>
/// Gets or sets the tool version.
/// </summary>
/// <value>The tool version.</value>
public MSBuildToolVersion ToolVersion { get; set; }
/// <summary>
/// Gets or sets the configuration.
/// </summary>
/// <value>The configuration.</value>
public string Configuration { get; set; }
/// <summary>
/// Gets or sets the maximum CPU count.
/// </summary>
/// <value>The maximum CPU count.</value>
public int MaxCpuCount { get; set; }
/// <summary>
/// Gets or sets whether or not node reuse is used.
/// When you’re doing multiple builds in a row, this helps reduce your total build time,
/// by avoiding the start up costs of each MSBuild child node.
/// </summary>
public bool? NodeReuse { get; set; }
/// <summary>
/// Gets or sets the amount of information to display in the build log.
/// Each logger displays events based on the verbosity level that you set for that logger.
/// </summary>
/// <value>The build log verbosity.</value>
public Verbosity Verbosity { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="MSBuildSettings"/> class.
/// </summary>
public MSBuildSettings()
{
_targets = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
_properties = new Dictionary<string, IList<string>>(StringComparer.OrdinalIgnoreCase);
ToolVersion = MSBuildToolVersion.Default;
Configuration = string.Empty;
Verbosity = Verbosity.Normal;
MSBuildPlatform = MSBuildPlatform.Automatic;
}
}
} | mit |
six519/disclose.ph | gulp/git.js | 318 | 'use strict';
var gulp = require('gulp');
var shell = require('gulp-shell');
module.exports = function () {
gulp.task('git-add', function () {
return gulp.src('*.js', {
read: false
}).pipe(shell(['git ls-files --others docroot/sites/all | egrep \'.css|.js|.png|.map\' | xargs git add -f']));
});
};
| mit |
prat0318/dbms | mini_dbms/je-5.0.103/src/com/sleepycat/persist/evolve/Converter.java | 3660 | /*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2002, 2014 Oracle and/or its affiliates. All rights reserved.
*
*/
package com.sleepycat.persist.evolve;
import java.lang.reflect.Method;
import com.sleepycat.compat.DbCompat;
/**
* A mutation for converting an old version of an object value to conform to
* the current class or field definition. For example:
*
* <pre class="code">
* package my.package;
*
* // The old class. Version 0 is implied.
* //
* {@literal @Entity}
* class Person {
* // ...
* }
*
* // The new class. A new version number must be assigned.
* //
* {@literal @Entity(version=1)}
* class Person {
* // Incompatible changes were made here...
* }
*
* // Add a converter mutation.
* //
* Mutations mutations = new Mutations();
*
* mutations.addConverter(new Converter(Person.class.getName(), 0,
* new MyConversion()));
*
* // Configure the mutations as described {@link Mutations here}.</pre>
*
* <p>See {@link Conversion} for more information.</p>
*
* @see com.sleepycat.persist.evolve Class Evolution
* @author Mark Hayes
*/
public class Converter extends Mutation {
private static final long serialVersionUID = 4558176842096181863L;
private Conversion conversion;
/**
* Creates a mutation for converting all instances of the given class
* version to the current version of the class.
*/
public Converter(String className,
int classVersion,
Conversion conversion) {
this(className, classVersion, null, conversion);
}
/**
* Creates a mutation for converting all values of the given field in the
* given class version to a type compatible with the current declared type
* of the field.
*/
public Converter(String declaringClassName,
int declaringClassVersion,
String fieldName,
Conversion conversion) {
super(declaringClassName, declaringClassVersion, fieldName);
this.conversion = conversion;
/* Require explicit implementation of the equals method. */
Class cls = conversion.getClass();
try {
Method m = cls.getMethod("equals", Object.class);
if (m.getDeclaringClass() == Object.class) {
throw new IllegalArgumentException
("Conversion class does not implement the equals method " +
"explicitly (Object.equals is not sufficient): " +
cls.getName());
}
} catch (NoSuchMethodException e) {
throw DbCompat.unexpectedException(e);
}
}
/**
* Returns the converter instance specified to the constructor.
*/
public Conversion getConversion() {
return conversion;
}
/**
* Returns true if the conversion objects are equal in this object and
* given object, and if the {@link Mutation#equals} superclass method
* returns true.
*/
@Override
public boolean equals(Object other) {
if (other instanceof Converter) {
Converter o = (Converter) other;
return conversion.equals(o.conversion) &&
super.equals(other);
} else {
return false;
}
}
@Override
public int hashCode() {
return conversion.hashCode() + super.hashCode();
}
@Override
public String toString() {
return "[Converter " + super.toString() +
" Conversion: " + conversion + ']';
}
}
| mit |
blyk/BlackCode-Fuse | Welcome/.build/Simulator/Android/include/Fuse.Scripting.NativePromise-2.PromiseClosure.h | 2442 | // This file was generated based on 'C:\ProgramData\Uno\Packages\Fuse.Scripting\0.19.3\$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Scripting{struct Context;}}}
namespace g{namespace Fuse{namespace Scripting{struct Function;}}}
namespace g{namespace Fuse{namespace Scripting{struct NativePromise__PromiseClosure;}}}
namespace g{namespace Uno{namespace Threading{struct Future1;}}}
namespace g{namespace Uno{struct Exception;}}
namespace g{
namespace Fuse{
namespace Scripting{
// private sealed class NativePromise<T, TJSResult>.PromiseClosure :342
// {
uType* NativePromise__PromiseClosure_typeof();
void NativePromise__PromiseClosure__ctor__fn(NativePromise__PromiseClosure* __this, ::g::Fuse::Scripting::Context* context, ::g::Uno::Threading::Future1* promise, uDelegate* converter);
void NativePromise__PromiseClosure__InternalResolve_fn(NativePromise__PromiseClosure* __this);
void NativePromise__PromiseClosure__New1_fn(uType* __type, ::g::Fuse::Scripting::Context* context, ::g::Uno::Threading::Future1* promise, uDelegate* converter, NativePromise__PromiseClosure** __retval);
void NativePromise__PromiseClosure__Reject_fn(NativePromise__PromiseClosure* __this, ::g::Uno::Exception* reason);
void NativePromise__PromiseClosure__Resolve_fn(NativePromise__PromiseClosure* __this, void* result);
void NativePromise__PromiseClosure__Run_fn(NativePromise__PromiseClosure* __this, uArray* args, uObject** __retval);
struct NativePromise__PromiseClosure : uObject
{
uStrong< ::g::Fuse::Scripting::Context*> _c;
uStrong<uDelegate*> _converter;
uStrong< ::g::Uno::Threading::Future1*> _promise;
uStrong< ::g::Fuse::Scripting::Function*> _reject;
uStrong< ::g::Fuse::Scripting::Function*> _resolve;
uTField _result() { return __type->Field(this, 5); }
void ctor_(::g::Fuse::Scripting::Context* context, ::g::Uno::Threading::Future1* promise, uDelegate* converter);
void InternalResolve();
void Reject(::g::Uno::Exception* reason);
template<class T>
void Resolve(T result) { NativePromise__PromiseClosure__Resolve_fn(this, uConstrain(__type->T(0), result)); }
uObject* Run(uArray* args);
static NativePromise__PromiseClosure* New1(uType* __type, ::g::Fuse::Scripting::Context* context, ::g::Uno::Threading::Future1* promise, uDelegate* converter);
};
// }
}}} // ::g::Fuse::Scripting
| mit |
kakra/rack-offline | lib/rack/offline/config.rb | 490 | module Rack
class Offline
class Config
def initialize(root, &block)
@cache = []
@network = []
@fallback = {}
@root = root
instance_eval(&block) if block_given?
end
def cache(*names)
@cache.concat(names)
end
def network(*names)
@network.concat(names)
end
def fallback(hash = {})
@fallback.merge!(hash)
end
def root
@root
end
end
end
end
| mit |
plumer/codana | tomcat_files/8.0.22/Introspection.java | 6566 | /*
* 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.catalina.util;
import java.beans.Introspector;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;
import org.apache.catalina.Context;
import org.apache.catalina.Globals;
import org.apache.juli.logging.Log;
import org.apache.tomcat.util.ExceptionUtils;
import org.apache.tomcat.util.res.StringManager;
/**
* Provides introspection utilities that either require knowledge of Tomcat
* internals or are solely used by Tomcat internals.
*/
public class Introspection {
private static final StringManager sm =
StringManager.getManager("org.apache.catalina.util");
/**
* Extract the Java Bean property name from the setter name.
*
* Note: This method assumes that the method name has already been checked
* for correctness.
*/
public static String getPropertyName(Method setter) {
return Introspector.decapitalize(setter.getName().substring(3));
}
/**
* Determines if a method has a valid name and signature for a Java Bean
* setter.
*
* @param method The method to test
*
* @return <code>true</code> if the method does have a valid name and
* signature, else <code>false</code>
*/
public static boolean isValidSetter(Method method) {
if (method.getName().startsWith("set")
&& method.getName().length() > 3
&& method.getParameterTypes().length == 1
&& method.getReturnType().getName().equals("void")) {
return true;
}
return false;
}
/**
* Determines if a method is a valid lifecycle callback method.
*
* @param method
* The method to test
*
* @return <code>true</code> if the method is a valid lifecycle callback
* method, else <code>false</code>
*/
public static boolean isValidLifecycleCallback(Method method) {
if (method.getParameterTypes().length != 0
|| Modifier.isStatic(method.getModifiers())
|| method.getExceptionTypes().length > 0
|| !method.getReturnType().getName().equals("void")) {
return false;
}
return true;
}
/**
* Obtain the declared fields for a class taking account of any security
* manager that may be configured.
*/
public static Field[] getDeclaredFields(final Class<?> clazz) {
Field[] fields = null;
if (Globals.IS_SECURITY_ENABLED) {
fields = AccessController.doPrivileged(
new PrivilegedAction<Field[]>(){
@Override
public Field[] run(){
return clazz.getDeclaredFields();
}
});
} else {
fields = clazz.getDeclaredFields();
}
return fields;
}
/**
* Obtain the declared methods for a class taking account of any security
* manager that may be configured.
*/
public static Method[] getDeclaredMethods(final Class<?> clazz) {
Method[] methods = null;
if (Globals.IS_SECURITY_ENABLED) {
methods = AccessController.doPrivileged(
new PrivilegedAction<Method[]>(){
@Override
public Method[] run(){
return clazz.getDeclaredMethods();
}
});
} else {
methods = clazz.getDeclaredMethods();
}
return methods;
}
/**
* Attempt to load a class using the given Container's class loader. If the
* class cannot be loaded, a debug level log message will be written to the
* Container's log and null will be returned.
*/
public static Class<?> loadClass(Context context, String className) {
ClassLoader cl = context.getLoader().getClassLoader();
Log log = context.getLogger();
Class<?> clazz = null;
try {
clazz = cl.loadClass(className);
} catch (ClassNotFoundException e) {
log.debug(sm.getString("introspection.classLoadFailed", className), e);
} catch (NoClassDefFoundError e) {
log.debug(sm.getString("introspection.classLoadFailed", className), e);
} catch (ClassFormatError e) {
log.debug(sm.getString("introspection.classLoadFailed", className), e);
} catch (Throwable t) {
ExceptionUtils.handleThrowable(t);
log.debug(sm.getString("introspection.classLoadFailed", className), t);
}
return clazz;
}
/**
* Converts the primitive type to its corresponding wrapper.
*
* @param clazz
* Class that will be evaluated
* @return if the parameter is a primitive type returns its wrapper;
* otherwise returns the same class
*/
public static Class<?> convertPrimitiveType(Class<?> clazz) {
if (clazz.equals(char.class)) {
return Character.class;
} else if (clazz.equals(int.class)) {
return Integer.class;
} else if (clazz.equals(boolean.class)) {
return Boolean.class;
} else if (clazz.equals(double.class)) {
return Double.class;
} else if (clazz.equals(byte.class)) {
return Byte.class;
} else if (clazz.equals(short.class)) {
return Short.class;
} else if (clazz.equals(long.class)) {
return Long.class;
} else if (clazz.equals(float.class)) {
return Float.class;
} else {
return clazz;
}
}
}
| mit |
ryfeus/lambda-packs | pytorch/source/PIL/FpxImagePlugin.py | 6282 | #
# THIS IS WORK IN PROGRESS
#
# The Python Imaging Library.
# $Id$
#
# FlashPix support for PIL
#
# History:
# 97-01-25 fl Created (reads uncompressed RGB images only)
#
# Copyright (c) Secret Labs AB 1997.
# Copyright (c) Fredrik Lundh 1997.
#
# See the README file for information on usage and redistribution.
#
from __future__ import print_function
from . import Image, ImageFile
from ._binary import i32le as i32, i8
import olefile
__version__ = "0.1"
# we map from colour field tuples to (mode, rawmode) descriptors
MODES = {
# opacity
(0x00007ffe): ("A", "L"),
# monochrome
(0x00010000,): ("L", "L"),
(0x00018000, 0x00017ffe): ("RGBA", "LA"),
# photo YCC
(0x00020000, 0x00020001, 0x00020002): ("RGB", "YCC;P"),
(0x00028000, 0x00028001, 0x00028002, 0x00027ffe): ("RGBA", "YCCA;P"),
# standard RGB (NIFRGB)
(0x00030000, 0x00030001, 0x00030002): ("RGB", "RGB"),
(0x00038000, 0x00038001, 0x00038002, 0x00037ffe): ("RGBA", "RGBA"),
}
#
# --------------------------------------------------------------------
def _accept(prefix):
return prefix[:8] == olefile.MAGIC
##
# Image plugin for the FlashPix images.
class FpxImageFile(ImageFile.ImageFile):
format = "FPX"
format_description = "FlashPix"
def _open(self):
#
# read the OLE directory and see if this is a likely
# to be a FlashPix file
try:
self.ole = olefile.OleFileIO(self.fp)
except IOError:
raise SyntaxError("not an FPX file; invalid OLE file")
if self.ole.root.clsid != "56616700-C154-11CE-8553-00AA00A1F95B":
raise SyntaxError("not an FPX file; bad root CLSID")
self._open_index(1)
def _open_index(self, index=1):
#
# get the Image Contents Property Set
prop = self.ole.getproperties([
"Data Object Store %06d" % index,
"\005Image Contents"
])
# size (highest resolution)
self._size = prop[0x1000002], prop[0x1000003]
size = max(self.size)
i = 1
while size > 64:
size = size / 2
i += 1
self.maxid = i - 1
# mode. instead of using a single field for this, flashpix
# requires you to specify the mode for each channel in each
# resolution subimage, and leaves it to the decoder to make
# sure that they all match. for now, we'll cheat and assume
# that this is always the case.
id = self.maxid << 16
s = prop[0x2000002 | id]
colors = []
for i in range(i32(s, 4)):
# note: for now, we ignore the "uncalibrated" flag
colors.append(i32(s, 8+i*4) & 0x7fffffff)
self.mode, self.rawmode = MODES[tuple(colors)]
# load JPEG tables, if any
self.jpeg = {}
for i in range(256):
id = 0x3000001 | (i << 16)
if id in prop:
self.jpeg[i] = prop[id]
self._open_subimage(1, self.maxid)
def _open_subimage(self, index=1, subimage=0):
#
# setup tile descriptors for a given subimage
stream = [
"Data Object Store %06d" % index,
"Resolution %04d" % subimage,
"Subimage 0000 Header"
]
fp = self.ole.openstream(stream)
# skip prefix
fp.read(28)
# header stream
s = fp.read(36)
size = i32(s, 4), i32(s, 8)
# tilecount = i32(s, 12)
tilesize = i32(s, 16), i32(s, 20)
# channels = i32(s, 24)
offset = i32(s, 28)
length = i32(s, 32)
if size != self.size:
raise IOError("subimage mismatch")
# get tile descriptors
fp.seek(28 + offset)
s = fp.read(i32(s, 12) * length)
x = y = 0
xsize, ysize = size
xtile, ytile = tilesize
self.tile = []
for i in range(0, len(s), length):
compression = i32(s, i+8)
if compression == 0:
self.tile.append(("raw", (x, y, x+xtile, y+ytile),
i32(s, i) + 28, (self.rawmode)))
elif compression == 1:
# FIXME: the fill decoder is not implemented
self.tile.append(("fill", (x, y, x+xtile, y+ytile),
i32(s, i) + 28, (self.rawmode, s[12:16])))
elif compression == 2:
internal_color_conversion = i8(s[14])
jpeg_tables = i8(s[15])
rawmode = self.rawmode
if internal_color_conversion:
# The image is stored as usual (usually YCbCr).
if rawmode == "RGBA":
# For "RGBA", data is stored as YCbCrA based on
# negative RGB. The following trick works around
# this problem :
jpegmode, rawmode = "YCbCrK", "CMYK"
else:
jpegmode = None # let the decoder decide
else:
# The image is stored as defined by rawmode
jpegmode = rawmode
self.tile.append(("jpeg", (x, y, x+xtile, y+ytile),
i32(s, i) + 28, (rawmode, jpegmode)))
# FIXME: jpeg tables are tile dependent; the prefix
# data must be placed in the tile descriptor itself!
if jpeg_tables:
self.tile_prefix = self.jpeg[jpeg_tables]
else:
raise IOError("unknown/invalid compression")
x = x + xtile
if x >= xsize:
x, y = 0, y + ytile
if y >= ysize:
break # isn't really required
self.stream = stream
self.fp = None
def load(self):
if not self.fp:
self.fp = self.ole.openstream(self.stream[:2] +
["Subimage 0000 Data"])
return ImageFile.ImageFile.load(self)
#
# --------------------------------------------------------------------
Image.register_open(FpxImageFile.format, FpxImageFile, _accept)
Image.register_extension(FpxImageFile.format, ".fpx")
| mit |
Thijzer/forkcms | src/Backend/Modules/ContentBlocks/Event/ContentBlockCreated.php | 283 | <?php
namespace Backend\Modules\ContentBlocks\Event;
final class ContentBlockCreated extends ContentBlockEvent
{
/**
* @var string The name the listener needs to listen to to catch this event.
*/
const EVENT_NAME = 'content_blocks.event.content_block_created';
}
| mit |
liaojing/videomorphing | include/resample/extension.h | 1425 | #ifndef EXTENSION_H
#define EXTENSION_H
#include <cmath>
namespace extension {
class base {
public:
virtual ~base() { ; }
virtual float operator()(float t) const = 0;
virtual int operator()(int i, int n) const = 0;
virtual float wrap(float t) const { return (*this)(t); }
virtual int wrap(int i, int n) const { return (*this)(i, n); }
};
class none: public base {
public:
float operator()(float t) const {
return t;
}
int operator()(int i, int n) const {
(void) n;
return i;
}
};
class clamp: public base {
public:
float operator()(float t) const {
if (t < 0.f) return 0.f;
else if (t > 1.f) return 1.f;
else return t;
}
int operator()(int i, int n) const {
if (i < 0) return 0;
else if (i >= n) return n-1;
else return i;
}
};
class repeat: public base {
public:
float operator()(float t) const {
t = fmodf(t, 1.f);
return t < 0.f? t+1.f: t;
}
int operator()(int i, int n) const {
if (i >= 0) return i % n;
else return (n-1) - ((-i-1) % n);
}
};
class mirror: public base {
public:
float operator()(float t) const {
t = fabs(fmodf(t, 2.f));
return t > 1.f? 2.f-t: t;
}
int operator()(int i, int n) const {
repeat r;
i = r(i, 2*n);
if (i >= n) return i = (2*n)-i-1;
else return i;
}
};
}
#endif
| mit |
wjyadlx/simple-rtmp-server | trunk/src/utest/srs_utest_amf0.cpp | 32587 | /*
The MIT License (MIT)
Copyright (c) 2013-2014 winlin
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <srs_utest_amf0.hpp>
#include <string>
using namespace std;
#include <srs_core_autofree.hpp>
#include <srs_kernel_error.hpp>
#include <srs_kernel_stream.hpp>
// user scenario: coding and decoding with amf0
VOID TEST(AMF0Test, ScenarioMain)
{
// coded amf0 object
int nb_bytes = 0;
char* bytes = NULL;
// coding data to binaries by amf0
// for example, send connect app response to client.
if (true) {
// props: object
// fmsVer: string
// capabilities: number
// mode: number
// info: object
// level: string
// code: string
// descrption: string
// objectEncoding: number
// data: array
// version: string
// srs_sig: string
SrsAmf0Object* props = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, props, false);
props->set("fmsVer", SrsAmf0Any::str("FMS/3,5,3,888"));
props->set("capabilities", SrsAmf0Any::number(253));
props->set("mode", SrsAmf0Any::number(123));
SrsAmf0Object* info = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, info, false);
info->set("level", SrsAmf0Any::str("info"));
info->set("code", SrsAmf0Any::str("NetStream.Connnect.Success"));
info->set("descrption", SrsAmf0Any::str("connected"));
info->set("objectEncoding", SrsAmf0Any::number(3));
SrsAmf0EcmaArray* data = SrsAmf0Any::ecma_array();
info->set("data", data);
data->set("version", SrsAmf0Any::str("FMS/3,5,3,888"));
data->set("srs_sig", SrsAmf0Any::str("srs"));
// buf store the serialized props/info
nb_bytes = props->total_size() + info->total_size();
ASSERT_GT(nb_bytes, 0);
bytes = new char[nb_bytes];
// use SrsStream to write props/info to binary buf.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
EXPECT_EQ(ERROR_SUCCESS, props->write(&s));
EXPECT_EQ(ERROR_SUCCESS, info->write(&s));
EXPECT_TRUE(s.empty());
// now, user can use the buf
EXPECT_EQ(0x03, bytes[0]);
EXPECT_EQ(0x09, bytes[nb_bytes - 1]);
}
SrsAutoFree(char, bytes, true);
// decoding amf0 object from bytes
// when user know the schema
if (true) {
ASSERT_TRUE(NULL != bytes);
// use SrsStream to assist amf0 object to read from bytes.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
// decoding
// if user know the schema, for instance, it's an amf0 object,
// user can use specified object to decoding.
SrsAmf0Object* props = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, props, false);
EXPECT_EQ(ERROR_SUCCESS, props->read(&s));
// user can use specified object to decoding.
SrsAmf0Object* info = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, info, false);
EXPECT_EQ(ERROR_SUCCESS, info->read(&s));
// use the decoded data.
SrsAmf0Any* prop = NULL;
// if user requires specified property, use ensure of amf0 object
EXPECT_TRUE(NULL != (prop = props->ensure_property_string("fmsVer")));
// the property can assert to string.
ASSERT_TRUE(prop->is_string());
// get the prop string value.
EXPECT_STREQ("FMS/3,5,3,888", prop->to_str().c_str());
// get other type property value
EXPECT_TRUE(NULL != (prop = info->get_property("data")));
// we cannot assert the property is ecma array
if (prop->is_ecma_array()) {
SrsAmf0EcmaArray* data = prop->to_ecma_array();
// it must be a ecma array.
ASSERT_TRUE(NULL != data);
// get property of array
EXPECT_TRUE(NULL != (prop = data->ensure_property_string("srs_sig")));
ASSERT_TRUE(prop->is_string());
EXPECT_STREQ("srs", prop->to_str().c_str());
}
// confidence about the schema
EXPECT_TRUE(NULL != (prop = info->ensure_property_string("level")));
ASSERT_TRUE(prop->is_string());
EXPECT_STREQ("info", prop->to_str().c_str());
}
// use any to decoding it,
// if user donot know the schema
if (true) {
ASSERT_TRUE(NULL != bytes);
// use SrsStream to assist amf0 object to read from bytes.
SrsStream s;
EXPECT_EQ(ERROR_SUCCESS, s.initialize(bytes, nb_bytes));
// decoding a amf0 any, for user donot know
SrsAmf0Any* any = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &any));
SrsAutoFree(SrsAmf0Any, any, false);
// for amf0 object
if (any->is_object()) {
SrsAmf0Object* obj = any->to_object();
ASSERT_TRUE(NULL != obj);
// use foreach to process properties
for (int i = 0; i < obj->count(); ++i) {
string name = obj->key_at(i);
SrsAmf0Any* value = obj->value_at(i);
// use the property name
EXPECT_TRUE("" != name);
// use the property value
EXPECT_TRUE(NULL != value);
}
}
}
}
VOID TEST(AMF0Test, ApiSize)
{
// size of elem
EXPECT_EQ(2+6, SrsAmf0Size::utf8("winlin"));
EXPECT_EQ(2+0, SrsAmf0Size::utf8(""));
EXPECT_EQ(1+2+6, SrsAmf0Size::str("winlin"));
EXPECT_EQ(1+2+0, SrsAmf0Size::str(""));
EXPECT_EQ(1+8, SrsAmf0Size::number());
EXPECT_EQ(1, SrsAmf0Size::null());
EXPECT_EQ(1, SrsAmf0Size::undefined());
EXPECT_EQ(1+1, SrsAmf0Size::boolean());
// object: empty
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// object: elem
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("age")+SrsAmf0Size::number();
o->set("age", SrsAmf0Any::number(9));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::null();
o->set("email", SrsAmf0Any::null());
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::undefined();
o->set("email", SrsAmf0Any::undefined());
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("sex")+SrsAmf0Size::boolean();
o->set("sex", SrsAmf0Any::boolean(true));
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: empty
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// array: elem
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("age")+SrsAmf0Size::number();
o->set("age", SrsAmf0Any::number(9));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::null();
o->set("email", SrsAmf0Any::null());
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("email")+SrsAmf0Size::undefined();
o->set("email", SrsAmf0Any::undefined());
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("sex")+SrsAmf0Size::boolean();
o->set("sex", SrsAmf0Any::boolean(true));
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// object: array
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
SrsAmf0EcmaArray* params = SrsAmf0Any::ecma_array();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::ecma_array(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: object
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
SrsAmf0Object* params = SrsAmf0Any::object();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::object(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
// object: object
if (true) {
int size = 1+3;
SrsAmf0Object* o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0Object* args = SrsAmf0Any::object();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::object(args);
o->set("args", args);
SrsAmf0Object* params = SrsAmf0Any::object();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::object(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::object(o));
}
// array: array
if (true) {
int size = 1+4+3;
SrsAmf0EcmaArray* o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
size += SrsAmf0Size::utf8("name")+SrsAmf0Size::str("winlin");
o->set("name", SrsAmf0Any::str("winlin"));
SrsAmf0EcmaArray* args = SrsAmf0Any::ecma_array();
args->set("p0", SrsAmf0Any::str("function"));
size += SrsAmf0Size::utf8("args")+SrsAmf0Size::ecma_array(args);
o->set("args", args);
SrsAmf0EcmaArray* params = SrsAmf0Any::ecma_array();
params->set("p1", SrsAmf0Any::number(10));
size += SrsAmf0Size::utf8("params")+SrsAmf0Size::ecma_array(params);
o->set("params", params);
EXPECT_EQ(size, SrsAmf0Size::ecma_array(o));
}
}
VOID TEST(AMF0Test, ApiAnyElem)
{
SrsAmf0Any* o = NULL;
// string
if (true) {
o = SrsAmf0Any::str();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_string());
EXPECT_STREQ("", o->to_str().c_str());
}
if (true) {
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_string());
EXPECT_STREQ("winlin", o->to_str().c_str());
}
// bool
if (true) {
o = SrsAmf0Any::boolean();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_FALSE(o->to_boolean());
}
if (true) {
o = SrsAmf0Any::boolean(false);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_FALSE(o->to_boolean());
}
if (true) {
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_boolean());
EXPECT_TRUE(o->to_boolean());
}
// number
if (true) {
o = SrsAmf0Any::number();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(0, o->to_number());
}
if (true) {
o = SrsAmf0Any::number(100);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(100, o->to_number());
}
if (true) {
o = SrsAmf0Any::number(-100);
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_number());
EXPECT_DOUBLE_EQ(-100, o->to_number());
}
// null
if (true) {
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_null());
}
// undefined
if (true) {
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
ASSERT_TRUE(NULL != o);
EXPECT_TRUE(o->is_undefined());
}
}
VOID TEST(AMF0Test, ApiAnyIO)
{
SrsStream s;
SrsAmf0Any* o = NULL;
char buf[1024];
memset(buf, 0, sizeof(buf));
EXPECT_EQ(ERROR_SUCCESS, s.initialize(buf, sizeof(buf)));
// object eof
if (true) {
s.reset();
s.current()[2] = 0x09;
o = SrsAmf0Any::object_eof();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_EQ(3, s.pos());
s.reset();
s.current()[0] = 0x01;
EXPECT_NE(ERROR_SUCCESS, o->read(&s));
}
if (true) {
s.reset();
o = SrsAmf0Any::object_eof();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_EQ(3, s.pos());
s.skip(-3);
EXPECT_EQ(0x09, s.read_3bytes());
}
// string
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(2, s.read_1bytes());
EXPECT_EQ(6, s.read_2bytes());
EXPECT_EQ('w', s.current()[0]);
EXPECT_EQ('n', s.current()[5]);
s.reset();
s.current()[3] = 'x';
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_STREQ("xinlin", o->to_str().c_str());
}
// number
if (true) {
s.reset();
o = SrsAmf0Any::number(10);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(0, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_DOUBLE_EQ(10, o->to_number());
}
// boolean
if (true) {
s.reset();
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(1, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->to_boolean());
}
if (true) {
s.reset();
o = SrsAmf0Any::boolean(false);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(1, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_FALSE(o->to_boolean());
}
// null
if (true) {
s.reset();
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(5, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->is_null());
}
// undefined
if (true) {
s.reset();
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
EXPECT_EQ(6, s.read_1bytes());
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->read(&s));
EXPECT_EQ(o->total_size(), s.pos());
EXPECT_TRUE(o->is_undefined());
}
// any: string
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_string());
EXPECT_STREQ("winlin", po->to_str().c_str());
}
// any: number
if (true) {
s.reset();
o = SrsAmf0Any::number(10);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_number());
EXPECT_DOUBLE_EQ(10, po->to_number());
}
// any: boolean
if (true) {
s.reset();
o = SrsAmf0Any::boolean(true);
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_boolean());
EXPECT_TRUE(po->to_boolean());
}
// any: null
if (true) {
s.reset();
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_null());
}
// any: undefined
if (true) {
s.reset();
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(o->total_size(), s.pos());
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
SrsAutoFree(SrsAmf0Any, po, false);
ASSERT_TRUE(po->is_undefined());
}
// mixed any
if (true) {
s.reset();
o = SrsAmf0Any::str("winlin");
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::number(10);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::boolean(true);
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::null();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
o = SrsAmf0Any::undefined();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
srs_freep(o);
s.reset();
SrsAmf0Any* po = NULL;
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_string());
EXPECT_STREQ("winlin", po->to_str().c_str());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_number());
EXPECT_DOUBLE_EQ(10, po->to_number());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_boolean());
EXPECT_TRUE(po->to_boolean());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_null());
srs_freep(po);
EXPECT_EQ(ERROR_SUCCESS, srs_amf0_read_any(&s, &po));
ASSERT_TRUE(NULL != po);
ASSERT_TRUE(po->is_undefined());
srs_freep(po);
}
}
VOID TEST(AMF0Test, ApiAnyAssert)
{
SrsStream s;
SrsAmf0Any* o = NULL;
char buf[1024];
memset(buf, 0, sizeof(buf));
EXPECT_EQ(ERROR_SUCCESS, s.initialize(buf, sizeof(buf)));
// read any
if (true) {
s.reset();
s.current()[0] = 0x12;
EXPECT_NE(ERROR_SUCCESS, srs_amf0_read_any(&s, &o));
EXPECT_TRUE(NULL == o);
srs_freep(o);
}
// any convert
if (true) {
o = SrsAmf0Any::str();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_string());
}
if (true) {
o = SrsAmf0Any::number();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_number());
}
if (true) {
o = SrsAmf0Any::boolean();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_boolean());
}
if (true) {
o = SrsAmf0Any::null();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_null());
}
if (true) {
o = SrsAmf0Any::undefined();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_undefined());
}
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_object());
}
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0Any, o, false);
EXPECT_TRUE(o->is_ecma_array());
}
// empty object
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Any, o, false);
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(1+3, s.pos());
}
// empty ecma array
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0Any, o, false);
s.reset();
EXPECT_EQ(ERROR_SUCCESS, o->write(&s));
EXPECT_EQ(1+4+3, s.pos());
}
}
VOID TEST(AMF0Test, ApiObjectProps)
{
SrsAmf0Object* o = NULL;
// get/set property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_TRUE(NULL == o->get_property("name"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->get_property("name"));
EXPECT_TRUE(NULL == o->get_property("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->get_property("age"));
}
// index property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
o->set("age", SrsAmf0Any::number(100));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
EXPECT_STREQ("age", o->key_at(1).c_str());
ASSERT_TRUE(o->value_at(1)->is_number());
EXPECT_DOUBLE_EQ(100, o->value_at(1)->to_number());
}
// ensure property
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_TRUE(NULL == o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL != o->ensure_property_number("age"));
EXPECT_TRUE(NULL == o->ensure_property_string("age"));
}
// count
if (true) {
o = SrsAmf0Any::object();
SrsAutoFree(SrsAmf0Object, o, false);
EXPECT_EQ(0, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("age", SrsAmf0Any::number(100));
EXPECT_EQ(2, o->count());
}
}
VOID TEST(AMF0Test, ApiEcmaArrayProps)
{
SrsAmf0EcmaArray* o = NULL;
// get/set property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_TRUE(NULL == o->get_property("name"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->get_property("name"));
EXPECT_TRUE(NULL == o->get_property("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->get_property("age"));
}
// index property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
o->set("age", SrsAmf0Any::number(100));
EXPECT_STREQ("name", o->key_at(0).c_str());
ASSERT_TRUE(o->value_at(0)->is_string());
EXPECT_STREQ("winlin", o->value_at(0)->to_str().c_str());
EXPECT_STREQ("age", o->key_at(1).c_str());
ASSERT_TRUE(o->value_at(1)->is_number());
EXPECT_DOUBLE_EQ(100, o->value_at(1)->to_number());
}
// ensure property
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_TRUE(NULL == o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("age"));
o->set("age", SrsAmf0Any::number(100));
EXPECT_TRUE(NULL != o->ensure_property_string("name"));
EXPECT_TRUE(NULL == o->ensure_property_number("name"));
EXPECT_TRUE(NULL != o->ensure_property_number("age"));
EXPECT_TRUE(NULL == o->ensure_property_string("age"));
}
// count
if (true) {
o = SrsAmf0Any::ecma_array();
SrsAutoFree(SrsAmf0EcmaArray, o, false);
EXPECT_EQ(0, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("name", SrsAmf0Any::str("winlin"));
EXPECT_EQ(1, o->count());
o->set("age", SrsAmf0Any::number(100));
EXPECT_EQ(2, o->count());
}
}
| mit |
mitchgu/TAMProxy-Firmware | src/Packet.h | 246 | #ifndef PACKET_H
#define PACKET_H
#include <cstdint>
#include <vector>
// A packet struct. Pretty self explanatory.
namespace tamproxy {
struct Packet {
public:
uint16_t id;
uint8_t dest;
std::vector<uint8_t> payload;
};
}
#endif | mit |
bankonme/bitcoind.js | example/index.js | 502 | #!/usr/bin/env node
'use strict';
/**
* bitcoind.js example
*/
process.title = 'bitcoind.js';
/**
* daemon
*/
var daemon = require('../').daemon({
datadir: process.env.BITCOINDJS_DIR || '~/.bitcoin',
});
daemon.on('ready', function() {
console.log('ready');
});
daemon.on('tx', function(txid) {
console.log('txid', txid);
});
daemon.on('error', function(err) {
daemon.log('error="%s"', err.message);
});
daemon.on('open', function(status) {
daemon.log('status="%s"', status);
});
| mit |
LiuWenJu/v2ray-core | common/protocol/id.go | 1634 | package protocol
import (
"crypto/hmac"
"crypto/md5"
"hash"
"v2ray.com/core/common"
"v2ray.com/core/common/uuid"
)
const (
IDBytesLen = 16
)
type IDHash func(key []byte) hash.Hash
func DefaultIDHash(key []byte) hash.Hash {
return hmac.New(md5.New, key)
}
// The ID of en entity, in the form of a UUID.
type ID struct {
uuid uuid.UUID
cmdKey [IDBytesLen]byte
}
// Equals returns true if this ID equals to the other one.
func (id *ID) Equals(another *ID) bool {
return id.uuid.Equals(&(another.uuid))
}
func (id *ID) Bytes() []byte {
return id.uuid.Bytes()
}
func (id *ID) String() string {
return id.uuid.String()
}
func (id *ID) UUID() uuid.UUID {
return id.uuid
}
func (id ID) CmdKey() []byte {
return id.cmdKey[:]
}
// NewID returns an ID with given UUID.
func NewID(uuid uuid.UUID) *ID {
id := &ID{uuid: uuid}
md5hash := md5.New()
common.Must2(md5hash.Write(uuid.Bytes()))
common.Must2(md5hash.Write([]byte("c48619fe-8f02-49e0-b9e9-edf763e17e21")))
md5hash.Sum(id.cmdKey[:0])
return id
}
func nextID(u *uuid.UUID) uuid.UUID {
md5hash := md5.New()
common.Must2(md5hash.Write(u.Bytes()))
common.Must2(md5hash.Write([]byte("16167dc8-16b6-4e6d-b8bb-65dd68113a81")))
var newid uuid.UUID
for {
md5hash.Sum(newid[:0])
if !newid.Equals(u) {
return newid
}
common.Must2(md5hash.Write([]byte("533eff8a-4113-4b10-b5ce-0f5d76b98cd2")))
}
}
func NewAlterIDs(primary *ID, alterIDCount uint16) []*ID {
alterIDs := make([]*ID, alterIDCount)
prevID := primary.UUID()
for idx := range alterIDs {
newid := nextID(&prevID)
alterIDs[idx] = NewID(newid)
prevID = newid
}
return alterIDs
}
| mit |
widgetworks/rails_admin | spec/rails_admin/config/fields/types/string_like_spec.rb | 2109 | require 'spec_helper'
RSpec.describe RailsAdmin::Config::Fields::Types::StringLike do
describe '#treat_empty_as_nil?', active_record: true do
context 'with a nullable field' do
subject do
RailsAdmin.config('Team').fields.detect do |f|
f.name == :name
end.with(object: Team.new)
end
it 'is true' do
expect(subject.treat_empty_as_nil?).to be true
end
end
context 'with a non-nullable field' do
subject do
RailsAdmin.config('Team').fields.detect do |f|
f.name == :manager
end.with(object: Team.new)
end
it 'is false' do
expect(subject.treat_empty_as_nil?).to be false
end
end
end
describe '#parse_input' do
subject do
RailsAdmin.config('FieldTest').fields.detect do |f|
f.name == :string_field
end.with(object: FieldTest.new)
end
context 'with treat_empty_as_nil being true' do
before do
RailsAdmin.config FieldTest do
field :string_field do
treat_empty_as_nil true
end
end
end
context 'when value is empty' do
let(:params) { {string_field: ''} }
it 'makes the value nil' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be true
expect(params[:string_field]).to be nil
end
end
context 'when value does not exist in params' do
let(:params) { {} }
it 'does not touch params' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be false
end
end
end
context 'with treat_empty_as_nil being false' do
before do
RailsAdmin.config FieldTest do
field :string_field do
treat_empty_as_nil false
end
end
end
let(:params) { {string_field: ''} }
it 'keeps the value untouched' do
subject.parse_input(params)
expect(params.key?(:string_field)).to be true
expect(params[:string_field]).to eq ''
end
end
end
end
| mit |
ACOKing/ArcherSys | owncloud-serv/apps/files_sharing/l10n/ru.php | 1975 | <?php
$TRANSLATIONS = array(
"Shared with you" => "Опубликованы вами",
"Shared with others" => "Опубликованы другими",
"Shared by link" => "Доступно по ссылке",
"No files have been shared with you yet." => "Вы ещё не опубликовали файлы",
"You haven't shared any files yet." => "Вы не имеете файлов в открытом доступе",
"Add {name} from {owner}@{remote}" => "Добавить {name} из {owner}@{remote}",
"Password" => "Пароль",
"Invalid ownCloud url" => "Не верный ownCloud адрес",
"Shared by {owner}" => "Доступ открыл {owner}",
"Shared by" => "Опубликовано",
"This share is password-protected" => "Для доступа к информации необходимо ввести пароль",
"The password is wrong. Try again." => "Неверный пароль. Попробуйте еще раз.",
"Name" => "Имя",
"Share time" => "Дата публикации",
"Sorry, this link doesn’t seem to work anymore." => "Эта ссылка устарела и более не действительна.",
"Reasons might be:" => "Причиной может быть:",
"the item was removed" => "объект был удалён",
"the link expired" => "срок действия ссылки истёк",
"sharing is disabled" => "доступ к информации заблокирован",
"For more info, please ask the person who sent this link." => "Для получения дополнительной информации, пожалуйста, свяжитесь с тем, кто отправил Вам эту ссылку.",
"Save" => "Сохранить",
"Download" => "Скачать",
"Download %s" => "Скачать %s",
"Direct link" => "Прямая ссылка"
);
$PLURAL_FORMS = "nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);";
| mit |
VelvetMirror/test | vendor/bundles/Sensio/Bundle/GeneratorBundle/PHP-Parser/lib/Node/BreakStmt.php | 52 | <?php
class Node_BreakStmt extends NodeAbstract
{
} | mit |
wakiyamap/electrum-mona | electrum_mona/dnssec.py | 5922 | #!/usr/bin/env python
#
# Electrum - lightweight Bitcoin client
# Copyright (C) 2015 Thomas Voegtlin
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Check DNSSEC trust chain.
# Todo: verify expiration dates
#
# Based on
# http://backreference.org/2010/11/17/dnssec-verification-with-dig/
# https://github.com/rthalley/dnspython/blob/master/tests/test_dnssec.py
import dns
import dns.name
import dns.query
import dns.dnssec
import dns.message
import dns.resolver
import dns.rdatatype
import dns.rdtypes.ANY.NS
import dns.rdtypes.ANY.CNAME
import dns.rdtypes.ANY.DLV
import dns.rdtypes.ANY.DNSKEY
import dns.rdtypes.ANY.DS
import dns.rdtypes.ANY.NSEC
import dns.rdtypes.ANY.NSEC3
import dns.rdtypes.ANY.NSEC3PARAM
import dns.rdtypes.ANY.RRSIG
import dns.rdtypes.ANY.SOA
import dns.rdtypes.ANY.TXT
import dns.rdtypes.IN.A
import dns.rdtypes.IN.AAAA
from .logging import get_logger
_logger = get_logger(__name__)
# hard-coded trust anchors (root KSKs)
trust_anchors = [
# KSK-2017:
dns.rrset.from_text('.', 1 , 'IN', 'DNSKEY', '257 3 8 AwEAAaz/tAm8yTn4Mfeh5eyI96WSVexTBAvkMgJzkKTOiW1vkIbzxeF3+/4RgWOq7HrxRixHlFlExOLAJr5emLvN7SWXgnLh4+B5xQlNVz8Og8kvArMtNROxVQuCaSnIDdD5LKyWbRd2n9WGe2R8PzgCmr3EgVLrjyBxWezF0jLHwVN8efS3rCj/EWgvIWgb9tarpVUDK/b58Da+sqqls3eNbuv7pr+eoZG+SrDK6nWeL3c6H5Apxz7LjVc1uTIdsIXxuOLYA4/ilBmSVIzuDWfdRUfhHdY6+cn8HFRm+2hM8AnXGXws9555KrUB5qihylGa8subX2Nn6UwNR1AkUTV74bU='),
# KSK-2010:
dns.rrset.from_text('.', 15202, 'IN', 'DNSKEY', '257 3 8 AwEAAagAIKlVZrpC6Ia7gEzahOR+9W29euxhJhVVLOyQbSEW0O8gcCjF FVQUTf6v58fLjwBd0YI0EzrAcQqBGCzh/RStIoO8g0NfnfL2MTJRkxoX bfDaUeVPQuYEhg37NZWAJQ9VnMVDxP/VHL496M/QZxkjf5/Efucp2gaD X6RS6CXpoY68LsvPVjR0ZSwzz1apAzvN9dlzEheX7ICJBBtuA6G3LQpz W5hOA2hzCTMjJPJ8LbqF6dsV6DoBQzgul0sGIcGOYl7OyQdXfZ57relS Qageu+ipAdTTJ25AsRTAoub8ONGcLmqrAmRLKBP1dfwhYB4N7knNnulq QxA+Uk1ihz0='),
]
def _check_query(ns, sub, _type, keys):
q = dns.message.make_query(sub, _type, want_dnssec=True)
response = dns.query.tcp(q, ns, timeout=5)
assert response.rcode() == 0, 'No answer'
answer = response.answer
assert len(answer) != 0, ('No DNS record found', sub, _type)
assert len(answer) != 1, ('No DNSSEC record found', sub, _type)
if answer[0].rdtype == dns.rdatatype.RRSIG:
rrsig, rrset = answer
elif answer[1].rdtype == dns.rdatatype.RRSIG:
rrset, rrsig = answer
else:
raise Exception('No signature set in record')
if keys is None:
keys = {dns.name.from_text(sub):rrset}
dns.dnssec.validate(rrset, rrsig, keys)
return rrset
def _get_and_validate(ns, url, _type):
# get trusted root key
root_rrset = None
for dnskey_rr in trust_anchors:
try:
# Check if there is a valid signature for the root dnskey
root_rrset = _check_query(ns, '', dns.rdatatype.DNSKEY, {dns.name.root: dnskey_rr})
break
except dns.dnssec.ValidationFailure:
# It's OK as long as one key validates
continue
if not root_rrset:
raise dns.dnssec.ValidationFailure('None of the trust anchors found in DNS')
keys = {dns.name.root: root_rrset}
# top-down verification
parts = url.split('.')
for i in range(len(parts), 0, -1):
sub = '.'.join(parts[i-1:])
name = dns.name.from_text(sub)
# If server is authoritative, don't fetch DNSKEY
query = dns.message.make_query(sub, dns.rdatatype.NS)
response = dns.query.udp(query, ns, 3)
assert response.rcode() == dns.rcode.NOERROR, "query error"
rrset = response.authority[0] if len(response.authority) > 0 else response.answer[0]
rr = rrset[0]
if rr.rdtype == dns.rdatatype.SOA:
continue
# get DNSKEY (self-signed)
rrset = _check_query(ns, sub, dns.rdatatype.DNSKEY, None)
# get DS (signed by parent)
ds_rrset = _check_query(ns, sub, dns.rdatatype.DS, keys)
# verify that a signed DS validates DNSKEY
for ds in ds_rrset:
for dnskey in rrset:
htype = 'SHA256' if ds.digest_type == 2 else 'SHA1'
good_ds = dns.dnssec.make_ds(name, dnskey, htype)
if ds == good_ds:
break
else:
continue
break
else:
raise Exception("DS does not match DNSKEY")
# set key for next iteration
keys = {name: rrset}
# get TXT record (signed by zone)
rrset = _check_query(ns, url, _type, keys)
return rrset
def query(url, rtype):
# 8.8.8.8 is Google's public DNS server
nameservers = ['8.8.8.8']
ns = nameservers[0]
try:
out = _get_and_validate(ns, url, rtype)
validated = True
except Exception as e:
_logger.info(f"DNSSEC error: {repr(e)}")
out = dns.resolver.resolve(url, rtype)
validated = False
return out, validated
| mit |
beagleboard/bonescript | test/TODO/basic_sanity.sh | 210 | #!/bin/sh
cd $(dirname $0)
node -pe "'Name: ' + require('../index').getPlatform().name"
node -pe "'Version: ' + require('../index').getPlatform().bonescript"
node -pe "require('../index').digitalRead('P8_19')"
| mit |
itowtips/shirasagi | config/routes/gws/report/routes.rb | 1375 | SS::Application.routes.draw do
Gws::Report::Initializer
concern :deletion do
get :delete, on: :member
delete :destroy_all, on: :collection, path: ''
end
gws 'report' do
get '/' => redirect { |p, req| "#{req.path}/forms" }, as: :setting
resources :forms, concerns: :deletion do
match :publish, on: :member, via: [:get, :post]
match :depublish, on: :member, via: [:get, :post]
resources :columns, concerns: :deletion
end
resources :categories, concerns: [:deletion]
scope :files do
get '/' => redirect { |p, req| "#{req.path}/inbox" }, as: :files_main
resources :trashes, concerns: [:deletion], except: [:new, :create, :edit, :update] do
match :undo_delete, on: :member, via: [:get, :post]
end
resources :files, path: ':state', except: [:destroy] do
get :print, on: :member
match :publish, on: :member, via: [:get, :post]
match :depublish, on: :member, via: [:get, :post]
match :copy, on: :member, via: [:get, :post]
match :soft_delete, on: :member, via: [:get, :post]
post :soft_delete_all, on: :collection
end
resources :files, path: ':state/:form_id', only: [:new, :create], as: 'form_files'
end
namespace 'apis' do
get 'categories' => 'categories#index'
get 'files' => 'files#index'
end
end
end
| mit |
wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/mkdirp/node_modules/mock-fs/lib/directory.js | 2300 | var path = require('path');
var util = require('util');
var Item = require('./item');
var constants = process.binding('constants');
/**
* A directory.
* @constructor
*/
function Directory() {
Item.call(this);
/**
* Items in this directory.
* @type {Object.<string, Item>}
*/
this._items = {};
/**
* Permissions.
*/
this._mode = 0777;
}
util.inherits(Directory, Item);
/**
* Add an item to the directory.
* @param {string} name The name to give the item.
* @param {Item} item The item to add.
* @return {Item} The added item.
*/
Directory.prototype.addItem = function(name, item) {
if (this._items.hasOwnProperty(name)) {
throw new Error('Item with the same name already exists: ' + name);
}
this._items[name] = item;
++item.links;
if (item instanceof Directory) {
// for '.' entry
++item.links;
// for subdirectory
++this.links;
}
this.setMTime(new Date());
return item;
};
/**
* Get a named item.
* @param {string} name Item name.
* @return {Item} The named item (or null if none).
*/
Directory.prototype.getItem = function(name) {
var item = null;
if (this._items.hasOwnProperty(name)) {
item = this._items[name];
}
return item;
};
/**
* Remove an item.
* @param {string} name Name of item to remove.
* @return {Item} The orphan item.
*/
Directory.prototype.removeItem = function(name) {
if (!this._items.hasOwnProperty(name)) {
throw new Error('Item does not exist in directory: ' + name);
}
var item = this._items[name];
delete this._items[name];
--item.links;
if (item instanceof Directory) {
// for '.' entry
--item.links;
// for subdirectory
--this.links;
}
this.setMTime(new Date());
return item;
};
/**
* Get list of item names in this directory.
* @return {Array.<string>} Item names.
*/
Directory.prototype.list = function() {
return Object.keys(this._items).sort();
};
/**
* Get directory stats.
* @return {Object} Stats properties.
*/
Directory.prototype.getStats = function() {
var stats = Item.prototype.getStats.call(this);
stats.mode = this.getMode() | constants.S_IFDIR;
stats.size = 1;
stats.blocks = 1;
return stats;
};
/**
* Export the constructor.
* @type {function()}
*/
exports = module.exports = Directory;
| mit |
gdomorski/client-recon | contribute.md | 2774 | ##Project tools
####Initial Set-Up
Clone down the repo and head over to [Initial Set-Up](https://github.com/laudatory-flannel/client-recon/blob/master/setup.md) for step-by-step instructions to get Rapport running on your machine.
####Git-Splainin
This is a way to create Pull Request templates that can be used across the entire team and make it really easy to populate PR forms. It is a really great tool developed as a chrome extension. You can find it at the webstore.
[Get Git-Splainin](https://chrome.google.com/webstore/detail/git-splainin/adbhpaolgdpdjmejdnpakfncfkdneeea?hl=en-US)
####Getting Floobits
Floobits is awesome platform to collaboratively create and edit associated with the project. The repo is created as a workspace and then you connect your editor to the workspace. You will then have your sublime text/Atom/whatever be like google docs for code writing.
[Floobits project_url](https://floobits.com/urbantumbleweed/client-recon)
This project url is on the organization repo on the floo branch.
[set-up instruction](https://floobits.com/help/plugins/sublime)
##Github Tools:
[Github Guide to Issues and Milestones](https://guides.github.com/features/issues/)
####Milestones:
Milestones are an excellent way to contain tasks or issues associated with a feature. Milestones have a title, description and due-date. Github issues can be added to milestones.
####Pull Requests and Issues
Github issues and pull requests are a great way manage the development of a project. Issues are created with atomic feature additions or bugs. Pull requests are the means to merge development effort into master branch for production.
Issue definitions should be small and atomic. This is important so they can represent small, focused changes in code which are in turn encapsulated by small focused commits. Pull requests should be created with the specific issue or set of issues they address. It is possible to create the Pull Request before the issues are completed and create the points they will address as checkboxes.
[Task lists in issues and PRs](https://github.com/blog/1375%0A-task-lists-in-gfm-issues-pulls-comments)
Issues can have labels, assignees, and milestones.
Both issues an pull requests can have comment threads. All issues related communication should be kept with the issue on github. Issues can be linked from other issues. This is a great way to estabish relationships between related issues.
Also, it is possible to reference issues from commit messages to either close or reference them.
[Closing issues from commits](https://help.github.com/articles/closing-issues-via-commit-messages/)
[Linking issues with mentions](https://github.com/blog/957-introducing-issue-mentions)
####Labels and Assignees
| mit |
eslint/eslint.github.io | docs/developer-guide/scope-manager-interface.md | 10366 | ---
title: ScopeManager
layout: doc
edit_link: https://github.com/eslint/eslint/edit/master/docs/developer-guide/scope-manager-interface.md
---
<!-- Note: No pull requests accepted for this file. See README.md in the root directory for details. -->
# ScopeManager
This document was written based on the implementation of [eslint-scope](https://github.com/eslint/eslint-scope), a fork of [escope](https://github.com/estools/escope), and deprecates some members ESLint is not using.
----
## ScopeManager interface
`ScopeManager` object has all variable scopes.
### Fields
#### scopes
* **Type:** `Scope[]`
* **Description:** All scopes.
#### globalScope
* **Type:** `Scope`
* **Description:** The root scope.
### Methods
#### acquire(node, inner = false)
* **Parameters:**
* `node` (`ASTNode`) ... An AST node to get their scope.
* `inner` (`boolean`) ... If the node has multiple scope, this returns the outermost scope normally. If `inner` is `true` then this returns the innermost scope. Default is `false`.
* **Return type:** `Scope | null`
* **Description:** Get the scope of a given AST node. The gotten scope's `block` property is the node. This method never returns `function-expression-name` scope. If the node does not have their scope, this returns `null`.
#### getDeclaredVariables(node)
* **Parameters:**
* `node` (`ASTNode`) ... An AST node to get their variables.
* **Return type:** `Variable[]`
* **Description:** Get the variables that a given AST node defines. The gotten variables' `def[].node`/`def[].parent` property is the node. If the node does not define any variable, this returns an empty array.
### Deprecated members
Those members are defined but not used in ESLint.
#### isModule()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this program is module.
#### isImpliedStrict()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this program is strict mode implicitly. I.e., `options.impliedStrict === true`.
#### isStrictModeSupported()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this program supports strict mode. I.e., `options.ecmaVersion >= 5`.
#### acquireAll(node)
* **Parameters:**
* `node` (`ASTNode`) ... An AST node to get their scope.
* **Return type:** `Scope[] | null`
* **Description:** Get the scopes of a given AST node. The gotten scopes' `block` property is the node. If the node does not have their scope, this returns `null`.
----
## Scope interface
`Scope` object has all variables and references in the scope.
### Fields
#### type
* **Type:** `string`
* **Description:** The type of this scope. This is one of `"block"`, `"catch"`, `"class"`, `"for"`, `"function"`, `"function-expression-name"`, `"global"`, `"module"`, `"switch"`, `"with"`
#### isStrict
* **Type:** `boolean`
* **Description:** `true` if this scope is strict mode.
#### upper
* **Type:** `Scope | null`
* **Description:** The parent scope. If this is the global scope then this property is `null`.
#### childScopes
* **Type:** `Scope[]`
* **Description:** The array of child scopes. This does not include grandchild scopes.
#### variableScope
* **Type:** `Scope`
* **Description:** The scope which hosts variables which are defined by `var` declarations.
#### block
* **Type:** `ASTNode`
* **Description:** The AST node which created this scope.
#### variables
* **Type:** `Variable[]`
* **Description:** The array of all variables which are defined on this scope. This does not include variables which are defined in child scopes.
#### set
* **Type:** `Map<string, Variable>`
* **Description:** The map from variable names to variable objects.
> I hope to rename `set` field or replace by a method.
#### references
* **Type:** `Reference[]`
* **Description:** The array of all references on this scope. This does not include references in child scopes.
#### through
* **Type:** `Reference[]`
* **Description:** The array of references which could not be resolved in this scope.
#### functionExpressionScope
* **Type:** `boolean`
* **Description:** `true` if this scope is `"function-expression-name"` scope.
> I hope to deprecate `functionExpressionScope` field as replacing by `scope.type === "function-expression-name"`.
### Deprecated members
Those members are defined but not used in ESLint.
#### taints
* **Type:** `Map<string, boolean>`
* **Description:** The map from variable names to `tainted` flag.
#### dynamic
* **Type:** `boolean`
* **Description:** `true` if this scope is dynamic. I.e., the type of this scope is `"global"` or `"with"`.
#### directCallToEvalScope
* **Type:** `boolean`
* **Description:** `true` if this scope contains `eval()` invocations.
#### thisFound
* **Type:** `boolean`
* **Description:** `true` if this scope contains `this`.
#### resolve(node)
* **Parameters:**
* `node` (`ASTNode`) ... An AST node to get their reference object. The type of the node must be `"Identifier"`.
* **Return type:** `Reference | null`
* **Description:** Returns `this.references.find(r => r.identifier === node)`.
#### isStatic()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** Returns `!this.dynamic`.
#### isArgumentsMaterialized()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this is a `"function"` scope which has used `arguments` variable.
#### isThisMaterialized()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** Returns `this.thisFound`.
#### isUsedName(name)
* **Parameters:**
* `name` (`string`) ... The name to check.
* **Return type:** `boolean`
* **Description:** `true` if a given name is used in variable names or reference names.
----
## Variable interface
`Variable` object is variable's information.
### Fields
#### name
* **Type:** `string`
* **Description:** The name of this variable.
#### identifiers
* **Type:** `ASTNode[]`
* **Description:** The array of `Identifier` nodes which define this variable. If this variable is redeclared, this array includes two or more nodes.
> I hope to deprecate `identifiers` field as replacing by `defs[].name` field.
#### references
* **Type:** `Reference[]`
* **Description:** The array of the references of this variable.
#### defs
* **Type:** `Definition[]`
* **Description:** The array of the definitions of this variable.
### Deprecated members
Those members are defined but not used in ESLint.
#### tainted
* **Type:** `boolean`
* **Description:** The `tainted` flag. (always `false`)
#### stack
* **Type:** `boolean`
* **Description:** The `stack` flag. (I'm not sure what this means.)
----
## Reference interface
`Reference` object is reference's information.
### Fields
#### identifier
* **Type:** `ASTNode`
* **Description:** The `Identifier` node of this reference.
#### from
* **Type:** `Scope`
* **Description:** The `Scope` object that this reference is on.
#### resolved
* **Type:** `Variable | null`
* **Description:** The `Variable` object that this reference refers. If such variable was not defined, this is `null`.
#### writeExpr
* **Type:** `ASTNode | null`
* **Description:** The ASTNode object which is right-hand side.
#### init
* **Type:** `boolean`
* **Description:** `true` if this writing reference is a variable initializer or a default value.
### Methods
#### isWrite()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this reference is writing.
#### isRead()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this reference is reading.
#### isWriteOnly()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this reference is writing but not reading.
#### isReadOnly()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this reference is reading but not writing.
#### isReadWrite()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this reference is reading and writing.
### Deprecated members
Those members are defined but not used in ESLint.
#### tainted
* **Type:** `boolean`
* **Description:** The `tainted` flag. (always `false`)
#### flag
* **Type:** `number`
* **Description:** `1` is reading, `2` is writing, `3` is reading/writing.
#### partial
* **Type:** `boolean`
* **Description:** The `partial` flag.
#### isStatic()
* **Parameters:**
* **Return type:** `boolean`
* **Description:** `true` if this reference is resolved statically.
----
## Definition interface
`Definition` object is variable definition's information.
### Fields
#### type
* **Type:** `string`
* **Description:** The type of this definition. One of `"CatchClause"`, `"ClassName"`, `"FunctionName"`, `"ImplicitGlobalVariable"`, `"ImportBinding"`, `"Parameter"`, and `"Variable"`.
#### name
* **Type:** `ASTNode`
* **Description:** The `Identifier` node of this definition.
#### node
* **Type:** `ASTNode`
* **Description:** The enclosing node of the name.
| type | node |
|:---------------------------|:-----|
| `"CatchClause"` | `CatchClause`
| `"ClassName"` | `ClassDeclaration` or `ClassExpression`
| `"FunctionName"` | `FunctionDeclaration` or `FunctionExpression`
| `"ImplicitGlobalVariable"` | `Program`
| `"ImportBinding"` | `ImportSpecifier`, `ImportDefaultSpecifier`, or `ImportNamespaceSpecifier`
| `"Parameter"` | `FunctionDeclaration`, `FunctionExpression`, or `ArrowFunctionExpression`
| `"Variable"` | `VariableDeclarator`
#### parent
* **Type:** `ASTNode | undefined | null`
* **Description:** The enclosing statement node of the name.
| type | parent |
|:---------------------------|:-------|
| `"CatchClause"` | `null`
| `"ClassName"` | `null`
| `"FunctionName"` | `null`
| `"ImplicitGlobalVariable"` | `null`
| `"ImportBinding"` | `ImportDeclaration`
| `"Parameter"` | `null`
| `"Variable"` | `VariableDeclaration`
### Deprecated members
Those members are defined but not used in ESLint.
#### index
* **Type:** `number | undefined | null`
* **Description:** The index in the declaration statement.
#### kind
* **Type:** `string | undefined | null`
* **Description:** The kind of the declaration statement.
| mit |
beachyapp/standalone-migrations | vendor/migration_helpers/lib/migration_helper.rb | 1887 | module MigrationConstraintHelpers
# Creates a foreign key from +table+.+field+ against referenced_table.referenced_field
#
# table: The tablename
# field: A field of the table
# referenced_table: The table which contains the field referenced
# referenced_field: The field (which should be part of the primary key) of the referenced table
# cascade: delete & update on cascade?
def foreign_key(table, field, referenced_table, referenced_field = :id, cascade = true)
execute "ALTER TABLE #{table} ADD CONSTRAINT #{constraint_name(table, field)}
FOREIGN KEY #{constraint_name(table, field)} (#{field_list(field)})
REFERENCES #{referenced_table}(#{field_list(referenced_field)})
#{(cascade ? 'ON DELETE CASCADE ON UPDATE CASCADE' : '')}"
end
# Drops a foreign key from +table+.+field+ that has been created before with
# foreign_key method
#
# table: The table name
# field: A field (or array of fields) of the table
def drop_foreign_key(table, field)
execute "ALTER TABLE #{table} DROP FOREIGN KEY #{constraint_name(table, field)}"
end
# Creates a primary key for +table+, which right now HAS NOT primary key defined
#
# table: The table name
# field: A field (or array of fields) of the table that will be part of the primary key
def primary_key(table, field)
execute "ALTER TABLE #{table} ADD PRIMARY KEY(#{field_list(field)})"
end
private
# Creates a constraint name for table and field given as parameters
#
# table: The table name
# field: A field of the table
def constraint_name(table, field)
"fk_#{table}_#{field_list_name(field)}"
end
def field_list(fields)
fields.is_a?(Array) ? fields.join(',') : fields
end
def field_list_name(fields)
fields.is_a?(Array) ? fields.join('_') : fields
end
end
| mit |
zzamboni/hammerspoon | extensions/uielement/test_uielement.lua | 2388 | hs.uielement = require("hs.uielement")
hs.window = require("hs.window")
hs.timer = require("hs.timer")
hs.eventtap = require("hs.eventtap")
hs.application = require("hs.application")
function getPrefs()
hs.openPreferences()
return hs.uielement.focusedElement()
end
function getConsole()
hs.openConsole()
return hs.uielement.focusedElement()
end
function testHammerspoonElements()
local consoleElem = getConsole()
assertFalse(consoleElem:isApplication())
assertFalse(consoleElem:isWindow())
assertIsEqual("AXTextField", consoleElem:role())
local prefsElem = getPrefs()
assertFalse(prefsElem:isApplication())
assertFalse(prefsElem:isWindow())
assertIsEqual("AXCheckBox", prefsElem:role())
assertIsEqual(nil, prefsElem:selectedText())
local consoleElem2 = getConsole()
assertFalse(consoleElem:isApplication())
assertFalse(consoleElem:isWindow())
assertIsEqual("AXTextField", consoleElem:role())
assertFalse(consoleElem==prefsElem)
assertTrue(consoleElem==consoleElem2)
assertTrue(hs.window.find("Hammerspoon Console"):close())
assertTrue(hs.window.find("Hammerspoon Preferences"):close())
return success()
end
function testSelectedText()
local text = "abc123"
local textedit = hs.application.open("com.apple.TextEdit")
hs.timer.usleep(1000000)
hs.eventtap.keyStroke({"cmd"}, "n")
hs.timer.usleep(1000000)
hs.eventtap.keyStrokes(text)
hs.timer.usleep(20000)
hs.eventtap.keyStroke({"cmd"}, "a")
assertIsEqual(text, hs.uielement.focusedElement():selectedText())
textedit:kill9()
return success()
end
function testWatcherValues()
if (type(elemEvent) == "string" and elemEvent == "AXWindowMoved") then
app:kill()
return success()
else
return "Waiting for success..."
end
end
function testWatcher()
app = hs.application.open("com.apple.systempreferences", 1, true)
hs.timer.doAfter(1, function()
hs.window.find("System Preferences"):focus()
local elem = hs.uielement.focusedElement()
watcher = elem:newWatcher(function(element, event, thisWatcher, userdata)
elemEvent = event
assertIsEqual(watcher, thisWatcher:stop())
end)
assertIsEqual(watcher, watcher:start({hs.uielement.watcher.windowMoved}))
assertIsEqual(elem, watcher:element())
hs.timer.doAfter(1, function() elem:move({1,1}) end)
end)
return success()
end
| mit |
cbetheridge/simpleclassroom | static/third-party/closure-library/closure/goog/net/xhrio.js | 43124 | // Copyright 2006 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 Wrapper class for handling XmlHttpRequests.
*
* One off requests can be sent through goog.net.XhrIo.send() or an
* instance can be created to send multiple requests. Each request uses its
* own XmlHttpRequest object and handles clearing of the event callback to
* ensure no leaks.
*
* XhrIo is event based, it dispatches events on success, failure, finishing,
* ready-state change, or progress (download and upload).
*
* The ready-state or timeout event fires first, followed by
* a generic completed event. Then the abort, error, or success event
* is fired as appropriate. Progress events are fired as they are
* received. Lastly, the ready event will fire to indicate that the
* object may be used to make another request.
*
* The error event may also be called before completed and
* ready-state-change if the XmlHttpRequest.open() or .send() methods throw.
*
* This class does not support multiple requests, queuing, or prioritization.
*
* When progress events are supported by the browser, and progress is
* enabled via .setProgressEventsEnabled(true), the
* goog.net.EventType.PROGRESS event will be the re-dispatched browser
* progress event. Additionally, a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event
* will be fired for download and upload progress respectively.
*
*/
goog.provide('goog.net.XhrIo');
goog.provide('goog.net.XhrIo.ResponseType');
goog.require('goog.Timer');
goog.require('goog.array');
goog.require('goog.asserts');
goog.require('goog.debug.entryPointRegistry');
goog.require('goog.events.EventTarget');
goog.require('goog.json');
goog.require('goog.log');
goog.require('goog.net.ErrorCode');
goog.require('goog.net.EventType');
goog.require('goog.net.HttpStatus');
goog.require('goog.net.XmlHttp');
goog.require('goog.object');
goog.require('goog.string');
goog.require('goog.structs');
goog.require('goog.structs.Map');
goog.require('goog.uri.utils');
goog.require('goog.userAgent');
goog.forwardDeclare('goog.Uri');
/**
* Basic class for handling XMLHttpRequests.
* @param {goog.net.XmlHttpFactory=} opt_xmlHttpFactory Factory to use when
* creating XMLHttpRequest objects.
* @constructor
* @extends {goog.events.EventTarget}
*/
goog.net.XhrIo = function(opt_xmlHttpFactory) {
goog.net.XhrIo.base(this, 'constructor');
/**
* Map of default headers to add to every request, use:
* XhrIo.headers.set(name, value)
* @type {!goog.structs.Map}
*/
this.headers = new goog.structs.Map();
/**
* Optional XmlHttpFactory
* @private {goog.net.XmlHttpFactory}
*/
this.xmlHttpFactory_ = opt_xmlHttpFactory || null;
/**
* Whether XMLHttpRequest is active. A request is active from the time send()
* is called until onReadyStateChange() is complete, or error() or abort()
* is called.
* @private {boolean}
*/
this.active_ = false;
/**
* The XMLHttpRequest object that is being used for the transfer.
* @private {?goog.net.XhrLike.OrNative}
*/
this.xhr_ = null;
/**
* The options to use with the current XMLHttpRequest object.
* @private {Object}
*/
this.xhrOptions_ = null;
/**
* Last URL that was requested.
* @private {string|goog.Uri}
*/
this.lastUri_ = '';
/**
* Method for the last request.
* @private {string}
*/
this.lastMethod_ = '';
/**
* Last error code.
* @private {!goog.net.ErrorCode}
*/
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
/**
* Last error message.
* @private {Error|string}
*/
this.lastError_ = '';
/**
* Used to ensure that we don't dispatch an multiple ERROR events. This can
* happen in IE when it does a synchronous load and one error is handled in
* the ready statte change and one is handled due to send() throwing an
* exception.
* @private {boolean}
*/
this.errorDispatched_ = false;
/**
* Used to make sure we don't fire the complete event from inside a send call.
* @private {boolean}
*/
this.inSend_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.open.
* @private {boolean}
*/
this.inOpen_ = false;
/**
* Used in determining if a call to {@link #onReadyStateChange_} is from
* within a call to this.xhr_.abort.
* @private {boolean}
*/
this.inAbort_ = false;
/**
* Number of milliseconds after which an incomplete request will be aborted
* and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no timeout
* is set.
* @private {number}
*/
this.timeoutInterval_ = 0;
/**
* Timer to track request timeout.
* @private {?number}
*/
this.timeoutId_ = null;
/**
* The requested type for the response. The empty string means use the default
* XHR behavior.
* @private {goog.net.XhrIo.ResponseType}
*/
this.responseType_ = goog.net.XhrIo.ResponseType.DEFAULT;
/**
* Whether a "credentialed" request is to be sent (one that is aware of
* cookies and authentication). This is applicable only for cross-domain
* requests and more recent browsers that support this part of the HTTP Access
* Control standard.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-withcredentials-attribute
*
* @private {boolean}
*/
this.withCredentials_ = false;
/**
* Whether progress events are enabled for this request. This is
* disabled by default because setting a progress event handler
* causes pre-flight OPTIONS requests to be sent for CORS requests,
* even in cases where a pre-flight request would not otherwise be
* sent.
*
* @see http://xhr.spec.whatwg.org/#security-considerations
*
* Note that this can cause problems for Firefox 22 and below, as an
* older "LSProgressEvent" will be dispatched by the browser. That
* progress event is no longer supported, and can lead to failures,
* including throwing exceptions.
*
* @see http://bugzilla.mozilla.org/show_bug.cgi?id=845631
* @see b/23469793
*
* @private {boolean}
*/
this.progressEventsEnabled_ = false;
/**
* True if we can use XMLHttpRequest's timeout directly.
* @private {boolean}
*/
this.useXhr2Timeout_ = false;
};
goog.inherits(goog.net.XhrIo, goog.events.EventTarget);
/**
* Response types that may be requested for XMLHttpRequests.
* @enum {string}
* @see http://www.w3.org/TR/XMLHttpRequest/#the-responsetype-attribute
*/
goog.net.XhrIo.ResponseType = {
DEFAULT: '',
TEXT: 'text',
DOCUMENT: 'document',
// Not supported as of Chrome 10.0.612.1 dev
BLOB: 'blob',
ARRAY_BUFFER: 'arraybuffer'
};
/**
* A reference to the XhrIo logger
* @private {goog.debug.Logger}
* @const
*/
goog.net.XhrIo.prototype.logger_ = goog.log.getLogger('goog.net.XhrIo');
/**
* The Content-Type HTTP header name
* @type {string}
*/
goog.net.XhrIo.CONTENT_TYPE_HEADER = 'Content-Type';
/**
* The pattern matching the 'http' and 'https' URI schemes
* @type {!RegExp}
*/
goog.net.XhrIo.HTTP_SCHEME_PATTERN = /^https?$/i;
/**
* The methods that typically come along with form data. We set different
* headers depending on whether the HTTP action is one of these.
*/
goog.net.XhrIo.METHODS_WITH_FORM_DATA = ['POST', 'PUT'];
/**
* The Content-Type HTTP header value for a url-encoded form
* @type {string}
*/
goog.net.XhrIo.FORM_CONTENT_TYPE =
'application/x-www-form-urlencoded;charset=utf-8';
/**
* The XMLHttpRequest Level two timeout delay ms property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_TIMEOUT_ = 'timeout';
/**
* The XMLHttpRequest Level two ontimeout handler property name.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
*
* @private {string}
* @const
*/
goog.net.XhrIo.XHR2_ON_TIMEOUT_ = 'ontimeout';
/**
* All non-disposed instances of goog.net.XhrIo created
* by {@link goog.net.XhrIo.send} are in this Array.
* @see goog.net.XhrIo.cleanup
* @private {!Array<!goog.net.XhrIo>}
*/
goog.net.XhrIo.sendInstances_ = [];
/**
* Static send that creates a short lived instance of XhrIo to send the
* request.
* @see goog.net.XhrIo.cleanup
* @param {string|goog.Uri} url Uri to make request to.
* @param {?function(this:goog.net.XhrIo, ?)=} opt_callback Callback function
* for when request is complete.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
* @param {number=} opt_timeoutInterval Number of milliseconds after which an
* incomplete request will be aborted; 0 means no timeout is set.
* @param {boolean=} opt_withCredentials Whether to send credentials with the
* request. Default to false. See {@link goog.net.XhrIo#setWithCredentials}.
* @return {!goog.net.XhrIo} The sent XhrIo.
*/
goog.net.XhrIo.send = function(
url, opt_callback, opt_method, opt_content, opt_headers,
opt_timeoutInterval, opt_withCredentials) {
var x = new goog.net.XhrIo();
goog.net.XhrIo.sendInstances_.push(x);
if (opt_callback) {
x.listen(goog.net.EventType.COMPLETE, opt_callback);
}
x.listenOnce(goog.net.EventType.READY, x.cleanupSend_);
if (opt_timeoutInterval) {
x.setTimeoutInterval(opt_timeoutInterval);
}
if (opt_withCredentials) {
x.setWithCredentials(opt_withCredentials);
}
x.send(url, opt_method, opt_content, opt_headers);
return x;
};
/**
* Disposes all non-disposed instances of goog.net.XhrIo created by
* {@link goog.net.XhrIo.send}.
* {@link goog.net.XhrIo.send} cleans up the goog.net.XhrIo instance
* it creates when the request completes or fails. However, if
* the request never completes, then the goog.net.XhrIo is not disposed.
* This can occur if the window is unloaded before the request completes.
* We could have {@link goog.net.XhrIo.send} return the goog.net.XhrIo
* it creates and make the client of {@link goog.net.XhrIo.send} be
* responsible for disposing it in this case. However, this makes things
* significantly more complicated for the client, and the whole point
* of {@link goog.net.XhrIo.send} is that it's simple and easy to use.
* Clients of {@link goog.net.XhrIo.send} should call
* {@link goog.net.XhrIo.cleanup} when doing final
* cleanup on window unload.
*/
goog.net.XhrIo.cleanup = function() {
var instances = goog.net.XhrIo.sendInstances_;
while (instances.length) {
instances.pop().dispose();
}
};
/**
* Installs exception protection for all entry point introduced by
* goog.net.XhrIo instances which are not protected by
* {@link goog.debug.ErrorHandler#protectWindowSetTimeout},
* {@link goog.debug.ErrorHandler#protectWindowSetInterval}, or
* {@link goog.events.protectBrowserEventEntryPoint}.
*
* @param {goog.debug.ErrorHandler} errorHandler Error handler with which to
* protect the entry point(s).
*/
goog.net.XhrIo.protectEntryPoints = function(errorHandler) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
errorHandler.protectEntryPoint(
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
};
/**
* Disposes of the specified goog.net.XhrIo created by
* {@link goog.net.XhrIo.send} and removes it from
* {@link goog.net.XhrIo.pendingStaticSendInstances_}.
* @private
*/
goog.net.XhrIo.prototype.cleanupSend_ = function() {
this.dispose();
goog.array.remove(goog.net.XhrIo.sendInstances_, this);
};
/**
* Returns the number of milliseconds after which an incomplete request will be
* aborted, or 0 if no timeout is set.
* @return {number} Timeout interval in milliseconds.
*/
goog.net.XhrIo.prototype.getTimeoutInterval = function() {
return this.timeoutInterval_;
};
/**
* Sets the number of milliseconds after which an incomplete request will be
* aborted and a {@link goog.net.EventType.TIMEOUT} event raised; 0 means no
* timeout is set.
* @param {number} ms Timeout interval in milliseconds; 0 means none.
*/
goog.net.XhrIo.prototype.setTimeoutInterval = function(ms) {
this.timeoutInterval_ = Math.max(0, ms);
};
/**
* Sets the desired type for the response. At time of writing, this is only
* supported in very recent versions of WebKit (10.0.612.1 dev and later).
*
* If this is used, the response may only be accessed via {@link #getResponse}.
*
* @param {goog.net.XhrIo.ResponseType} type The desired type for the response.
*/
goog.net.XhrIo.prototype.setResponseType = function(type) {
this.responseType_ = type;
};
/**
* Gets the desired type for the response.
* @return {goog.net.XhrIo.ResponseType} The desired type for the response.
*/
goog.net.XhrIo.prototype.getResponseType = function() {
return this.responseType_;
};
/**
* Sets whether a "credentialed" request that is aware of cookie and
* authentication information should be made. This option is only supported by
* browsers that support HTTP Access Control. As of this writing, this option
* is not supported in IE.
*
* @param {boolean} withCredentials Whether this should be a "credentialed"
* request.
*/
goog.net.XhrIo.prototype.setWithCredentials = function(withCredentials) {
this.withCredentials_ = withCredentials;
};
/**
* Gets whether a "credentialed" request is to be sent.
* @return {boolean} The desired type for the response.
*/
goog.net.XhrIo.prototype.getWithCredentials = function() {
return this.withCredentials_;
};
/**
* Sets whether progress events are enabled for this request. Note
* that progress events require pre-flight OPTIONS request handling
* for CORS requests, and may cause trouble with older browsers. See
* progressEventsEnabled_ for details.
* @param {boolean} enabled Whether progress events should be enabled.
*/
goog.net.XhrIo.prototype.setProgressEventsEnabled = function(enabled) {
this.progressEventsEnabled_ = enabled;
};
/**
* Gets whether progress events are enabled.
* @return {boolean} Whether progress events are enabled for this request.
*/
goog.net.XhrIo.prototype.getProgressEventsEnabled = function() {
return this.progressEventsEnabled_;
};
/**
* Instance send that actually uses XMLHttpRequest to make a server call.
* @param {string|goog.Uri} url Uri to make request to.
* @param {string=} opt_method Send method, default: GET.
* @param {ArrayBuffer|ArrayBufferView|Blob|Document|FormData|string=}
* opt_content Body data.
* @param {Object|goog.structs.Map=} opt_headers Map of headers to add to the
* request.
*/
goog.net.XhrIo.prototype.send = function(
url, opt_method, opt_content, opt_headers) {
if (this.xhr_) {
throw Error(
'[goog.net.XhrIo] Object is active with another request=' +
this.lastUri_ + '; newUri=' + url);
}
var method = opt_method ? opt_method.toUpperCase() : 'GET';
this.lastUri_ = url;
this.lastError_ = '';
this.lastErrorCode_ = goog.net.ErrorCode.NO_ERROR;
this.lastMethod_ = method;
this.errorDispatched_ = false;
this.active_ = true;
// Use the factory to create the XHR object and options
this.xhr_ = this.createXhr();
this.xhrOptions_ = this.xmlHttpFactory_ ? this.xmlHttpFactory_.getOptions() :
goog.net.XmlHttp.getOptions();
// Set up the onreadystatechange callback
this.xhr_.onreadystatechange = goog.bind(this.onReadyStateChange_, this);
// Set up upload/download progress events, if progress events are supported.
if (this.getProgressEventsEnabled() && 'onprogress' in this.xhr_) {
this.xhr_.onprogress =
goog.bind(function(e) { this.onProgressHandler_(e, true); }, this);
if (this.xhr_.upload) {
this.xhr_.upload.onprogress = goog.bind(this.onProgressHandler_, this);
}
}
/**
* Try to open the XMLHttpRequest (always async), if an error occurs here it
* is generally permission denied
* @preserveTry
*/
try {
goog.log.fine(this.logger_, this.formatMsg_('Opening Xhr'));
this.inOpen_ = true;
this.xhr_.open(method, String(url), true); // Always async!
this.inOpen_ = false;
} catch (err) {
goog.log.fine(
this.logger_, this.formatMsg_('Error opening Xhr: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
return;
}
// We can't use null since this won't allow requests with form data to have a
// content length specified which will cause some proxies to return a 411
// error.
var content = opt_content || '';
var headers = this.headers.clone();
// Add headers specific to this request
if (opt_headers) {
goog.structs.forEach(
opt_headers, function(value, key) { headers.set(key, value); });
}
// Find whether a content type header is set, ignoring case.
// HTTP header names are case-insensitive. See:
// http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
var contentTypeKey =
goog.array.find(headers.getKeys(), goog.net.XhrIo.isContentTypeHeader_);
var contentIsFormData =
(goog.global['FormData'] && (content instanceof goog.global['FormData']));
if (goog.array.contains(goog.net.XhrIo.METHODS_WITH_FORM_DATA, method) &&
!contentTypeKey && !contentIsFormData) {
// For requests typically with form data, default to the url-encoded form
// content type unless this is a FormData request. For FormData,
// the browser will automatically add a multipart/form-data content type
// with an appropriate multipart boundary.
headers.set(
goog.net.XhrIo.CONTENT_TYPE_HEADER, goog.net.XhrIo.FORM_CONTENT_TYPE);
}
// Add the headers to the Xhr object
headers.forEach(function(value, key) {
this.xhr_.setRequestHeader(key, value);
}, this);
if (this.responseType_) {
this.xhr_.responseType = this.responseType_;
}
if (goog.object.containsKey(this.xhr_, 'withCredentials')) {
this.xhr_.withCredentials = this.withCredentials_;
}
/**
* Try to send the request, or other wise report an error (404 not found).
* @preserveTry
*/
try {
this.cleanUpTimeoutTimer_(); // Paranoid, should never be running.
if (this.timeoutInterval_ > 0) {
this.useXhr2Timeout_ = goog.net.XhrIo.shouldUseXhr2Timeout_(this.xhr_);
goog.log.fine(
this.logger_, this.formatMsg_(
'Will abort after ' + this.timeoutInterval_ +
'ms if incomplete, xhr2 ' + this.useXhr2Timeout_));
if (this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_TIMEOUT_] = this.timeoutInterval_;
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] =
goog.bind(this.timeout_, this);
} else {
this.timeoutId_ =
goog.Timer.callOnce(this.timeout_, this.timeoutInterval_, this);
}
}
goog.log.fine(this.logger_, this.formatMsg_('Sending request'));
this.inSend_ = true;
this.xhr_.send(content);
this.inSend_ = false;
} catch (err) {
goog.log.fine(this.logger_, this.formatMsg_('Send error: ' + err.message));
this.error_(goog.net.ErrorCode.EXCEPTION, err);
}
};
/**
* Determines if the argument is an XMLHttpRequest that supports the level 2
* timeout value and event.
*
* Currently, FF 21.0 OS X has the fields but won't actually call the timeout
* handler. Perhaps the confusion in the bug referenced below hasn't
* entirely been resolved.
*
* @see http://www.w3.org/TR/XMLHttpRequest/#the-timeout-attribute
* @see https://bugzilla.mozilla.org/show_bug.cgi?id=525816
*
* @param {!goog.net.XhrLike.OrNative} xhr The request.
* @return {boolean} True if the request supports level 2 timeout.
* @private
*/
goog.net.XhrIo.shouldUseXhr2Timeout_ = function(xhr) {
return goog.userAgent.IE && goog.userAgent.isVersionOrHigher(9) &&
goog.isNumber(xhr[goog.net.XhrIo.XHR2_TIMEOUT_]) &&
goog.isDef(xhr[goog.net.XhrIo.XHR2_ON_TIMEOUT_]);
};
/**
* @param {string} header An HTTP header key.
* @return {boolean} Whether the key is a content type header (ignoring
* case.
* @private
*/
goog.net.XhrIo.isContentTypeHeader_ = function(header) {
return goog.string.caseInsensitiveEquals(
goog.net.XhrIo.CONTENT_TYPE_HEADER, header);
};
/**
* Creates a new XHR object.
* @return {!goog.net.XhrLike.OrNative} The newly created XHR object.
* @protected
*/
goog.net.XhrIo.prototype.createXhr = function() {
return this.xmlHttpFactory_ ? this.xmlHttpFactory_.createInstance() :
goog.net.XmlHttp();
};
/**
* The request didn't complete after {@link goog.net.XhrIo#timeoutInterval_}
* milliseconds; raises a {@link goog.net.EventType.TIMEOUT} event and aborts
* the request.
* @private
*/
goog.net.XhrIo.prototype.timeout_ = function() {
if (typeof goog == 'undefined') {
// If goog is undefined then the callback has occurred as the application
// is unloading and will error. Thus we let it silently fail.
} else if (this.xhr_) {
this.lastError_ =
'Timed out after ' + this.timeoutInterval_ + 'ms, aborting';
this.lastErrorCode_ = goog.net.ErrorCode.TIMEOUT;
goog.log.fine(this.logger_, this.formatMsg_(this.lastError_));
this.dispatchEvent(goog.net.EventType.TIMEOUT);
this.abort(goog.net.ErrorCode.TIMEOUT);
}
};
/**
* Something errorred, so inactivate, fire error callback and clean up
* @param {goog.net.ErrorCode} errorCode The error code.
* @param {Error} err The error object.
* @private
*/
goog.net.XhrIo.prototype.error_ = function(errorCode, err) {
this.active_ = false;
if (this.xhr_) {
this.inAbort_ = true;
this.xhr_.abort(); // Ensures XHR isn't hung (FF)
this.inAbort_ = false;
}
this.lastError_ = err;
this.lastErrorCode_ = errorCode;
this.dispatchErrors_();
this.cleanUpXhr_();
};
/**
* Dispatches COMPLETE and ERROR in case of an error. This ensures that we do
* not dispatch multiple error events.
* @private
*/
goog.net.XhrIo.prototype.dispatchErrors_ = function() {
if (!this.errorDispatched_) {
this.errorDispatched_ = true;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ERROR);
}
};
/**
* Abort the current XMLHttpRequest
* @param {goog.net.ErrorCode=} opt_failureCode Optional error code to use -
* defaults to ABORT.
*/
goog.net.XhrIo.prototype.abort = function(opt_failureCode) {
if (this.xhr_ && this.active_) {
goog.log.fine(this.logger_, this.formatMsg_('Aborting'));
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
this.lastErrorCode_ = opt_failureCode || goog.net.ErrorCode.ABORT;
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.ABORT);
this.cleanUpXhr_();
}
};
/**
* Nullifies all callbacks to reduce risks of leaks.
* @override
* @protected
*/
goog.net.XhrIo.prototype.disposeInternal = function() {
if (this.xhr_) {
// We explicitly do not call xhr_.abort() unless active_ is still true.
// This is to avoid unnecessarily aborting a successful request when
// dispose() is called in a callback triggered by a complete response, but
// in which browser cleanup has not yet finished.
// (See http://b/issue?id=1684217.)
if (this.active_) {
this.active_ = false;
this.inAbort_ = true;
this.xhr_.abort();
this.inAbort_ = false;
}
this.cleanUpXhr_(true);
}
goog.net.XhrIo.base(this, 'disposeInternal');
};
/**
* Internal handler for the XHR object's readystatechange event. This method
* checks the status and the readystate and fires the correct callbacks.
* If the request has ended, the handlers are cleaned up and the XHR object is
* nullified.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChange_ = function() {
if (this.isDisposed()) {
// This method is the target of an untracked goog.Timer.callOnce().
return;
}
if (!this.inOpen_ && !this.inSend_ && !this.inAbort_) {
// Were not being called from within a call to this.xhr_.send
// this.xhr_.abort, or this.xhr_.open, so this is an entry point
this.onReadyStateChangeEntryPoint_();
} else {
this.onReadyStateChangeHelper_();
}
};
/**
* Used to protect the onreadystatechange handler entry point. Necessary
* as {#onReadyStateChange_} maybe called from within send or abort, this
* method is only called when {#onReadyStateChange_} is called as an
* entry point.
* {@see #protectEntryPoints}
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ = function() {
this.onReadyStateChangeHelper_();
};
/**
* Helper for {@link #onReadyStateChange_}. This is used so that
* entry point calls to {@link #onReadyStateChange_} can be routed through
* {@link #onReadyStateChangeEntryPoint_}.
* @private
*/
goog.net.XhrIo.prototype.onReadyStateChangeHelper_ = function() {
if (!this.active_) {
// can get called inside abort call
return;
}
if (typeof goog == 'undefined') {
// NOTE(user): If goog is undefined then the callback has occurred as the
// application is unloading and will error. Thus we let it silently fail.
} else if (
this.xhrOptions_[goog.net.XmlHttp.OptionType.LOCAL_REQUEST_ERROR] &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE &&
this.getStatus() == 2) {
// NOTE(user): In IE if send() errors on a *local* request the readystate
// is still changed to COMPLETE. We need to ignore it and allow the
// try/catch around send() to pick up the error.
goog.log.fine(
this.logger_,
this.formatMsg_('Local request error detected and ignored'));
} else {
// In IE when the response has been cached we sometimes get the callback
// from inside the send call and this usually breaks code that assumes that
// XhrIo is asynchronous. If that is the case we delay the callback
// using a timer.
if (this.inSend_ &&
this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE) {
goog.Timer.callOnce(this.onReadyStateChange_, 0, this);
return;
}
this.dispatchEvent(goog.net.EventType.READY_STATE_CHANGE);
// readyState indicates the transfer has finished
if (this.isComplete()) {
goog.log.fine(this.logger_, this.formatMsg_('Request complete'));
this.active_ = false;
try {
// Call the specific callbacks for success or failure. Only call the
// success if the status is 200 (HTTP_OK) or 304 (HTTP_CACHED)
if (this.isSuccess()) {
this.dispatchEvent(goog.net.EventType.COMPLETE);
this.dispatchEvent(goog.net.EventType.SUCCESS);
} else {
this.lastErrorCode_ = goog.net.ErrorCode.HTTP_ERROR;
this.lastError_ =
this.getStatusText() + ' [' + this.getStatus() + ']';
this.dispatchErrors_();
}
} finally {
this.cleanUpXhr_();
}
}
}
};
/**
* Internal handler for the XHR object's onprogress event. Fires both a generic
* PROGRESS event and either a DOWNLOAD_PROGRESS or UPLOAD_PROGRESS event to
* allow specific binding for each XHR progress event.
* @param {!ProgressEvent} e XHR progress event.
* @param {boolean=} opt_isDownload Whether the current progress event is from a
* download. Used to determine whether DOWNLOAD_PROGRESS or UPLOAD_PROGRESS
* event should be dispatched.
* @private
*/
goog.net.XhrIo.prototype.onProgressHandler_ = function(e, opt_isDownload) {
goog.asserts.assert(
e.type === goog.net.EventType.PROGRESS,
'goog.net.EventType.PROGRESS is of the same type as raw XHR progress.');
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(e, goog.net.EventType.PROGRESS));
this.dispatchEvent(
goog.net.XhrIo.buildProgressEvent_(
e, opt_isDownload ? goog.net.EventType.DOWNLOAD_PROGRESS :
goog.net.EventType.UPLOAD_PROGRESS));
};
/**
* Creates a representation of the native ProgressEvent. IE doesn't support
* constructing ProgressEvent via "new", and the alternatives (e.g.,
* ProgressEvent.initProgressEvent) are non-standard or deprecated.
* @param {!ProgressEvent} e XHR progress event.
* @param {!goog.net.EventType} eventType The type of the event.
* @return {!ProgressEvent} The progress event.
* @private
*/
goog.net.XhrIo.buildProgressEvent_ = function(e, eventType) {
return /** @type {!ProgressEvent} */ ({
type: eventType,
lengthComputable: e.lengthComputable,
loaded: e.loaded,
total: e.total
});
};
/**
* Remove the listener to protect against leaks, and nullify the XMLHttpRequest
* object.
* @param {boolean=} opt_fromDispose If this is from the dispose (don't want to
* fire any events).
* @private
*/
goog.net.XhrIo.prototype.cleanUpXhr_ = function(opt_fromDispose) {
if (this.xhr_) {
// Cancel any pending timeout event handler.
this.cleanUpTimeoutTimer_();
// Save reference so we can mark it as closed after the READY event. The
// READY event may trigger another request, thus we must nullify this.xhr_
var xhr = this.xhr_;
var clearedOnReadyStateChange =
this.xhrOptions_[goog.net.XmlHttp.OptionType.USE_NULL_FUNCTION] ?
goog.nullFunction :
null;
this.xhr_ = null;
this.xhrOptions_ = null;
if (!opt_fromDispose) {
this.dispatchEvent(goog.net.EventType.READY);
}
try {
// NOTE(user): Not nullifying in FireFox can still leak if the callbacks
// are defined in the same scope as the instance of XhrIo. But, IE doesn't
// allow you to set the onreadystatechange to NULL so nullFunction is
// used.
xhr.onreadystatechange = clearedOnReadyStateChange;
} catch (e) {
// This seems to occur with a Gears HTTP request. Delayed the setting of
// this onreadystatechange until after READY is sent out and catching the
// error to see if we can track down the problem.
goog.log.error(
this.logger_,
'Problem encountered resetting onreadystatechange: ' + e.message);
}
}
};
/**
* Make sure the timeout timer isn't running.
* @private
*/
goog.net.XhrIo.prototype.cleanUpTimeoutTimer_ = function() {
if (this.xhr_ && this.useXhr2Timeout_) {
this.xhr_[goog.net.XhrIo.XHR2_ON_TIMEOUT_] = null;
}
if (goog.isNumber(this.timeoutId_)) {
goog.Timer.clear(this.timeoutId_);
this.timeoutId_ = null;
}
};
/**
* @return {boolean} Whether there is an active request.
*/
goog.net.XhrIo.prototype.isActive = function() {
return !!this.xhr_;
};
/**
* @return {boolean} Whether the request has completed.
*/
goog.net.XhrIo.prototype.isComplete = function() {
return this.getReadyState() == goog.net.XmlHttp.ReadyState.COMPLETE;
};
/**
* @return {boolean} Whether the request completed with a success.
*/
goog.net.XhrIo.prototype.isSuccess = function() {
var status = this.getStatus();
// A zero status code is considered successful for local files.
return goog.net.HttpStatus.isSuccess(status) ||
status === 0 && !this.isLastUriEffectiveSchemeHttp_();
};
/**
* @return {boolean} whether the effective scheme of the last URI that was
* fetched was 'http' or 'https'.
* @private
*/
goog.net.XhrIo.prototype.isLastUriEffectiveSchemeHttp_ = function() {
var scheme = goog.uri.utils.getEffectiveScheme(String(this.lastUri_));
return goog.net.XhrIo.HTTP_SCHEME_PATTERN.test(scheme);
};
/**
* Get the readystate from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {goog.net.XmlHttp.ReadyState} goog.net.XmlHttp.ReadyState.*.
*/
goog.net.XhrIo.prototype.getReadyState = function() {
return this.xhr_ ?
/** @type {goog.net.XmlHttp.ReadyState} */ (this.xhr_.readyState) :
goog.net.XmlHttp.ReadyState
.UNINITIALIZED;
};
/**
* Get the status from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {number} Http status.
*/
goog.net.XhrIo.prototype.getStatus = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
* @preserveTry
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.status :
-1;
} catch (e) {
return -1;
}
};
/**
* Get the status text from the Xhr object
* Will only return correct result when called from the context of a callback
* @return {string} Status text.
*/
goog.net.XhrIo.prototype.getStatusText = function() {
/**
* IE doesn't like you checking status until the readystate is greater than 2
* (i.e. it is receiving or complete). The try/catch is used for when the
* page is unloading and an ERROR_NOT_AVAILABLE may occur when accessing xhr_.
* @preserveTry
*/
try {
return this.getReadyState() > goog.net.XmlHttp.ReadyState.LOADED ?
this.xhr_.statusText :
'';
} catch (e) {
goog.log.fine(this.logger_, 'Can not get status: ' + e.message);
return '';
}
};
/**
* Get the last Uri that was requested
* @return {string} Last Uri.
*/
goog.net.XhrIo.prototype.getLastUri = function() {
return String(this.lastUri_);
};
/**
* Get the response text from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {string} Result from the server, or '' if no result available.
*/
goog.net.XhrIo.prototype.getResponseText = function() {
/** @preserveTry */
try {
return this.xhr_ ? this.xhr_.responseText : '';
} catch (e) {
// http://www.w3.org/TR/XMLHttpRequest/#the-responsetext-attribute
// states that responseText should return '' (and responseXML null)
// when the state is not LOADING or DONE. Instead, IE can
// throw unexpected exceptions, for example when a request is aborted
// or no data is available yet.
goog.log.fine(this.logger_, 'Can not get responseText: ' + e.message);
return '';
}
};
/**
* Get the response body from the Xhr object. This property is only available
* in IE since version 7 according to MSDN:
* http://msdn.microsoft.com/en-us/library/ie/ms534368(v=vs.85).aspx
* Will only return correct result when called from the context of a callback.
*
* One option is to construct a VBArray from the returned object and convert
* it to a JavaScript array using the toArray method:
* {@code (new window['VBArray'](xhrIo.getResponseBody())).toArray()}
* This will result in an array of numbers in the range of [0..255]
*
* Another option is to use the VBScript CStr method to convert it into a
* string as outlined in http://stackoverflow.com/questions/1919972
*
* @return {Object} Binary result from the server or null if not available.
*/
goog.net.XhrIo.prototype.getResponseBody = function() {
/** @preserveTry */
try {
if (this.xhr_ && 'responseBody' in this.xhr_) {
return this.xhr_['responseBody'];
}
} catch (e) {
// IE can throw unexpected exceptions, for example when a request is aborted
// or no data is yet available.
goog.log.fine(this.logger_, 'Can not get responseBody: ' + e.message);
}
return null;
};
/**
* Get the response XML from the Xhr object
* Will only return correct result when called from the context of a callback.
* @return {Document} The DOM Document representing the XML file, or null
* if no result available.
*/
goog.net.XhrIo.prototype.getResponseXml = function() {
/** @preserveTry */
try {
return this.xhr_ ? this.xhr_.responseXML : null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get responseXML: ' + e.message);
return null;
}
};
/**
* Get the response and evaluates it as JSON from the Xhr object
* Will only return correct result when called from the context of a callback
* @param {string=} opt_xssiPrefix Optional XSSI prefix string to use for
* stripping of the response before parsing. This needs to be set only if
* your backend server prepends the same prefix string to the JSON response.
* @return {Object|undefined} JavaScript object.
*/
goog.net.XhrIo.prototype.getResponseJson = function(opt_xssiPrefix) {
if (!this.xhr_) {
return undefined;
}
var responseText = this.xhr_.responseText;
if (opt_xssiPrefix && responseText.indexOf(opt_xssiPrefix) == 0) {
responseText = responseText.substring(opt_xssiPrefix.length);
}
return goog.json.parse(responseText);
};
/**
* Get the response as the type specificed by {@link #setResponseType}. At time
* of writing, this is only directly supported in very recent versions of WebKit
* (10.0.612.1 dev and later). If the field is not supported directly, we will
* try to emulate it.
*
* Emulating the response means following the rules laid out at
* http://www.w3.org/TR/XMLHttpRequest/#the-response-attribute
*
* On browsers with no support for this (Chrome < 10, Firefox < 4, etc), only
* response types of DEFAULT or TEXT may be used, and the response returned will
* be the text response.
*
* On browsers with Mozilla's draft support for array buffers (Firefox 4, 5),
* only response types of DEFAULT, TEXT, and ARRAY_BUFFER may be used, and the
* response returned will be either the text response or the Mozilla
* implementation of the array buffer response.
*
* On browsers will full support, any valid response type supported by the
* browser may be used, and the response provided by the browser will be
* returned.
*
* @return {*} The response.
*/
goog.net.XhrIo.prototype.getResponse = function() {
/** @preserveTry */
try {
if (!this.xhr_) {
return null;
}
if ('response' in this.xhr_) {
return this.xhr_.response;
}
switch (this.responseType_) {
case goog.net.XhrIo.ResponseType.DEFAULT:
case goog.net.XhrIo.ResponseType.TEXT:
return this.xhr_.responseText;
// DOCUMENT and BLOB don't need to be handled here because they are
// introduced in the same spec that adds the .response field, and would
// have been caught above.
// ARRAY_BUFFER needs an implementation for Firefox 4, where it was
// implemented using a draft spec rather than the final spec.
case goog.net.XhrIo.ResponseType.ARRAY_BUFFER:
if ('mozResponseArrayBuffer' in this.xhr_) {
return this.xhr_.mozResponseArrayBuffer;
}
}
// Fell through to a response type that is not supported on this browser.
goog.log.error(
this.logger_, 'Response type ' + this.responseType_ + ' is not ' +
'supported on this browser');
return null;
} catch (e) {
goog.log.fine(this.logger_, 'Can not get response: ' + e.message);
return null;
}
};
/**
* Get the value of the response-header with the given name from the Xhr object
* Will only return correct result when called from the context of a callback
* and the request has completed
* @param {string} key The name of the response-header to retrieve.
* @return {string|undefined} The value of the response-header named key.
*/
goog.net.XhrIo.prototype.getResponseHeader = function(key) {
return this.xhr_ && this.isComplete() ? this.xhr_.getResponseHeader(key) :
undefined;
};
/**
* Gets the text of all the headers in the response.
* Will only return correct result when called from the context of a callback
* and the request has completed.
* @return {string} The value of the response headers or empty string.
*/
goog.net.XhrIo.prototype.getAllResponseHeaders = function() {
return this.xhr_ && this.isComplete() ? this.xhr_.getAllResponseHeaders() :
'';
};
/**
* Returns all response headers as a key-value map.
* Multiple values for the same header key can be combined into one,
* separated by a comma and a space.
* Note that the native getResponseHeader method for retrieving a single header
* does a case insensitive match on the header name. This method does not
* include any case normalization logic, it will just return a key-value
* representation of the headers.
* See: http://www.w3.org/TR/XMLHttpRequest/#the-getresponseheader()-method
* @return {!Object<string, string>} An object with the header keys as keys
* and header values as values.
*/
goog.net.XhrIo.prototype.getResponseHeaders = function() {
var headersObject = {};
var headersArray = this.getAllResponseHeaders().split('\r\n');
for (var i = 0; i < headersArray.length; i++) {
if (goog.string.isEmptyOrWhitespace(headersArray[i])) {
continue;
}
var keyValue = goog.string.splitLimit(headersArray[i], ': ', 2);
if (headersObject[keyValue[0]]) {
headersObject[keyValue[0]] += ', ' + keyValue[1];
} else {
headersObject[keyValue[0]] = keyValue[1];
}
}
return headersObject;
};
/**
* Get the last error message
* @return {goog.net.ErrorCode} Last error code.
*/
goog.net.XhrIo.prototype.getLastErrorCode = function() {
return this.lastErrorCode_;
};
/**
* Get the last error message
* @return {string} Last error message.
*/
goog.net.XhrIo.prototype.getLastError = function() {
return goog.isString(this.lastError_) ? this.lastError_ :
String(this.lastError_);
};
/**
* Adds the last method, status and URI to the message. This is used to add
* this information to the logging calls.
* @param {string} msg The message text that we want to add the extra text to.
* @return {string} The message with the extra text appended.
* @private
*/
goog.net.XhrIo.prototype.formatMsg_ = function(msg) {
return msg + ' [' + this.lastMethod_ + ' ' + this.lastUri_ + ' ' +
this.getStatus() + ']';
};
// Register the xhr handler as an entry point, so that
// it can be monitored for exception handling, etc.
goog.debug.entryPointRegistry.register(
/**
* @param {function(!Function): !Function} transformer The transforming
* function.
*/
function(transformer) {
goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_ =
transformer(goog.net.XhrIo.prototype.onReadyStateChangeEntryPoint_);
});
| mit |
n1ghtmare/Algorithm-Implementations | Ranrot-B-Pseudo_Random_Number_Generator/Go/jcla1/ranrotb_prng.go | 443 | package ranrotb
// Call with seed and it will return a closure
// which will return pseudo-random numbers on
// consecutive calls
// Note: seed could be uint32(time.Now().Unix())
func rrbRand(seed uint32) func() uint32 {
var lo, hi uint32
// In Go ^ is the bitwise complement operator
// In C this would be the tilde (~)
lo, hi = seed, ^seed
return func() uint32 {
hi = (hi << 16) + (lo >> 16)
hi += lo
lo += hi
return hi
}
}
| mit |
Bragaman/atom | lecture6/source/src/main/java/ru/atom/model/dao/MatchDao.java | 737 | package ru.atom.model.dao;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import ru.atom.model.data.Match;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
public class MatchDao implements Dao<Match> {
private static final Logger log = LogManager.getLogger(MatchDao.class);
@Override
public List<Match> getAll() {
throw new NotImplementedException();
}
@Override
public List<Match> getAllWhere(String... hqlConditions) {
throw new NotImplementedException();
}
@Override
public void insert(Match match) {
}
}
| mit |
XristosMallios/cache | exareme-master/src/main/java/madgik/exareme/master/engine/rmi/OptimizerConstants.java | 248 | /**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.master.engine.rmi;
/**
* @author heraldkllapi
*/
public class OptimizerConstants {
public static boolean USE_SKETCH = false;
public static int MAX_TABLE_PARTS = 2;
}
| mit |
fahidRM/aqua-couch-test | test/client/pages/admin/statuses/search/actions.js | 4225 | 'use strict';
const Code = require('code');
const Constants = require('../../../../../../client/pages/admin/statuses/search/constants');
const FluxConstant = require('flux-constant');
const Lab = require('lab');
const Proxyquire = require('proxyquire');
const lab = exports.lab = Lab.script();
const stub = {
ApiActions: {
get: function () {
stub.ApiActions.get.mock.apply(null, arguments);
},
post: function () {
stub.ApiActions.post.mock.apply(null, arguments);
}
},
Store: {
dispatch: function () {
stub.Store.dispatch.mock.apply(null, arguments);
}
},
ReactRouter: {
browserHistory: {
push: () => {},
replace: () => {}
}
}
};
const Actions = Proxyquire('../../../../../../client/pages/admin/statuses/search/actions', {
'../../../../actions/api': stub.ApiActions,
'./store': stub.Store,
'react-router': stub.ReactRouter
});
lab.experiment('Admin Statuses Search Actions', () => {
lab.test('it calls ApiActions.get from getResults', (done) => {
stub.ApiActions.get.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.not.exist();
done();
};
Actions.getResults({});
});
lab.test('it calls browserHistory.push from changeSearchQuery', (done) => {
const scrollTo = global.window.scrollTo;
global.window.scrollTo = function () {
global.window.scrollTo = scrollTo;
done();
};
stub.ReactRouter.browserHistory.push = function (config) {
stub.ReactRouter.browserHistory.push = () => {};
Code.expect(config.pathname).to.be.a.string();
Code.expect(config.query).to.be.an.object();
};
Actions.changeSearchQuery({});
});
lab.test('it calls dispatch from showCreateNew', (done) => {
stub.Store.dispatch.mock = function (action) {
if (action.type === Constants.SHOW_CREATE_NEW) {
done();
}
};
Actions.showCreateNew();
});
lab.test('it calls dispatch from hideCreateNew', (done) => {
stub.Store.dispatch.mock = function (action) {
if (action.type === Constants.HIDE_CREATE_NEW) {
done();
}
};
Actions.hideCreateNew();
});
lab.test('it calls ApiActions.post from createNew (success)', (done) => {
stub.Store.dispatch.mock = () => {};
stub.ReactRouter.browserHistory.replace = function (location) {
stub.ReactRouter.browserHistory.replace = () => {};
Code.expect(location).to.be.an.object();
done();
};
stub.ApiActions.post.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.exist();
callback(null, {});
};
Actions.createNew({});
});
lab.test('it calls ApiActions.post from createNew (failure)', (done) => {
stub.ApiActions.post.mock = function (url, data, store, typeReq, typeRes, callback) {
Code.expect(url).to.be.a.string();
Code.expect(data).to.be.an.object();
Code.expect(store).to.be.an.object();
Code.expect(typeReq).to.be.an.instanceof(FluxConstant);
Code.expect(typeRes).to.be.an.instanceof(FluxConstant);
Code.expect(callback).to.exist();
callback(new Error('sorry pal'));
done();
};
Actions.createNew({});
});
});
| mit |
mu-editor/mu-editor.github.io | es/tutorials/1.1/shortcuts.md | 4941 | ---
layout: default
title: Keyboard Shortcuts
i18n: en
---
# Keyboard Shortcuts
All the features in Mu can be accessed via keyboard shortcuts. Here's how they
work!
## Common Buttons
<dl>
<dt>CTRL SHIFT M</dt>
<dd>Change mode (the same as clicking "Modes").</dd>
<dt>CTRL N</dt>
<dd>Create a new empty tab (the same as clicking "New").</dd>
<dt>CTRL O</dt>
<dd>Open a new file (the same as clicking "Open").</dd>
<dt>CTRL S</dt>
<dd>Save a file (the same as clicking "Save").</dd>
<dt>CTRL +</dt>
<dd>Zoom in (the same as clicking "Zoom In").</dd>
<dt>CTRL -</dt>
<dd>Zoom out (the same as clicking "Zoom Out").</dd>
<dt>F1</dt>
<dd>Toggle themes (the same as clicking "Theme").</dd>
<dt>F2</dt>
<dd>Check code (the same as clicking "Check").</dd>
<dt>CTRL H</dt>
<dd>Display help (the same as clicking "Help").</dd>
<dt>CTRL Q</dt>
<dd>Quit Mu (the same as clicking "Quit").</dd>
</dl>
## Mode Related Buttons
### Python 3
<dl>
<dt>F5</dt>
<dd>Run / Stop your code (the same as clicking "Run" or "Stop").</dd>
<dt>F6</dt>
<dd>Debug your code (the same as clicking "Debug").</dd>
<dt>CTRL SHIFT I</dt>
<dd>Toggle the REPL (the same as clicking "REPL").</dd>
<dt>CTRL SHIFT P</dt>
<dd>Toggle the Plotter (the same as clicking "Plotter").</dd>
</dl>
### Debugger
<dl>
<dt>SHIFT F5</dt>
<dd>Stop debugger (the same as clicking "Stop").</dd>
<dt>F5</dt>
<dd>Continue running code (the same as clicking "Continue").</dd>
<dt>F10</dt>
<dd>Step over a line of code (the same as clicking "Step Over").</dd>
<dt>F11</dt>
<dd>Step into a block of code (the same as clicking "Step In").</dd>
<dt>SHIFT F11</dt>
<dd>Step out of a block of code (the same as clicking "Step Out").</dd>
</dl>
### PyGame Zero
<dl>
<dt>F5</dt>
<dd>Play or stop your game (the same as clicking "Play" or "Stop").</dd>
<dt>CTRL SHIFT I</dt>
<dd>Show image asset directory (the same as clicking "Images").</dd>
<dt>CTRL SHIFT F</dt>
<dd>Show font asset directory (the same as clicking "Fonts").</dd>
<dt>CTRL SHIFT N</dt>
<dd>Show the sound/noise asset directory (the same as clicking "Sounds").</dd>
<dt>CTRL SHIFT M</dt>
<dd>Show the music asset directory (the same as clicking "Music").</dd>
</dl>
### Adafruit
<dl>
<dt>CTRL SHIFT U</dt>
<dd>Toggle the USB serial connection (the same as clicking "Serial").</dd>
<dt>CTRL SHIFT P</dt>
<dd>Toggle the Plotter (the same as clicking "Plotter").</dd>
</dl>
The following key combinations work in the serial pane:
<dl>
<dt>CTRL SHIFT C</dt>
<dd>Copy highlighted text into the clipboard.</dd>
<dt>CTRL SHIFT V</dt>
<dd>Paste text into the REPL from the clipboard.</dd>
</dl>
### Microbit
<dl>
<dt>F3</dt>
<dd>Flash code onto device (the same as clicking "Flash").</dd>
<dt>F4</dt>
<dd>Toggle the filesystem (the same as clicking "Files").</dd>
<dt>CTRL SHIFT I</dt>
<dd>Toggle the REPL (the same as clicking "REPL").</dd>
<dt>CTRL SHIFT P</dt>
<dd>Toggle the Plotter (the same as clicking "Plotter").</dd>
</dl>
The micro:bit's REPL pane understands the following key combinations:
<dl>
<dt>CTRL SHIFT C</dt>
<dd>Copy highlighted text into the clipboard.</dd>
<dt>CTRL SHIFT V</dt>
<dd>Paste text into the REPL from the clipboard.</dd>
</dl>
## Text Editing
<dl>
<dt>CTRL F</dt>
<dd>Show the find and replace dialog.</dd>
<dt>CTRL K</dt>
<dd>Toggle comments for the current or selected lines of code.</dd>
<dt>TAB</dt>
<dd>Indent the current or selected lines by four spaces.</dd>
<dt>SHIFT TAB</dt>
<dd>Unindent the current or selected lines by four spaces.</dd>
<dt>CTRL Z</dt>
<dd>Undo (keep pressing to keep undoing).</dd>
<dt>CTRL Y</dt>
<dd>Redo (keep pressing to keep redoing).</dd>
<dt>CTRL A</dt>
<dd>Select all</dd>
<dt>CTRL X</dt>
<dd>Cut selected text into the clipboard.</dd>
<dt>CTRL C</dt>
<dd>Copy selected text into the clipboard.</dd>
<dt>CTRL V</dt>
<dd>Paste text from the clipboard.</dd>
<dt>UP, DOWN, LEFT, RIGHT (arrows)</dt>
<dd>Move the cursor one character in the specified direction.</dd>
<dt>CTRL LEFT / CTRL RIGHT</dt>
<dd>Move the cursor one word in the specified direction.</dd>
<dt>SHIFT UP / SHIFT DOWN / SHIFT LEFT / SHIFT RIGHT</dt>
<dd>Select text in the specified direction.</dd>
<dt>CTRL SHIFT LEFT / CTRL SHIFT RIGHT</dt>
<dd>Select text one word in the specified direction.</dd>
</dl>
## Miscellaneous Others
<dl>
<dt>CTRL SHIFT S</dt>
<dd>Save the current tab with a new name (the same as double clicking the
tab's name).</dd>
<dt>CTRL SHIFT D</dt>
<dd>Show the admin dialog (the same as clicking the cog in the bottom right
of Mu's window).</dd>
</dl>
| mit |
yogeshsaroya/new-cdnjs | ajax/libs/bootstrap-datepicker/1.2.0-rc.1/js/locales/bootstrap-datepicker.et.min.js | 128 | version https://git-lfs.github.com/spec/v1
oid sha256:3e7e8daeb7e94086c854616e881862ffc0555684031d339b30c0b67afa82b530
size 492
| mit |
imyzf/element | packages/table/src/table-body.js | 7259 | import { getCell, getColumnByCell, getRowIdentity } from './util';
import ElCheckbox from 'element-ui/packages/checkbox';
export default {
components: {
ElCheckbox
},
props: {
store: {
required: true
},
context: {},
layout: {
required: true
},
rowClassName: [String, Function],
rowStyle: [Object, Function],
fixed: String,
highlight: Boolean
},
render(h) {
const columnsHidden = this.columns.map((column, index) => this.isColumnHidden(index));
return (
<table
class="el-table__body"
cellspacing="0"
cellpadding="0"
border="0">
<colgroup>
{
this._l(this.columns, column =>
<col
name={ column.id }
width={ column.realWidth || column.width }
/>)
}
</colgroup>
<tbody>
{
this._l(this.data, (row, $index) =>
[<tr
style={ this.rowStyle ? this.getRowStyle(row, $index) : null }
key={ this.table.rowKey ? this.getKeyOfRow(row, $index) : $index }
on-dblclick={ ($event) => this.handleDoubleClick($event, row) }
on-click={ ($event) => this.handleClick($event, row) }
on-contextmenu={ ($event) => this.handleContextMenu($event, row) }
on-mouseenter={ _ => this.handleMouseEnter($index) }
on-mouseleave={ _ => this.handleMouseLeave() }
class={ [this.getRowClass(row, $index)] }>
{
this._l(this.columns, (column, cellIndex) =>
<td
class={ [column.id, column.align, column.className || '', columnsHidden[cellIndex] ? 'is-hidden' : '' ] }
on-mouseenter={ ($event) => this.handleCellMouseEnter($event, row) }
on-mouseleave={ this.handleCellMouseLeave }>
{
column.renderCell.call(this._renderProxy, h, { row, column, $index, store: this.store, _self: this.context || this.table.$vnode.context }, columnsHidden[cellIndex])
}
</td>
)
}
{
!this.fixed && this.layout.scrollY && this.layout.gutterWidth ? <td class="gutter" /> : ''
}
</tr>,
this.store.states.expandRows.indexOf(row) > -1
? (<tr>
<td colspan={ this.columns.length } class="el-table__expanded-cell">
{ this.table.renderExpanded ? this.table.renderExpanded(h, { row, $index, store: this.store }) : ''}
</td>
</tr>)
: ''
]
)
}
</tbody>
</table>
);
},
watch: {
'store.states.hoverRow'(newVal, oldVal) {
if (!this.store.states.isComplex) return;
const el = this.$el;
if (!el) return;
const rows = el.querySelectorAll('tbody > tr');
const oldRow = rows[oldVal];
const newRow = rows[newVal];
if (oldRow) {
oldRow.classList.remove('hover-row');
}
if (newRow) {
newRow.classList.add('hover-row');
}
},
'store.states.currentRow'(newVal, oldVal) {
if (!this.highlight) return;
const el = this.$el;
if (!el) return;
const data = this.store.states.data;
const rows = el.querySelectorAll('tbody > tr');
const oldRow = rows[data.indexOf(oldVal)];
const newRow = rows[data.indexOf(newVal)];
if (oldRow) {
oldRow.classList.remove('current-row');
} else if (rows) {
[].forEach.call(rows, row => row.classList.remove('current-row'));
}
if (newRow) {
newRow.classList.add('current-row');
}
}
},
computed: {
table() {
return this.$parent;
},
data() {
return this.store.states.data;
},
columnsCount() {
return this.store.states.columns.length;
},
leftFixedCount() {
return this.store.states.fixedColumns.length;
},
rightFixedCount() {
return this.store.states.rightFixedColumns.length;
},
columns() {
return this.store.states.columns;
}
},
data() {
return {
tooltipDisabled: true
};
},
methods: {
getKeyOfRow(row, index) {
const rowKey = this.table.rowKey;
if (rowKey) {
return getRowIdentity(row, rowKey);
}
return index;
},
isColumnHidden(index) {
if (this.fixed === true || this.fixed === 'left') {
return index >= this.leftFixedCount;
} else if (this.fixed === 'right') {
return index < this.columnsCount - this.rightFixedCount;
} else {
return (index < this.leftFixedCount) || (index >= this.columnsCount - this.rightFixedCount);
}
},
getRowStyle(row, index) {
const rowStyle = this.rowStyle;
if (typeof rowStyle === 'function') {
return rowStyle.call(null, row, index);
}
return rowStyle;
},
getRowClass(row, index) {
const classes = [];
const rowClassName = this.rowClassName;
if (typeof rowClassName === 'string') {
classes.push(rowClassName);
} else if (typeof rowClassName === 'function') {
classes.push(rowClassName.call(null, row, index) || '');
}
return classes.join(' ');
},
handleCellMouseEnter(event, row) {
const table = this.table;
const cell = getCell(event);
if (cell) {
const column = getColumnByCell(table, cell);
const hoverState = table.hoverState = {cell, column, row};
table.$emit('cell-mouse-enter', hoverState.row, hoverState.column, hoverState.cell, event);
}
// 判断是否text-overflow, 如果是就显示tooltip
const cellChild = event.target.querySelector('.cell');
this.tooltipDisabled = cellChild.scrollWidth <= cellChild.offsetWidth;
},
handleCellMouseLeave(event) {
const cell = getCell(event);
if (!cell) return;
const oldHoverState = this.table.hoverState;
this.table.$emit('cell-mouse-leave', oldHoverState.row, oldHoverState.column, oldHoverState.cell, event);
},
handleMouseEnter(index) {
this.store.commit('setHoverRow', index);
},
handleMouseLeave() {
this.store.commit('setHoverRow', null);
},
handleContextMenu(event, row) {
this.handleEvent(event, row, 'contextmenu');
},
handleDoubleClick(event, row) {
this.handleEvent(event, row, 'dblclick');
},
handleClick(event, row) {
this.store.commit('setCurrentRow', row);
this.handleEvent(event, row, 'click');
},
handleEvent(event, row, name) {
const table = this.table;
const cell = getCell(event);
let column;
if (cell) {
column = getColumnByCell(table, cell);
if (column) {
table.$emit(`cell-${name}`, row, column, cell, event);
}
}
table.$emit(`row-${name}`, row, event, column);
},
handleExpandClick(row) {
this.store.commit('toggleRowExpanded', row);
}
}
};
| mit |
Neurosploit/StratisBitcoinFullNode | src/Stratis.Bitcoin.Features.BlockStore/Pruning/IPruneBlockStoreService.cs | 1414 | using System;
using NBitcoin;
namespace Stratis.Bitcoin.Features.BlockStore.Pruning
{
/// <summary>
/// This service starts an async loop task that periodically deletes from the blockstore.
/// <para>
/// If the height of the node's block store is more than <see cref="PruneBlockStoreService.MaxBlocksToKeep"/>, the node will
/// be pruned, leaving a margin of <see cref="PruneBlockStoreService.MaxBlocksToKeep"/> in the block database.
/// </para>
/// <para>
/// For example if the block store's height is 5000, the node will be pruned up to height 4000, meaning that 1000 blocks will be kept on disk.
/// </para>
/// </summary>
public interface IPruneBlockStoreService : IDisposable
{
/// <summary>
/// This is the header of where the node has been pruned up to.
/// <para>
/// It should be noted that deleting (pruning) blocks from the repository only removes the reference, it does not decrease the actual size on disk.
/// </para>
/// </summary>
ChainedHeader PrunedUpToHeaderTip { get; }
/// <summary>
/// Starts an async loop task that periodically deletes from the blockstore.
/// </summary>
void Initialize();
/// <summary>
/// Delete blocks continuously from the back of the store.
/// </summary>
void PruneBlocks();
}
}
| mit |
GRAVITYLab/edda | html/search/variables_15.js | 362 | var searchData=
[
['w',['w',['../structedda_1_1dist_1_1GMMTuple.html#a3f52857178189dcb76b5132a60c0a50a',1,'edda::dist::GMMTuple']]],
['weights',['weights',['../classedda_1_1dist_1_1JointGMM.html#a479a4af061d7414da3a2b42df3f2e87f',1,'edda::dist::JointGMM']]],
['width',['width',['../structBMPImage.html#a35875dd635eb414965fd87e169b8fb25',1,'BMPImage']]]
];
| mit |
DmsChrisPena/EnergyPro-CodeRed | public/modules/locations/views/view-location.client.view.html | 717 | <section data-ng-controller="LocationsController" data-ng-init="findOne()">
<div class="page-header">
<h1 data-ng-bind="location.name"></h1>
</div>
<div class="pull-right" data-ng-show="((authentication.user) && (authentication.user._id == location.user._id))">
<a class="btn btn-primary" href="/#!/locations/{{location._id}}/edit">
<i class="glyphicon glyphicon-edit"></i>
</a>
<a class="btn btn-primary" data-ng-click="remove();">
<i class="glyphicon glyphicon-trash"></i>
</a>
</div>
<small>
<em class="text-muted">
Posted on
<span data-ng-bind="location.created | date:'mediumDate'"></span>
by
<span data-ng-bind="location.user.displayName"></span>
</em>
</small>
</section>
| mit |
OnekO/respond | app/Exceptions/Handler.php | 1610 | <?php
namespace App\Exceptions;
use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
class Handler extends ExceptionHandler
{
/**
* A list of the exception types that should not be reported.
*
* @var array
*/
protected $dontReport = [
AuthorizationException::class,
HttpException::class,
ModelNotFoundException::class,
ValidationException::class,
];
/**
* Report or log an exception.
*
* This is a great spot to send exceptions to Sentry, Bugsnag, etc.
*
* @param \Exception $e
* @return void
*/
public function report(Exception $e)
{
parent::report($e);
}
/**
* Render an exception into an HTTP response.
*
* @param \Illuminate\Http\Request $request
* @param \Exception $e
* @return \Illuminate\Http\Response
*/
public function render($request, Exception $e)
{
// support friendly urls for files within the application
$path = $request->path();
if(strpos($path, 'sites/') !== FALSE) {
if(strpos($path, '.html') === FALSE) {
$file = app()->basePath('public/'.$path.'.html');
if(file_exists($file)) {
return file_get_contents($file);
}
}
}
return parent::render($request, $e);
}
}
| mit |
savichris/spongycastle | core/src/main/java/org/spongycastle/LICENSE.java | 3397 | package org.spongycastle;
/**
* The Bouncy Castle License
*
* Copyright (c) 2000-2015 The Legion Of The Bouncy Castle Inc. (http://www.bouncycastle.org)
* <p>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* <p>
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
* <p>
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
public class LICENSE
{
public static String licenseText =
"Copyright (c) 2000-2015 The Legion of the Bouncy Castle Inc. (http://www.bouncycastle.org) "
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "Permission is hereby granted, free of charge, to any person obtaining a copy of this software "
+ System.getProperty("line.separator")
+ "and associated documentation files (the \"Software\"), to deal in the Software without restriction, "
+ System.getProperty("line.separator")
+ "including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, "
+ System.getProperty("line.separator")
+ "and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,"
+ System.getProperty("line.separator")
+ "subject to the following conditions:"
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "The above copyright notice and this permission notice shall be included in all copies or substantial"
+ System.getProperty("line.separator")
+ "portions of the Software."
+ System.getProperty("line.separator")
+ System.getProperty("line.separator")
+ "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,"
+ System.getProperty("line.separator")
+ "INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR"
+ System.getProperty("line.separator")
+ "PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE"
+ System.getProperty("line.separator")
+ "LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR"
+ System.getProperty("line.separator")
+ "OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER"
+ System.getProperty("line.separator")
+ "DEALINGS IN THE SOFTWARE.";
public static void main(
String[] args)
{
System.out.println(licenseText);
}
}
| mit |
libin/kanboard | app/Controller/ExternalTaskViewController.php | 895 | <?php
namespace Kanboard\Controller;
use Kanboard\Core\ExternalTask\ExternalTaskException;
/**
* Class ExternalTaskViewController
*
* @package Kanboard\Controller
* @author Frederic Guillot
*/
class ExternalTaskViewController extends BaseController
{
public function show()
{
try {
$task = $this->getTask();
$taskProvider = $this->externalTaskManager->getProvider($task['external_provider']);
$externalTask = $taskProvider->fetch($task['external_uri'], $task['project_id']);
$this->response->html($this->template->render($taskProvider->getViewTemplate(), array(
'task' => $task,
'external_task' => $externalTask,
)));
} catch (ExternalTaskException $e) {
$this->response->html('<div class="alert alert-error">'.$e->getMessage().'</div>');
}
}
}
| mit |
dotnet-bot/corefx | src/System.Drawing.Common/src/System/Drawing/Drawing2D/CustomLineCapType.cs | 396 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace System.Drawing.Drawing2D
{
/**
* Various custom line cap types
*/
internal enum CustomLineCapType
{
Default = 0,
AdjustableArrowCap = 1
}
}
| mit |
sinnwerkstatt/common-good-online-balance | ecg_balancing/templates/ecg_balancing/dustjs/gwoe-matrix-data_en.js | 15425 | var Data = {};
Data.matrix = {
valueName: 'Wert',
stakeholdersName : 'Berührungs​gruppe',
negativeCriteriaName : 'Negativ-Kriterien',
values : [
'Menschen​würde',
'Solidarität',
'Ökologische Nachhaltigkeit',
'Soziale Gerechtigkeit',
'Demokratische Mitbestimmung & Transparenz'
],
stakeholders : [
{
shortcode : 'A',
name: 'Lieferant​Innen',
values: [
{
shortcode : 'A1',
shortcodeSlug : 'a1',
title: 'Ethisches Beschaffungsmanagement',
content: 'Aktive Auseinandersetzung mit den Risiken zugekaufter Produkte / Dienstleistungen, Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl von LieferantInnen und DienstleistungsnehmerInnen.',
points: 90,
soleProprietorship: true
}
]
},
{
shortcode : 'B',
name: 'Geldgeber​Innen',
values: [
{
shortcode : 'B1',
shortcodeSlug : 'b1',
title: 'Ethisches Finanzmanagement',
content: 'Berücksichtigung sozialer und ökologischer Aspekte bei der Auswahl der Finanzdienstleistungen; gemeinwohlorienterte Veranlagung und Finanzierung',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'C',
name: 'Mitarbeiter​Innen inklusive Eigentümer​Innen',
values: [
{
shortcode : 'C1',
shortcodeSlug : 'c1',
title: 'Arbeitsplatz​qualität und Gleichstellung',
content: 'Mitarbeiter​orientierte Organisations-kultur und –strukturen, Faire Beschäftigungs- und Entgeltpolitik, Arbeitsschutz und Gesundheits​förderung einschließlich Work-Life-Balance/flexible Arbeitszeiten, Gleichstellung und Diversität',
points: 90,
soleProprietorship: true
},
{
shortcode : 'C2',
shortcodeSlug : 'c2',
title: 'Gerechte Verteilung der Erwerbsarbeit',
content: 'Abbau von Überstunden, Verzicht auf All-inclusive-Verträge, Reduktion der Regelarbeitszeit, Beitrag zur Reduktion der Arbeitslosigkeit',
points: 50,
soleProprietorship: true
},
{
shortcode : 'C3',
shortcodeSlug : 'c3',
title: 'Förderung ökologischen Verhaltens der Mitarbeiter​Innen',
content: 'Aktive Förderung eines nachhaltigen Lebensstils der MitarbeiterInnen (Mobilität, Ernährung), Weiterbildung und Bewusstsein schaffende Maßnahmen, nachhaltige Organisationskultur',
points: 30,
soleProprietorship: true
},
{
shortcode : 'C4',
shortcodeSlug : 'c4',
title: 'Gerechte Verteilung des Einkommens',
content: 'Geringe innerbetriebliche Einkommens​spreizung (netto), Einhaltung von Mindest​einkommen und Höchst​einkommen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'C5',
shortcodeSlug : 'c5',
title: 'Inner​betriebliche Demokratie und Transparenz',
content: 'Umfassende innerbetriebliche Transparenz, Wahl der Führungskräfte durch die Mitarbeiter, konsensuale Mitbestimmung bei Grundsatz- und Rahmen​entscheidungen, Übergabe Eigentum an MitarbeiterInnen. Z.B. Soziokratie',
points: 90,
soleProprietorship: false
}
]
},
{
shortcode : 'D',
name: 'KundInnen / Produkte / Dienst​leistungen / Mit​unternehmen',
values: [
{
shortcode : 'D1',
shortcodeSlug : 'd1',
title: 'Ethische Kunden​beziehung',
content: 'Ethischer Umgang mit KundInnen, KundInnen​orientierung/ - mitbestimmung, gemeinsame Produkt​entwicklung, hohe Servicequalität, hohe Produkt​transparenz',
points: 50,
soleProprietorship: true
},
{
shortcode : 'D2',
shortcodeSlug : 'd2',
title: 'Solidarität mit Mit​unternehmen',
content: 'Weitergabe von Information, Know-how, Arbeitskräften, Aufträgen, zinsfreien Krediten; Beteiligung an kooperativem Marketing und kooperativer Krisenbewältigung',
points: 70,
soleProprietorship: true
},
{
shortcode : 'D3',
shortcodeSlug : 'd3',
title: 'Ökologische Gestaltung der Produkte und Dienst​leistungen',
content: 'Angebot ökologisch höherwertiger Produkte / Dienstleistungen; Bewusstsein schaffende Maßnahmen; Berücksichtigung ökologischer Aspekte bei der KundInnenwahl',
points: 90,
soleProprietorship: true
},
{
shortcode : 'D4',
shortcodeSlug : 'd4',
title: 'Soziale Gestaltung der Produkte und Dienst​leistungen',
content: 'Informationen / Produkten / Dienstleistungen für benachteiligte KundInnen-Gruppen. Unterstützung förderungs​würdiger Marktstrukturen.',
points: 30,
soleProprietorship: true
},
{
shortcode : 'D5',
shortcodeSlug : 'd5',
title: 'Erhöhung der sozialen und ökologischen Branchen​standards',
content: 'Vorbildwirkung, Entwicklung von höheren Standards mit MitbewerberInnen, Lobbying',
points: 30,
soleProprietorship: true
}
]
},
{
shortcode : 'E',
name: 'Gesell​schaftliches Umfeld:',
explanation: 'Region, Souverän, zukünftige Generationen, Zivil​gesellschaft, Mitmenschen und Natur',
values: [
{
shortcode : 'E1',
shortcodeSlug : 'e1',
title: 'Sinn und Gesell​schaftliche Wirkung der Produkte / Dienst​leistungen',
content: 'P/DL decken den Grundbedarf oder dienen der Entwicklung der Menschen / der Gemeinschaft / der Erde und generieren positiven Nutzen.',
points: 50,
soleProprietorship: true
},
{
shortcode : 'E2',
shortcodeSlug : 'e2',
title: 'Beitrag zum Gemeinwesen',
content: 'Gegenseitige Unterstützung und Kooperation durch Finanzmittel, Dienstleistungen, Produkte, Logistik, Zeit, Know-How, Wissen, Kontakte, Einfluss',
points: 40,
soleProprietorship: true
},
{
shortcode : 'E3',
shortcodeSlug : 'e3',
title: 'Reduktion ökologischer Auswirkungen',
content: 'Reduktion der Umwelt​auswirkungen auf ein zukunftsfähiges Niveau: Ressourcen, Energie & Klima, Emissionen, Abfälle etc.',
points: 70,
soleProprietorship: true
},
{
shortcode : 'E4',
shortcodeSlug : 'e4',
title: 'Gemeinwohl​orientierte Gewinn-Verteilung',
content: 'Sinkende / keine Gewinn​ausschüttung an Externe, Ausschüttung an Mitarbeiter, Stärkung des Eigenkapitals, sozial-ökologische Investitionen',
points: 60,
soleProprietorship: false
},
{
shortcode : 'E5',
shortcodeSlug : 'e5',
title: 'Gesellschaft​liche Transparenz und Mitbestimmung',
content: 'Gemeinwohl- oder Nachhaltigkeits​bericht, Mitbestimmung von regionalen und zivilgesell​schaftlichen Berührungs​gruppen',
points: 30,
soleProprietorship: true
}
]
}
],
negativeCriteria : [
{
values: [
{
shortcode : 'N1',
shortcodeSlug : 'n1',
titleShort: 'Verletzung der ILO-Arbeitsnormen / Menschenrechte',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N2',
shortcodeSlug : 'n2',
titleShort: 'Menschen​unwürdige Produkte, z.B. Tretminen, Atomstrom, GMO',
title: 'Menschenunwürdige Produkte und Dienstleistungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N3',
shortcodeSlug : 'n3',
titleShort: 'Beschaffung bei / Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
title: 'Menschenunwürdige Produkte und Dienstbeschaffung bei bzt. Kooperation mit Unternehmen, welche die Menschenwürde verletzen',
points: -150,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N4',
shortcodeSlug : 'n4',
titleShort: 'Feindliche Übernahme',
title: 'Feindliche Übernahme',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N5',
shortcodeSlug : 'n5',
titleShort: 'Sperrpatente',
title: 'Sperrpatente',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N6',
shortcodeSlug : 'n6',
titleShort: 'Dumping​preise',
title: 'Dumpingpreise',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N7',
shortcodeSlug : 'n7',
titleShort: 'Illegitime Umweltbelastungen',
title: 'Illegitime Umweltbelastungen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N8',
shortcodeSlug : 'n8',
titleShort: 'Verstöße gegen Umweltauflagen',
title: 'Verstöße gegen Umweltauflagen',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N9',
shortcodeSlug : 'n9',
titleShort: 'Geplante Obsoleszenz (kurze Lebensdauer der Produkte)',
title: 'Geplante Obsoleszenz',
points: -100,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N10',
shortcodeSlug : 'n10',
titleShort: 'Arbeits​rechtliches Fehlverhalten seitens des Unternehmens',
title: 'Arbeitsrechtliches Fehlverhalten seitens des Unternehmens',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N11',
shortcodeSlug : 'n11',
titleShort: 'Arbeitsplatz​abbau oder Standortverlagerung bei Gewinn',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N12',
shortcodeSlug : 'n12',
titleShort: 'Umgehung der Steuerpflicht',
title: 'Arbeitsplatzabbau oder Standortverlagerung trotz Gewinn',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N13',
shortcodeSlug : 'n13',
titleShort: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
title: 'Keine unangemessene Verzinsung für nicht mitarbeitende Gesellschafter',
points: -200,
soleProprietorship: true
}
]
},
{
values: [
{
shortcode : 'N14',
shortcodeSlug : 'n14',
titleShort: 'Nicht​offenlegung aller Beteiligungen und Töchter',
title: 'Nichtoffenlegung aller Beteiligungen und Töchter',
points: -100,
soleProprietorship: true
},
{
shortcode : 'N15',
shortcodeSlug : 'n15',
titleShort: 'Verhinderung eines Betriebsrats',
title: 'Verhinderung eines Betriebsrats',
points: -150,
soleProprietorship: true
},
{
shortcode : 'N16',
shortcodeSlug : 'n16',
titleShort: 'Nicht​offenlegung aller Finanzflüsse an Lobbies / Eintragung in das EU-Lobbyregister',
title: 'Nichtoffenlegung aller Finanzflüsse an Lobbyisten und Lobby-Organisationen / Nichteintragung ins Lobby-Register der EU',
points: -200,
soleProprietorship: true
},
{
shortcode : 'N17',
shortcodeSlug : 'n17',
titleShort: 'Exzessive Einkommensspreizung',
title: 'Exzessive Einkommensspreizung',
points: -100,
soleProprietorship: true
}
]
}
]
};
exports.Data = Data;
| mit |
CONDACORE/fahndo-app | plugins/cordova-plugin-facebook4/src/android/ConnectPlugin.java | 37503 | package org.apache.cordova.facebook;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookDialogException;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.FacebookSdk;
import com.facebook.FacebookServiceException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.share.ShareApi;
import com.facebook.share.Sharer;
import com.facebook.share.model.GameRequestContent;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.model.ShareOpenGraphObject;
import com.facebook.share.model.ShareOpenGraphAction;
import com.facebook.share.model.ShareOpenGraphContent;
import com.facebook.share.model.AppInviteContent;
import com.facebook.share.widget.GameRequestDialog;
import com.facebook.share.widget.MessageDialog;
import com.facebook.share.widget.ShareDialog;
import com.facebook.share.widget.AppInviteDialog;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.Collection;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class ConnectPlugin extends CordovaPlugin {
private static final int INVALID_ERROR_CODE = -2; //-1 is FacebookRequestError.INVALID_ERROR_CODE
private static final String PUBLISH_PERMISSION_PREFIX = "publish";
private static final String MANAGE_PERMISSION_PREFIX = "manage";
@SuppressWarnings("serial")
private static final Set<String> OTHER_PUBLISH_PERMISSIONS = new HashSet<String>() {
{
add("ads_management");
add("create_event");
add("rsvp_event");
}
};
private final String TAG = "ConnectPlugin";
private CallbackManager callbackManager;
private AppEventsLogger logger;
private CallbackContext loginContext = null;
private CallbackContext showDialogContext = null;
private CallbackContext graphContext = null;
private String graphPath;
private ShareDialog shareDialog;
private GameRequestDialog gameRequestDialog;
private AppInviteDialog appInviteDialog;
private MessageDialog messageDialog;
@Override
protected void pluginInitialize() {
FacebookSdk.sdkInitialize(cordova.getActivity().getApplicationContext());
// create callbackManager
callbackManager = CallbackManager.Factory.create();
// create AppEventsLogger
logger = AppEventsLogger.newLogger(cordova.getActivity().getApplicationContext());
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(final LoginResult loginResult) {
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject jsonObject, GraphResponse response) {
if (response.getError() != null) {
if (graphContext != null) {
graphContext.error(getFacebookRequestErrorResponse(response.getError()));
} else if (loginContext != null) {
loginContext.error(getFacebookRequestErrorResponse(response.getError()));
}
return;
}
// If this login comes after doing a new permission request
// make the outstanding graph call
if (graphContext != null) {
makeGraphCall();
return;
}
Log.d(TAG, "returning login object " + jsonObject.toString());
loginContext.success(getResponse());
loginContext = null;
}
}).executeAsync();
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, loginContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, loginContext);
}
});
shareDialog = new ShareDialog(cordova.getActivity());
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {
if (showDialogContext != null) {
showDialogContext.success(result.getPostId());
showDialogContext = null;
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
messageDialog = new MessageDialog(cordova.getActivity());
messageDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {
if (showDialogContext != null) {
showDialogContext.success();
showDialogContext = null;
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
gameRequestDialog = new GameRequestDialog(cordova.getActivity());
gameRequestDialog.registerCallback(callbackManager, new FacebookCallback<GameRequestDialog.Result>() {
@Override
public void onSuccess(GameRequestDialog.Result result) {
if (showDialogContext != null) {
try {
JSONObject json = new JSONObject();
json.put("requestId", result.getRequestId());
json.put("recipientsIds", new JSONArray(result.getRequestRecipients()));
showDialogContext.success(json);
showDialogContext = null;
} catch (JSONException ex) {
showDialogContext.success();
showDialogContext = null;
}
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
appInviteDialog = new AppInviteDialog(cordova.getActivity());
appInviteDialog.registerCallback(callbackManager, new FacebookCallback<AppInviteDialog.Result>() {
@Override
public void onSuccess(AppInviteDialog.Result result) {
if (showDialogContext != null) {
try {
JSONObject json = new JSONObject();
Bundle bundle = result.getData();
for (String key : bundle.keySet()) {
json.put(key, wrapObject(bundle.get(key)));
}
showDialogContext.success(json);
showDialogContext = null;
} catch (JSONException e) {
showDialogContext.success();
showDialogContext = null;
}
}
}
@Override
public void onCancel() {
FacebookOperationCanceledException e = new FacebookOperationCanceledException();
handleError(e, showDialogContext);
}
@Override
public void onError(FacebookException e) {
Log.e("Activity", String.format("Error: %s", e.toString()));
handleError(e, showDialogContext);
}
});
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
// Developers can observe how frequently users activate their app by logging an app activation event.
AppEventsLogger.activateApp(cordova.getActivity());
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
AppEventsLogger.deactivateApp(cordova.getActivity());
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
Log.d(TAG, "activity result in plugin: requestCode(" + requestCode + "), resultCode(" + resultCode + ")");
callbackManager.onActivityResult(requestCode, resultCode, intent);
}
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals("login")) {
executeLogin(args, callbackContext);
return true;
} else if (action.equals("logout")) {
if (hasAccessToken()) {
LoginManager.getInstance().logOut();
callbackContext.success();
} else {
callbackContext.error("No valid session found, must call init and login before logout.");
}
return true;
} else if (action.equals("getLoginStatus")) {
callbackContext.success(getResponse());
return true;
} else if (action.equals("getAccessToken")) {
if (hasAccessToken()) {
callbackContext.success(AccessToken.getCurrentAccessToken().getToken());
} else {
// Session not open
callbackContext.error("Session not open.");
}
return true;
} else if (action.equals("logEvent")) {
executeLogEvent(args, callbackContext);
return true;
} else if (action.equals("logPurchase")) {
/*
* While calls to logEvent can be made to register purchase events,
* there is a helper method that explicitly takes a currency indicator.
*/
if (args.length() != 2) {
callbackContext.error("Invalid arguments");
return true;
}
int value = args.getInt(0);
String currency = args.getString(1);
logger.logPurchase(BigDecimal.valueOf(value), Currency.getInstance(currency));
callbackContext.success();
return true;
} else if (action.equals("showDialog")) {
executeDialog(args, callbackContext);
return true;
} else if (action.equals("graphApi")) {
executeGraph(args, callbackContext);
return true;
} else if (action.equals("appInvite")) {
executeAppInvite(args, callbackContext);
return true;
} else if (action.equals("activateApp")) {
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
AppEventsLogger.activateApp(cordova.getActivity());
}
});
return true;
}
return false;
}
private void executeAppInvite(JSONArray args, CallbackContext callbackContext) {
String url = null;
String picture = null;
JSONObject parameters;
try {
parameters = args.getJSONObject(0);
} catch (JSONException e) {
parameters = new JSONObject();
}
if (parameters.has("url")) {
try {
url = parameters.getString("url");
} catch (JSONException e) {
Log.e(TAG, "Non-string 'url' parameter provided to dialog");
callbackContext.error("Incorrect 'url' parameter");
return;
}
} else {
callbackContext.error("Missing required 'url' parameter");
return;
}
if (parameters.has("picture")) {
try {
picture = parameters.getString("picture");
} catch (JSONException e) {
Log.e(TAG, "Non-string 'picture' parameter provided to dialog");
callbackContext.error("Incorrect 'picture' parameter");
return;
}
}
if (AppInviteDialog.canShow()) {
AppInviteContent.Builder builder = new AppInviteContent.Builder();
builder.setApplinkUrl(url);
if (picture != null) {
builder.setPreviewImageUrl(picture);
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
cordova.setActivityResultCallback(this);
appInviteDialog.show(builder.build());
} else {
callbackContext.error("Unable to show dialog");
}
}
private void executeDialog(JSONArray args, CallbackContext callbackContext) throws JSONException {
Map<String, String> params = new HashMap<String, String>();
String method = null;
JSONObject parameters;
try {
parameters = args.getJSONObject(0);
} catch (JSONException e) {
parameters = new JSONObject();
}
Iterator<String> iter = parameters.keys();
while (iter.hasNext()) {
String key = iter.next();
if (key.equals("method")) {
try {
method = parameters.getString(key);
} catch (JSONException e) {
Log.w(TAG, "Nonstring method parameter provided to dialog");
}
} else {
try {
params.put(key, parameters.getString(key));
} catch (JSONException e) {
// Need to handle JSON parameters
Log.w(TAG, "Non-string parameter provided to dialog discarded");
}
}
}
if (method == null) {
callbackContext.error("No method provided");
} else if (method.equalsIgnoreCase("apprequests")) {
if (!GameRequestDialog.canShow()) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
GameRequestContent.Builder builder = new GameRequestContent.Builder();
if (params.containsKey("message"))
builder.setMessage(params.get("message"));
if (params.containsKey("to"))
builder.setTo(params.get("to"));
if (params.containsKey("data"))
builder.setData(params.get("data"));
if (params.containsKey("title"))
builder.setTitle(params.get("title"));
if (params.containsKey("objectId"))
builder.setObjectId(params.get("objectId"));
if (params.containsKey("actionType")) {
try {
final GameRequestContent.ActionType actionType = GameRequestContent.ActionType.valueOf(params.get("actionType"));
builder.setActionType(actionType);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Discarding invalid argument actionType");
}
}
if (params.containsKey("filters")) {
try {
final GameRequestContent.Filters filters = GameRequestContent.Filters.valueOf(params.get("filters"));
builder.setFilters(filters);
} catch (IllegalArgumentException e) {
Log.w(TAG, "Discarding invalid argument filters");
}
}
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
gameRequestDialog.show(builder.build());
} else if (method.equalsIgnoreCase("share") || method.equalsIgnoreCase("feed")) {
if (!ShareDialog.canShow(ShareLinkContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
ShareLinkContent content = buildContent(params);
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
shareDialog.show(content);
} else if (method.equalsIgnoreCase("share_open_graph")) {
if (!ShareDialog.canShow(ShareOpenGraphContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
if (!params.containsKey("action")) {
callbackContext.error("Missing required parameter 'action'");
}
if (!params.containsKey("object")) {
callbackContext.error("Missing required parameter 'object'.");
}
ShareOpenGraphObject.Builder objectBuilder = new ShareOpenGraphObject.Builder();
JSONObject jObject = new JSONObject(params.get("object"));
Iterator<?> objectKeys = jObject.keys();
String objectType = "";
while ( objectKeys.hasNext() ) {
String key = (String)objectKeys.next();
String value = jObject.getString(key);
objectBuilder.putString(key, value);
if (key.equals("og:type"))
objectType = value;
}
if (objectType.equals("")) {
callbackContext.error("Missing required object parameter 'og:type'");
}
ShareOpenGraphAction.Builder actionBuilder = new ShareOpenGraphAction.Builder();
actionBuilder.setActionType(params.get("action"));
if (params.containsKey("action_properties")) {
JSONObject jActionProperties = new JSONObject(params.get("action_properties"));
Iterator<?> actionKeys = jActionProperties.keys();
while ( actionKeys.hasNext() ) {
String actionKey = (String)actionKeys.next();
actionBuilder.putString(actionKey, jActionProperties.getString(actionKey));
}
}
actionBuilder.putObject(objectType, objectBuilder.build());
ShareOpenGraphContent.Builder content = new ShareOpenGraphContent.Builder()
.setPreviewPropertyName(objectType)
.setAction(actionBuilder.build());
shareDialog.show(content.build());
} else if (method.equalsIgnoreCase("send")) {
if (!MessageDialog.canShow(ShareLinkContent.class)) {
callbackContext.error("Cannot show dialog");
return;
}
showDialogContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
showDialogContext.sendPluginResult(pr);
ShareLinkContent.Builder builder = new ShareLinkContent.Builder();
if(params.containsKey("link"))
builder.setContentUrl(Uri.parse(params.get("link")));
if(params.containsKey("caption"))
builder.setContentTitle(params.get("caption"));
if(params.containsKey("picture"))
builder.setImageUrl(Uri.parse(params.get("picture")));
if(params.containsKey("description"))
builder.setContentDescription(params.get("description"));
messageDialog.show(builder.build());
} else {
callbackContext.error("Unsupported dialog method.");
}
}
private void executeGraph(JSONArray args, CallbackContext callbackContext) throws JSONException {
graphContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
graphContext.sendPluginResult(pr);
graphPath = args.getString(0);
JSONArray arr = args.getJSONArray(1);
final Set<String> permissions = new HashSet<String>(arr.length());
for (int i = 0; i < arr.length(); i++) {
permissions.add(arr.getString(i));
}
if (permissions.size() == 0) {
makeGraphCall();
return;
}
boolean publishPermissions = false;
boolean readPermissions = false;
String declinedPermission = null;
AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (accessToken.getPermissions().containsAll(permissions)) {
makeGraphCall();
return;
}
Set<String> declined = accessToken.getDeclinedPermissions();
// Figure out if we have all permissions
for (String permission : permissions) {
if (declined.contains(permission)) {
declinedPermission = permission;
break;
}
if (isPublishPermission(permission)) {
publishPermissions = true;
} else {
readPermissions = true;
}
// Break if we have a mixed bag, as this is an error
if (publishPermissions && readPermissions) {
break;
}
}
if (declinedPermission != null) {
graphContext.error("This request needs declined permission: " + declinedPermission);
}
if (publishPermissions && readPermissions) {
graphContext.error("Cannot ask for both read and publish permissions.");
return;
}
cordova.setActivityResultCallback(this);
LoginManager loginManager = LoginManager.getInstance();
// Check for write permissions, the default is read (empty)
if (publishPermissions) {
// Request new publish permissions
loginManager.logInWithPublishPermissions(cordova.getActivity(), permissions);
} else {
// Request new read permissions
loginManager.logInWithReadPermissions(cordova.getActivity(), permissions);
}
}
private void executeLogEvent(JSONArray args, CallbackContext callbackContext) throws JSONException {
if (args.length() == 0) {
// Not enough parameters
callbackContext.error("Invalid arguments");
return;
}
String eventName = args.getString(0);
if (args.length() == 1) {
logger.logEvent(eventName);
callbackContext.success();
return;
}
// Arguments is greater than 1
JSONObject params = args.getJSONObject(1);
Bundle parameters = new Bundle();
Iterator<String> iter = params.keys();
while (iter.hasNext()) {
String key = iter.next();
try {
// Try get a String
String value = params.getString(key);
parameters.putString(key, value);
} catch (JSONException e) {
// Maybe it was an int
Log.w(TAG, "Type in AppEvent parameters was not String for key: " + key);
try {
int value = params.getInt(key);
parameters.putInt(key, value);
} catch (JSONException e2) {
// Nope
Log.e(TAG, "Unsupported type in AppEvent parameters for key: " + key);
}
}
}
if (args.length() == 2) {
logger.logEvent(eventName, parameters);
callbackContext.success();
}
if (args.length() == 3) {
double value = args.getDouble(2);
logger.logEvent(eventName, value, parameters);
callbackContext.success();
}
}
private void executeLogin(JSONArray args, CallbackContext callbackContext) throws JSONException {
Log.d(TAG, "login FB");
// Get the permissions
Set<String> permissions = new HashSet<String>(args.length());
for (int i = 0; i < args.length(); i++) {
permissions.add(args.getString(i));
}
// Set a pending callback to cordova
loginContext = callbackContext;
PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
pr.setKeepCallback(true);
loginContext.sendPluginResult(pr);
// Check if the active session is open
if (!hasAccessToken()) {
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
// Create the request
LoginManager.getInstance().logInWithReadPermissions(cordova.getActivity(), permissions);
return;
}
// Reauthorize flow
boolean publishPermissions = false;
boolean readPermissions = false;
// Figure out if this will be a read or publish reauthorize
if (permissions.size() == 0) {
// No permissions, read
readPermissions = true;
}
// Loop through the permissions to see what
// is being requested
for (String permission : permissions) {
if (isPublishPermission(permission)) {
publishPermissions = true;
} else {
readPermissions = true;
}
// Break if we have a mixed bag, as this is an error
if (publishPermissions && readPermissions) {
break;
}
}
if (publishPermissions && readPermissions) {
loginContext.error("Cannot ask for both read and publish permissions.");
loginContext = null;
return;
}
// Set up the activity result callback to this class
cordova.setActivityResultCallback(this);
// Check for write permissions, the default is read (empty)
if (publishPermissions) {
// Request new publish permissions
LoginManager.getInstance().logInWithPublishPermissions(cordova.getActivity(), permissions);
} else {
// Request new read permissions
LoginManager.getInstance().logInWithReadPermissions(cordova.getActivity(), permissions);
}
}
private ShareLinkContent buildContent(Map<String, String> paramBundle) {
ShareLinkContent.Builder builder = new ShareLinkContent.Builder();
if (paramBundle.containsKey("caption"))
builder.setContentTitle(paramBundle.get("caption"));
if (paramBundle.containsKey("description"))
builder.setContentDescription(paramBundle.get("description"));
if (paramBundle.containsKey("href"))
builder.setContentUrl(Uri.parse(paramBundle.get("href")));
if (paramBundle.containsKey("picture"))
builder.setImageUrl(Uri.parse(paramBundle.get("picture")));
return builder.build();
}
// Simple active session check
private boolean hasAccessToken() {
return AccessToken.getCurrentAccessToken() != null;
}
private void handleError(FacebookException exception, CallbackContext context) {
if (exception.getMessage() != null) {
Log.e(TAG, exception.toString());
}
String errMsg = "Facebook error: " + exception.getMessage();
int errorCode = INVALID_ERROR_CODE;
// User clicked "x"
if (exception instanceof FacebookOperationCanceledException) {
errMsg = "User cancelled dialog";
errorCode = 4201;
} else if (exception instanceof FacebookDialogException) {
// Dialog error
errMsg = "Dialog error: " + exception.getMessage();
}
if (context != null) {
context.error(getErrorResponse(exception, errMsg, errorCode));
} else {
Log.e(TAG, "Error already sent so no context, msg: " + errMsg + ", code: " + errorCode);
}
}
private void makeGraphCall() {
//If you're using the paging URLs they will be URLEncoded, let's decode them.
try {
graphPath = URLDecoder.decode(graphPath, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String[] urlParts = graphPath.split("\\?");
String graphAction = urlParts[0];
GraphRequest graphRequest = GraphRequest.newGraphPathRequest(AccessToken.getCurrentAccessToken(), graphAction, new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {
if (graphContext != null) {
if (response.getError() != null) {
graphContext.error(getFacebookRequestErrorResponse(response.getError()));
} else {
graphContext.success(response.getJSONObject());
}
graphPath = null;
graphContext = null;
}
}
});
Bundle params = graphRequest.getParameters();
if (urlParts.length > 1) {
String[] queries = urlParts[1].split("&");
for (String query : queries) {
int splitPoint = query.indexOf("=");
if (splitPoint > 0) {
String key = query.substring(0, splitPoint);
String value = query.substring(splitPoint + 1, query.length());
params.putString(key, value);
}
}
}
graphRequest.setParameters(params);
graphRequest.executeAsync();
}
/*
* Checks for publish permissions
*/
private boolean isPublishPermission(String permission) {
return permission != null &&
(permission.startsWith(PUBLISH_PERMISSION_PREFIX) ||
permission.startsWith(MANAGE_PERMISSION_PREFIX) ||
OTHER_PUBLISH_PERMISSIONS.contains(permission));
}
/**
* Create a Facebook Response object that matches the one for the Javascript SDK
* @return JSONObject - the response object
*/
public JSONObject getResponse() {
String response;
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
if (hasAccessToken()) {
Date today = new Date();
long expiresTimeInterval = (accessToken.getExpires().getTime() - today.getTime()) / 1000L;
response = "{"
+ "\"status\": \"connected\","
+ "\"authResponse\": {"
+ "\"accessToken\": \"" + accessToken.getToken() + "\","
+ "\"expiresIn\": \"" + Math.max(expiresTimeInterval, 0) + "\","
+ "\"session_key\": true,"
+ "\"sig\": \"...\","
+ "\"userID\": \"" + accessToken.getUserId() + "\""
+ "}"
+ "}";
} else {
response = "{"
+ "\"status\": \"unknown\""
+ "}";
}
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
public JSONObject getFacebookRequestErrorResponse(FacebookRequestError error) {
String response = "{"
+ "\"errorCode\": \"" + error.getErrorCode() + "\","
+ "\"errorType\": \"" + error.getErrorType() + "\","
+ "\"errorMessage\": \"" + error.getErrorMessage() + "\"";
if (error.getErrorUserMessage() != null) {
response += ",\"errorUserMessage\": \"" + error.getErrorUserMessage() + "\"";
}
if (error.getErrorUserTitle() != null) {
response += ",\"errorUserTitle\": \"" + error.getErrorUserTitle() + "\"";
}
response += "}";
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
public JSONObject getErrorResponse(Exception error, String message, int errorCode) {
if (error instanceof FacebookServiceException) {
return getFacebookRequestErrorResponse(((FacebookServiceException) error).getRequestError());
}
String response = "{";
if (error instanceof FacebookDialogException) {
errorCode = ((FacebookDialogException) error).getErrorCode();
}
if (errorCode != INVALID_ERROR_CODE) {
response += "\"errorCode\": \"" + errorCode + "\",";
}
if (message == null) {
message = error.getMessage();
}
response += "\"errorMessage\": \"" + message + "\"}";
try {
return new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
return new JSONObject();
}
/**
* Wraps the given object if necessary.
*
* If the object is null or , returns {@link #JSONObject.NULL}.
* If the object is a {@code JSONArray} or {@code JSONObject}, no wrapping is necessary.
* If the object is {@code JSONObject.NULL}, no wrapping is necessary.
* If the object is an array or {@code Collection}, returns an equivalent {@code JSONArray}.
* If the object is a {@code Map}, returns an equivalent {@code JSONObject}.
* If the object is a primitive wrapper type or {@code String}, returns the object.
* Otherwise if the object is from a {@code java} package, returns the result of {@code toString}.
* If wrapping fails, returns null.
*/
private static Object wrapObject(Object o) {
if (o == null) {
return JSONObject.NULL;
}
if (o instanceof JSONArray || o instanceof JSONObject) {
return o;
}
if (o.equals(JSONObject.NULL)) {
return o;
}
try {
if (o instanceof Collection) {
return new JSONArray((Collection) o);
} else if (o.getClass().isArray()) {
return new JSONArray(o);
}
if (o instanceof Map) {
return new JSONObject((Map) o);
}
if (o instanceof Boolean ||
o instanceof Byte ||
o instanceof Character ||
o instanceof Double ||
o instanceof Float ||
o instanceof Integer ||
o instanceof Long ||
o instanceof Short ||
o instanceof String) {
return o;
}
if (o.getClass().getPackage().getName().startsWith("java.")) {
return o.toString();
}
} catch (Exception ignored) {
}
return null;
}
}
| mit |
eyeswebcrea/cheminee-mario.com | spip/ecrire/inc/rechercher.php | 10890 | <?php
/***************************************************************************\
* SPIP, Systeme de publication pour l'internet *
* *
* Copyright (c) 2001-2011 *
* Arnaud Martin, Antoine Pitrou, Philippe Riviere, Emmanuel Saint-James *
* *
* Ce programme est un logiciel libre distribue sous licence GNU/GPL. *
* Pour plus de details voir le fichier COPYING.txt ou l'aide en ligne. *
\***************************************************************************/
if (!defined('_ECRIRE_INC_VERSION')) return;
// Donne la liste des champs/tables ou l'on sait chercher/remplacer
// avec un poids pour le score
// http://doc.spip.org/@liste_des_champs
function liste_des_champs() {
return
pipeline('rechercher_liste_des_champs',
array(
'article' => array(
'surtitre' => 5, 'titre' => 8, 'soustitre' => 5, 'chapo' => 3,
'texte' => 1, 'ps' => 1, 'nom_site' => 1, 'url_site' => 1,
'descriptif' => 4
),
'breve' => array(
'titre' => 8, 'texte' => 2, 'lien_titre' => 1, 'lien_url' => 1
),
'rubrique' => array(
'titre' => 8, 'descriptif' => 5, 'texte' => 1
),
'site' => array(
'nom_site' => 5, 'url_site' => 1, 'descriptif' => 3
),
'mot' => array(
'titre' => 8, 'texte' => 1, 'descriptif' => 5
),
'auteur' => array(
'nom' => 5, 'bio' => 1, 'email' => 1, 'nom_site' => 1, 'url_site' => 1, 'login' => 1
),
'forum' => array(
'titre' => 3, 'texte' => 1, 'auteur' => 2, 'email_auteur' => 2, 'nom_site' => 1, 'url_site' => 1
),
'document' => array(
'titre' => 3, 'descriptif' => 1, 'fichier' => 1
),
'syndic_article' => array(
'titre' => 5, 'descriptif' => 1
),
'signature' => array(
'nom_email' => 2, 'ad_email' => 4,
'nom_site' => 2, 'url_site' => 4,
'message' => 1
)
)
);
}
// Recherche des auteurs et mots-cles associes
// en ne regardant que le titre ou le nom
// http://doc.spip.org/@liste_des_jointures
function liste_des_jointures() {
return
pipeline('rechercher_liste_des_jointures',
array(
'article' => array(
'auteur' => array('nom' => 10),
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'breve' => array(
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'rubrique' => array(
'mot' => array('titre' => 3),
'document' => array('titre' => 2, 'descriptif' => 1)
),
'document' => array(
'mot' => array('titre' => 3)
)
)
);
}
// Effectue une recherche sur toutes les tables de la base de donnees
// options :
// - toutvoir pour eviter autoriser(voir)
// - flags pour eviter les flags regexp par defaut (UimsS)
// - champs pour retourner les champs concernes
// - score pour retourner un score
// On peut passer les tables, ou une chaine listant les tables souhaitees
// http://doc.spip.org/@recherche_en_base
function recherche_en_base($recherche='', $tables=NULL, $options=array(), $serveur='') {
include_spip('base/abstract_sql');
if (!is_array($tables)) {
$liste = liste_des_champs();
if (is_string($tables)
AND $tables != '') {
$toutes = array();
foreach(explode(',', $tables) as $t)
if (isset($liste[$t]))
$toutes[$t] = $liste[$t];
$tables = $toutes;
unset($toutes);
} else
$tables = $liste;
}
include_spip('inc/autoriser');
// options par defaut
$options = array_merge(array(
'preg_flags' => 'UimsS',
'toutvoir' => false,
'champs' => false,
'score' => false,
'matches' => false,
'jointures' => false
),
$options
);
$results = array();
if (!strlen($recherche) OR !count($tables))
return array();
include_spip('inc/charsets');
$recherche = translitteration($recherche);
$is_preg = false;
if (substr($recherche,0,1)=='/' AND substr($recherche,-1,1)=='/'){
// c'est une preg
$preg = $recherche.$options['preg_flags'];
$is_preg = true;
}
else
$preg = '/'.str_replace('/', '\\/', $recherche).'/' . $options['preg_flags'];
// Si la chaine est inactive, on va utiliser LIKE pour aller plus vite
// ou si l'expression reguliere est invalide
if (!$is_preg
OR (@preg_match($preg,'')===FALSE) ) {
$methode = 'LIKE';
$u = $GLOBALS['meta']['pcre_u'];
// eviter les parentheses et autres caractères qui interferent avec pcre par la suite (dans le preg_match_all) s'il y a des reponses
$recherche = str_replace(
array('(',')','?','[', ']', '+', '*', '/'),
array('\(','\)','[?]', '\[', '\]', '\+', '\*', '\/'),
$recherche);
$recherche_mod = $recherche;
// echapper les % et _
$q = str_replace(array('%','_'), array('\%', '\_'), trim($recherche));
// les expressions entre " " sont un mot a chercher tel quel
// -> on remplace les espaces par un _ et on enleve les guillemets
if (preg_match(',["][^"]+["],Uims',$q,$matches)){
foreach($matches as $match){
// corriger le like dans le $q
$word = preg_replace(",\s+,Uims","_",$match);
$word = trim($word,'"');
$q = str_replace($match,$word,$q);
// corriger la regexp
$word = preg_replace(",\s+,Uims","[\s]",$match);
$word = trim($word,'"');
$recherche_mod = str_replace($match,$word,$recherche_mod);
}
}
$q = sql_quote(
"%"
. preg_replace(",\s+,".$u, "%", $q)
. "%"
);
$preg = '/'.preg_replace(",\s+,".$u, ".+", trim($recherche_mod)).'/' . $options['preg_flags'];
} else {
$methode = 'REGEXP';
$q = sql_quote(substr($recherche,1,-1));
}
$jointures = $options['jointures']
? liste_des_jointures()
: array();
foreach ($tables as $table => $champs) {
$requete = array(
"SELECT"=>array(),
"FROM"=>array(),
"WHERE"=>array(),
"GROUPBY"=>array(),
"ORDERBY"=>array(),
"LIMIT"=>"",
"HAVING"=>array()
);
$_id_table = id_table_objet($table);
$requete['SELECT'][] = "t.".$_id_table;
$a = array();
// Recherche fulltext
foreach ($champs as $champ => $poids) {
if (is_array($champ)){
spip_log("requetes imbriquees interdites");
} else {
if (strpos($champ,".")===FALSE)
$champ = "t.$champ";
$requete['SELECT'][] = $champ;
$a[] = $champ.' '.$methode.' '.$q;
}
}
if ($a) $requete['WHERE'][] = join(" OR ", $a);
$requete['FROM'][] = table_objet_sql($table).' AS t';
$s = sql_select(
$requete['SELECT'], $requete['FROM'], $requete['WHERE'],
implode(" ",$requete['GROUPBY']),
$requete['ORDERBY'], $requete['LIMIT'],
$requete['HAVING'], $serveur
);
while ($t = sql_fetch($s,$serveur)) {
$id = intval($t[$_id_table]);
if ($options['toutvoir']
OR autoriser('voir', $table, $id)) {
// indiquer les champs concernes
$champs_vus = array();
$score = 0;
$matches = array();
$vu = false;
foreach ($champs as $champ => $poids) {
$champ = explode('.',$champ);
$champ = end($champ);
if ($n =
($options['score'] || $options['matches'])
? preg_match_all($preg, translitteration_rapide($t[$champ]), $regs, PREG_SET_ORDER)
: preg_match($preg, translitteration_rapide($t[$champ]))
) {
$vu = true;
if ($options['champs'])
$champs_vus[$champ] = $t[$champ];
if ($options['score'])
$score += $n * $poids;
if ($options['matches'])
$matches[$champ] = $regs;
if (!$options['champs']
AND !$options['score']
AND !$options['matches'])
break;
}
}
if ($vu) {
if (!isset($results[$table]))
$results[$table] = array();
$results[$table][$id] = array();
if ($champs_vus)
$results[$table][$id]['champs'] = $champs_vus;
if ($score)
$results[$table][$id]['score'] = $score;
if ($matches)
$results[$table][$id]['matches'] = $matches;
}
}
}
// Gerer les donnees associees
if (isset($jointures[$table])
AND $joints = recherche_en_base(
$recherche,
$jointures[$table],
array_merge($options, array('jointures' => false))
)
) {
foreach ($joints as $table_liee => $ids_trouves) {
if (!$rechercher_joints = charger_fonction("rechercher_joints_${table}_${table_liee}","inc",true)){
$cle_depart = id_table_objet($table);
$cle_arrivee = id_table_objet($table_liee);
$table_sql = preg_replace('/^spip_/', '', table_objet_sql($table));
$table_liee_sql = preg_replace('/^spip_/', '', table_objet_sql($table_liee));
if ($table_liee == 'document')
$s = sql_select("id_objet as $cle_depart, $cle_arrivee", "spip_documents_liens", array("objet='$table'",sql_in('id_'.${table_liee}, array_keys($ids_trouves))), '','','','',$serveur);
else
$s = sql_select("$cle_depart,$cle_arrivee", "spip_${table_liee_sql}_${table_sql}", sql_in('id_'.${table_liee}, array_keys($ids_trouves)), '','','','',$serveur);
}
else
list($cle_depart,$cle_arrivee,$s) = $rechercher_joints($table,$table_liee,array_keys($ids_trouves), $serveur);
while ($t = is_array($s)?array_shift($s):sql_fetch($s)) {
$id = $t[$cle_depart];
$joint = $ids_trouves[$t[$cle_arrivee]];
if (!isset($results[$table]))
$results[$table] = array();
if (!isset($results[$table][$id]))
$results[$table][$id] = array();
if ($joint['score'])
$results[$table][$id]['score'] += $joint['score'];
if ($joint['champs'])
foreach($joint['champs'] as $c => $val)
$results[$table][$id]['champs'][$table_liee.'.'.$c] = $val;
if ($joint['matches'])
foreach($joint['matches'] as $c => $val)
$results[$table][$id]['matches'][$table_liee.'.'.$c] = $val;
}
}
}
}
return $results;
}
// Effectue une recherche sur toutes les tables de la base de donnees
// http://doc.spip.org/@remplace_en_base
function remplace_en_base($recherche='', $remplace=NULL, $tables=NULL, $options=array()) {
include_spip('inc/modifier');
// options par defaut
$options = array_merge(array(
'preg_flags' => 'UimsS',
'toutmodifier' => false
),
$options
);
$options['champs'] = true;
if (!is_array($tables))
$tables = liste_des_champs();
$results = recherche_en_base($recherche, $tables, $options);
$preg = '/'.str_replace('/', '\\/', $recherche).'/' . $options['preg_flags'];
foreach ($results as $table => $r) {
$_id_table = id_table_objet($table);
foreach ($r as $id => $x) {
if ($options['toutmodifier']
OR autoriser('modifier', $table, $id)) {
$modifs = array();
foreach ($x['champs'] as $key => $val) {
if ($key == $_id_table) next;
$repl = preg_replace($preg, $remplace, $val);
if ($repl <> $val)
$modifs[$key] = $repl;
}
if ($modifs)
modifier_contenu($table, $id,
array(
'champs' => array_keys($modifs),
),
$modifs);
}
}
}
}
?>
| mit |
Maijin/sdb | bindings/nodejs/nan/README.md | 668 | SDB bindings for nodejs
=======================
SDB is a fast and small key-value database.
All keys and values can only be strings, those strings are
interpreted as arrays, numbers, booleans, pointers, or even
JSON objects that can be parsed and indented pretty quickly.
The SDB database works like memcache, as it is designed to
run in memory, but supports atomic sync to disk and journaling.
Getting Started
===============
```js
var sdb = require('sdb');
var db = new sdb.Database("test.db");
// quick json indentation
console.log(sdb.json_unindent(
sdb.json_indent('{"pop":33,"caca":123}')));
db.set("foo", "bar")
console.log ("Hello "+db.get("bar"));
```
| mit |
camperjz/trident | modules/boonex/organizations/updates/8.0.1_8.0.2/install/config.php | 1044 | <?php
/**
* Copyright (c) BoonEx Pty Limited - http://www.boonex.com/
* CC-BY License - http://creativecommons.org/licenses/by/3.0/
*/
$aConfig = array(
/**
* Main Section.
*/
'title' => 'Organizations',
'version_from' => '8.0.1',
'version_to' => '8.0.2',
'vendor' => 'BoonEx',
'compatible_with' => array(
'8.0.0.A8'
),
/**
* 'home_dir' and 'home_uri' - should be unique. Don't use spaces in 'home_uri' and the other special chars.
*/
'home_dir' => 'boonex/organizations/updates/update_8.0.1_8.0.2/',
'home_uri' => 'orgs_update_801_802',
'module_dir' => 'boonex/organizations/',
'module_uri' => 'orgs',
'db_prefix' => 'bx_organizations_',
'class_prefix' => 'BxOrgs',
/**
* Installation/Uninstallation Section.
*/
'install' => array(
'execute_sql' => 1,
'update_files' => 1,
'update_languages' => 1,
'clear_db_cache' => 1,
),
/**
* Category for language keys.
*/
'language_category' => 'Organizations',
);
| mit |
colemickens/autorest | ClientRuntimes/CSharp/ClientRuntime.Azure.Authentication/ActiveDirectoryServiceSettings.cs | 3207 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest.Azure.Authentication.Properties;
namespace Microsoft.Rest.Azure.Authentication
{
/// <summary>
/// Settings for authentication with an Azure or Azure Stack service using Active Directory.
/// </summary>
public sealed class ActiveDirectoryServiceSettings
{
private Uri _authenticationEndpoint;
private static readonly ActiveDirectoryServiceSettings AzureSettings = new ActiveDirectoryServiceSettings
{
AuthenticationEndpoint= new Uri("https://login.windows.net/"),
TokenAudience = new Uri("https://management.core.windows.net/"),
ValidateAuthority = true
};
private static readonly ActiveDirectoryServiceSettings AzureChinaSettings = new ActiveDirectoryServiceSettings
{
AuthenticationEndpoint= new Uri("https://login.chinacloudapi.cn/"),
TokenAudience = new Uri("https://management.core.chinacloudapi.cn/"),
ValidateAuthority = true
};
/// <summary>
/// Gets the serviceSettings for authentication with Azure
/// </summary>
public static ActiveDirectoryServiceSettings Azure { get { return AzureSettings; } }
/// <summary>
/// Gets the serviceSettings for authentication with Azure China
/// </summary>
public static ActiveDirectoryServiceSettings AzureChina { get { return AzureChinaSettings; } }
/// <summary>
/// Gets or sets the ActiveDirectory Endpoint for the Azure Environment
/// </summary>
public Uri AuthenticationEndpoint
{
get { return _authenticationEndpoint; }
set { _authenticationEndpoint = EnsureTrailingSlash(value); }
}
/// <summary>
/// Gets or sets the Token audience for an endpoint
/// </summary>
public Uri TokenAudience { get; set; }
/// <summary>
/// Gets or sets a value that determines whether the authentication endpoint should be validated with Azure AD
/// </summary>
public bool ValidateAuthority { get; set; }
private static Uri EnsureTrailingSlash(Uri authenticationEndpoint)
{
if (authenticationEndpoint == null)
{
throw new ArgumentNullException("authenticationEndpoint");
}
UriBuilder builder = new UriBuilder(authenticationEndpoint);
if (!string.IsNullOrEmpty(builder.Query))
{
throw new ArgumentOutOfRangeException(Resources.AuthenticationEndpointContainsQuery);
}
var path = builder.Path;
if (string.IsNullOrWhiteSpace(path))
{
path = "/";
}
else if (!path.EndsWith("/", StringComparison.Ordinal))
{
path = path + "/";
}
builder.Path = path;
return builder.Uri;
}
}
}
| mit |
femtoio/femto-usb-blink-example | blinky/sam0/applications/dmac_cpu_usage_demo/adc_no_dmac_usart.c | 16015 | /**
* \file
*
* \brief SAMD10/SAMD11 DMAC Application Note Example for the case 'ADC_NO_DMAC_USART'
*
* Copyright (C) 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/*
* Include header files for all drivers that have been imported from
* Atmel Software Framework (ASF).
*/
/**
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#include <asf.h>
#include <string.h>
#if defined(ADC_NO_DMAC_USART)
/* FUNCTION PROTOTYPES */
/*! \brief Initializes and enables ADC */
void configure_adc(void);
/*! \brief Initializes and enables SERCOM - USART */
void configure_usart(void);
/*! \brief Initializes and enables PORT */
void configure_port(void);
/*! \brief Initializes and enables System Timer (SysTick) */
void systick_init(void);
/*! This function calculates number of cycles taken from SysTick time stamp */
uint32_t calculate_cycles_taken(uint32_t start_cycle, uint32_t end_cycle);
/*! Writes data to SERCOM - USART */
void usart_write_data(struct usart_module *const module, uint8_t *usart_tx_data, uint32_t length);
/*! ADC interrupt Handler */
static void _adc_interrupt_handler(void);
/*! USART interrupt Handler */
static void _usart_interrupt_handler(void);
/* MACRO Definitions */
/*! Maximum reload value that can be loaded to SysTick */
#define SYSTICK_MAX_VALUE (SysTick_LOAD_RELOAD_Msk - 1) //// Niyas - Not the right approach to load the maximum value; In this case it works as SysTick_LOAD_RELOAD_Pos is 0
/*! Number of ADC samples to be taken and transferred (for with and without case) */
#define BLOCK_COUNT 1024
/*! brief Flag to indicate adc conversion done when not using DMA */
volatile bool adc_conv_done = false;
/*! brief Number of ADC samples done when not using DMA */
uint32_t adc_sample_count = 0;
/*! SysTick variables to take time stamp at different instance */
uint32_t time_stamp1 =0,time_stamp2=0;
/*! brief Contains the number of cycles taken from SysTick time stamp */
uint32_t cycles_taken=0, idle_loop_count=0;
/*! brief buffer tp store ADC result */
uint8_t adc_result[BLOCK_COUNT],adc_result_copy[BLOCK_COUNT];
/*! brief Initialize SysTick reload and overflow counter variable */
static volatile uint32_t systick_reload = 0,systick_counter = 0;
/*! brief USART module instance */
struct usart_module usart_instance;
/*! brief ADC module instance */
struct adc_module adc_instance;
/*! brief PORT base address */
volatile PortGroup *const port_base = PORT;
/**
* \brief Enable ADC interrupt
* \param module_inst ADC module instance
* \param interrupt_mask Interrupts to be enabled in ADC
*/
static inline void adc_interrupt_enable(struct adc_module *const module_inst,
uint8_t interrupt_mask)
{
/* ADC module base address */
Adc *const adc_module = module_inst->hw;
/* Enable interrupts */
adc_module->INTENSET.reg = interrupt_mask;
}
/**
* \brief ADC interrupt Handler
* \param adc_module_inst ADC module instance
* \param usart_module_inst USART module instance
*/
static void _adc_interrupt_handler(void)
{
/* ADC base address */
Adc *const adc_hw = adc_instance.hw;
/* get interrupt flags */
uint32_t flags = adc_hw->INTFLAG.reg;
/* Check if the all the samples has been done by ADC */
if (adc_sample_count == BLOCK_COUNT){
/* Disable ADC */
adc_hw->CTRLA.reg &= ~ADC_CTRLA_ENABLE;
/* Write samples to USART */
usart_write_data(&usart_instance,adc_result,BLOCK_COUNT);
/* Indicate conversion has been done */
adc_conv_done = true;
/* Get the time stamp from SysTick */
time_stamp2 = SysTick->VAL;
}else if (flags & ADC_INTFLAG_RESRDY) {
/* Clear ADC interrupt */
adc_hw->INTFLAG.reg = ADC_INTFLAG_RESRDY;
/* Store ADC result to RAM buffer */
adc_result[adc_sample_count] = adc_hw->RESULT.reg;
/* Count the number of samples taken so far */
++adc_sample_count;
/* Trigger next ADC conversion */
adc_start_conversion(&adc_instance);
}
} /* End of ADC Hander */
/**
* \brief Actual ADC Handler
* NOTE: This will point to the _adc_interrupt_handler function
* where the ADC interrupt is being processed.
*/
void ADC_Handler()
{
#if defined (ENABLE_PORT_TOGGLE)
/* Use oscilloscope to probe the pin. */
port_base->OUTTGL.reg = (1UL << PIN_PA14 % 32 );
#endif
_adc_interrupt_handler();
}
/**
* \brief USART interrupt Handler
* \param usart_module_inst USART module instance
*/
static void _usart_interrupt_handler(void)
{
/* Pointer to the hardware module instance */
SercomUsart *const usart_hw = &(usart_instance.hw->USART);
/* To store current interrupt status */
uint8_t interrupt_status;
/* Read interrupt flag register */
interrupt_status = usart_hw->INTFLAG.reg;
if (interrupt_status & SERCOM_USART_INTFLAG_TXC) {
/* Clear Transfer Complete Interrupt */
usart_hw->INTFLAG.reg = SERCOM_USART_INTENCLR_TXC;
}
} /* End of USART Handler */
/**
* \brief Actual SERCOM Handler
* NOTE: This will point to the _usart_interrupt_handler function
* where the USART interrupt is being processed.
*/
void SERCOM2_Handler()
{
_usart_interrupt_handler();
}
/**
* \brief Write data to USART DATA register
* \param usart_tx_data Data to be written
* \param length Buffer length
*/
void usart_write_data(struct usart_module *const module, uint8_t *usart_tx_data, uint32_t length)
{
/* Temporary count variable */
uint32_t count ;
/* SERCOM - USART base address */
SercomUsart *const usart_hw = &(module->hw->USART);
for (count =0; count < length;count++){
/* Wait until data register is empty */
while(!(usart_hw->INTFLAG.reg & SERCOM_USART_INTFLAG_DRE));
/* Write data to USART module */
usart_hw->DATA.reg = usart_tx_data[count];
}
}
/**
* \brief SysTick interrupt handler
*/
void SysTick_Handler(void)
{
/* Increment the software counter */
systick_counter++;
}
/**
* \brief Initialize the SysTick timer
*
*/
void systick_init()
{
/* Calculate the reload value */
systick_reload = SYSTICK_MAX_VALUE;// Niyas - what is the need of this and what will be the interrupt time interval with this value?
/* Initialize software counter */
systick_counter = 0;
/* Disable the SYSTICK Counter */
SysTick->CTRL &= (~SysTick_CTRL_ENABLE_Msk);
/* set reload register */
SysTick->LOAD = systick_reload;
/* set Priority for Cortex-M0 System Interrupts */
NVIC_SetPriority (SysTick_IRQn, (1<<__NVIC_PRIO_BITS) - 1);
/* Load the SysTick Counter Value */
SysTick->VAL = systick_reload;
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk;
/* Enable SysTick interrupt */
NVIC_EnableIRQ(SysTick_IRQn);
}
/**
* \brief configure and enable SERCOM - USART
*/
void configure_usart(void)
{
/* USART set up configuration */
struct usart_config config_usart;
/* USART base address */
SercomUsart *const usart_hw = SERCOM2;
/* Get USART default configuration */
usart_get_config_defaults(&config_usart);
/* Configure USART baud rate and pad */
config_usart.baudrate = 460800;
config_usart.mux_setting = EDBG_CDC_SERCOM_MUX_SETTING;
config_usart.pinmux_pad0 = EDBG_CDC_SERCOM_PINMUX_PAD0;
config_usart.pinmux_pad1 = EDBG_CDC_SERCOM_PINMUX_PAD1;
config_usart.pinmux_pad2 = EDBG_CDC_SERCOM_PINMUX_PAD2;
config_usart.pinmux_pad3 = EDBG_CDC_SERCOM_PINMUX_PAD3;
/* Initialize USART */
while (usart_init(&usart_instance,
EDBG_CDC_MODULE, &config_usart) != STATUS_OK) {
}
/* Enable interrupt */
system_interrupt_enable(SERCOM2_IRQn);
/* Enable USART */
usart_enable(&usart_instance);
/* Enable USART transfer complete interrupt */
usart_hw->INTENSET.reg = SERCOM_USART_INTFLAG_TXC;
}
/**
* \brief Configure and enable ADC
*/
void configure_adc(void)
{
/* ADC configuration set up */
struct adc_config config_adc;
/* Get default ADC configuration */
adc_get_config_defaults(&config_adc);
config_adc.gain_factor = ADC_GAIN_FACTOR_DIV2;
config_adc.clock_prescaler = ADC_CLOCK_PRESCALER_DIV64;
config_adc.reference = ADC_REFERENCE_INTVCC1;
config_adc.positive_input = ADC_POSITIVE_INPUT_PIN0;
config_adc.resolution = ADC_RESOLUTION_8BIT;
/* Initialize ADC */
adc_init(&adc_instance, ADC, &config_adc);
/* Enable ADC Result ready interrupt */
adc_interrupt_enable(&adc_instance,ADC_INTFLAG_RESRDY);
/* Enable ADC module interrupt in NVIC */
system_interrupt_enable(SYSTEM_INTERRUPT_MODULE_ADC);
/* Enable ADC module */
adc_enable(&adc_instance);
}
/**
* \brief Calculate number of cycles taken to execute certain number of
* instructions from the time stamp taken with system timer (SysTick)
*/
uint32_t calculate_cycles_taken(uint32_t start_cycle, uint32_t end_cycle)
{
uint32_t total_cycles =0;
/* Check if counter flow occurs */
if (systick_counter == 0){
/* Ensure Start cycle is greater than end cycle */
if(start_cycle > end_cycle)
total_cycles = start_cycle - end_cycle;
}else if (systick_counter > 0){
total_cycles = start_cycle + ((systick_counter-1) * SYSTICK_MAX_VALUE)
+ (SYSTICK_MAX_VALUE - end_cycle);
}
return total_cycles;
}
/**
* \brief Configure port pins PA14 and PA16 as output with zero
* as initial out value.
*/
void configure_port(void)// Niyas - why this configuration? Can be conditional if it is for debugging
{
/* Set PA14 and PA15 as output */
port_base->DIRSET.reg = (1UL << PIN_PA14 % 32 ) | (1UL << PIN_PA16 % 32 );
/* Set OUT value to zero */
port_base->OUT.reg = (0UL << PIN_PA14 % 32 ) | (0UL << PIN_PA16 % 32 );
}
/**
* \brief Main Application Routine \n
* - Initialize the system clocks \n
* NOTE: The clock should be configured in conf_clock.h \n
* - Configure port pins (PA14 and PA16) are used here \n
* - Enable Global Interrupt \n
* - Configure and enable USART \n
* - Configure and enable ADC \n
* - Configure and enable DMAC and EVSYS if DMAC mode is chosen \n
* - Start first ADC conversion \n
* - Count idle loop count in forever loop \n
*/
int main(void)
{
/* Initialize system clocks */
system_init();
#if defined(ENABLE_PORT_TOGGLE)
/* Configure PORT pins PA14 and PA16 are configured here
* NOTE: Use oscilloscope to probe the pin.
*/
configure_port();
#endif
/* ENable Global interrupt */
system_interrupt_enable_global();
/* Start SysTick Timer */
systick_init();
/* Configure SERCOM - USART */
configure_usart();
/* Configure and enable ADC */
configure_adc();
/* Get the time stamp 1 before starting ADC transfer */
time_stamp1 = SysTick->VAL;
/*
* Trigger first ADC conversion through software.
* NOTE: In case of using DMA, further conversions are triggered through
* event generated when previous ADC result is transferred to destination
* (can be USART DATA register [or] RAM buffer).
* When DMA is not used, further conversions are triggered via software in
* ADC handler after each result ready.
*/
adc_start_conversion(&adc_instance);
while (1){
#if defined (ENABLE_PORT_TOGGLE)
/* Use oscilloscope to probe the pin. */
port_base->OUTTGL.reg = (1UL << PIN_PA16 % 32 );
#endif
/* Increment idle count whenever application reached while(1) loop */
idle_loop_count++;
/*
* Check if 1024 bytes transfer is done in either case (I.e. with or without
* using DMA.
* 'adc_conv_done' flag is set to true in the ADC handler once
* 'adc_sample_count' reaches BLOCK_COUNT.
* 'adc_dma_transfer_is_done' is set to true once DMA transfer is done
* in DMA call back for channel zero when 'ADC_DMAC_USART' is chosen.
* When choosing ADC_DMAC_MEM_MEM_USART mode, 'adc_dma_transfer_is_done'
* is set to true in DMA channel call back for channel 2.
* DMA channel is disabled once reaching BLOCK_COUNT (with DMA cases).
* ADC is disabled once reaching BLOBK_COUNT samples (without DMA cases).
*/
if (adc_conv_done == true){
/*
* Calculate number of cycles taken from the time stamp
* taken before start of the conversion and after 1024 transfer
* is completed.
* NOTE: This value in relation to the idle_loop_count is
* used in calculating CPU usage.
*/
cycles_taken = calculate_cycles_taken(time_stamp1,time_stamp2);
/* Write the CPU cycles taken on USART */
usart_write_data(&usart_instance,(uint8_t *)&cycles_taken, sizeof(cycles_taken));
/* Print idle loop count on USART */
usart_write_data(&usart_instance,(uint8_t *)&idle_loop_count, sizeof(idle_loop_count));
/*
* Enter into forever loop as all transfers are completed and
* DMAC/ADC is disabled
*/
while(1);
}
}
}//end of main
// Application Documentation
/*! \main page
* \section intro Introduction
* This application demonstrates CPU usage when an application is
* implemented with and without DMA. Also it demonstrates different
* DMA transfer types such as Peripheral to peripheral, Peripheral
* to memory, memory to memory and memory to peripheral.
*
* ADC is sampled and the result data is sent to USART. This application is
* implemented with and without DMAC. These different cases are chosen by
* switching compiler options in the file conf_dma.h.
*
* The CPU cycles taken is calculated for all the cases using
* System Timer (SysTick). A variable is also incremented in the while(1) loop
* which executes whenever CPU is available. The proportion of these two values
* are used to calculate the CPU usage for the chosen case.
*
* For more details about this application, please refer to the Application
* note "AT07685: CPU Usage demonstration using DMAC Application" in the
* link http://www.atmel.com/devices/ATSAMD11D14A.aspx?tab=documents
*
* \section referenceinfo References
* - SAMD10/11 device data sheet
* - SAMD11 Xplained Pro board schematics
* - IO1 Xplained board schematics
* - ATxxxx Application note
*
* \section compinfo Compiler Support
* This example application supports
* - GNU GCC for ARM
*
* \section deviceinfo Device support
* - ATSAMD11/10 Series
*
* \author
* Atmel Corporation : http://www.atmel.com \n
*/
#endif
| mit |
felipecvo/rails | activesupport/lib/active_support/number_helper/number_to_rounded_converter.rb | 1873 | # frozen_string_literal: true
module ActiveSupport
module NumberHelper
class NumberToRoundedConverter < NumberConverter # :nodoc:
self.namespace = :precision
self.validate_float = true
def convert
helper = RoundingHelper.new(options)
rounded_number = helper.round(number)
if precision = options[:precision]
if options[:significant] && precision > 0
digits = helper.digit_count(rounded_number)
precision -= digits
precision = 0 if precision < 0 # don't let it be negative
end
formatted_string =
if BigDecimal === rounded_number && rounded_number.finite?
s = rounded_number.to_s("F")
s << "0".freeze * precision
a, b = s.split(".".freeze, 2)
a << ".".freeze
a << b[0, precision]
else
"%00.#{precision}f" % rounded_number
end
else
formatted_string = rounded_number
end
delimited_number = NumberToDelimitedConverter.convert(formatted_string, options)
format_number(delimited_number)
end
private
def calculate_rounded_number(multiplier)
(number / BigDecimal.new(multiplier.to_f.to_s)).round * multiplier
end
def digit_count(number)
number.zero? ? 1 : (Math.log10(absolute_number(number)) + 1).floor
end
def strip_insignificant_zeros
options[:strip_insignificant_zeros]
end
def format_number(number)
if strip_insignificant_zeros
escaped_separator = Regexp.escape(options[:separator])
number.sub(/(#{escaped_separator})(\d*[1-9])?0+\z/, '\1\2').sub(/#{escaped_separator}\z/, "")
else
number
end
end
end
end
end
| mit |
otgaard/zap | third_party/asio/doc/asio/reference/serial_port_service/native_handle.html | 2830 | <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>serial_port_service::native_handle</title>
<link rel="stylesheet" href="../../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.75.2">
<link rel="home" href="../../../index.html" title="Asio">
<link rel="up" href="../serial_port_service.html" title="serial_port_service">
<link rel="prev" href="native.html" title="serial_port_service::native">
<link rel="next" href="native_handle_type.html" title="serial_port_service::native_handle_type">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr><td valign="top"><img alt="asio C++ library" width="250" height="60" src="../../../asio.png"></td></tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="native.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../serial_port_service.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="native_handle_type.html"><img src="../../../next.png" alt="Next"></a>
</div>
<div class="section">
<div class="titlepage"><div><div><h4 class="title">
<a name="asio.reference.serial_port_service.native_handle"></a><a class="link" href="native_handle.html" title="serial_port_service::native_handle">serial_port_service::native_handle</a>
</h4></div></div></div>
<p>
<a class="indexterm" name="idp170787904"></a>
Get the native handle implementation.
</p>
<pre class="programlisting"><span class="identifier">native_handle_type</span> <span class="identifier">native_handle</span><span class="special">(</span>
<span class="identifier">implementation_type</span> <span class="special">&</span> <span class="identifier">impl</span><span class="special">);</span>
</pre>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2003-2015 Christopher M.
Kohlhoff<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="native.html"><img src="../../../prev.png" alt="Prev"></a><a accesskey="u" href="../serial_port_service.html"><img src="../../../up.png" alt="Up"></a><a accesskey="h" href="../../../index.html"><img src="../../../home.png" alt="Home"></a><a accesskey="n" href="native_handle_type.html"><img src="../../../next.png" alt="Next"></a>
</div>
</body>
</html>
| mit |
wenjoy/homePage | node_modules/node-captcha/node_modules/canvas/node_modules/mocha/node_modules/mkdirp/node_modules/mock-fs/node_modules/rewire/node_modules/expect.js/node_modules/serve/node_modules/less-middleware/node_modules/express/lib/application.js | 10240 | /**
* Module dependencies.
*/
var finalhandler = require('finalhandler');
var flatten = require('./utils').flatten;
var Router = require('./router');
var methods = require('methods');
var middleware = require('./middleware/init');
var query = require('./middleware/query');
var debug = require('debug')('express:application');
var View = require('./view');
var http = require('http');
var compileETag = require('./utils').compileETag;
var compileQueryParser = require('./utils').compileQueryParser;
var compileTrust = require('./utils').compileTrust;
var deprecate = require('depd')('express');
var merge = require('utils-merge');
var resolve = require('path').resolve;
var slice = Array.prototype.slice;
/**
* Application prototype.
*/
var app = exports = module.exports = {};
/**
* Initialize the server.
*
* - setup default configuration
* - setup default middleware
* - setup route reflection methods
*
* @api private
*/
app.init = function(){
this.cache = {};
this.settings = {};
this.engines = {};
this.defaultConfiguration();
};
/**
* Initialize application configuration.
*
* @api private
*/
app.defaultConfiguration = function(){
// default settings
this.enable('x-powered-by');
this.set('etag', 'weak');
var env = process.env.NODE_ENV || 'development';
this.set('env', env);
this.set('query parser', 'extended');
this.set('subdomain offset', 2);
this.set('trust proxy', false);
debug('booting in %s mode', env);
// inherit protos
this.on('mount', function(parent){
this.request.__proto__ = parent.request;
this.response.__proto__ = parent.response;
this.engines.__proto__ = parent.engines;
this.settings.__proto__ = parent.settings;
});
// setup locals
this.locals = Object.create(null);
// top-most app is mounted at /
this.mountpath = '/';
// default locals
this.locals.settings = this.settings;
// default configuration
this.set('view', View);
this.set('views', resolve('views'));
this.set('jsonp callback name', 'callback');
if (env === 'production') {
this.enable('view cache');
}
Object.defineProperty(this, 'router', {
get: function() {
throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.');
}
});
};
/**
* lazily adds the base router if it has not yet been added.
*
* We cannot add the base router in the defaultConfiguration because
* it reads app settings which might be set after that has run.
*
* @api private
*/
app.lazyrouter = function() {
if (!this._router) {
this._router = new Router({
caseSensitive: this.enabled('case sensitive routing'),
strict: this.enabled('strict routing')
});
this._router.use(query(this.get('query parser fn')));
this._router.use(middleware.init(this));
}
};
/**
* Dispatch a req, res pair into the application. Starts pipeline processing.
*
* If no _done_ callback is provided, then default error handlers will respond
* in the event of an error bubbling through the stack.
*
* @api private
*/
app.handle = function(req, res, done) {
var router = this._router;
// final handler
done = done || finalhandler(req, res, {
env: this.get('env'),
onerror: logerror.bind(this)
});
// no routes
if (!router) {
debug('no routes defined on app');
done();
return;
}
router.handle(req, res, done);
};
/**
* Proxy `Router#use()` to add middleware to the app router.
* See Router#use() documentation for details.
*
* If the _fn_ parameter is an express app, then it will be
* mounted at the _route_ specified.
*
* @api public
*/
app.use = function use(fn) {
var offset = 0;
var path = '/';
// default path to '/'
// disambiguate app.use([fn])
if (typeof fn !== 'function') {
var arg = fn;
while (Array.isArray(arg) && arg.length !== 0) {
arg = arg[0];
}
// first arg is the path
if (typeof arg !== 'function') {
offset = 1;
path = fn;
}
}
var fns = flatten(slice.call(arguments, offset));
if (fns.length === 0) {
throw new TypeError('app.use() requires middleware functions');
}
// setup router
this.lazyrouter();
var router = this._router;
fns.forEach(function (fn) {
// non-express app
if (!fn || !fn.handle || !fn.set) {
return router.use(path, fn);
}
debug('.use app under %s', path);
fn.mountpath = path;
fn.parent = this;
// restore .app property on req and res
router.use(path, function mounted_app(req, res, next) {
var orig = req.app;
fn.handle(req, res, function (err) {
req.__proto__ = orig.request;
res.__proto__ = orig.response;
next(err);
});
});
// mounted an app
fn.emit('mount', this);
}, this);
return this;
};
/**
* Proxy to the app `Router#route()`
* Returns a new `Route` instance for the _path_.
*
* Routes are isolated middleware stacks for specific paths.
* See the Route api docs for details.
*
* @api public
*/
app.route = function(path){
this.lazyrouter();
return this._router.route(path);
};
/**
* Register the given template engine callback `fn`
* as `ext`.
*
* By default will `require()` the engine based on the
* file extension. For example if you try to render
* a "foo.jade" file Express will invoke the following internally:
*
* app.engine('jade', require('jade').__express);
*
* For engines that do not provide `.__express` out of the box,
* or if you wish to "map" a different extension to the template engine
* you may use this method. For example mapping the EJS template engine to
* ".html" files:
*
* app.engine('html', require('ejs').renderFile);
*
* In this case EJS provides a `.renderFile()` method with
* the same signature that Express expects: `(path, options, callback)`,
* though note that it aliases this method as `ejs.__express` internally
* so if you're using ".ejs" extensions you dont need to do anything.
*
* Some template engines do not follow this convention, the
* [Consolidate.js](https://github.com/tj/consolidate.js)
* library was created to map all of node's popular template
* engines to follow this convention, thus allowing them to
* work seamlessly within Express.
*
* @param {String} ext
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.engine = function(ext, fn){
if ('function' != typeof fn) throw new Error('callback function required');
if ('.' != ext[0]) ext = '.' + ext;
this.engines[ext] = fn;
return this;
};
/**
* Proxy to `Router#param()` with one added api feature. The _name_ parameter
* can be an array of names.
*
* See the Router#param() docs for more details.
*
* @param {String|Array} name
* @param {Function} fn
* @return {app} for chaining
* @api public
*/
app.param = function(name, fn){
this.lazyrouter();
if (Array.isArray(name)) {
name.forEach(function(key) {
this.param(key, fn);
}, this);
return this;
}
this._router.param(name, fn);
return this;
};
/**
* Assign `setting` to `val`, or return `setting`'s value.
*
* app.set('foo', 'bar');
* app.get('foo');
* // => "bar"
*
* Mounted servers inherit their parent server's settings.
*
* @param {String} setting
* @param {*} [val]
* @return {Server} for chaining
* @api public
*/
app.set = function(setting, val){
if (arguments.length === 1) {
// app.get(setting)
return this.settings[setting];
}
// set value
this.settings[setting] = val;
// trigger matched settings
switch (setting) {
case 'etag':
debug('compile etag %s', val);
this.set('etag fn', compileETag(val));
break;
case 'query parser':
debug('compile query parser %s', val);
this.set('query parser fn', compileQueryParser(val));
break;
case 'trust proxy':
debug('compile trust proxy %s', val);
this.set('trust proxy fn', compileTrust(val));
break;
}
return this;
};
/**
* Return the app's absolute pathname
* based on the parent(s) that have
* mounted it.
*
* For example if the application was
* mounted as "/admin", which itself
* was mounted as "/blog" then the
* return value would be "/blog/admin".
*
* @return {String}
* @api private
*/
app.path = function(){
return this.parent
? this.parent.path() + this.mountpath
: '';
};
/**
* Check if `setting` is enabled (truthy).
*
* app.enabled('foo')
* // => false
*
* app.enable('foo')
* app.enabled('foo')
* // => true
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.enabled = function(setting){
return !!this.set(setting);
};
/**
* Check if `setting` is disabled.
*
* app.disabled('foo')
* // => true
*
* app.enable('foo')
* app.disabled('foo')
* // => false
*
* @param {String} setting
* @return {Boolean}
* @api public
*/
app.disabled = function(setting){
return !this.set(setting);
};
/**
* Enable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.enable = function(setting){
return this.set(setting, true);
};
/**
* Disable `setting`.
*
* @param {String} setting
* @return {app} for chaining
* @api public
*/
app.disable = function(setting){
return this.set(setting, false);
};
/**
* Delegate `.VERB(...)` calls to `router.VERB(...)`.
*/
methods.forEach(function(method){
app[method] = function(path){
if ('get' == method && 1 == arguments.length) return this.set(path);
this.lazyrouter();
var route = this._router.route(path);
route[method].apply(route, slice.call(arguments, 1));
return this;
};
});
/**
* Special-cased "all" method, applying the given route `path`,
* middleware, and callback to _every_ HTTP method.
*
* @param {String} path
* @param {Function} ...
* @return {app} for chaining
* @api public
*/
app.all = function(path){
this.lazyrouter();
var route = this._router.route(path);
var args = slice.call(arguments, 1);
methods.forEach(function(method){
route[method].apply(route, args);
});
return this;
};
// del -> delete alias
app.del = deprecate.function(app.d | mit |
aspose-cells/Aspose.Cells-for-Cloud | SDKs/Aspose.Cells-Cloud-SDK-for-Python/asposecellscloud/models/PivotFilter.py | 1456 | #!/usr/bin/env python
class PivotFilter(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually."""
def __init__(self):
"""
Attributes:
swaggerTypes (dict): The key is attribute name and the value is attribute type.
attributeMap (dict): The key is attribute name and the value is json key in definition.
"""
self.swaggerTypes = {
'AutoFilter': 'AutoFilter',
'EvaluationOrder': 'int',
'FieldIndex': 'int',
'FilterType': 'str',
'MeasureFldIndex': 'int',
'MemberPropertyFieldIndex': 'int',
'Name': 'str',
'Value1': 'str',
'Value2': 'str'
}
self.attributeMap = {
'AutoFilter': 'AutoFilter','EvaluationOrder': 'EvaluationOrder','FieldIndex': 'FieldIndex','FilterType': 'FilterType','MeasureFldIndex': 'MeasureFldIndex','MemberPropertyFieldIndex': 'MemberPropertyFieldIndex','Name': 'Name','Value1': 'Value1','Value2': 'Value2'}
self.AutoFilter = None # AutoFilter
self.EvaluationOrder = None # int
self.FieldIndex = None # int
self.FilterType = None # str
self.MeasureFldIndex = None # int
self.MemberPropertyFieldIndex = None # int
self.Name = None # str
self.Value1 = None # str
self.Value2 = None # str
| mit |
femtoio/femto-usb-blink-example | blinky/blinky/asf-3.21.0/thirdparty/freertos/demo/avr32_uc3_example/at32uc3l064_uc3l_ek/iar/asf.h | 4041 | /**
* \file
*
* \brief Autogenerated API include file for the Atmel Software Framework (ASF)
*
* Copyright (c) 2012 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
#ifndef ASF_H
#define ASF_H
/*
* This file includes all API header files for the selected drivers from ASF.
* Note: There might be duplicate includes required by more than one driver.
*
* The file is automatically generated and will be re-written when
* running the ASF driver selector tool. Any changes will be discarded.
*/
// From module: Compiler abstraction layer and code utilities
#include <compiler.h>
#include <status_codes.h>
// From module: FLASH Controller Double-Word (FLASHCDW)
#include <flashcdw.h>
// From module: FreeRTOS mini Real-Time Kernel
#include <FreeRTOS.h>
#include <StackMacros.h>
#include <croutine.h>
#include <list.h>
#include <mpu_wrappers.h>
#include <portable.h>
#include <projdefs.h>
#include <queue.h>
#include <semphr.h>
#include <task.h>
#include <timers.h>
// From module: GPIO - General-Purpose Input/Output
#include <gpio.h>
// From module: Generic board support
#include <board.h>
// From module: INTC - Interrupt Controller
#include <intc.h>
// From module: Interrupt management - UC3 implementation
#include <interrupt.h>
// From module: PM Power Manager - UC3 L0 implementation
#include <power_clocks_lib.h>
#include <sleep.h>
// From module: Part identification macros
#include <parts.h>
// From module: RTOS - FreeRTOS examples helper files
#include <AltBlckQ.h>
#include <AltBlock.h>
#include <AltPollQ.h>
#include <AltQTest.h>
#include <BlockQ.h>
#include <GenQTest.h>
#include <IntQueue.h>
#include <PollQ.h>
#include <QPeek.h>
#include <blocktim.h>
#include <comtest.h>
#include <comtest2.h>
#include <countsem.h>
#include <crflash.h>
#include <crhook.h>
#include <death.h>
#include <dynamic.h>
#include <fileIO.h>
#include <flash.h>
#include <flop.h>
#include <integer.h>
#include <mevents.h>
#include <partest.h>
#include <print.h>
#include <recmutex.h>
#include <semtest.h>
#include <serial.h>
// From module: SCIF System Control Interface - UC3L implementation
#include <scif_uc3l.h>
// From module: TC - Timer/Counter
#include <tc.h>
// From module: UC3L-EK
#include <led.h>
// From module: USART - Universal Synchronous/Asynchronous Receiver/Transmitter
#include <usart.h>
#endif // ASF_H
| mit |
octavioalapizco/diem | dmCorePlugin/web/lib/dmMarkitup/skins/markitup/style.css | 1818 | div.markItUp a:link,
div.markItUp a:visited {
color:#000;
text-decoration:none;
}
div.markItUp {
}
div.markItUpContainer {
border:1px solid #3C769D;
background:#FFF url(images/bg-container.png) repeat-x top left;
padding:5px 5px 2px 5px;
font:11px Verdana, Arial, Helvetica, sans-serif;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
}
textarea.markItUpEditor,
textarea.markItUpEditor:active,
.dm textarea.markItUpEditor,
.dm textarea.markItUpEditor:active,
.sf_admin_form_row_inner textarea.markItUpEditor {
font:12px 'Courier New', Courier, monospace;
border:3px solid #3C769D;
width: 98%;
background:#FFF url(images/bg-editor.png) repeat-x top left;
clear:both; display:block;
line-height:18px;
overflow:auto;
}
div.markItUpFooter {
width:100%;
}
div.markItUpResizeHandler {
overflow:hidden;
width:22px; height:5px;
margin-left:auto;
margin-right:auto;
background-image:url(images/handle.png);
}
/***************************************************************************************/
/* first row of buttons */
div.markItUpHeader ul li {
list-style:none;
float:left;
position:relative;
}
div.markItUpHeader ul li.markItUpSeparator {
margin:0 10px;
width:1px;
height:16px;
overflow:hidden;
background-color:#CCC;
}
div.markItUpHeader ul a {
display:block;
width:16px; height:16px;
text-indent:-10000px;
background-repeat:no-repeat;
padding:3px !important;
margin:0px;
}
.markdown_preview {
padding: 10px;
border: 1px solid #3C769D;
background: #F8F8F8;
background-position: 0 -28px;
overflow-y: auto;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
}
div.markItUpContainer div.ui-resizable-s {
bottom: 0;
background: url(images/handle.png) no-repeat center 2px;
} | mit |
marko-asplund/github-services | services/presently.rb | 1116 | class Service::Presently < Service
string :subdomain, :group_name, :username
password :password
white_list :subdomain, :group_name, :username
def receive_push
repository = payload['repository']['name']
prefix = (data['group_name'].nil? || data['group_name'] == '') ? '' : "b #{data['group_name']} "
payload['commits'].each do |commit|
status = "#{prefix}[#{repository}] #{commit['author']['name']} - #{commit['message']}"
status = status[0...137] + '...' if status.length > 140
paste = "\"Commit #{commit['id']}\":#{commit['url']}\n\n"
paste << "#{commit['message']}\n\n"
%w(added modified removed).each do |kind|
commit[kind].each do |filename|
paste << "* *#{kind.capitalize}* '#{filename}'\n"
end
end
http.url_prefix = "https://#{data['subdomain']}.presently.com"
http.basic_auth(data['username'], data['password'])
http_post "/api/twitter/statuses/update.xml",
'status' => status,
'source' => 'GitHub',
'paste_format' => 'textile',
'paste_text' => paste
end
end
end
| mit |
JustinMuniz/HoverChat-iOS-App | Spika/lib/DatabaseManager.h | 12928 | /*
The MIT License (MIT)
Copyright (c) 2013 Clover Studio Ltd. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>
#import "Models.h"
#import "HUOfflinePushNotification.h"
#import "HUHTTPClient.h"
#define TargetTypeUser 1
#define TargetTypeGroup 2
typedef void (^DMFindOneBlock)(id result);
typedef void (^DMArrayBlock)(NSArray *);
typedef void (^DMArrayPagingBlock)(NSArray *results, NSInteger totalResults);
typedef void (^DMUpdateBlock)(BOOL, NSString *);
typedef void (^DMUpdateDocumentBlock)(BOOL, NSDictionary *result);
typedef void (^DMErrorBlock)(NSString *errorString);
typedef void (^DMLoadImageBlock)(UIImage *image);
typedef void (^DMLoadVoice)(NSData *data);
@interface DatabaseManager : NSObject
@property (nonatomic, strong, readonly) HUOfflinePushNotification *offlineNotificationModel;
@property (nonatomic, strong) ModelRecentActivity *recentActivity;
+(DatabaseManager *) defaultManager;
#pragma mark - check methods
-(NSDictionary *) checkUniqueSynchronous:(NSString *) key
value:(NSString *) value;
-(NSString *)sendReminderSynchronous:(NSString *)email;
#pragma mark - User Methods
-(void) loginUserByEmail:(NSString *)email
password:(NSString *)password
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findUserByEmail:(NSString *)email
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)createUserByEmail:(NSString *)email
name:(NSString *)name
password:(NSString *)password
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)saveUserAvatarImage:(ModelUser *)toUser
image:(UIImage *)image
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findUsers:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void) findUsersContainingString:(NSString*) string
fromAge:(NSNumber*) fromAge
toAge:(NSNumber*) toAge
gender:(HUGender) gender
success:(DMArrayBlock) successBlock
error:(DMErrorBlock) errorBlock;
-(void)findUsersContainingString:(NSString *)string
success:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)reloadUser:(ModelUser *)user
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findUserWithID:(NSString *)userId
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findUserByName:(NSString *)userName
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)findUserListByGroupID:(NSString *)groupId
count:(int)count
offset:(int)offset
success:(DMArrayPagingBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findUserContactList:(ModelUser *)user
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)updateUser:(ModelUser *)toUser
oldEmail:(NSString *)oldEmail
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)updateUserAddRemoveContacts:(ModelUser *)user
contactId:(NSString *)contactId
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)saveUserPushNotificationToken:(ModelUser *)toUser
token:(NSString *)token
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)updatePassword:(ModelUser *)toUser
newPassword:(NSString *)password
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
#pragma mark - Group Methods
-(void)loadGroups:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findGroupByName:(NSString *)name
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)createGroup:(NSString *)name
description:(NSString *)description
password:(NSString *)password
categoryID:(NSString *)categoryID
categoryName:(NSString *)categoryName
ower:(ModelUser *)user
avatarImage:(UIImage *)avatarImage
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)findGroupByID:(NSString *)groupId
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)findGroupsByCategoryId:(NSString *)groupCategoryId
success:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)addGroupToFavorite:(ModelGroup *)group
toUser:(ModelUser *)user
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)removeGroupFromFavorite:(ModelGroup *)group
toUser:(ModelUser *)user
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)updateGroup:(ModelGroup *)newGroup
avatarImage:(UIImage *)avatarImage
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)reloadGroup:(ModelGroup *)group
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)deleteGroup:(ModelGroup *)newGroup
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)getUsersInGroup:(ModelGroup *)group
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void) findUserFavoriteGroups:(ModelUser *)user
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)saveGroupAvatarImage:(ModelGroup *)toGroup
image:(UIImage *)image
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void) findGroupCategories:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findOneGroupByName:(NSString *)userName
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
#pragma mark - Message Methods
-(void)sendTextMessage:(int) targetType
toUser:(ModelUser *)toUser
toGroup:(ModelGroup *)toGroup
from:(ModelUser *)fromUser
message:(NSString *)message
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findUserMessagesByUser:(ModelUser *) user
partner:(ModelUser *) partner
page:(int) page
success:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)findMessagesByGroup:(ModelGroup *) group
page:(int) page
success:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)reloadMessage:(ModelMessage *)message
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
#pragma mark - Emoticons
- (void)loadEmoticons:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
#pragma mark - Image Methods
-(void)sendImageMessage:(ModelUser *)toUser
toGroup:(ModelGroup *)toGroup
from:(ModelUser *)fromUser
image:(UIImage *)image
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)postImageComment:(ModelMessage *) message
byUser:(ModelUser *)user
comment:(NSString *)comment
success:(DMUpdateDocumentBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)sendEmoticonMessage:(int) targetType
toUser:(ModelUser *)toUser
toGroup:(ModelGroup *)toGroup
from:(ModelUser *)fromUser
emoticonData:(NSDictionary *)data
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)loadImage:(NSString *)imageUrl
success:(DMLoadImageBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)loadCategoryIconByName:(NSString *)categoryName
success:(DMLoadImageBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)loadEmoticons:(NSString *)imageUrl
toBtn:(CSButton *)button
success:(DMLoadImageBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)getCommentsByMessage:(ModelMessage *) message
page:(int) page
success:(DMArrayBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void)getCommentsCountByMessage:(ModelMessage *) message
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(UIImage *) readFromCache:(NSString *)url;
-(void) clearCache;
#pragma mark - Video Methods
-(void)sendVideoMessage:(ModelUser *)toUser
toGroup:(ModelGroup *)toGroup
from:(ModelUser *)fromUser
fileURL:(NSURL *)videoUrl
title:(NSString *)title
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
#pragma mark - Audio Methods
- (void)sendVoiceMessage:(ModelUser *)toUser
toGroup:(ModelGroup *)toGroup
from:(ModelUser *)fromUser
fileURL:(NSURL *)videoUrl
title:(NSString *)title
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
- (void)loadVoice:(NSString *)loadVoice
success:(DMLoadVoice)successBlock
error:(DMErrorBlock)errorBlock;
- (void)loadVideo:(NSString *)loadVoice
success:(DMLoadVoice)successBlock
error:(DMErrorBlock)errorBlock;
#pragma mark - Location Methods
-(void)sendLocationMessageOfType:(int)targetType
toUser:(ModelUser *)toUser
toGroup:(ModelGroup *)toGroup
from:(ModelUser *)fromUser
withLocation:(CLLocation *)location
success:(DMUpdateBlock)successBlock
error:(DMErrorBlock)errorBlock;
#pragma mark - Recent activity
-(void) recentActivityForUser:(ModelUser *)user
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void) recentActivityForUserId:(NSString *)userId
success:(DMFindOneBlock)successBlock
error:(DMErrorBlock)errorBlock;
-(void) insertWatchinGroupLog:(NSString *) userId
groupId:(NSString *) groupdId;
-(void) deleteWatchinGroupLog:(NSString *) userId;
-(void) doLogout:(CSResultBlock) successBlock;
-(void) report:(ModelMessage *)message success:(CSResultBlock) successBlock;
-(void) setDeleteOnMessageId:(NSString *)_id deleteType:(int)deleteType success:(DMFindOneBlock)successBlock;
-(void) getServerListWithSuccess:(DMArrayBlock)successBlock
andError:(DMErrorBlock)errorBlock;
-(void) test;
@end
| mit |
faister/azure-iot-sdks | doc/iotcertification/iot_certification_linux_nodejs/iot_certification_linux_nodejs.md | 12347 | How to certify IoT devices running Linux with Azure IoT SDK
===
---
# Table of Contents
- [Introduction](#Introduction)
- [Step 1: Configure Azure IoT Hub](#Configure)
- [Step 2: Register Device](#Register)
- [Step 3: Build and validate the sample using Node JS client libraries](#Build)
- [3.1 Load the Azure IoT bits and prerequisites on device](#Load)
- [3.2 Build the samples](#BuildSamples)
- [3.3 Run and Validate the Samples](#Run)
- [Step 4: Package and Share](#PackageShare)
- [4.1 Package build logs and sample test results](#Package)
- [4.2 Share package with Engineering Support](#Share)
- [4.3 Next steps](#Next)
- [Step 5: Troubleshooting](#Troubleshooting)
<a name="Introduction"/>
# Introduction
**About this document**
This document provides step-by-step guidance to IoT hardware publishers on how to certify an IoT enabled hardware with Azure IoT SDK. This multi-step process includes:
- Configuring Azure IoT Hub
- Registering your IoT device
- Build and deploy Azure IoT SDK on device
- Packaging and sharing the logs
**Prepare**
Before executing any of the steps below, read through each process, step by step to ensure end to end understanding. You should have the following items ready before beginning the process:
- Computer with GitHub installed and access to the [azure-iot-sdks](https://github.com/Azure/azure-iot-sdks) GitHub private repository
- SSH client, such as [PuTTY](http://www.putty.org/), so you can access the command line
- Required hardware to certify
***Note:*** *If you haven’t contacted Microsoft about being an Azure Certified for IoT partner, please submit this [form](<https://iotcert.cloudapp.net/>) first to request it and then follow these instructions.*
<a name="Configure"/>
# Step 1: Sign Up To Azure IoT Hub
Follow the instructions [here](https://account.windowsazure.com/signup?offer=ms-azr-0044p) on how to sign up to the Azure IoT Hub service.
As part of the sign up process, you will receive the connection string.
- **IoT Hub Connection String**: An example of IoT Hub Connection String is as below:
HostName=[YourIoTHubName];CredentialType=SharedAccessSignature;CredentialScope=[ContosoIotHub];SharedAccessKeyName=[YourAccessKeyName];SharedAccessKey=[YourAccessKey]
<a name="Register"/>
# Step 2: Register Device
In this section, you will register your device using DeviceExplorer. The DeviceExplorer is a Windows application that interfaces with Azure IoT Hub and can perform the following operations:
- Device management
- Create new devices
- List existing devices and expose device properties stored on Device Hub
- Provides ability to update device keys
- Provides ability to delete a device
- Monitoring events from your device.
- Sending messages to your device.
To run DeviceExplorer tool, follow the configuration strings as described in [Step1](#Configure):
- IoT Hub Connection String
**Steps:**
1. Click [here](<https://github.com/Azure/azure-iot-sdks/blob/develop/tools/DeviceExplorer/doc/how_to_use_device_explorer.md>) to download and install DeviceExplorer.
2. Add connection information under the Configuration tab and click the **Update** button.
3. Create and register the device with your IoT Hub using instructions as below.
a. Click the **Management** tab.
b. Your registered devices will be visible in the list. In case your device is not there in the list, click **Refresh** button. If this is your first time, then you shouldn't retrieve anything.
c. Click **Create** button to create a device ID and key.
d. Once created successfully, device will be listed in DeviceExplorer.
e. Right click the device and from context menu select "**Copy connection string for selected device**".
f. Save this information in Notepad. You will need this information in later steps.
***Not running Windows on your PC?*** - Please send us an email on
<[email protected]> and we will follow up with you with
instructions.
<a name="Build"/>
# Step 3: Build and validate the sample using Node JS client libraries
This section walks you through building, deploying and validating the IoT Client SDK on your device running a Linux operating system. You will install necessary prerequisites on your device. Once done, you will build and deploy the IoT Client SDK and validate the sample tests required for IoT certification with the Azure IoT SDK.
<a name="Load"/>
## 3.1 Load the Azure IoT bits and prerequisites on device
- Open a PuTTY session and connect to the device.
- Choose your commands in next steps based on the OS running on your device.
- Run following command to check if NodeJS is already installed
node --version
If version is **0.12.x or greater**, then skip next step of installing prerequisite packages. Else uninstall it by issuing following command from command line on the device.
**Debian or Ubuntu**
sudo apt-get remove nodejs
**Fedora**
sudo dnf remove nodejs
**Any Other Linux OS**
Use equivalent commands on the target OS
- Install the prerequisite packages by issuing the following commands from the command line on the device. Choose your commands based on the OS running on your device.
**Debian or Ubuntu**
curl -sL https://deb.nodesource.com/setup_4.x | sudo bash -
sudo apt-get install -y nodejs
**Fedora**
wget http://nodejs.org/dist/v4.2.1/node-v4.2.1-linux-x64.tar.gz
tar xvf node-v4.2.1-linux-x64.tar.gz
sudo mv node-v4.2.1-linux-x64 /opt
echo "export PATH=\$PATH:/opt/node-v4.2.1-linux-x64/bin" >> ~/.bashrc
source ~/.bashrc
**Any Other Linux OS**
Use equivalent commands on the target OS
**Note:** To test successful installation of Node JS, try to fetch its version information by running following command:
node --version
- Download the SDK to the board by issuing the following command in
PuTTY:
git clone https://github.com/Azure/azure-iot-sdks.git
- Verify that you now have a copy of the source code under the directory ~/azure-iot-sdks.
<a name="BuildSamples"/>
## 3.2 Build the samples
- To validate the source code run the following commands on the device.
cd ~/azure-iot-sdks/node
build/dev-setup.sh
build/build.sh | tee LogFile.txt
***Note:*** *LogFile.txt in above command should be replaced with a file name where build output will be written.*
- To update samples run the following command on device.
**For simple_sample_http.js:**
cd ~/azure-iot-sdks/node/device/samples
nano simple_sample_http.js
**For send_batch_http.js:**
cd ~/azure-iot-sdks/node/device/samples
nano send_batch_http.js
- This launches a console-based text editor. Scroll down to the
connection information.
- Find the following place holder for IoT connection string:
var connectionString = "[IoT Device Connection String]";
- Replace the above placeholder with device connection string. You can get this from DeviceExplorer as explained in [Step 2](#Register), that you copied into Notepad.
- Save your changes by pressing Ctrl+O and when nano prompts you to save it as the same file, just press ENTER.
- Press Ctrl+X to exit nano.
- Run the following command before leaving the **~/azure-iot-sdks/node/device/samples** directory
npm link azure-iot-device
**For registry_sample.js:**
cd ~/azure-iot-sdks/node/service/samples
nano registry_sample.js
- This launches a console-based text editor. Scroll down to the
connection information.
- Find the following place holder for IoT connection string:
var connectionString = "[IoT Connection String]";
- Replace the above placeholder with "IoT Hub Connection String" which you used in [Step 2](#Register) for device registration.
- Save your changes by pressing Ctrl+O and when nano prompts you to save it as the same file, just press ENTER.
- Press Ctrl+X to exit nano.
- Run the following command before leaving the **~/azure-iot-sdks/node/service/samples** directory
npm link azure-iothub
<a name="Run"/>
## 3.3 Run and Validate the Samples
In this section you will run the Azure IoT client SDK samples to validate communication between your device and Azure IoT Hub service. You will send messages to the Azure IoT Hub service and validate that IoT Hub has successfully receive the data. You will also monitor any messages send from the Azure IoT Hub to client.
**Note:** Take screen shots of all operations, like sample screen shots, performed in below sections. These will be needed in [Step 4](#Share)
### 3.3.1 Send Device Events to IOT Hub:
1. Launch the DeviceExplorer as explained in [Step 2](#Register) and navigate to **Data** tab. Select the device name you created from the drop-down list of device IDs, click **Monitor** button.

2. DeviceExplorer is now monitoring data sent from the selected device to the IoT Hub.
3. Run the sample by issuing following command:
node ~/azure-iot-sdks/node/device/samples/simple_sample_http.js
4. Verify that data has been successfully sent and received. If any, then you may have incorrectly copied the device hub connection information.

5. DeviceExplorer should show that IoT Hub has successfully received data sent by sample test.

6. Run the sample by issuing following command and then repeat step 4 to 5:
node ~/azure-iot-sdks/node/device/samples/send_batch_http.js


7. Run the sample to register a device by issuing following command:
node ~/azure-iot-sdks/node/service/samples/registry_sample.js
8. Verify that you receive information for new device created in the messages.

9. In DeviceExplorer, go to Management tab and click List button. Your new device should show up in the list.

**Note:** The registry_sample.js sample will create and delete a device. In order to see it in the DeviceExplorer tool you will need to refresh your devices before the sample finishes running.
### 3.3.2 Receive messages from IoT Hub
1. To verify that you can send messages from the IoT Hub to your
device, go to the **Message To Device** tab in DeviceExplorer.
2. Select the device you created using Device ID drop down.
3. Add some text to the Message field, then click Send button.

4. You should be able to see the command received in the console window
of the client sample.

<a name="PackageShare"/>
# Step 4: Package and Share
<a name="Package"/>
## 4.1 Package build logs and sample test results
Package following artifacts from your device:
1. Build logs and E2E test results that were logged in the log file during build
run.
2. All the screenshots that are shown above in "**Send Device Events to IoT Hub**" section.
3. All the screenshots that are above in "**Receive messages from IoT Hub**" section.
4. If you made any changes to above steps for your hardware, send us clear instructions of how to run this sample with your hardware (explicitly highlighting the new steps for customers). As a guideline on how the instructions should look please refer the examples published on GitHub repository [here](<https://github.com/Azure/azure-iot-sdks/tree/master/node/doc>)
<a name="Share"/>
## 4.2 Share package with Engineering Support
Share the package in email to <[email protected]>.
<a name="Next"/>
## 4.3 Next steps
Once you shared the documents with us, we will contact you in the following 48 to 72 business hours with next steps.
<a name="Troubleshooting"/>
# Step 5: Troubleshooting
Please contact engineering support on <[email protected]> for help with troubleshooting.
| mit |
Giladx/BlindSelfPortrait | EraserLine/src/main.cpp | 159 | #include "ofApp.h"
#include "ofAppGlutWindow.h"
int main() {
ofAppGlutWindow window;
ofSetupOpenGL(&window, 512, 512, OF_WINDOW);
ofRunApp(new ofApp());
}
| mit |
braydonf/bitcore-node | lib/scaffold/find-config.js | 863 | 'use strict';
var bitcore = require('bitcore-lib');
var $ = bitcore.util.preconditions;
var _ = bitcore.deps._;
var path = require('path');
var fs = require('fs');
var utils = require('../utils');
/**
* Will return the path and bitcore-node configuration
* @param {String} cwd - The absolute path to the current working directory
*/
function findConfig(cwd) {
$.checkArgument(_.isString(cwd), 'Argument should be a string');
$.checkArgument(utils.isAbsolutePath(cwd), 'Argument should be an absolute path');
var directory = String(cwd);
while (!fs.existsSync(path.resolve(directory, 'bitcore-node.json'))) {
directory = path.resolve(directory, '../');
if (directory === '/') {
return false;
}
}
return {
path: directory,
config: require(path.resolve(directory, 'bitcore-node.json'))
};
}
module.exports = findConfig;
| mit |
mr-justin/tabula | lib/tabula_job_executor/jobs/generate_thumbnails.rb | 570 | require_relative '../executor.rb'
require_relative '../../thumbnail_generator.rb'
class GenerateThumbnailJob < Tabula::Background::Job
# args: (:file, :output_dir, :thumbnail_sizes, :page_index_job_uuid)
def perform
file_id = options[:file_id]
upload_id = self.uuid
filepath = options[:filepath]
output_dir = options[:output_dir]
thumbnail_sizes = options[:thumbnail_sizes]
generator = JPedalThumbnailGenerator.new(filepath, output_dir, thumbnail_sizes)
generator.add_observer(self, :at)
generator.generate_thumbnails!
end
end
| mit |
jamesrobertlloyd/gpss-research | experiments/2013-09-07.py | 710 | Experiment(description='No with centred periodic',
data_dir='../data/tsdlr/',
max_depth=8,
random_order=False,
k=1,
debug=False,
local_computation=False,
n_rand=9,
sd=4,
max_jobs=600,
verbose=False,
make_predictions=False,
skip_complete=True,
results_dir='../results/2013-09-07/',
iters=250,
base_kernels='StepTanh,CenPer,Cos,Lin,SE,Const,MT5,IMT3Lin',
zero_mean=True,
random_seed=1,
period_heuristic=5,
subset=True,
subset_size=250,
full_iters=0,
bundle_size=5)
| mit |
scapp281/cliff-effects | public/index.html | 1594 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>Cliff Effects</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
| mit |
flybayer/next.js | packages/react-dev-overlay/src/internal/components/Dialog/styles.ts | 2088 | import { noop as css } from '../../helpers/noop-template'
const styles = css`
[data-nextjs-dialog] {
display: flex;
flex-direction: column;
width: 100%;
margin-right: auto;
margin-left: auto;
outline: none;
background: white;
border-radius: var(--size-gap);
box-shadow: 0 var(--size-gap-half) var(--size-gap-double)
rgba(0, 0, 0, 0.25);
max-height: calc(100% - 56px);
overflow-y: hidden;
}
@media (max-height: 812px) {
[data-nextjs-dialog-overlay] {
max-height: calc(100% - 15px);
}
}
@media (min-width: 576px) {
[data-nextjs-dialog] {
max-width: 540px;
box-shadow: 0 var(--size-gap) var(--size-gap-quad) rgba(0, 0, 0, 0.25);
}
}
@media (min-width: 768px) {
[data-nextjs-dialog] {
max-width: 720px;
}
}
@media (min-width: 992px) {
[data-nextjs-dialog] {
max-width: 960px;
}
}
[data-nextjs-dialog-banner] {
position: relative;
}
[data-nextjs-dialog-banner].banner-warning {
border-color: var(--color-ansi-yellow);
}
[data-nextjs-dialog-banner].banner-error {
border-color: var(--color-ansi-red);
}
[data-nextjs-dialog-banner]::after {
z-index: 2;
content: '';
position: absolute;
top: 0;
right: 0;
width: 100%;
/* banner width: */
border-top-width: var(--size-gap-half);
border-bottom-width: 0;
border-top-style: solid;
border-bottom-style: solid;
border-top-color: inherit;
border-bottom-color: transparent;
}
[data-nextjs-dialog-content] {
overflow-y: auto;
border: none;
margin: 0;
/* calc(padding + banner width offset) */
padding: calc(var(--size-gap-double) + var(--size-gap-half))
var(--size-gap-double);
height: 100%;
display: flex;
flex-direction: column;
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-header] {
flex-shrink: 0;
margin-bottom: var(--size-gap-double);
}
[data-nextjs-dialog-content] > [data-nextjs-dialog-body] {
position: relative;
flex: 1 1 auto;
}
`
export { styles }
| mit |
dnnsoftware/Dnn.Platform | DNN Platform/Modules/ResourceManager/Services/Dto/FolderDetailsRequest.cs | 1005 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace Dnn.Modules.ResourceManager.Services.Dto
{
using System.Runtime.Serialization;
/// <summary>
/// Represents a request for folder details.
/// </summary>
public class FolderDetailsRequest
{
/// <summary>
/// Gets or sets the id of the folder.
/// </summary>
[DataMember(Name = "folderId")]
public int FolderId { get; set; }
/// <summary>
/// Gets or sets the name of the folder.
/// </summary>
[DataMember(Name = "folderName")]
public string FolderName { get; set; }
/// <summary>
/// Gets or sets the <see cref="FolderPermissions"/>.
/// </summary>
[DataMember(Name = "permissions")]
public FolderPermissions Permissions { get; set; }
}
}
| mit |
tecshuttle/tiegan | application/views_dev/user/register.php | 1180 | <div class="container-fluid">
<div class="row">
<div class="col-xs-6 col-xs-offset-3">
<div class="page-header" style="border:none;margin: 0px;">
<h1><?= $this->slogan ?></h1>
</div>
</div>
</div>
<div class="row" style="margin-bottom: 2em;">
<div class="col-xs-6 col-xs-offset-3">
<form action="/user/register_submit" method="post">
<div class="form-group">
<input type="email" class="form-control" name="email" placeholder="请您输入用户名">
</div>
<div class="form-group">
<input type="password" class="form-control" name="password" placeholder="请您输入密码">
</div>
<button type="submit" class="col-xs-12 col-sm-12 btn btn-success">注册</button>
</form>
<br/> <br/> <br/>
<a href="/user/login" class="col-xs-4 col-sm-4 btn btn-link">登入</a>
<span class="col-xs-4 col-sm-4 "></span>
<a href="#" class="col-xs-4 col-sm-4 btn btn-link">忘记密码?</a>
</div>
</div>
</div> | mit |
lucasallan/ruboto | assets/samples/sample_service.rb | 459 | require 'ruboto/util/toast'
# Services are complicated and don't really make sense unless you
# show the interaction between the Service and other parts of your
# app.
# For now, just take a look at the explanation and example in
# online:
# http://developer.android.com/reference/android/app/Service.html
class SampleService
def onStartCommand(intent, flags, startId)
toast 'Hello from the service'
android.app.Service::START_NOT_STICKY
end
end
| mit |
dynamicguy/gpweb | src/vendor/zend/library/Zend/Measure/Torque.php | 3276 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @namespace
*/
namespace Zend\Measure;
/**
* Class for handling torque conversions
*
* @uses Zend\Measure\Abstract
* @category Zend
* @package Zend_Measure
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Torque extends AbstractMeasure
{
const STANDARD = 'NEWTON_METER';
const DYNE_CENTIMETER = 'DYNE_CENTIMETER';
const GRAM_CENTIMETER = 'GRAM_CENTIMETER';
const KILOGRAM_CENTIMETER = 'KILOGRAM_CENTIMETER';
const KILOGRAM_METER = 'KILOGRAM_METER';
const KILONEWTON_METER = 'KILONEWTON_METER';
const KILOPOND_METER = 'KILOPOND_METER';
const MEGANEWTON_METER = 'MEGANEWTON_METER';
const MICRONEWTON_METER = 'MICRONEWTON_METER';
const MILLINEWTON_METER = 'MILLINEWTON_METER';
const NEWTON_CENTIMETER = 'NEWTON_CENTIMETER';
const NEWTON_METER = 'NEWTON_METER';
const OUNCE_FOOT = 'OUNCE_FOOT';
const OUNCE_INCH = 'OUNCE_INCH';
const POUND_FOOT = 'POUND_FOOT';
const POUNDAL_FOOT = 'POUNDAL_FOOT';
const POUND_INCH = 'POUND_INCH';
/**
* Calculations for all torque units
*
* @var array
*/
protected $_units = array(
'DYNE_CENTIMETER' => array('0.0000001', 'dyncm'),
'GRAM_CENTIMETER' => array('0.0000980665', 'gcm'),
'KILOGRAM_CENTIMETER' => array('0.0980665', 'kgcm'),
'KILOGRAM_METER' => array('9.80665', 'kgm'),
'KILONEWTON_METER' => array('1000', 'kNm'),
'KILOPOND_METER' => array('9.80665', 'kpm'),
'MEGANEWTON_METER' => array('1000000', 'MNm'),
'MICRONEWTON_METER' => array('0.000001', 'µNm'),
'MILLINEWTON_METER' => array('0.001', 'mNm'),
'NEWTON_CENTIMETER' => array('0.01', 'Ncm'),
'NEWTON_METER' => array('1', 'Nm'),
'OUNCE_FOOT' => array('0.084738622', 'ozft'),
'OUNCE_INCH' => array(array('' => '0.084738622', '/' => '12'), 'ozin'),
'POUND_FOOT' => array(array('' => '0.084738622', '*' => '16'), 'lbft'),
'POUNDAL_FOOT' => array('0.0421401099752144', 'plft'),
'POUND_INCH' => array(array('' => '0.084738622', '/' => '12', '*' => '16'), 'lbin'),
'STANDARD' => 'NEWTON_METER'
);
}
| mit |
glenngillen/dotfiles | .vscode/extensions/juanblanco.solidity-0.0.120/node_modules/solidity-comments-extractor/index.js | 2960 | const DOUBLE_QUOTE_STRING_STATE = 'double-quote-string-state';
const SINGLE_QUOTE_STRING_STATE = 'single-quote-string-state';
const LINE_COMMENT_STATE = 'line-comment-state';
const BLOCK_COMMENT_STATE = 'block-comment-state';
const ETC_STATE = 'etc-state';
function extractComments(str) {
let state = ETC_STATE;
let i = 0;
const comments = [];
let currentComment = null;
while (i + 1 < str.length) {
if (state === ETC_STATE && str[i] === '/' && str[i + 1] === '/') {
state = LINE_COMMENT_STATE;
currentComment = {
type: 'LineComment',
range: [i]
};
i += 2;
continue;
}
if (state === LINE_COMMENT_STATE && str[i] === '\n') {
state = ETC_STATE;
currentComment.range.push(i);
comments.push(currentComment);
currentComment = null;
i += 1;
continue;
}
if (state === ETC_STATE && str[i] === '/' && str[i + 1] === '*') {
state = BLOCK_COMMENT_STATE;
currentComment = {
type: 'BlockComment',
range: [i]
};
i += 2;
continue;
}
if (state === BLOCK_COMMENT_STATE && str[i] === '*' && str[i + 1] === '/') {
state = ETC_STATE;
currentComment.range.push(i + 2);
comments.push(currentComment);
currentComment = null;
i += 2;
continue;
}
if (state === ETC_STATE && str[i] === '"') {
state = DOUBLE_QUOTE_STRING_STATE;
i += 1;
continue;
}
if (
state === DOUBLE_QUOTE_STRING_STATE &&
str[i] === '"' &&
(str[i - 1] !== '\\' || str[i - 2] === '\\') // ignore previous backslash unless it's escaped
) {
state = ETC_STATE;
i += 1;
continue;
}
if (state === ETC_STATE && str[i] === "'") {
state = SINGLE_QUOTE_STRING_STATE;
i += 1;
continue;
}
if (
state === SINGLE_QUOTE_STRING_STATE &&
str[i] === "'" &&
(str[i - 1] !== '\\' || str[i - 2] === '\\') // ignore previous backslash unless it's escaped
) {
state = ETC_STATE;
i += 1;
continue;
}
i += 1;
}
if (currentComment !== null && currentComment.type === 'LineComment') {
if (str[i] === '\n') {
currentComment.range.push(str.length - 1);
} else {
currentComment.range.push(str.length);
}
comments.push(currentComment);
}
return comments.map((comment) => {
const start = comment.range[0] + 2;
const end =
comment.type === 'LineComment' ? comment.range[1] : comment.range[1] - 2;
const raw = str.slice(start, end);
// removing the leading asterisks from the value is necessary for jsdoc-style comments
let value = raw;
if (comment.type === 'BlockComment') {
value = value
.split('\n')
.map((x) => x.replace(/^\s*\*/, ''))
.join('\n')
.trimRight();
}
return {
...comment,
raw,
value
};
});
}
module.exports = extractComments;
| mit |
annkupi/picard | src/main/java/picard/analysis/GcBiasUtils.java | 5467 | /*
* The MIT License
*
* Copyright (c) 2015 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package picard.analysis;
import htsjdk.samtools.reference.ReferenceSequence;
import htsjdk.samtools.reference.ReferenceSequenceFile;
import htsjdk.samtools.reference.ReferenceSequenceFileFactory;
import htsjdk.samtools.util.SequenceUtil;
import htsjdk.samtools.util.StringUtil;
import java.io.File;
/** Utilities to calculate GC Bias
* Created by kbergin on 9/23/15.
*/
public class GcBiasUtils {
/////////////////////////////////////////////////////////////////////////////
// Calculates GC as a number from 0 to 100 in the specified window.
// If the window includes more than five no-calls then -1 is returned.
/////////////////////////////////////////////////////////////////////////////
public static int calculateGc(final byte[] bases, final int startIndex, final int endIndex, final CalculateGcState state) {
if (state.init) {
state.init = false;
state.gcCount = 0;
state.nCount = 0;
for (int i = startIndex; i < endIndex; ++i) {
final byte base = bases[i];
if (SequenceUtil.basesEqual(base, (byte)'G') || SequenceUtil.basesEqual(base, (byte)'C')) ++state.gcCount;
else if (SequenceUtil.basesEqual(base, (byte)'N')) ++state.nCount;
}
} else {
final byte newBase = bases[endIndex - 1];
if (SequenceUtil.basesEqual(newBase, (byte)'G') || SequenceUtil.basesEqual(newBase, (byte)'C')) ++state.gcCount;
else if (newBase == 'N') ++state.nCount;
if (SequenceUtil.basesEqual(state.priorBase, (byte)'G') || SequenceUtil.basesEqual(state.priorBase, (byte)'C')) --state.gcCount;
else if (SequenceUtil.basesEqual(state.priorBase, (byte)'N')) --state.nCount;
}
state.priorBase = bases[startIndex];
if (state.nCount > 4) return -1;
else return (state.gcCount * 100) / (endIndex - startIndex);
}
/////////////////////////////////////////////////////////////////////////////
// Calculate number of 100bp windows in the refBases passed in that fall into
// each gc content bin (0-100% gc)
/////////////////////////////////////////////////////////////////////////////
public static int[] calculateRefWindowsByGc(final int windows, final File referenceSequence, final int windowSize) {
final ReferenceSequenceFile refFile = ReferenceSequenceFileFactory.getReferenceSequenceFile(referenceSequence);
ReferenceSequence ref;
final int [] windowsByGc = new int [windows];
while ((ref = refFile.nextSequence()) != null) {
final byte[] refBases = ref.getBases();
StringUtil.toUpperCase(refBases);
final int refLength = refBases.length;
final int lastWindowStart = refLength - windowSize;
final CalculateGcState state = new GcBiasUtils().new CalculateGcState();
for (int i = 1; i < lastWindowStart; ++i) {
final int windowEnd = i + windowSize;
final int gcBin = calculateGc(refBases, i, windowEnd, state);
if (gcBin != -1) windowsByGc[gcBin]++;
}
}
return windowsByGc;
}
/////////////////////////////////////////////////////////////////////////////
// Calculate all the GC values for all windows
/////////////////////////////////////////////////////////////////////////////
public static byte [] calculateAllGcs(final byte[] refBases, final int lastWindowStart, final int windowSize) {
final CalculateGcState state = new GcBiasUtils().new CalculateGcState();
final int refLength = refBases.length;
final byte[] gc = new byte[refLength + 1];
for (int i = 1; i < lastWindowStart; ++i) {
final int windowEnd = i + windowSize;
final int windowGc = calculateGc(refBases, i, windowEnd, state);
gc[i] = (byte) windowGc;
}
return gc;
}
/////////////////////////////////////////////////////////////////////////////
// Keeps track of current GC calculation state
/////////////////////////////////////////////////////////////////////////////
class CalculateGcState {
boolean init = true;
int nCount;
int gcCount;
byte priorBase;
}
}
| mit |
njam/CM | client-vendor/source/logger/handlers/recorder.js | 3930 | var util = require('util');
/**
* @class Recorder
* @param {{retention: <Number>}} [options]
*/
var Recorder = function(options) {
this._records = [];
this._options = _.defaults(options || {}, {
retention: 300, // seconds
recordMaxSize: 200, // nb records
jsonMaxSize: 50,
format: '[{date} {level}] {message}'
});
};
Recorder.prototype = {
/**
* @returns {String}
*/
getFormattedRecords: function() {
return _.map(this.getRecords(), function(record) {
return this._recordFormatter(record);
}, this).join('\n');
},
/**
* @returns {{date: {Date}, messages: *[], context: {Object}}[]}
*/
getRecords: function() {
return this._records;
},
/**
* @param {*[]} messages
* @param {Object} context
*/
addRecord: function(messages, context) {
var record = {
date: this._getDate(),
messages: messages,
context: context
};
this._records.push(record);
this._cleanupRecords();
},
flushRecords: function() {
this._records = [];
},
/**
* @private
*/
_cleanupRecords: function() {
var retention = this._options.retention;
var recordMaxSize = this._options.recordMaxSize;
if (retention > 0) {
var retentionTime = this._getDate() - (retention * 1000);
this._records = _.filter(this._records, function(record) {
return record.date > retentionTime;
});
}
if (recordMaxSize > 0 && this._records.length > recordMaxSize) {
this._records = this._records.slice(-recordMaxSize);
}
},
/**
* @param {{date: {Date}, messages: *[], context: {Object}}} record
* @returns {String}
* @private
*/
_recordFormatter: function(record) {
var log = this._options.format;
_.each({
date: record.date.toISOString(),
level: record.context.level.name,
message: this._messageFormatter(record.messages)
}, function(value, key) {
var pattern = new RegExp('{' + key + '}', 'g');
log = log.replace(pattern, value);
});
return log;
},
/**
* @param {*[]} messages
* @returns {String}
* @private
*/
_messageFormatter: function(messages) {
var clone = _.toArray(messages);
var index, value, encoded;
for (index = 0; index < clone.length; index++) {
encoded = value = clone[index];
if (_.isString(value) && 0 === index) {
// about console.log and util.format substitution,
// see https://developers.google.com/web/tools/chrome-devtools/debug/console/console-write#string-substitution-and-formatting
// and https://nodejs.org/api/util.html#util_util_format_format
value = value.replace(/%[idfoO]/g, '%s');
} else if (value instanceof RegExp) {
value = value.toString();
} else if (value instanceof Date) {
value = value.toISOString();
} else if (_.isObject(value) && value._class) {
value = '[' + value._class + (value._id && value._id.id ? ':' + value._id.id : '') + ']';
} else if (_.isObject(value) && /^\[object ((?!Object).)+\]$/.test(value.toString())) {
value = value.toString();
}
try {
if (_.isString(value) || _.isNumber(value)) {
encoded = value;
} else {
encoded = JSON.stringify(value);
if (encoded.length > this._options.jsonMaxSize) {
encoded = encoded.slice(0, this._options.jsonMaxSize - 4) + '…' + encoded[encoded.length - 1];
}
}
} catch (e) {
if (_.isUndefined(value)) {
encoded = 'undefined';
} else if (_.isNull(value)) {
encoded = 'null';
} else {
encoded = '[unknown]'
}
}
clone[index] = encoded;
}
return util.format.apply(util.format, clone);
},
/**
* @returns {Date}
* @private
*/
_getDate: function() {
return new Date();
}
};
module.exports = Recorder;
| mit |
CAWAS/ElectronicObserverExtended | ElectronicObserver/Data/ShipGroup/ExpressionManager.cs | 2741 | using ElectronicObserver.Utility.Storage;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicObserver.Data.ShipGroup
{
[DataContract(Name = "ExpressionManager")]
public sealed class ExpressionManager : DataStorage, ICloneable
{
[DataMember]
public List<ExpressionList> Expressions { get; set; }
[IgnoreDataMember]
private Expression<Func<ShipData, bool>> predicate;
[IgnoreDataMember]
private Expression expression;
public ExpressionManager() : base()
{
Initialize();
}
public override void Initialize()
{
Expressions = new List<ExpressionList>();
predicate = null;
expression = null;
}
public ExpressionList this[int index]
{
get { return Expressions[index]; }
set { Expressions[index] = value; }
}
public void Compile()
{
Expression ex = null;
var paramex = Expression.Parameter(typeof(ShipData), "ship");
foreach (var exlist in Expressions)
{
if (!exlist.Enabled)
continue;
if (ex == null)
{
ex = exlist.Compile(paramex);
}
else
{
if (exlist.ExternalAnd)
{
ex = Expression.AndAlso(ex, exlist.Compile(paramex));
}
else
{
ex = Expression.OrElse(ex, exlist.Compile(paramex));
}
}
}
if (ex == null)
{
ex = Expression.Constant(true, typeof(bool)); //:-P
}
predicate = Expression.Lambda<Func<ShipData, bool>>(ex, paramex);
expression = ex;
}
public IEnumerable<ShipData> GetResult(IEnumerable<ShipData> list)
{
if (predicate == null)
throw new InvalidOperationException("式がコンパイルされていません。");
return list.AsQueryable().Where(predicate).AsEnumerable();
}
public bool IsAvailable => predicate != null;
public override string ToString()
{
if (Expressions == null)
return "(なし)";
StringBuilder sb = new StringBuilder();
foreach (var ex in Expressions)
{
if (!ex.Enabled)
continue;
else if (sb.Length == 0)
sb.Append(ex.ToString());
else
sb.AppendFormat(" {0} {1}", ex.ExternalAnd ? "かつ" : "または", ex.ToString());
}
if (sb.Length == 0)
sb.Append("(なし)");
return sb.ToString();
}
public string ToExpressionString()
{
return expression.ToString();
}
public ExpressionManager Clone()
{
var clone = (ExpressionManager)MemberwiseClone();
clone.Expressions = Expressions?.Select(e => e.Clone()).ToList();
clone.predicate = null;
clone.expression = null;
return clone;
}
object ICloneable.Clone()
{
return Clone();
}
}
}
| mit |
bussiere/pypyjs | website/demo/home/rfk/repos/pypy/lib-python/2.7/test/test_pprint.py | 25311 | import pprint
import test.test_support
import unittest
import test.test_set
try:
uni = unicode
except NameError:
def uni(x):
return x
# list, tuple and dict subclasses that do or don't overwrite __repr__
class list2(list):
pass
class list3(list):
def __repr__(self):
return list.__repr__(self)
class tuple2(tuple):
pass
class tuple3(tuple):
def __repr__(self):
return tuple.__repr__(self)
class dict2(dict):
pass
class dict3(dict):
def __repr__(self):
return dict.__repr__(self)
class QueryTestCase(unittest.TestCase):
def setUp(self):
self.a = range(100)
self.b = range(200)
self.a[-12] = self.b
def test_basic(self):
# Verify .isrecursive() and .isreadable() w/o recursion
pp = pprint.PrettyPrinter()
for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, uni("yaddayadda"),
self.a, self.b):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_knotted(self):
# Verify .isrecursive() and .isreadable() w/ recursion
# Tie a knot.
self.b[67] = self.a
# Messy dict.
self.d = {}
self.d[0] = self.d[1] = self.d[2] = self.d
pp = pprint.PrettyPrinter()
for icky in self.a, self.b, self.d, (self.d, self.d):
self.assertTrue(pprint.isrecursive(icky), "expected isrecursive")
self.assertFalse(pprint.isreadable(icky), "expected not isreadable")
self.assertTrue(pp.isrecursive(icky), "expected isrecursive")
self.assertFalse(pp.isreadable(icky), "expected not isreadable")
# Break the cycles.
self.d.clear()
del self.a[:]
del self.b[:]
for safe in self.a, self.b, self.d, (self.d, self.d):
# module-level convenience functions
self.assertFalse(pprint.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pprint.isreadable(safe),
"expected isreadable for %r" % (safe,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(safe),
"expected not isrecursive for %r" % (safe,))
self.assertTrue(pp.isreadable(safe),
"expected isreadable for %r" % (safe,))
def test_unreadable(self):
# Not recursive but not readable anyway
pp = pprint.PrettyPrinter()
for unreadable in type(3), pprint, pprint.isrecursive:
# module-level convenience functions
self.assertFalse(pprint.isrecursive(unreadable),
"expected not isrecursive for %r" % (unreadable,))
self.assertFalse(pprint.isreadable(unreadable),
"expected not isreadable for %r" % (unreadable,))
# PrettyPrinter methods
self.assertFalse(pp.isrecursive(unreadable),
"expected not isrecursive for %r" % (unreadable,))
self.assertFalse(pp.isreadable(unreadable),
"expected not isreadable for %r" % (unreadable,))
def test_same_as_repr(self):
# Simple objects, small containers and classes that overwrite __repr__
# For those the result should be the same as repr().
# Ahem. The docs don't say anything about that -- this appears to
# be testing an implementation quirk. Starting in Python 2.5, it's
# not true for dicts: pprint always sorts dicts by key now; before,
# it sorted a dict display if and only if the display required
# multiple lines. For that reason, dicts with more than one element
# aren't tested here.
for simple in (0, 0L, 0+0j, 0.0, "", uni(""),
(), tuple2(), tuple3(),
[], list2(), list3(),
{}, dict2(), dict3(),
self.assertTrue, pprint,
-6, -6L, -6-6j, -1.5, "x", uni("x"), (3,), [3], {3: 6},
(1,2), [3,4], {5: 6},
tuple2((1,2)), tuple3((1,2)), tuple3(range(100)),
[3,4], list2([3,4]), list3([3,4]), list3(range(100)),
dict2({5: 6}), dict3({5: 6}),
range(10, -11, -1)
):
native = repr(simple)
for function in "pformat", "saferepr":
f = getattr(pprint, function)
got = f(simple)
self.assertEqual(native, got,
"expected %s got %s from pprint.%s" %
(native, got, function))
def test_basic_line_wrap(self):
# verify basic line-wrapping operation
o = {'RPM_cal': 0,
'RPM_cal2': 48059,
'Speed_cal': 0,
'controldesk_runtime_us': 0,
'main_code_runtime_us': 0,
'read_io_runtime_us': 0,
'write_io_runtime_us': 43690}
exp = """\
{'RPM_cal': 0,
'RPM_cal2': 48059,
'Speed_cal': 0,
'controldesk_runtime_us': 0,
'main_code_runtime_us': 0,
'read_io_runtime_us': 0,
'write_io_runtime_us': 43690}"""
for type in [dict, dict2]:
self.assertEqual(pprint.pformat(type(o)), exp)
o = range(100)
exp = '[%s]' % ',\n '.join(map(str, o))
for type in [list, list2]:
self.assertEqual(pprint.pformat(type(o)), exp)
o = tuple(range(100))
exp = '(%s)' % ',\n '.join(map(str, o))
for type in [tuple, tuple2]:
self.assertEqual(pprint.pformat(type(o)), exp)
# indent parameter
o = range(100)
exp = '[ %s]' % ',\n '.join(map(str, o))
for type in [list, list2]:
self.assertEqual(pprint.pformat(type(o), indent=4), exp)
def test_nested_indentations(self):
o1 = list(range(10))
o2 = dict(first=1, second=2, third=3)
o = [o1, o2]
expected = """\
[ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
{ 'first': 1,
'second': 2,
'third': 3}]"""
self.assertEqual(pprint.pformat(o, indent=4, width=42), expected)
def test_sorted_dict(self):
# Starting in Python 2.5, pprint sorts dict displays by key regardless
# of how small the dictionary may be.
# Before the change, on 32-bit Windows pformat() gave order
# 'a', 'c', 'b' here, so this test failed.
d = {'a': 1, 'b': 1, 'c': 1}
self.assertEqual(pprint.pformat(d), "{'a': 1, 'b': 1, 'c': 1}")
self.assertEqual(pprint.pformat([d, d]),
"[{'a': 1, 'b': 1, 'c': 1}, {'a': 1, 'b': 1, 'c': 1}]")
# The next one is kind of goofy. The sorted order depends on the
# alphabetic order of type names: "int" < "str" < "tuple". Before
# Python 2.5, this was in the test_same_as_repr() test. It's worth
# keeping around for now because it's one of few tests of pprint
# against a crazy mix of types.
self.assertEqual(pprint.pformat({"xy\tab\n": (3,), 5: [[]], (): {}}),
r"{5: [[]], 'xy\tab\n': (3,), (): {}}")
def test_subclassing(self):
o = {'names with spaces': 'should be presented using repr()',
'others.should.not.be': 'like.this'}
exp = """\
{'names with spaces': 'should be presented using repr()',
others.should.not.be: like.this}"""
self.assertEqual(DottedPrettyPrinter().pformat(o), exp)
def test_set_reprs(self):
self.assertEqual(pprint.pformat(set()), 'set()')
self.assertEqual(pprint.pformat(set(range(3))), 'set([0, 1, 2])')
self.assertEqual(pprint.pformat(frozenset()), 'frozenset()')
self.assertEqual(pprint.pformat(frozenset(range(3))), 'frozenset([0, 1, 2])')
cube_repr_tgt = """\
{frozenset([]): frozenset([frozenset([2]), frozenset([0]), frozenset([1])]),
frozenset([0]): frozenset([frozenset(),
frozenset([0, 2]),
frozenset([0, 1])]),
frozenset([1]): frozenset([frozenset(),
frozenset([1, 2]),
frozenset([0, 1])]),
frozenset([2]): frozenset([frozenset(),
frozenset([1, 2]),
frozenset([0, 2])]),
frozenset([1, 2]): frozenset([frozenset([2]),
frozenset([1]),
frozenset([0, 1, 2])]),
frozenset([0, 2]): frozenset([frozenset([2]),
frozenset([0]),
frozenset([0, 1, 2])]),
frozenset([0, 1]): frozenset([frozenset([0]),
frozenset([1]),
frozenset([0, 1, 2])]),
frozenset([0, 1, 2]): frozenset([frozenset([1, 2]),
frozenset([0, 2]),
frozenset([0, 1])])}"""
cube = test.test_set.cube(3)
# XXX issues of dictionary order, and for the case below,
# order of items in the frozenset([...]) representation.
# Whether we get precisely cube_repr_tgt or not is open
# to implementation-dependent choices (this test probably
# fails horribly in CPython if we tweak the dict order too).
got = pprint.pformat(cube)
if test.test_support.check_impl_detail(cpython=True):
self.assertEqual(got, cube_repr_tgt)
else:
self.assertEqual(eval(got), cube)
cubo_repr_tgt = """\
{frozenset([frozenset([0, 2]), frozenset([0])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([0, 1]), frozenset([1])]): frozenset([frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([1])])]),
frozenset([frozenset([1, 2]), frozenset([1])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([1, 2]), frozenset([2])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset([2]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([]), frozenset([0])]): frozenset([frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([]), frozenset([1])]): frozenset([frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([1]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([2])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([2]), frozenset([])]): frozenset([frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset(),
frozenset([1])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([0, 1, 2]), frozenset([0, 1])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
1])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([0]), frozenset([0, 1])]): frozenset([frozenset([frozenset(),
frozenset([0])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset([1]),
frozenset([0,
1])])]),
frozenset([frozenset([2]), frozenset([0, 2])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset(),
frozenset([2])])]),
frozenset([frozenset([0, 1, 2]), frozenset([0, 2])]): frozenset([frozenset([frozenset([1,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0]),
frozenset([0,
2])]),
frozenset([frozenset([2]),
frozenset([0,
2])])]),
frozenset([frozenset([1, 2]), frozenset([0, 1, 2])]): frozenset([frozenset([frozenset([0,
2]),
frozenset([0,
1,
2])]),
frozenset([frozenset([0,
1]),
frozenset([0,
1,
2])]),
frozenset([frozenset([2]),
frozenset([1,
2])]),
frozenset([frozenset([1]),
frozenset([1,
2])])])}"""
cubo = test.test_set.linegraph(cube)
got = pprint.pformat(cubo)
if test.test_support.check_impl_detail(cpython=True):
self.assertEqual(got, cubo_repr_tgt)
else:
self.assertEqual(eval(got), cubo)
def test_depth(self):
nested_tuple = (1, (2, (3, (4, (5, 6)))))
nested_dict = {1: {2: {3: {4: {5: {6: 6}}}}}}
nested_list = [1, [2, [3, [4, [5, [6, []]]]]]]
self.assertEqual(pprint.pformat(nested_tuple), repr(nested_tuple))
self.assertEqual(pprint.pformat(nested_dict), repr(nested_dict))
self.assertEqual(pprint.pformat(nested_list), repr(nested_list))
lv1_tuple = '(1, (...))'
lv1_dict = '{1: {...}}'
lv1_list = '[1, [...]]'
self.assertEqual(pprint.pformat(nested_tuple, depth=1), lv1_tuple)
self.assertEqual(pprint.pformat(nested_dict, depth=1), lv1_dict)
self.assertEqual(pprint.pformat(nested_list, depth=1), lv1_list)
class DottedPrettyPrinter(pprint.PrettyPrinter):
def format(self, object, context, maxlevels, level):
if isinstance(object, str):
if ' ' in object:
return repr(object), 1, 0
else:
return object, 0, 0
else:
return pprint.PrettyPrinter.format(
self, object, context, maxlevels, level)
def test_main():
test.test_support.run_unittest(QueryTestCase)
if __name__ == "__main__":
test_main()
| mit |
GRAVITYLab/edda | vis/src/vtk/eddaRandomProbeFilter.h | 7336 | /*=========================================================================
Program: Visualization Toolkit
Module: vtkProbeFilter.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkProbeFilter - sample data values at specified point locations
// .SECTION Description
// vtkProbeFilter is a filter that computes point attributes (e.g., scalars,
// vectors, etc.) at specified point positions. The filter has two inputs:
// the Input and Source. The Input geometric structure is passed through the
// filter. The point attributes are computed at the Input point positions
// by interpolating into the source data. For example, we can compute data
// values on a plane (plane specified as Input) from a volume (Source).
// The cell data of the source data is copied to the output based on in
// which source cell each input point is. If an array of the same name exists
// both in source's point and cell data, only the one from the point data is
// probed.
//
// This filter can be used to resample data, or convert one dataset form into
// another. For example, an unstructured grid (vtkUnstructuredGrid) can be
// probed with a volume (three-dimensional vtkImageData), and then volume
// rendering techniques can be used to visualize the results. Another example:
// a line or curve can be used to probe data to produce x-y plots along
// that line or curve.
#ifndef eddaRandomProbeFilter_h
#define eddaRandomProbeFilter_h
#include "vtkFiltersCoreModule.h" // For export macro
#include "vtkDataSetAlgorithm.h"
#include "vtkDataSetAttributes.h" // needed for vtkDataSetAttributes::FieldList
class vtkIdTypeArray;
class vtkCharArray;
class vtkMaskPoints;
class eddaRandomProbeFilter : public vtkDataSetAlgorithm
{
public:
static eddaRandomProbeFilter *New();
vtkTypeMacro(eddaRandomProbeFilter,vtkDataSetAlgorithm)
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Specify the point locations used to probe input. Any geometry
// can be used.
void SetSourceData(vtkDataObject *source);
vtkDataObject *GetSource();
// Description:
// Specify the point locations used to probe input. Any geometry
// can be used. New style. Equivalent to SetInputConnection(1, algOutput).
void SetSourceConnection(vtkAlgorithmOutput* algOutput);
// Description:
// This flag is used only when a piece is requested to update. By default
// the flag is off. Because no spatial correspondence between input pieces
// and source pieces is known, all of the source has to be requested no
// matter what piece of the output is requested. When there is a spatial
// correspondence, the user/application can set this flag. This hint allows
// the breakup of the probe operation to be much more efficient. When piece
// m of n is requested for update by the user, then only n of m needs to
// be requested of the source.
vtkSetMacro(SpatialMatch, int)
vtkGetMacro(SpatialMatch, int)
vtkBooleanMacro(SpatialMatch, int)
// Description:
// Get the list of point ids in the output that contain attribute data
// interpolated from the source.
vtkGetObjectMacro(ValidPoints, vtkIdTypeArray)
// Description:
// Returns the name of the char array added to the output with values 1 for
// valid points and 0 for invalid points.
// Set to "vtkValidPointMask" by default.
vtkSetStringMacro(ValidPointMaskArrayName)
vtkGetStringMacro(ValidPointMaskArrayName)
// Description:
// Shallow copy the input cell data arrays to the output.
// Off by default.
vtkSetMacro(PassCellArrays, int)
vtkBooleanMacro(PassCellArrays, int)
vtkGetMacro(PassCellArrays, int)
// Description:
// Shallow copy the input point data arrays to the output
// Off by default.
vtkSetMacro(PassPointArrays, int)
vtkBooleanMacro(PassPointArrays, int)
vtkGetMacro(PassPointArrays, int)
// Description:
// Set whether to pass the field-data arrays from the Input i.e. the input
// providing the geometry to the output. On by default.
vtkSetMacro(PassFieldArrays, int)
vtkBooleanMacro(PassFieldArrays, int)
vtkGetMacro(PassFieldArrays, int)
// Description:
// Set the tolerance used to compute whether a point in the
// source is in a cell of the input. This value is only used
// if ComputeTolerance is off.
vtkSetMacro(Tolerance, double)
vtkGetMacro(Tolerance, double)
// Description:
// Set whether to use the Tolerance field or precompute the tolerance.
// When on, the tolerance will be computed and the field
// value is ignored. Off by default.
vtkSetMacro(ComputeTolerance, bool)
vtkBooleanMacro(ComputeTolerance, bool)
vtkGetMacro(ComputeTolerance, bool)
//BTX
protected:
eddaRandomProbeFilter();
~eddaRandomProbeFilter();
int PassCellArrays;
int PassPointArrays;
int PassFieldArrays;
int SpatialMatch;
double Tolerance;
bool ComputeTolerance;
virtual int RequestData(vtkInformation *, vtkInformationVector **,
vtkInformationVector *);
virtual int RequestInformation(vtkInformation *, vtkInformationVector **,
vtkInformationVector *);
virtual int RequestUpdateExtent(vtkInformation *, vtkInformationVector **,
vtkInformationVector *);
// Description:
// Call at end of RequestData() to pass attribute data respecting the
// PassCellArrays, PassPointArrays, PassFieldArrays flags.
void PassAttributeData(
vtkDataSet* input, vtkDataObject* source, vtkDataSet* output);
// Description:
// Equivalent to calling InitializeForProbing(); ProbeEmptyPoints().
void Probe(vtkDataSet *input, vtkDataSet *source, vtkDataSet *output);
// Description:
// Build the field lists. This is required before calling
// InitializeForProbing().
void BuildFieldList(vtkDataSet* source);
// Description:
// Initializes output and various arrays which keep track for probing status.
virtual void InitializeForProbing(vtkDataSet *input, vtkDataSet *output);
// Description:
// Probe only those points that are marked as not-probed by the MaskPoints
// array.
// srcIdx is the index in the PointList for the given source.
void ProbeEmptyPoints(vtkDataSet *input, int srcIdx, vtkDataSet *source,
vtkDataSet *output);
char* ValidPointMaskArrayName;
vtkIdTypeArray *ValidPoints;
vtkCharArray* MaskPoints;
int NumberOfValidPoints;
// Agreed, this is sort of a hack to allow subclasses to override the default
// behavior of this filter to call NullPoint() for every point that is
// not-a-hit when probing. This makes it possible for subclasses to initialize
// the arrays with different defaults.
bool UseNullPoint;
vtkDataSetAttributes::FieldList* CellList;
vtkDataSetAttributes::FieldList* PointList;
private:
eddaRandomProbeFilter(const eddaRandomProbeFilter&); // Not implemented.
void operator=(const eddaRandomProbeFilter&); // Not implemented.
class vtkVectorOfArrays;
vtkVectorOfArrays* CellArrays;
//ETX
};
#endif
| mit |
kxbmap/MyFleetGirls | client/src/main/scala/com/ponkotuy/restype/CreateShip.scala | 705 | package com.ponkotuy.restype
import com.ponkotuy.data
import com.ponkotuy.parser.Query
import scala.collection.mutable
import scala.util.matching.Regex
/**
* @author ponkotuy
* Date: 15/04/12.
*/
case object CreateShip extends ResType {
import ResType._
// KDock + CreateShipのデータが欲しいのでKDockIDをKeyにCreateShipを溜めておく
private[restype] val createShips: mutable.Map[Int, data.CreateShip] = mutable.Map()
override def regexp: Regex = s"\\A$ReqKousyou/createship\\z".r
override def postables(q: Query): Seq[Result] = {
val createShip = data.CreateShip.fromMap(q.req, DeckPort.firstFleet.head)
createShips(createShip.kDock) = createShip
Nil
}
}
| mit |
the-ress/vscode | src/vs/platform/workspace/test/common/workspace.test.ts | 10178 | /*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as assert from 'assert';
import * as path from 'vs/base/common/path';
import { Workspace, toWorkspaceFolders, WorkspaceFolder } from 'vs/platform/workspace/common/workspace';
import { URI } from 'vs/base/common/uri';
import { IRawFileWorkspaceFolder } from 'vs/platform/workspaces/common/workspaces';
import { isWindows } from 'vs/base/common/platform';
suite('Workspace', () => {
const fileFolder = isWindows ? 'c:\\src' : '/src';
const abcFolder = isWindows ? 'c:\\abc' : '/abc';
const testFolderUri = URI.file(path.join(fileFolder, 'test'));
const mainFolderUri = URI.file(path.join(fileFolder, 'main'));
const test1FolderUri = URI.file(path.join(fileFolder, 'test1'));
const test2FolderUri = URI.file(path.join(fileFolder, 'test2'));
const test3FolderUri = URI.file(path.join(fileFolder, 'test3'));
const abcTest1FolderUri = URI.file(path.join(abcFolder, 'test1'));
const abcTest3FolderUri = URI.file(path.join(abcFolder, 'test3'));
const workspaceConfigUri = URI.file(path.join(fileFolder, 'test.code-workspace'));
test('getFolder returns the folder with given uri', () => {
const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 });
let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), expected, new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 2 })]);
const actual = testObject.getFolder(expected.uri);
assert.equal(actual, expected);
});
test('getFolder returns the folder if the uri is sub', () => {
const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 0 });
let testObject = new Workspace('', [expected, new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 1 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 2 })]);
const actual = testObject.getFolder(URI.file(path.join(fileFolder, 'test/a')));
assert.equal(actual, expected);
});
test('getFolder returns the closest folder if the uri is sub', () => {
const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 });
let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 }), expected]);
const actual = testObject.getFolder(URI.file(path.join(fileFolder, 'test/a')));
assert.equal(actual, expected);
});
test('getFolder returns the folder even if the uri has query path', () => {
const expected = new WorkspaceFolder({ uri: testFolderUri, name: '', index: 2 });
let testObject = new Workspace('', [new WorkspaceFolder({ uri: mainFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 }), expected]);
const actual = testObject.getFolder(URI.file(path.join(fileFolder, 'test/a')).with({ query: 'somequery' }));
assert.equal(actual, expected);
});
test('getFolder returns null if the uri is not sub', () => {
let testObject = new Workspace('', [new WorkspaceFolder({ uri: testFolderUri, name: '', index: 0 }), new WorkspaceFolder({ uri: URI.file('/src/code'), name: '', index: 1 })]);
const actual = testObject.getFolder(URI.file(path.join(fileFolder, 'main/a')));
assert.equal(actual, undefined);
});
test('toWorkspaceFolders with single absolute folder', () => {
const actual = toWorkspaceFolders([{ path: '/src/test' }], workspaceConfigUri);
assert.equal(actual.length, 1);
assert.equal(actual[0].uri.fsPath, testFolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test');
});
test('toWorkspaceFolders with single relative folder', () => {
const actual = toWorkspaceFolders([{ path: './test' }], workspaceConfigUri);
assert.equal(actual.length, 1);
assert.equal(actual[0].uri.fsPath, testFolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, './test');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test');
});
test('toWorkspaceFolders with single absolute folder with name', () => {
const actual = toWorkspaceFolders([{ path: '/src/test', name: 'hello' }], workspaceConfigUri);
assert.equal(actual.length, 1);
assert.equal(actual[0].uri.fsPath, testFolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'hello');
});
test('toWorkspaceFolders with multiple unique absolute folders', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3' }, { path: '/src/test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'test3');
assert.equal(actual[2].uri.fsPath, test1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, '/src/test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
test('toWorkspaceFolders with multiple unique absolute folders with names', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3', name: 'noName' }, { path: '/src/test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'noName');
assert.equal(actual[2].uri.fsPath, test1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, '/src/test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
test('toWorkspaceFolders with multiple unique absolute and relative folders', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/abc/test3', name: 'noName' }, { path: './test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, abcTest3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/abc/test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'noName');
assert.equal(actual[2].uri.fsPath, test1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, './test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
test('toWorkspaceFolders with multiple absolute folders with duplicates', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test2', name: 'noName' }, { path: '/src/test1' }], workspaceConfigUri);
assert.equal(actual.length, 2);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test1');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'test1');
});
test('toWorkspaceFolders with multiple absolute and relative folders with duplicates', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '/src/test3', name: 'noName' }, { path: './test3' }, { path: '/abc/test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, '/src/test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'noName');
assert.equal(actual[2].uri.fsPath, abcTest1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, '/abc/test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
test('toWorkspaceFolders with multiple absolute and relative folders with invalid paths', () => {
const actual = toWorkspaceFolders([{ path: '/src/test2' }, { path: '', name: 'noName' }, { path: './test3' }, { path: '/abc/test1' }], workspaceConfigUri);
assert.equal(actual.length, 3);
assert.equal(actual[0].uri.fsPath, test2FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[0].raw).path, '/src/test2');
assert.equal(actual[0].index, 0);
assert.equal(actual[0].name, 'test2');
assert.equal(actual[1].uri.fsPath, test3FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[1].raw).path, './test3');
assert.equal(actual[1].index, 1);
assert.equal(actual[1].name, 'test3');
assert.equal(actual[2].uri.fsPath, abcTest1FolderUri.fsPath);
assert.equal((<IRawFileWorkspaceFolder>actual[2].raw).path, '/abc/test1');
assert.equal(actual[2].index, 2);
assert.equal(actual[2].name, 'test1');
});
});
| mit |
femtoio/femto-usb-blink-example | blinky/common/services/spi/usart_spi_master_example/sam3n4c_sam3n_ek/conf_board.h | 2135 | /**
* \file
*
* \brief Board configuration.
*
* Copyright (c) 2011 - 2014 Atmel Corporation. All rights reserved.
*
* \asf_license_start
*
* \page License
*
* 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. The name of Atmel may not be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* 4. This software may only be redistributed and used in connection with an
* Atmel microcontroller product.
*
* THIS SOFTWARE IS PROVIDED BY ATMEL "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
* EXPRESSLY AND SPECIFICALLY DISCLAIMED. IN NO EVENT SHALL ATMEL 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.
*
* \asf_license_stop
*
*/
/**
* Support and FAQ: visit <a href="http://www.atmel.com/design-support/">Atmel Support</a>
*/
#ifndef CONF_BOARD_H_INCLUDED
#define CONF_BOARD_H_INCLUDED
/* USART1 module is used in SPI mode. */
#define CONF_BOARD_USART_RXD
#define CONF_BOARD_USART_TXD
#define CONF_BOARD_USART_SCK
#define CONF_BOARD_USART_RTS
#define CONF_BOARD_USART_CTS
#endif /* CONF_BOARD_H_INCLUDED */
| mit |
baerjam/rails | activerecord/lib/active_record/core.rb | 20695 | # frozen_string_literal: true
require "active_support/core_ext/hash/indifferent_access"
require "active_support/core_ext/string/filters"
require "concurrent/map"
require "set"
module ActiveRecord
module Core
extend ActiveSupport::Concern
FILTERED = "[FILTERED]" # :nodoc:
included do
##
# :singleton-method:
#
# Accepts a logger conforming to the interface of Log4r which is then
# passed on to any new database connections made and which can be
# retrieved on both a class and instance level by calling +logger+.
mattr_accessor :logger, instance_writer: false
##
# :singleton-method:
#
# Specifies if the methods calling database queries should be logged below
# their relevant queries. Defaults to false.
mattr_accessor :verbose_query_logs, instance_writer: false, default: false
##
# Contains the database configuration - as is typically stored in config/database.yml -
# as an ActiveRecord::DatabaseConfigurations object.
#
# For example, the following database.yml...
#
# development:
# adapter: sqlite3
# database: db/development.sqlite3
#
# production:
# adapter: sqlite3
# database: db/production.sqlite3
#
# ...would result in ActiveRecord::Base.configurations to look like this:
#
# #<ActiveRecord::DatabaseConfigurations:0x00007fd1acbdf800 @configurations=[
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbded10 @env_name="development",
# @spec_name="primary", @config={"adapter"=>"sqlite3", "database"=>"db/development.sqlite3"}>,
# #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fd1acbdea90 @env_name="production",
# @spec_name="primary", @config={"adapter"=>"mysql2", "database"=>"db/production.sqlite3"}>
# ]>
def self.configurations=(config)
@@configurations = ActiveRecord::DatabaseConfigurations.new(config)
end
self.configurations = {}
# Returns fully resolved ActiveRecord::DatabaseConfigurations object
def self.configurations
@@configurations
end
##
# :singleton-method:
# Determines whether to use Time.utc (using :utc) or Time.local (using :local) when pulling
# dates and times from the database. This is set to :utc by default.
mattr_accessor :default_timezone, instance_writer: false, default: :utc
##
# :singleton-method:
# Specifies the format to use when dumping the database schema with Rails'
# Rakefile. If :sql, the schema is dumped as (potentially database-
# specific) SQL statements. If :ruby, the schema is dumped as an
# ActiveRecord::Schema file which can be loaded into any database that
# supports migrations. Use :ruby if you want to have different database
# adapters for, e.g., your development and test environments.
mattr_accessor :schema_format, instance_writer: false, default: :ruby
##
# :singleton-method:
# Specifies if an error should be raised if the query has an order being
# ignored when doing batch queries. Useful in applications where the
# scope being ignored is error-worthy, rather than a warning.
mattr_accessor :error_on_ignored_order, instance_writer: false, default: false
# :singleton-method:
# Specify the behavior for unsafe raw query methods. Values are as follows
# deprecated - Warnings are logged when unsafe raw SQL is passed to
# query methods.
# disabled - Unsafe raw SQL passed to query methods results in
# UnknownAttributeReference exception.
mattr_accessor :allow_unsafe_raw_sql, instance_writer: false, default: :deprecated
##
# :singleton-method:
# Specify whether or not to use timestamps for migration versions
mattr_accessor :timestamped_migrations, instance_writer: false, default: true
##
# :singleton-method:
# Specify whether schema dump should happen at the end of the
# db:migrate rails command. This is true by default, which is useful for the
# development environment. This should ideally be false in the production
# environment where dumping schema is rarely needed.
mattr_accessor :dump_schema_after_migration, instance_writer: false, default: true
##
# :singleton-method:
# Specifies which database schemas to dump when calling db:structure:dump.
# If the value is :schema_search_path (the default), any schemas listed in
# schema_search_path are dumped. Use :all to dump all schemas regardless
# of schema_search_path, or a string of comma separated schemas for a
# custom list.
mattr_accessor :dump_schemas, instance_writer: false, default: :schema_search_path
##
# :singleton-method:
# Specify a threshold for the size of query result sets. If the number of
# records in the set exceeds the threshold, a warning is logged. This can
# be used to identify queries which load thousands of records and
# potentially cause memory bloat.
mattr_accessor :warn_on_records_fetched_greater_than, instance_writer: false
mattr_accessor :maintain_test_schema, instance_accessor: false
mattr_accessor :belongs_to_required_by_default, instance_accessor: false
class_attribute :default_connection_handler, instance_writer: false
self.filter_attributes = []
def self.connection_handler
ActiveRecord::RuntimeRegistry.connection_handler || default_connection_handler
end
def self.connection_handler=(handler)
ActiveRecord::RuntimeRegistry.connection_handler = handler
end
self.default_connection_handler = ConnectionAdapters::ConnectionHandler.new
end
module ClassMethods
def initialize_find_by_cache # :nodoc:
@find_by_statement_cache = { true => Concurrent::Map.new, false => Concurrent::Map.new }
end
def inherited(child_class) # :nodoc:
# initialize cache at class definition for thread safety
child_class.initialize_find_by_cache
super
end
def find(*ids) # :nodoc:
# We don't have cache keys for this stuff yet
return super unless ids.length == 1
return super if block_given? ||
primary_key.nil? ||
scope_attributes? ||
columns_hash.include?(inheritance_column)
id = ids.first
return super if StatementCache.unsupported_value?(id)
key = primary_key
statement = cached_find_by_statement(key) { |params|
where(key => params.bind).limit(1)
}
record = statement.execute([id], connection).first
unless record
raise RecordNotFound.new("Couldn't find #{name} with '#{primary_key}'=#{id}",
name, primary_key, id)
end
record
rescue ::RangeError
raise RecordNotFound.new("Couldn't find #{name} with an out of range value for '#{primary_key}'",
name, primary_key)
end
def find_by(*args) # :nodoc:
return super if scope_attributes? || reflect_on_all_aggregations.any?
hash = args.first
return super if !(Hash === hash) || hash.values.any? { |v|
StatementCache.unsupported_value?(v)
}
# We can't cache Post.find_by(author: david) ...yet
return super unless hash.keys.all? { |k| columns_hash.has_key?(k.to_s) }
keys = hash.keys
statement = cached_find_by_statement(keys) { |params|
wheres = keys.each_with_object({}) { |param, o|
o[param] = params.bind
}
where(wheres).limit(1)
}
begin
statement.execute(hash.values, connection).first
rescue TypeError
raise ActiveRecord::StatementInvalid
rescue ::RangeError
nil
end
end
def find_by!(*args) # :nodoc:
find_by(*args) || raise(RecordNotFound.new("Couldn't find #{name}", name))
end
def initialize_generated_modules # :nodoc:
generated_association_methods
end
def generated_association_methods # :nodoc:
@generated_association_methods ||= begin
mod = const_set(:GeneratedAssociationMethods, Module.new)
private_constant :GeneratedAssociationMethods
include mod
mod
end
end
# Returns columns which shouldn't be exposed while calling +#inspect+.
def filter_attributes
if defined?(@filter_attributes)
@filter_attributes
else
superclass.filter_attributes
end
end
# Specifies columns which shouldn't be exposed while calling +#inspect+.
def filter_attributes=(attributes_names)
@filter_attributes = attributes_names.map(&:to_s).to_set
end
# Returns a string like 'Post(id:integer, title:string, body:text)'
def inspect # :nodoc:
if self == Base
super
elsif abstract_class?
"#{super}(abstract)"
elsif !connected?
"#{super} (call '#{super}.connection' to establish a connection)"
elsif table_exists?
attr_list = attribute_types.map { |name, type| "#{name}: #{type.type}" } * ", "
"#{super}(#{attr_list})"
else
"#{super}(Table doesn't exist)"
end
end
# Overwrite the default class equality method to provide support for decorated models.
def ===(object) # :nodoc:
object.is_a?(self)
end
# Returns an instance of <tt>Arel::Table</tt> loaded with the current table name.
#
# class Post < ActiveRecord::Base
# scope :published_and_commented, -> { published.and(arel_table[:comments_count].gt(0)) }
# end
def arel_table # :nodoc:
@arel_table ||= Arel::Table.new(table_name, type_caster: type_caster)
end
def arel_attribute(name, table = arel_table) # :nodoc:
name = attribute_alias(name) if attribute_alias?(name)
table[name]
end
def predicate_builder # :nodoc:
@predicate_builder ||= PredicateBuilder.new(table_metadata)
end
def type_caster # :nodoc:
TypeCaster::Map.new(self)
end
private
def cached_find_by_statement(key, &block)
cache = @find_by_statement_cache[connection.prepared_statements]
cache.compute_if_absent(key) { StatementCache.create(connection, &block) }
end
def relation
relation = Relation.create(self)
if finder_needs_type_condition? && !ignore_default_scope?
relation.where!(type_condition)
relation.create_with!(inheritance_column.to_s => sti_name)
else
relation
end
end
def table_metadata
TableMetadata.new(self, arel_table)
end
end
# New objects can be instantiated as either empty (pass no construction parameter) or pre-set with
# attributes but not yet saved (pass a hash with key names matching the associated table column names).
# In both instances, valid attribute keys are determined by the column names of the associated table --
# hence you can't have attributes that aren't part of the table columns.
#
# ==== Example:
# # Instantiates a single new object
# User.new(first_name: 'Jamie')
def initialize(attributes = nil)
self.class.define_attribute_methods
@attributes = self.class._default_attributes.deep_dup
init_internals
initialize_internals_callback
assign_attributes(attributes) if attributes
yield self if block_given?
_run_initialize_callbacks
end
# Initialize an empty model object from +coder+. +coder+ should be
# the result of previously encoding an Active Record model, using
# #encode_with.
#
# class Post < ActiveRecord::Base
# end
#
# old_post = Post.new(title: "hello world")
# coder = {}
# old_post.encode_with(coder)
#
# post = Post.allocate
# post.init_with(coder)
# post.title # => 'hello world'
def init_with(coder)
coder = LegacyYamlAdapter.convert(self.class, coder)
@attributes = self.class.yaml_encoder.decode(coder)
init_internals
@new_record = coder["new_record"]
self.class.define_attribute_methods
yield self if block_given?
_run_find_callbacks
_run_initialize_callbacks
self
end
##
# Initializer used for instantiating objects that have been read from the
# database. +attributes+ should be an attributes object, and unlike the
# `initialize` method, no assignment calls are made per attribute.
#
# :nodoc:
def init_from_db(attributes)
init_internals
@new_record = false
@attributes = attributes
self.class.define_attribute_methods
yield self if block_given?
_run_find_callbacks
_run_initialize_callbacks
self
end
##
# :method: clone
# Identical to Ruby's clone method. This is a "shallow" copy. Be warned that your attributes are not copied.
# That means that modifying attributes of the clone will modify the original, since they will both point to the
# same attributes hash. If you need a copy of your attributes hash, please use the #dup method.
#
# user = User.first
# new_user = user.clone
# user.name # => "Bob"
# new_user.name = "Joe"
# user.name # => "Joe"
#
# user.object_id == new_user.object_id # => false
# user.name.object_id == new_user.name.object_id # => true
#
# user.name.object_id == user.dup.name.object_id # => false
##
# :method: dup
# Duped objects have no id assigned and are treated as new records. Note
# that this is a "shallow" copy as it copies the object's attributes
# only, not its associations. The extent of a "deep" copy is application
# specific and is therefore left to the application to implement according
# to its need.
# The dup method does not preserve the timestamps (created|updated)_(at|on).
##
def initialize_dup(other) # :nodoc:
@attributes = @attributes.deep_dup
@attributes.reset(self.class.primary_key)
_run_initialize_callbacks
@new_record = true
@destroyed = false
@_start_transaction_state = {}
@transaction_state = nil
super
end
# Populate +coder+ with attributes about this record that should be
# serialized. The structure of +coder+ defined in this method is
# guaranteed to match the structure of +coder+ passed to the #init_with
# method.
#
# Example:
#
# class Post < ActiveRecord::Base
# end
# coder = {}
# Post.new.encode_with(coder)
# coder # => {"attributes" => {"id" => nil, ... }}
def encode_with(coder)
self.class.yaml_encoder.encode(@attributes, coder)
coder["new_record"] = new_record?
coder["active_record_yaml_version"] = 2
end
# Returns true if +comparison_object+ is the same exact object, or +comparison_object+
# is of the same type and +self+ has an ID and it is equal to +comparison_object.id+.
#
# Note that new records are different from any other record by definition, unless the
# other record is the receiver itself. Besides, if you fetch existing records with
# +select+ and leave the ID out, you're on your own, this predicate will return false.
#
# Note also that destroying a record preserves its ID in the model instance, so deleted
# models are still comparable.
def ==(comparison_object)
super ||
comparison_object.instance_of?(self.class) &&
!id.nil? &&
comparison_object.id == id
end
alias :eql? :==
# Delegates to id in order to allow two records of the same type and id to work with something like:
# [ Person.find(1), Person.find(2), Person.find(3) ] & [ Person.find(1), Person.find(4) ] # => [ Person.find(1) ]
def hash
if id
self.class.hash ^ id.hash
else
super
end
end
# Clone and freeze the attributes hash such that associations are still
# accessible, even on destroyed records, but cloned models will not be
# frozen.
def freeze
@attributes = @attributes.clone.freeze
self
end
# Returns +true+ if the attributes hash has been frozen.
def frozen?
@attributes.frozen?
end
# Allows sort on objects
def <=>(other_object)
if other_object.is_a?(self.class)
to_key <=> other_object.to_key
else
super
end
end
# Returns +true+ if the record is read only. Records loaded through joins with piggy-back
# attributes will be marked as read only since they cannot be saved.
def readonly?
@readonly
end
# Marks this record as read only.
def readonly!
@readonly = true
end
def connection_handler
self.class.connection_handler
end
# Returns the contents of the record as a nicely formatted string.
def inspect
# We check defined?(@attributes) not to issue warnings if the object is
# allocated but not initialized.
inspection = if defined?(@attributes) && @attributes
self.class.attribute_names.collect do |name|
if has_attribute?(name)
if filter_attribute?(name)
"#{name}: #{ActiveRecord::Core::FILTERED}"
else
"#{name}: #{attribute_for_inspect(name)}"
end
end
end.compact.join(", ")
else
"not initialized"
end
"#<#{self.class} #{inspection}>"
end
# Takes a PP and prettily prints this record to it, allowing you to get a nice result from <tt>pp record</tt>
# when pp is required.
def pretty_print(pp)
return super if custom_inspect_method_defined?
pp.object_address_group(self) do
if defined?(@attributes) && @attributes
column_names = self.class.column_names.select { |name| has_attribute?(name) || new_record? }
pp.seplist(column_names, proc { pp.text "," }) do |column_name|
pp.breakable " "
pp.group(1) do
pp.text column_name
pp.text ":"
pp.breakable
if filter_attribute?(column_name)
pp.text ActiveRecord::Core::FILTERED
else
pp.pp read_attribute(column_name)
end
end
end
else
pp.breakable " "
pp.text "not initialized"
end
end
end
# Returns a hash of the given methods with their names as keys and returned values as values.
def slice(*methods)
Hash[methods.flatten.map! { |method| [method, public_send(method)] }].with_indifferent_access
end
private
# +Array#flatten+ will call +#to_ary+ (recursively) on each of the elements of
# the array, and then rescues from the possible +NoMethodError+. If those elements are
# +ActiveRecord::Base+'s, then this triggers the various +method_missing+'s that we have,
# which significantly impacts upon performance.
#
# So we can avoid the +method_missing+ hit by explicitly defining +#to_ary+ as +nil+ here.
#
# See also https://tenderlovemaking.com/2011/06/28/til-its-ok-to-return-nil-from-to_ary.html
def to_ary
nil
end
def init_internals
@readonly = false
@destroyed = false
@marked_for_destruction = false
@destroyed_by_association = nil
@new_record = true
@_start_transaction_state = {}
@transaction_state = nil
end
def initialize_internals_callback
end
def thaw
if frozen?
@attributes = @attributes.dup
end
end
def custom_inspect_method_defined?
self.class.instance_method(:inspect).owner != ActiveRecord::Base.instance_method(:inspect).owner
end
def filter_attribute?(attribute_name)
self.class.filter_attributes.include?(attribute_name) && !read_attribute(attribute_name).nil?
end
end
end
| mit |
azat-co/react-quickly | spare-parts/ch05-es5/logger/js/script.js | 130 | ReactDOM.render(React.createElement(
'div',
null,
React.createElement(Content, null)
), document.getElementById('content')); | mit |
ascarter/Go.bbpackage | src/Text Filters/goimports.sh | 73 | #! /bin/sh
PATH="$(dirname "$0")/../Resources":$PATH
gorunner goimports
| mit |
davehorton/drachtio-server | deps/boost_1_77_0/libs/mp11/test/version.cpp | 405 |
// Copyright 2019 Peter Dimov
//
// Distributed under the Boost Software License, Version 1.0.
//
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
#include <boost/mp11/version.hpp>
#include <boost/version.hpp>
#include <boost/core/lightweight_test.hpp>
int main()
{
BOOST_TEST_EQ( BOOST_MP11_VERSION, BOOST_VERSION );
return boost::report_errors();
}
| mit |
jspaleta/SuperDARN_MSI_ROS | linux/home/radar/ros.3.6/doc/html/base/src.lib/task/convert/ConvertToShort.html | 2791 |
<head>
<title>ConvertToShort</title>
<link rel=stylesheet href=../../../../css/doc.css type=text/css>
</head>
<body>
<div id="root">
<div id="banner">
</div>
<div id="location">
<table width=100% class="location"><tr>
<td><a href="../../../../index.html">Home</a><td>|</td>
<td><a href=../../../../base/index.html>base</a></td>
<td>|</td><td><a href=../../../../base/src.lib/index.html>src.lib</a></td><td>|</td><td><a href=../../../../base/src.lib/task/index.html>task</a></td><td>|</td><td><a href=../../../../base/src.lib/task/convert/index.html>convert</a></td><td>|</td>
<td>ConvertToShort</td>
<td width=100% align=right><a href=../../../../base/src.lib/indexdoc.html>Index</a></td>
</tr>
</table>
</div>
<div id="main">
<h2 class="doctitle">ConvertToShort</h2>
<table>
<tr><td class="docsubtitle" valign=top>Syntax</td></tr>
<tr><td></td><td class="docbox" style="font-family: courier;">void ConvertToShort(unsigned char *cnv,int16 *val);</td></tr>
<tr><td class="docsubtitle" valign=top>Header</td></tr>
<tr><td></td>
<td class="docbox" style="font-family: courier;">base/rconvert.h</td></tr>
<tr><td class=docsubtitle>Library</td></tr>
<tr><td></td><td style="font-family: courier;"><a href="index.html">rcnv</a></td></tr>
<tr><td class="docsubtitle">Description</td></tr>
<tr><td></td><td class="docbody"><p>The <a href="ConvertToShort.html"><code>ConvertToShort</code></a> function converts a sequence of little-endian ordered bytes to a variable of type <code>int16</code> (16-bit integer).</p>
<p>The sequence of bytes to convert is pointed to by the argument <em>cnv</em> and the 16-bit integer number is stored at the location pointed to by <em>val</em>.</p>
</td></tr>
<tr><td class="docsubtitle">Returns</td></tr>
<tr><td></td><td>None</td></tr>
<tr><td class="docsubtitle">Errors</td></tr>
<tr><td></td><td>None</td></tr>
<tr><td class="docsubtitle">Example</td></tr>
<tr><td></td><td><br><center>Source Code: <a href="src/ConvertToShort.c">ConvertToShort.c</a></center><br><table width="540" cellpadding="4"><tr><td class="docbox"><pre width="60">/* ConvertToShort.c
================
Author: R.J.Barnes
*/
#include <stdio.h>
#include <stdlib.h>
#include "rtypes.h"
#include "rconvert.h"
int main(int argc,char *argv[]) {
int i;
int16 val;
unsigned char buf[2]={0xe0,0x3f};
ConvertToShort(buf,&val);
fprintf(stdout,"buf=");
for (i=0;i<2;i++) fprintf(stdout,"%.2x",buf[i]);
fprintf(stdout,"'n");
fprintf(stdout,"val=%d'n",val);
return 0;
}
</pre></td></tr></table><br></td></tr>
</table>
<br><br>
</div>
<div id="tail">
<center><p>
© Johns Hopkins Applied Physics Laboratory 2010
</p></center>
</div>
</div>
</body>
| mit |
kimalec/TodayWeather | client/import_today_ext/ta.run.sh | 617 | #!/bin/sh
cp package.json import_today_ext/package.json.backup
cp import_today_ext/ta.empty.package.json package.json
ionic state reset
cordova plugin add https://github.com/DavidStrausz/cordova-plugin-today-widget.git
cp config.xml import_today_ext/config.xml.backup
cp import_today_ext/ta.import.config.xml config.xml
cordova platform rm ios;cordova platform add ios
#cordova plugin rm cordova-plugin-today-widget
#cp -a ../ta.ios/TodayAir/*.lproj platforms/ios/TodayAir/
#mv import_today_ext/package.json.backup package.json
#mv import_today_ext/config.xml.backup config.xml
#open platforms/ios/TodayAir.xcodeproj
| mit |
RJFreund/OpenDSA | Exercises/Sorting/MergesortTFstable.html | 1010 | <!DOCTYPE html>
<html data-require="math">
<head>
<title>Mergesort Question: Stable</title>
<script src="//cdnjs.cloudflare.com/ajax/libs/require.js/2.1.14/require.min.js"></script>
<script src="../../khan-exercises/local-only/main.js" ></script>
</head>
<body>
<div class="exercise">
<div class="problems">
<div id="MergesortTFstablep">
<p class="problem">Answer TRUE or FALSE.
<p class="question">Mergesort (as the code is written in this
module) is a stable sorting algorithm. Recall that a stable sorting
algorithm maintains the relative order of records with equal keys.</p>
<div class="solution">True</div>
<ul class="choices" data-category="true">
<li>True</li>
<li>False</li>
</ul>
<div class="hints">
<p>What happens when two equal values are compared during merge?</p>
</div>
</div>
</div>
</div>
</body>
</html>
| mit |
mvnural/scalation | src/main/scala/scalation/event/EventNode.scala | 1916 |
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** @author John Miller
* @version 1.2
* @date Sun Jan 19 20:30:33 EST 2014
* @see LICENSE (MIT style license file).
*/
package scalation.event
import scalation.animation.CommandType._
import scalation.scala2d.Colors._
import scalation.scala2d.Ellipse
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `EventNode` class provides facilities for representing simulation events
* graphically. It extends the `Event` class with animation capabilities.
* Note: unique identification is mixed in via the `Identifiable` trait in
* the `Event` superclass.
* @param director the controller/scheduler that this event node is a part of
* @param at the location of this event node
*/
class EventNode (director: Model, at: Array [Double] = Array ())
extends Event (EventNode.makePrototype (director), director, -1.0, null)
{
director.animate (this, CreateNode, blue, Ellipse (), at)
def occur () { throw new NoSuchMethodException ("this occur should not be called") }
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** Tell the animation engine to display this node's outgoing `CausalLink`'s
* as edges.
*/
def displayLinks (links: Array [CausalLink])
{
if (links != null) {
for (arc <- links) arc.display (this, arc.causedEvent)
} // if
} // displayLinks
} // EventNode class
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
/** The `EventNode` companion object provides a method for making a prototype
* entity. A prototype event or entity is thought to exist before the
* simulation starts.
*/
object EventNode
{
def makePrototype (director: Model): Entity = Entity (-1.0, -1.0, director)
} // EventNode object
| mit |
mmkassem/gitlabhq | spec/fixtures/lib/kramdown/atlassian_document_format/mention.md | 97 | Mentioning @adf-mention:testuser
Mentioning @adf-mention:\"test user\" with space in user name
| mit |
rstoenescu/quasar-framework | ui/src/components.js | 3696 | export * from './components/ajax-bar/index.js'
export * from './components/avatar/index.js'
export * from './components/badge/index.js'
export * from './components/banner/index.js'
export * from './components/bar/index.js'
export * from './components/breadcrumbs/index.js'
export * from './components/btn/index.js'
export * from './components/btn-dropdown/index.js'
export * from './components/btn-group/index.js'
export * from './components/btn-toggle/index.js'
export * from './components/card/index.js'
export * from './components/carousel/index.js'
export * from './components/chat/index.js'
export * from './components/checkbox/index.js'
export * from './components/chip/index.js'
export * from './components/circular-progress/index.js'
export * from './components/color/index.js'
export * from './components/date/index.js'
export * from './components/dialog/index.js'
export * from './components/drawer/index.js'
export * from './components/editor/index.js'
export * from './components/expansion-item/index.js'
export * from './components/fab/index.js'
export * from './components/field/index.js'
export * from './components/file/index.js'
export * from './components/footer/index.js'
export * from './components/form/index.js'
export * from './components/header/index.js'
export * from './components/icon/index.js'
export * from './components/img/index.js'
export * from './components/infinite-scroll/index.js'
export * from './components/inner-loading/index.js'
export * from './components/input/index.js'
export * from './components/intersection/index.js'
export * from './components/item/index.js'
export * from './components/knob/index.js'
export * from './components/layout/index.js'
export * from './components/markup-table/index.js'
export * from './components/menu/index.js'
export * from './components/no-ssr/index.js'
export * from './components/option-group/index.js'
export * from './components/page/index.js'
export * from './components/page-scroller/index.js'
export * from './components/page-sticky/index.js'
export * from './components/pagination/index.js'
export * from './components/parallax/index.js'
export * from './components/popup-edit/index.js'
export * from './components/popup-proxy/index.js'
export * from './components/linear-progress/index.js'
export * from './components/pull-to-refresh/index.js'
export * from './components/radio/index.js'
export * from './components/range/index.js'
export * from './components/rating/index.js'
export * from './components/resize-observer/index.js'
export * from './components/responsive/index.js'
export * from './components/scroll-area/index.js'
export * from './components/scroll-observer/index.js'
export * from './components/select/index.js'
export * from './components/separator/index.js'
export * from './components/skeleton/index.js'
export * from './components/slide-item/index.js'
export * from './components/slide-transition/index.js'
export * from './components/slider/index.js'
export * from './components/space/index.js'
export * from './components/spinner/index.js'
export * from './components/splitter/index.js'
export * from './components/stepper/index.js'
export * from './components/tab-panels/index.js'
export * from './components/table/index.js'
export * from './components/tabs/index.js'
export * from './components/time/index.js'
export * from './components/timeline/index.js'
export * from './components/toggle/index.js'
export * from './components/toolbar/index.js'
export * from './components/tooltip/index.js'
export * from './components/tree/index.js'
export * from './components/uploader/index.js'
export * from './components/video/index.js'
export * from './components/virtual-scroll/index.js'
| mit |
wolfram74/numerical_methods_iserles_notes | venv/lib/python2.7/site-packages/IPython/testing/iptest.py | 18302 | # -*- coding: utf-8 -*-
"""IPython Test Suite Runner.
This module provides a main entry point to a user script to test IPython
itself from the command line. There are two ways of running this script:
1. With the syntax `iptest all`. This runs our entire test suite by
calling this script (with different arguments) recursively. This
causes modules and package to be tested in different processes, using nose
or trial where appropriate.
2. With the regular nose syntax, like `iptest -vvs IPython`. In this form
the script simply calls nose, but with special command line flags and
plugins loaded.
"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from __future__ import print_function
import glob
from io import BytesIO
import os
import os.path as path
import sys
from threading import Thread, Lock, Event
import warnings
import nose.plugins.builtin
from nose.plugins.xunit import Xunit
from nose import SkipTest
from nose.core import TestProgram
from nose.plugins import Plugin
from nose.util import safe_str
from IPython.utils.process import is_cmd_found
from IPython.utils.py3compat import bytes_to_str
from IPython.utils.importstring import import_item
from IPython.testing.plugin.ipdoctest import IPythonDoctest
from IPython.external.decorators import KnownFailure, knownfailureif
pjoin = path.join
#-----------------------------------------------------------------------------
# Globals
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Warnings control
#-----------------------------------------------------------------------------
# Twisted generates annoying warnings with Python 2.6, as will do other code
# that imports 'sets' as of today
warnings.filterwarnings('ignore', 'the sets module is deprecated',
DeprecationWarning )
# This one also comes from Twisted
warnings.filterwarnings('ignore', 'the sha module is deprecated',
DeprecationWarning)
# Wx on Fedora11 spits these out
warnings.filterwarnings('ignore', 'wxPython/wxWidgets release number mismatch',
UserWarning)
# ------------------------------------------------------------------------------
# Monkeypatch Xunit to count known failures as skipped.
# ------------------------------------------------------------------------------
def monkeypatch_xunit():
try:
knownfailureif(True)(lambda: None)()
except Exception as e:
KnownFailureTest = type(e)
def addError(self, test, err, capt=None):
if issubclass(err[0], KnownFailureTest):
err = (SkipTest,) + err[1:]
return self.orig_addError(test, err, capt)
Xunit.orig_addError = Xunit.addError
Xunit.addError = addError
#-----------------------------------------------------------------------------
# Check which dependencies are installed and greater than minimum version.
#-----------------------------------------------------------------------------
def extract_version(mod):
return mod.__version__
def test_for(item, min_version=None, callback=extract_version):
"""Test to see if item is importable, and optionally check against a minimum
version.
If min_version is given, the default behavior is to check against the
`__version__` attribute of the item, but specifying `callback` allows you to
extract the value you are interested in. e.g::
In [1]: import sys
In [2]: from IPython.testing.iptest import test_for
In [3]: test_for('sys', (2,6), callback=lambda sys: sys.version_info)
Out[3]: True
"""
try:
check = import_item(item)
except (ImportError, RuntimeError):
# GTK reports Runtime error if it can't be initialized even if it's
# importable.
return False
else:
if min_version:
if callback:
# extra processing step to get version to compare
check = callback(check)
return check >= min_version
else:
return True
# Global dict where we can store information on what we have and what we don't
# have available at test run time
have = {}
have['curses'] = test_for('_curses')
have['matplotlib'] = test_for('matplotlib')
have['numpy'] = test_for('numpy')
have['pexpect'] = test_for('IPython.external.pexpect')
have['pymongo'] = test_for('pymongo')
have['pygments'] = test_for('pygments')
have['qt'] = test_for('IPython.external.qt')
have['sqlite3'] = test_for('sqlite3')
have['tornado'] = test_for('tornado.version_info', (4,0), callback=None)
have['jinja2'] = test_for('jinja2')
have['mistune'] = test_for('mistune')
have['requests'] = test_for('requests')
have['sphinx'] = test_for('sphinx')
have['jsonschema'] = test_for('jsonschema')
have['terminado'] = test_for('terminado')
have['casperjs'] = is_cmd_found('casperjs')
have['phantomjs'] = is_cmd_found('phantomjs')
have['slimerjs'] = is_cmd_found('slimerjs')
min_zmq = (13,)
have['zmq'] = test_for('zmq.pyzmq_version_info', min_zmq, callback=lambda x: x())
#-----------------------------------------------------------------------------
# Test suite definitions
#-----------------------------------------------------------------------------
test_group_names = ['parallel', 'kernel', 'kernel.inprocess', 'config', 'core',
'extensions', 'lib', 'terminal', 'testing', 'utils',
'nbformat', 'qt', 'html', 'nbconvert'
]
class TestSection(object):
def __init__(self, name, includes):
self.name = name
self.includes = includes
self.excludes = []
self.dependencies = []
self.enabled = True
def exclude(self, module):
if not module.startswith('IPython'):
module = self.includes[0] + "." + module
self.excludes.append(module.replace('.', os.sep))
def requires(self, *packages):
self.dependencies.extend(packages)
@property
def will_run(self):
return self.enabled and all(have[p] for p in self.dependencies)
# Name -> (include, exclude, dependencies_met)
test_sections = {n:TestSection(n, ['IPython.%s' % n]) for n in test_group_names}
# Exclusions and dependencies
# ---------------------------
# core:
sec = test_sections['core']
if not have['sqlite3']:
sec.exclude('tests.test_history')
sec.exclude('history')
if not have['matplotlib']:
sec.exclude('pylabtools'),
sec.exclude('tests.test_pylabtools')
# lib:
sec = test_sections['lib']
if not have['zmq']:
sec.exclude('kernel')
# We do this unconditionally, so that the test suite doesn't import
# gtk, changing the default encoding and masking some unicode bugs.
sec.exclude('inputhookgtk')
# We also do this unconditionally, because wx can interfere with Unix signals.
# There are currently no tests for it anyway.
sec.exclude('inputhookwx')
# Testing inputhook will need a lot of thought, to figure out
# how to have tests that don't lock up with the gui event
# loops in the picture
sec.exclude('inputhook')
# testing:
sec = test_sections['testing']
# These have to be skipped on win32 because they use echo, rm, cd, etc.
# See ticket https://github.com/ipython/ipython/issues/87
if sys.platform == 'win32':
sec.exclude('plugin.test_exampleip')
sec.exclude('plugin.dtexample')
# terminal:
if (not have['pexpect']) or (not have['zmq']):
test_sections['terminal'].exclude('console')
# parallel
sec = test_sections['parallel']
sec.requires('zmq')
if not have['pymongo']:
sec.exclude('controller.mongodb')
sec.exclude('tests.test_mongodb')
# kernel:
sec = test_sections['kernel']
sec.requires('zmq')
# The in-process kernel tests are done in a separate section
sec.exclude('inprocess')
# importing gtk sets the default encoding, which we want to avoid
sec.exclude('zmq.gui.gtkembed')
sec.exclude('zmq.gui.gtk3embed')
if not have['matplotlib']:
sec.exclude('zmq.pylab')
# kernel.inprocess:
test_sections['kernel.inprocess'].requires('zmq')
# extensions:
sec = test_sections['extensions']
# This is deprecated in favour of rpy2
sec.exclude('rmagic')
# autoreload does some strange stuff, so move it to its own test section
sec.exclude('autoreload')
sec.exclude('tests.test_autoreload')
test_sections['autoreload'] = TestSection('autoreload',
['IPython.extensions.autoreload', 'IPython.extensions.tests.test_autoreload'])
test_group_names.append('autoreload')
# qt:
test_sections['qt'].requires('zmq', 'qt', 'pygments')
# html:
sec = test_sections['html']
sec.requires('zmq', 'tornado', 'requests', 'sqlite3', 'jsonschema')
# The notebook 'static' directory contains JS, css and other
# files for web serving. Occasionally projects may put a .py
# file in there (MathJax ships a conf.py), so we might as
# well play it safe and skip the whole thing.
sec.exclude('static')
sec.exclude('tasks')
if not have['jinja2']:
sec.exclude('notebookapp')
if not have['pygments'] or not have['jinja2']:
sec.exclude('nbconvert')
if not have['terminado']:
sec.exclude('terminal')
# config:
# Config files aren't really importable stand-alone
test_sections['config'].exclude('profile')
# nbconvert:
sec = test_sections['nbconvert']
sec.requires('pygments', 'jinja2', 'jsonschema', 'mistune')
# Exclude nbconvert directories containing config files used to test.
# Executing the config files with iptest would cause an exception.
sec.exclude('tests.files')
sec.exclude('exporters.tests.files')
if not have['tornado']:
sec.exclude('nbconvert.post_processors.serve')
sec.exclude('nbconvert.post_processors.tests.test_serve')
# nbformat:
test_sections['nbformat'].requires('jsonschema')
#-----------------------------------------------------------------------------
# Functions and classes
#-----------------------------------------------------------------------------
def check_exclusions_exist():
from IPython.utils.path import get_ipython_package_dir
from IPython.utils.warn import warn
parent = os.path.dirname(get_ipython_package_dir())
for sec in test_sections:
for pattern in sec.exclusions:
fullpath = pjoin(parent, pattern)
if not os.path.exists(fullpath) and not glob.glob(fullpath + '.*'):
warn("Excluding nonexistent file: %r" % pattern)
class ExclusionPlugin(Plugin):
"""A nose plugin to effect our exclusions of files and directories.
"""
name = 'exclusions'
score = 3000 # Should come before any other plugins
def __init__(self, exclude_patterns=None):
"""
Parameters
----------
exclude_patterns : sequence of strings, optional
Filenames containing these patterns (as raw strings, not as regular
expressions) are excluded from the tests.
"""
self.exclude_patterns = exclude_patterns or []
super(ExclusionPlugin, self).__init__()
def options(self, parser, env=os.environ):
Plugin.options(self, parser, env)
def configure(self, options, config):
Plugin.configure(self, options, config)
# Override nose trying to disable plugin.
self.enabled = True
def wantFile(self, filename):
"""Return whether the given filename should be scanned for tests.
"""
if any(pat in filename for pat in self.exclude_patterns):
return False
return None
def wantDirectory(self, directory):
"""Return whether the given directory should be scanned for tests.
"""
if any(pat in directory for pat in self.exclude_patterns):
return False
return None
class StreamCapturer(Thread):
daemon = True # Don't hang if main thread crashes
started = False
def __init__(self, echo=False):
super(StreamCapturer, self).__init__()
self.echo = echo
self.streams = []
self.buffer = BytesIO()
self.readfd, self.writefd = os.pipe()
self.buffer_lock = Lock()
self.stop = Event()
def run(self):
self.started = True
while not self.stop.is_set():
chunk = os.read(self.readfd, 1024)
with self.buffer_lock:
self.buffer.write(chunk)
if self.echo:
sys.stdout.write(bytes_to_str(chunk))
os.close(self.readfd)
os.close(self.writefd)
def reset_buffer(self):
with self.buffer_lock:
self.buffer.truncate(0)
self.buffer.seek(0)
def get_buffer(self):
with self.buffer_lock:
return self.buffer.getvalue()
def ensure_started(self):
if not self.started:
self.start()
def halt(self):
"""Safely stop the thread."""
if not self.started:
return
self.stop.set()
os.write(self.writefd, b'\0') # Ensure we're not locked in a read()
self.join()
class SubprocessStreamCapturePlugin(Plugin):
name='subprocstreams'
def __init__(self):
Plugin.__init__(self)
self.stream_capturer = StreamCapturer()
self.destination = os.environ.get('IPTEST_SUBPROC_STREAMS', 'capture')
# This is ugly, but distant parts of the test machinery need to be able
# to redirect streams, so we make the object globally accessible.
nose.iptest_stdstreams_fileno = self.get_write_fileno
def get_write_fileno(self):
if self.destination == 'capture':
self.stream_capturer.ensure_started()
return self.stream_capturer.writefd
elif self.destination == 'discard':
return os.open(os.devnull, os.O_WRONLY)
else:
return sys.__stdout__.fileno()
def configure(self, options, config):
Plugin.configure(self, options, config)
# Override nose trying to disable plugin.
if self.destination == 'capture':
self.enabled = True
def startTest(self, test):
# Reset log capture
self.stream_capturer.reset_buffer()
def formatFailure(self, test, err):
# Show output
ec, ev, tb = err
captured = self.stream_capturer.get_buffer().decode('utf-8', 'replace')
if captured.strip():
ev = safe_str(ev)
out = [ev, '>> begin captured subprocess output <<',
captured,
'>> end captured subprocess output <<']
return ec, '\n'.join(out), tb
return err
formatError = formatFailure
def finalize(self, result):
self.stream_capturer.halt()
def run_iptest():
"""Run the IPython test suite using nose.
This function is called when this script is **not** called with the form
`iptest all`. It simply calls nose with appropriate command line flags
and accepts all of the standard nose arguments.
"""
# Apply our monkeypatch to Xunit
if '--with-xunit' in sys.argv and not hasattr(Xunit, 'orig_addError'):
monkeypatch_xunit()
warnings.filterwarnings('ignore',
'This will be removed soon. Use IPython.testing.util instead')
arg1 = sys.argv[1]
if arg1 in test_sections:
section = test_sections[arg1]
sys.argv[1:2] = section.includes
elif arg1.startswith('IPython.') and arg1[8:] in test_sections:
section = test_sections[arg1[8:]]
sys.argv[1:2] = section.includes
else:
section = TestSection(arg1, includes=[arg1])
argv = sys.argv + [ '--detailed-errors', # extra info in tracebacks
'--with-ipdoctest',
'--ipdoctest-tests','--ipdoctest-extension=txt',
# We add --exe because of setuptools' imbecility (it
# blindly does chmod +x on ALL files). Nose does the
# right thing and it tries to avoid executables,
# setuptools unfortunately forces our hand here. This
# has been discussed on the distutils list and the
# setuptools devs refuse to fix this problem!
'--exe',
]
if '-a' not in argv and '-A' not in argv:
argv = argv + ['-a', '!crash']
if nose.__version__ >= '0.11':
# I don't fully understand why we need this one, but depending on what
# directory the test suite is run from, if we don't give it, 0 tests
# get run. Specifically, if the test suite is run from the source dir
# with an argument (like 'iptest.py IPython.core', 0 tests are run,
# even if the same call done in this directory works fine). It appears
# that if the requested package is in the current dir, nose bails early
# by default. Since it's otherwise harmless, leave it in by default
# for nose >= 0.11, though unfortunately nose 0.10 doesn't support it.
argv.append('--traverse-namespace')
# use our plugin for doctesting. It will remove the standard doctest plugin
# if it finds it enabled
plugins = [ExclusionPlugin(section.excludes), IPythonDoctest(), KnownFailure(),
SubprocessStreamCapturePlugin() ]
# Use working directory set by parent process (see iptestcontroller)
if 'IPTEST_WORKING_DIR' in os.environ:
os.chdir(os.environ['IPTEST_WORKING_DIR'])
# We need a global ipython running in this process, but the special
# in-process group spawns its own IPython kernels, so for *that* group we
# must avoid also opening the global one (otherwise there's a conflict of
# singletons). Ultimately the solution to this problem is to refactor our
# assumptions about what needs to be a singleton and what doesn't (app
# objects should, individual shells shouldn't). But for now, this
# workaround allows the test suite for the inprocess module to complete.
if 'kernel.inprocess' not in section.name:
from IPython.testing import globalipapp
globalipapp.start_ipython()
# Now nose can run
TestProgram(argv=argv, addplugins=plugins)
if __name__ == '__main__':
run_iptest()
| mit |
mbroadst/aurelia-plunker | jspm_packages/npm/[email protected]/aurelia-history-browser.js | 10044 | /* */
define(['exports', 'core-js', 'aurelia-pal', 'aurelia-history'], function (exports, _coreJs, _aureliaPal, _aureliaHistory) {
'use strict';
exports.__esModule = true;
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();
exports.configure = configure;
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
var LinkHandler = (function () {
function LinkHandler() {
_classCallCheck(this, LinkHandler);
}
LinkHandler.prototype.activate = function activate(history) {};
LinkHandler.prototype.deactivate = function deactivate() {};
return LinkHandler;
})();
exports.LinkHandler = LinkHandler;
var DefaultLinkHandler = (function (_LinkHandler) {
_inherits(DefaultLinkHandler, _LinkHandler);
function DefaultLinkHandler() {
var _this = this;
_classCallCheck(this, DefaultLinkHandler);
_LinkHandler.call(this);
this.handler = function (e) {
var _DefaultLinkHandler$getEventInfo = DefaultLinkHandler.getEventInfo(e);
var shouldHandleEvent = _DefaultLinkHandler$getEventInfo.shouldHandleEvent;
var href = _DefaultLinkHandler$getEventInfo.href;
if (shouldHandleEvent) {
e.preventDefault();
_this.history.navigate(href);
}
};
}
DefaultLinkHandler.prototype.activate = function activate(history) {
if (history._hasPushState) {
this.history = history;
_aureliaPal.DOM.addEventListener('click', this.handler, true);
}
};
DefaultLinkHandler.prototype.deactivate = function deactivate() {
_aureliaPal.DOM.removeEventListener('click', this.handler);
};
DefaultLinkHandler.getEventInfo = function getEventInfo(event) {
var info = {
shouldHandleEvent: false,
href: null,
anchor: null
};
var target = DefaultLinkHandler.findClosestAnchor(event.target);
if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) {
return info;
}
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return info;
}
var href = target.getAttribute('href');
info.anchor = target;
info.href = href;
var hasModifierKey = event.altKey || event.ctrlKey || event.metaKey || event.shiftKey;
var isRelative = href && !(href.charAt(0) === '#' || /^[a-z]+:/i.test(href));
info.shouldHandleEvent = !hasModifierKey && isRelative;
return info;
};
DefaultLinkHandler.findClosestAnchor = function findClosestAnchor(el) {
while (el) {
if (el.tagName === 'A') {
return el;
}
el = el.parentNode;
}
};
DefaultLinkHandler.targetIsThisWindow = function targetIsThisWindow(target) {
var targetWindow = target.getAttribute('target');
var win = _aureliaPal.PLATFORM.global;
return !targetWindow || targetWindow === win.name || targetWindow === '_self' || targetWindow === 'top' && win === win.top;
};
return DefaultLinkHandler;
})(LinkHandler);
exports.DefaultLinkHandler = DefaultLinkHandler;
function configure(config) {
config.singleton(_aureliaHistory.History, BrowserHistory);
config.transient(LinkHandler, DefaultLinkHandler);
}
var BrowserHistory = (function (_History) {
_inherits(BrowserHistory, _History);
_createClass(BrowserHistory, null, [{
key: 'inject',
value: [LinkHandler],
enumerable: true
}]);
function BrowserHistory(linkHandler) {
_classCallCheck(this, BrowserHistory);
_History.call(this);
this._isActive = false;
this._checkUrlCallback = this._checkUrl.bind(this);
this.location = _aureliaPal.PLATFORM.location;
this.history = _aureliaPal.PLATFORM.history;
this.linkHandler = linkHandler;
}
BrowserHistory.prototype.activate = function activate(options) {
if (this._isActive) {
throw new Error('History has already been activated.');
}
var wantsPushState = !!options.pushState;
this._isActive = true;
this.options = Object.assign({}, { root: '/' }, this.options, options);
this.root = ('/' + this.options.root + '/').replace(rootStripper, '/');
this._wantsHashChange = this.options.hashChange !== false;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var eventName = undefined;
if (this._hasPushState) {
eventName = 'popstate';
} else if (this._wantsHashChange) {
eventName = 'hashchange';
}
_aureliaPal.PLATFORM.addEventListener(eventName, this._checkUrlCallback);
if (this._wantsHashChange && wantsPushState) {
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
if (!this._hasPushState && !atRoot) {
this.fragment = this._getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
return true;
} else if (this._hasPushState && atRoot && loc.hash) {
this.fragment = this._getHash().replace(routeStripper, '');
this.history.replaceState({}, _aureliaPal.DOM.title, this.root + this.fragment + loc.search);
}
}
if (!this.fragment) {
this.fragment = this._getFragment();
}
this.linkHandler.activate(this);
if (!this.options.silent) {
return this._loadUrl();
}
};
BrowserHistory.prototype.deactivate = function deactivate() {
_aureliaPal.PLATFORM.removeEventListener('popstate', this._checkUrlCallback);
_aureliaPal.PLATFORM.removeEventListener('hashchange', this._checkUrlCallback);
this._isActive = false;
this.linkHandler.deactivate();
};
BrowserHistory.prototype.navigate = function navigate(fragment) {
var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref$trigger = _ref.trigger;
var trigger = _ref$trigger === undefined ? true : _ref$trigger;
var _ref$replace = _ref.replace;
var replace = _ref$replace === undefined ? false : _ref$replace;
if (fragment && absoluteUrl.test(fragment)) {
this.location.href = fragment;
return true;
}
if (!this._isActive) {
return false;
}
fragment = this._getFragment(fragment || '');
if (this.fragment === fragment && !replace) {
return false;
}
this.fragment = fragment;
var url = this.root + fragment;
if (fragment === '' && url !== '/') {
url = url.slice(0, -1);
}
if (this._hasPushState) {
url = url.replace('//', '/');
this.history[replace ? 'replaceState' : 'pushState']({}, _aureliaPal.DOM.title, url);
} else if (this._wantsHashChange) {
updateHash(this.location, fragment, replace);
} else {
return this.location.assign(url);
}
if (trigger) {
return this._loadUrl(fragment);
}
};
BrowserHistory.prototype.navigateBack = function navigateBack() {
this.history.back();
};
BrowserHistory.prototype.setTitle = function setTitle(title) {
_aureliaPal.DOM.title = title;
};
BrowserHistory.prototype._getHash = function _getHash() {
return this.location.hash.substr(1);
};
BrowserHistory.prototype._getFragment = function _getFragment(fragment, forcePushState) {
var root = undefined;
if (!fragment) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname + this.location.search;
root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) {
fragment = fragment.substr(root.length);
}
} else {
fragment = this._getHash();
}
}
return '/' + fragment.replace(routeStripper, '');
};
BrowserHistory.prototype._checkUrl = function _checkUrl() {
var current = this._getFragment();
if (current !== this.fragment) {
this._loadUrl();
}
};
BrowserHistory.prototype._loadUrl = function _loadUrl(fragmentOverride) {
var fragment = this.fragment = this._getFragment(fragmentOverride);
return this.options.routeHandler ? this.options.routeHandler(fragment) : false;
};
return BrowserHistory;
})(_aureliaHistory.History);
exports.BrowserHistory = BrowserHistory;
var routeStripper = /^#?\/*|\s+$/g;
var rootStripper = /^\/+|\/+$/g;
var trailingSlash = /\/$/;
var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i;
function updateHash(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
location.hash = '#' + fragment;
}
}
}); | mit |
jorgemancheno/boxen | vendor/bundle/ruby/2.0.0/gems/puppet-3.6.1/lib/puppet/pops/evaluator/callable_signature.rb | 3208 | # CallableSignature
# ===
# A CallableSignature describes how something callable expects to be called.
# Different implementation of this class are used for different types of callables.
#
# @api public
#
class Puppet::Pops::Evaluator::CallableSignature
# Returns the names of the parameters as an array of strings. This does not include the name
# of an optional block parameter.
#
# All implementations are not required to supply names for parameters. They may be used if present,
# to provide user feedback in errors etc. but they are not authoritative about the number of
# required arguments, optional arguments, etc.
#
# A derived class must implement this method.
#
# @return [Array<String>] - an array of names (that may be empty if names are unavailable)
#
# @api public
#
def parameter_names
raise NotImplementedError.new
end
# Returns a PCallableType with the type information, required and optional count, and type information about
# an optional block.
#
# A derived class must implement this method.
#
# @return [Puppet::Pops::Types::PCallableType]
# @api public
#
def type
raise NotImplementedError.new
end
# Returns the expected type for an optional block. The type may be nil, which means that the callable does
# not accept a block. If a type is returned it is one of Callable, Optional[Callable], Variant[Callable,...],
# or Optional[Variant[Callable, ...]]. The Variant type is used when multiple signatures are acceptable.
# The Optional type is used when the block is optional.
#
# @return [Puppet::Pops::Types::PAbstractType, nil] the expected type of a block given as the last parameter in a call.
#
# @api public
#
def block_type
type.block_type
end
# Returns the name of the block parameter if the callable accepts a block.
# @return [String] the name of the block parameter
# A derived class must implement this method.
# @api public
#
def block_name
raise NotImplementedError.new
end
# Returns a range indicating the optionality of a block. One of [0,0] (does not accept block), [0,1] (optional
# block), and [1,1] (block required)
#
# @return [Array(Integer, Integer)] the range of the block parameter
#
def block_range
type.block_range
end
# Returns the range of required/optional argument values as an array of [min, max], where an infinite
# end is given as INFINITY. To test against infinity, use the infinity? method.
#
# @return [Array[Integer, Numeric]] - an Array with [min, max]
#
# @api public
#
def args_range
type.size_range
end
# Returns true if the last parameter captures the rest of the arguments, with a possible cap, as indicated
# by the `args_range` method.
# A derived class must implement this method.
#
# @return [Boolean] true if last parameter captures the rest of the given arguments (up to a possible cap)
# @api public
#
def last_captures_rest?
raise NotImplementedError.new
end
# Returns true if the given x is infinity
# @return [Boolean] true, if given value represents infinity
#
# @api public
#
def infinity?(x)
x == Puppet::Pops::Types::INFINITY
end
end
| mit |
typesettin/NativeCMS | node_modules/react-web/Libraries/Navigator/NavigatorNavigationBarStylesAndroid.js | 4250 | /**
* Copyright (c) 2015-present, Alibaba Group Holding Limited.
* All rights reserved.
*
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @providesModule ReactNavigatorNavigationBarStylesAndroid
*/
'use strict';
import buildStyleInterpolator from './polyfills/buildStyleInterpolator';
import merge from './polyfills/merge';
// Android Material Design
var NAV_BAR_HEIGHT = 56;
var TITLE_LEFT = 72;
var BUTTON_SIZE = 24;
var TOUCH_TARGT_SIZE = 48;
var BUTTON_HORIZONTAL_MARGIN = 16;
var BUTTON_EFFECTIVE_MARGIN = BUTTON_HORIZONTAL_MARGIN - (TOUCH_TARGT_SIZE - BUTTON_SIZE) / 2;
var NAV_ELEMENT_HEIGHT = NAV_BAR_HEIGHT;
var BASE_STYLES = {
Title: {
position: 'absolute',
bottom: 0,
left: 0,
right: 0,
alignItems: 'flex-start',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
marginLeft: TITLE_LEFT,
},
LeftButton: {
position: 'absolute',
top: 0,
left: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
RightButton: {
position: 'absolute',
top: 0,
right: BUTTON_EFFECTIVE_MARGIN,
overflow: 'hidden',
alignItems: 'flex-end',
height: NAV_ELEMENT_HEIGHT,
backgroundColor: 'transparent',
},
};
// There are 3 stages: left, center, right. All previous navigation
// items are in the left stage. The current navigation item is in the
// center stage. All upcoming navigation items are in the right stage.
// Another way to think of the stages is in terms of transitions. When
// we move forward in the navigation stack, we perform a
// right-to-center transition on the new navigation item and a
// center-to-left transition on the current navigation item.
var Stages = {
Left: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
Center: {
Title: merge(BASE_STYLES.Title, { opacity: 1 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 1 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 1 }),
},
Right: {
Title: merge(BASE_STYLES.Title, { opacity: 0 }),
LeftButton: merge(BASE_STYLES.LeftButton, { opacity: 0 }),
RightButton: merge(BASE_STYLES.RightButton, { opacity: 0 }),
},
};
var opacityRatio = 100;
function buildSceneInterpolators(startStyles, endStyles) {
return {
Title: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.Title.opacity,
to: endStyles.Title.opacity,
min: 0,
max: 1,
},
left: {
type: 'linear',
from: startStyles.Title.left,
to: endStyles.Title.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
LeftButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.LeftButton.opacity,
to: endStyles.LeftButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.LeftButton.left,
to: endStyles.LeftButton.left,
min: 0,
max: 1,
},
}),
RightButton: buildStyleInterpolator({
opacity: {
type: 'linear',
from: startStyles.RightButton.opacity,
to: endStyles.RightButton.opacity,
min: 0,
max: 1,
round: opacityRatio,
},
left: {
type: 'linear',
from: startStyles.RightButton.left,
to: endStyles.RightButton.left,
min: 0,
max: 1,
extrapolate: true,
},
}),
};
}
var Interpolators = {
// Animating *into* the center stage from the right
RightToCenter: buildSceneInterpolators(Stages.Right, Stages.Center),
// Animating out of the center stage, to the left
CenterToLeft: buildSceneInterpolators(Stages.Center, Stages.Left),
// Both stages (animating *past* the center stage)
RightToLeft: buildSceneInterpolators(Stages.Right, Stages.Left),
};
module.exports = {
General: {
NavBarHeight: NAV_BAR_HEIGHT,
StatusBarHeight: 0,
TotalNavHeight: NAV_BAR_HEIGHT,
},
Interpolators,
Stages,
};
| mit |
esmakula/moskito | moskito-webui/src/main/java/net/anotheria/moskito/webui/threads/api/ThreadAPIFactory.java | 594 | package net.anotheria.moskito.webui.threads.api;
import net.anotheria.anoplass.api.APIFactory;
import net.anotheria.anoplass.api.APIFinder;
import net.anotheria.anoprise.metafactory.ServiceFactory;
/**
* TODO comment this class
*
* @author lrosenberg
* @since 14.02.13 11:46
*/
public class ThreadAPIFactory implements APIFactory<ThreadAPI>, ServiceFactory<ThreadAPI> {
@Override
public ThreadAPI createAPI() {
return new ThreadAPIImpl();
}
@Override
public ThreadAPI create() {
APIFinder.addAPIFactory(ThreadAPI.class, this);
return APIFinder.findAPI(ThreadAPI.class);
}
}
| mit |
Roquet87/SIGESRHI | vendor/vich/uploader-bundle/Vich/UploaderBundle/Resources/doc/index.md | 14531 | VichUploaderBundle
==================
The VichUploaderBundle is a Symfony2 bundle that attempts to ease file
uploads that are attached to an entity. The bundle will automatically name and
save the uploaded file according to the configuration specified on a per-property
basis using a mix of configuration and annotations. After the entity has been created
and the file has been saved, if configured to do so an instance of
`Symfony\Component\HttpFoundation\File\File` will be loaded into the annotated property
when the entity is loaded from the datastore. The bundle also provides templating helpers
for generating URLs to the file. The file can also be configured to be removed from the
file system upon removal of the entity.
The bundle provides different ways to interact with the filesystem; you can choose
your preferred one by configuration. Basically, you can choose to work with the local
filesystem or integrate gaufrette to have nice abstraction over the filesystem (for more
info see [FileSystemStorage VS GaufretteStorage](#filesystemstorage-vs-gaufrettestorage)).
You can also implement your own StorageInterface if you need to.
## Installation
### Get the bundle
To install the bundle, place it in the `vendor/bundles/Vich/UploaderBundle`
directory of your project. You can do this by adding the bundle to your deps file,
as a submodule, cloning it, or simply downloading the source.
Add the following lines in your composer.json:
```
{
"require": {
"vich/uploader-bundle": "dev-master",
"knplabs/knp-gaufrette-bundle" : "dev-master"
}
}
```
OR add to `deps` file:
```
[gaufrette]
git=http://github.com/KnpLabs/Gaufrette.git
version=v0.1.3
[KnpGaufretteBundle]
git=http://github.com/KnpLabs/KnpGaufretteBundle.git
target=/bundles/Knp/Bundle/GaufretteBundle
[VichUploaderBundle]
git=git://github.com/dustin10/VichUploaderBundle.git
target=/bundles/Vich/UploaderBundle
```
Or you may add the bundle as a git submodule:
``` bash
$ git submodule add https://github.com/dustin10/VichUploaderBundle.git vendor/bundles/Vich/UploaderBundle
```
### Add the namespace to your autoloader
Next you should add the `Vich` namespace to your autoloader:
``` php
<?php
// app/autoload.php
$loader->registerNamespaces(array(
// ...
'Knp\Bundle' => __DIR__.'/../vendor/bundles',
'Gaufrette' => __DIR__.'/../vendor/gaufrette/src',
'Vich' => __DIR__.'/../vendor/bundles'
));
```
### Initialize the bundle
To start using the bundle, register the bundle in your application's kernel class:
``` php
// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
// ...
new Knp\Bundle\GaufretteBundle\KnpGaufretteBundle(),
new Vich\UploaderBundle\VichUploaderBundle(),
);
)
```
**Note:**
> Even if you don't plan to use Gaufrette you must include it in your
> deps file and activate KnpGaufretteBundle
## Usage
VichUploaderBundle tries to handle file uploads according to a combination
of configuration parameters and annotations. In order to have your upload
working you have to:
* Choose which storage service you want to use (vich_uploader.storage.file_system
or vich_uploader.storage.gaufrette)
* Define a basic configuration set
* Annotate your Entities
* Optionally implement namer services (see Namer later)
*Please note that some bundle components have a slightly different meaning according to the
storage service you are using. Read more about it in [Configuration reference](#a-hrefreferenceaconfiguration-reference)*
### FileSystemStorage VS GaufretteStorage
Gaufrette is a great piece of code and provide a great level of filesystem
abstraction. Using Gaufrette, you will be able to store files locally, or using
some external service without impact on your application. This means that you
will be able to change the location of your files by changing configuration,
rather than code.
**For this reason GaufretteStorage if probably the most flexible solution and your
best choice as storage service.**
If you don't need this level of abstraction, if you prefer to
keep things simple, or if you just don't feel comfortable working
with gaufrette you can go with FileSystemStorage.
For more information on how use one storage instead of another,
go to [Configuration](#configuration) section
### Configuration
First configure the `db_driver` option. You must specify either `orm` or
`mongodb`.
``` yaml
# app/config/config.yml
vich_uploader:
db_driver: orm # or mongodb
```
And then add your mappings information. In order to map
configuration options to the property of the entity you first
need to create a mapping in the bundle configuration. You
create these mappings
under the `mappings` key. Each mapping should have a unique name.
So, if you wanted
to name your mapping `product_image`, the configuration for this
mapping would be
similar to:
``` yaml
vich_uploader:
db_driver: orm
mappings:
product_image:
uri_prefix: /images/products
upload_destination: %kernel.root_dir%/../web/images/products
```
The `upload_destination` is the only required configuration option for an entity mapping.
All options are listed below:
- `upload_destination`: The gaufrette fs id to upload the file to
- `namer`: The id of the file namer service for this entity (See [Namers](#namers) section below)
- `directory_namer`: The id of the directory namer service for this entity (See Namers section below)
- `delete_on_remove`: Set to true if the file should be deleted from the
filesystem when the entity is removed
- `delete_on_update`: Set to true if the file should be deleted from the
filesystem when the file is replaced by an other one
- `inject_on_load`: Set to true if the file should be injected into the uploadable
field property when it is loaded from the data store. The object will be an instance
of `Symfony\Component\HttpFoundation\File\File`
**Note:**
> This is the easiest configuration and will use the default
> storage service (vich_uploader.storage.file_system).
> If you want to use Gaufrette you will have to add some bit
> of configuration (see [gaufrette configuration](#gaufrette-configuration) for more help).
**Note:**
> A verbose configuration reference including all configuration options and their
> default values is included at the bottom of this document.
#### Gaufrette configuration
In order to use Gaufrette you have to configure it. Here is
a sample configuration that stores your file in your local filesystem,
but you can use your preferred adapters and FS (for details
on this topic you should refer to the gaufrette documentation).
``` yaml
knp_gaufrette:
adapters:
product_adapter:
local:
directory: %kernel.root_dir%/../web/images/products
filesystems:
product_image_fs:
adapter: product_adapter
vich_uploader:
db_driver: orm
gaufrette: true
storage: vich_uploader.storage.gaufrette
mappings:
product_image:
uri_prefix: /images/products
upload_destination: product_image_fs
```
Using vich_uploader.storage.gaufrette as the storage service
you can still use the same mappings options that you would
use with default storage.
**Note:**
> In this case upload_destination refer to a gaufrette filesystem
> and directory_namer should be used to generate a valid
> filesystem ID (and not a real path). See more about this
> in [Namers section](#namers)
### Annotate Entities
In order for your entity or document to work with the bundle, you need to add a
few annotations to it. First, annotate your class with the `Uploadable` annotation.
This lets the bundle know that it should look for files to upload in your class when
it is saved, inject the files when it is loaded and check to see if it needs to
remove files when it is removed. Next, you should annotate the fields which hold
the instance of `Symfony\Component\HttpFoundation\File\UploadedFile` when the form
is submitted with the `UploadableField` annotation. The `UploadableField` annotation
has a few required options. They are as follows:
- `mapping`: The mapping specified in the bundle configuration to use
- `fileNameProperty`: The property of the class that will be filled with the file name
generated by the bundle
Lets look at an example using a fictional `Product` ORM entity:
``` php
<?php
namespace Acme\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
/**
* @ORM\Entity
* @Vich\Uploadable
*/
class Product
{
/**
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
// ..... other fields
/**
* @Assert\File(
* maxSize="1M",
* mimeTypes={"image/png", "image/jpeg", "image/pjpeg"}
* )
* @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
*
* @var File $image
*/
protected $image;
/**
* @ORM\Column(type="string", length=255, name="image_name")
*
* @var string $imageName
*/
protected $imageName;
}
```
## Namers
The bundle uses namers to name the files and directories it saves to the filesystem. A namer
implements the `Vich\UploaderBundle\Naming\NamerInterface` interface. If no namer is
configured for a mapping, the bundle will simply use the name of the file that
was uploaded. If you would like to change this, you can use one of the provided namers or implement a custom one.
### File Namer
#### Provided file namer
At the moment there are two available namers:
- vich_uploader.namer_uniqid
- vich_uploader.namer_origname
**vich_uploader.namer_uniqid** will rename your uploaded files using a uniqueid for the name and
keep the extension. Using this namer, foo.jpg will be uploaded as something like 50eb3db039715.jpg.
**vich_uploader.namer_origname** will rename your uploaded files using a uniqueid as the prefix of the
filename and keeping the original name and extension. Using this namer, foo.jpg will be uploaded as
something like 50eb3db039715_foo.jpg
To use it, you just have to specify the service id for the `namer` configuration option of your mapping :
``` yaml
vich_uploader:
# ...
mappings:
product_image:
upload_destination: product_image_fs
namer: vich_uploader.namer_uniqid
```
#### Create a custom file namer
To create a custom file namer, simply implement the `Vich\UploaderBundle\Naming\NamerInterface`
and in the `name` method of your class return the desired file name. Since your entity
is passed to the `name` method, as well as the field name, you are free to get any information
from it to create the name, or inject any other services that you require.
**Note**:
> The name returned should include the file extension as well. This can easily
> be retrieved from the `UploadedFile` instance using the `getExtension` or `guessExtension`
> depending on what version of PHP you are running.
After you have created your namer and configured it as a service, you simply specify
the service id for the `namer` configuration option of your mapping. An example:
``` yaml
vich_uploader:
# ...
mappings:
product_image:
upload_destination: product_image
namer: my.namer.product
```
Here `my.namer.product` is the configured id of the service.
If no namer is configured for a mapping, the bundle will simply use the name of the file that
was uploaded.
### Directory Namer
To create a custom directory namer, simply implement the
`Vich\UploaderBundle\Naming\DirectoryNamerInterface`
and in the `directoryName` method of your class return the absolute directory.
Since your entity, field name
and default `upload_destination` are all passed to the `directoryName` method
you are free to get any information
from it to create the name, or inject any other services that you require.
After you have created your directory namer and configured it as a service, you simply specify
the service id for the `directory_namer` configuration option of your mapping. An example:
``` yaml
vich_uploader:
# ...
mappings:
product_image:
upload_destination: product_image
directory_namer: my.directory_namer.product
```
If no directory namer is configured for a mapping, the bundle will simply use the `upload_destination` configuration option.
**Note**:
> If you are using Gaufrette to abstract from the filesystem the name returned
> will be used as a gaufrette filesystem ID and not as a proper path.
## Generating URLs
To get a url for the file you can use the `vich_uploader.templating.helper`
service as follows:
``` php
$entity = // get the entity..
$helper = $this->container->get('vich_uploader.templating.helper.uploader_helper');
$path = $helper->asset($entity, 'image');
```
or in a Twig template you can use the `vich_uploader_asset` function:
``` twig
<img src="{{ vich_uploader_asset(product, 'image') }}" alt="{{ product.name }}" />
```
You must specify the annotated property you wish to get the file path for.
**Note:**
> The path returned is relative to the web directory which is specified
> using the `uri_prefix` configuration parameter.
## Configuration Reference
Below is the full default configuration for the bundle:
``` yaml
# app/config/config.yml
vich_uploader:
db_driver: orm # or mongodb
twig: true
gaufrette: false # set to true to enable gaufrette support
storage: vich_uploader.storage.file_system
mappings:
product_image:
uri_prefix: web # uri prefix to resource
upload_destination: ~ # gaufrette storage fs id, required
namer: ~ # specify a file namer service id for this entity, null default
directory_namer: ~ # specify a directory namer service id for this entity, null default
delete_on_remove: true # determines whether to delete file upon removal of entity
inject_on_load: true # determines whether to inject a File instance upon load
# ... more mappings
```
- `storage`: The id of the storage service used by the bundle to
store files. The bundle ships with vich_uploader.storage.file_system
and vich_uploader.storage.gaufrette see
[FileSystemStorage VS GaufretteStorage](#filesystemstorage-vs-gaufrettestorage)
| mit |
dzjuck/hamster | spec/lib/hamster/sorted_set/disjoint_spec.rb | 715 | require "spec_helper"
require "hamster/sorted_set"
describe Hamster::SortedSet do
describe "#disjoint?" do
[
[[], [], true],
[["A"], [], true],
[[], ["A"], true],
[["A"], ["A"], false],
[%w[A B C], ["B"], false],
[["B"], %w[A B C], false],
[%w[A B C], %w[D E], true],
[%w[F G H I], %w[A B C], true],
[%w[A B C], %w[A B C], false],
[%w[A B C], %w[A B C D], false],
[%w[D E F G], %w[A B C], true],
].each do |a, b, expected|
context "for #{a.inspect} and #{b.inspect}" do
it "returns #{expected}" do
Hamster.sorted_set(*a).disjoint?(Hamster.sorted_set(*b)).should be(expected)
end
end
end
end
end | mit |
Vinagility/engine_old | spec/lib/locomotive/liquid/tags/extends_spec.rb | 1826 | require 'spec_helper'
describe Locomotive::Liquid::Tags::Extends do
before(:each) do
@home = FactoryGirl.build(:page, :raw_template => 'Hello world')
@home.send :serialize_template
@home.instance_variable_set(:@template, nil)
@site = FactoryGirl.build(:site)
@site.stubs(:pages).returns([@home])
end
it 'works' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('parent', page).render.should == 'Hello world'
end
it 'looks for the index with the right locale' do
::Mongoid::Fields::I18n.with_locale 'fr' do
@home.raw_template = 'Bonjour le monde'
@home.send :serialize_template
end
@site.pages.expects(:where).with('fullpath.fr' => 'index').returns([@home])
::Mongoid::Fields::I18n.with_locale 'fr' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('index', page).render.should == 'Bonjour le monde'
end
end
context '#errors' do
it 'raises an error if the source page does not exist' do
lambda {
@site.pages.expects(:where).with('fullpath.en' => 'foo').returns([])
parse('foo')
}.should raise_error(Locomotive::Liquid::PageNotFound, "Page with fullpath 'foo' was not found")
end
it 'raises an error if the source page is not translated' do
lambda {
::Mongoid::Fields::I18n.with_locale 'fr' do
page = FactoryGirl.build(:page, :slug => 'sub_page_1', :parent => @home)
parse('parent', page)
end
}.should raise_error(Locomotive::Liquid::PageNotTranslated, "Page with fullpath 'parent' was not translated")
end
end
def parse(source = 'index', page = nil)
page ||= @home
Liquid::Template.parse("{% extends #{source} %}", { :site => @site, :page => page })
end
end
| mit |
umbraco/Umbraco-CMS | src/Umbraco.Web.UI.Client/src/common/directives/components/content/umbtabbedcontent.directive.js | 8522 | (function () {
'use strict';
/** This directive is used to render out the current variant tabs and properties and exposes an API for other directives to consume */
function tabbedContentDirective($timeout, $filter, contentEditingHelper, contentTypeHelper) {
function link($scope, $element) {
var appRootNode = $element[0];
// Directive for cached property groups.
var propertyGroupNodesDictionary = {};
var scrollableNode = appRootNode.closest(".umb-scrollable");
$scope.activeTabAlias = null;
$scope.tabs = [];
$scope.$watchCollection('content.tabs', (newValue) => {
contentTypeHelper.defineParentAliasOnGroups(newValue);
contentTypeHelper.relocateDisorientedGroups(newValue);
// make a collection with only tabs and not all groups
$scope.tabs = $filter("filter")(newValue, (tab) => {
return tab.type === contentTypeHelper.TYPE_TAB;
});
if ($scope.tabs.length > 0) {
// if we have tabs and some groups that doesn't belong to a tab we need to render those on an "Other" tab.
contentEditingHelper.registerGenericTab(newValue);
$scope.setActiveTab($scope.tabs[0]);
scrollableNode.removeEventListener("scroll", onScroll);
scrollableNode.removeEventListener("mousewheel", cancelScrollTween);
// only trigger anchor scroll when there are no tabs
} else {
scrollableNode.addEventListener("scroll", onScroll);
scrollableNode.addEventListener("mousewheel", cancelScrollTween);
}
});
function onScroll(event) {
var viewFocusY = scrollableNode.scrollTop + scrollableNode.clientHeight * .5;
for(var i in $scope.content.tabs) {
var group = $scope.content.tabs[i];
var node = propertyGroupNodesDictionary[group.id];
if (!node) {
return;
}
if (viewFocusY >= node.offsetTop && viewFocusY <= node.offsetTop + node.clientHeight) {
setActiveAnchor(group);
return;
}
}
}
function setActiveAnchor(tab) {
if (tab.active !== true) {
var i = $scope.content.tabs.length;
while(i--) {
$scope.content.tabs[i].active = false;
}
tab.active = true;
}
}
function getActiveAnchor() {
var i = $scope.content.tabs.length;
while(i--) {
if ($scope.content.tabs[i].active === true)
return $scope.content.tabs[i];
}
return false;
}
function getScrollPositionFor(id) {
if (propertyGroupNodesDictionary[id]) {
return propertyGroupNodesDictionary[id].offsetTop - 20;// currently only relative to closest relatively positioned parent
}
return null;
}
function scrollTo(id) {
var y = getScrollPositionFor(id);
if (getScrollPositionFor !== null) {
var viewportHeight = scrollableNode.clientHeight;
var from = scrollableNode.scrollTop;
var to = Math.min(y, scrollableNode.scrollHeight - viewportHeight);
var animeObject = {_y: from};
$scope.scrollTween = anime({
targets: animeObject,
_y: to,
easing: 'easeOutExpo',
duration: 200 + Math.min(Math.abs(to-from)/viewportHeight*100, 400),
update: () => {
scrollableNode.scrollTo(0, animeObject._y);
}
});
}
}
function jumpTo(id) {
var y = getScrollPositionFor(id);
if (getScrollPositionFor !== null) {
cancelScrollTween();
scrollableNode.scrollTo(0, y);
}
}
function cancelScrollTween() {
if($scope.scrollTween) {
$scope.scrollTween.pause();
}
}
$scope.registerPropertyGroup = function(element, appAnchor) {
propertyGroupNodesDictionary[appAnchor] = element;
};
$scope.setActiveTab = function(tab) {
$scope.activeTabAlias = tab.alias;
$scope.tabs.forEach(tab => tab.active = false);
tab.active = true;
};
$scope.$on("editors.apps.appChanged", function($event, $args) {
// if app changed to this app, then we want to scroll to the current anchor
if($args.app.alias === "umbContent" && $scope.tabs.length === 0) {
var activeAnchor = getActiveAnchor();
$timeout(jumpTo.bind(null, [activeAnchor.id]));
}
});
$scope.$on("editors.apps.appAnchorChanged", function($event, $args) {
if($args.app.alias === "umbContent") {
setActiveAnchor($args.anchor);
scrollTo($args.anchor.id);
}
});
//ensure to unregister from all dom-events
$scope.$on('$destroy', function () {
cancelScrollTween();
scrollableNode.removeEventListener("scroll", onScroll);
scrollableNode.removeEventListener("mousewheel", cancelScrollTween);
});
}
function controller($scope) {
//expose the property/methods for other directives to use
this.content = $scope.content;
if($scope.contentNodeModel) {
$scope.defaultVariant = _.find($scope.contentNodeModel.variants, variant => {
// defaultVariant will never have segment. Wether it has a language or not depends on the setup.
return !variant.segment && ((variant.language && variant.language.isDefault) || (!variant.language));
});
}
$scope.unlockInvariantValue = function(property) {
property.unlockInvariantValue = !property.unlockInvariantValue;
};
$scope.$watch("tabbedContentForm.$dirty",
function (newValue, oldValue) {
if (newValue === true) {
$scope.content.isDirty = true;
}
}
);
$scope.propertyEditorDisabled = function (property) {
if (property.unlockInvariantValue) {
return false;
}
var contentLanguage = $scope.content.language;
var canEditCulture = !contentLanguage ||
// If the property culture equals the content culture it can be edited
property.culture === contentLanguage.culture ||
// A culture-invariant property can only be edited by the default language variant
(property.culture == null && contentLanguage.isDefault);
var canEditSegment = property.segment === $scope.content.segment;
return !canEditCulture || !canEditSegment;
}
}
var directive = {
restrict: 'E',
replace: true,
templateUrl: 'views/components/content/umb-tabbed-content.html',
controller: controller,
link: link,
scope: {
content: "=", // in this context the content is the variant model.
contentNodeModel: "=?", //contentNodeModel is the content model for the node,
contentApp: "=?" // contentApp is the origin app model for this view
}
};
return directive;
}
angular.module('umbraco.directives').directive('umbTabbedContent', tabbedContentDirective);
})();
| mit |
upsoft/bond | examples/cpp/core/time_alias/time_alias.cpp | 971 | #include "time_alias_reflection.h"
#include <bond/core/bond.h>
#include <bond/stream/output_buffer.h>
using namespace examples::time;
int main()
{
Example obj, obj2;
using namespace boost::gregorian;
using namespace boost::posix_time;
// In the generated code we use boost::posix_time_ptime::ptime to represent
// the type alias 'time' (see makefile.inc for code gen flags).
obj.when = ptime(date(2016, 1, 29));
obj.bdays["bill"] = ptime(from_string("1955/10/28"));
bond::OutputBuffer output;
bond::CompactBinaryWriter<bond::OutputBuffer> writer(output);
// Serialize the object
Serialize(obj, writer);
bond::CompactBinaryReader<bond::InputBuffer> reader(output.GetBuffer());
// De-serialize the object
Deserialize(reader, obj2);
std::string followingSunday = to_simple_string(
first_day_of_the_week_after(Sunday).get_date(obj2.when.date()));
BOOST_ASSERT(obj == obj2);
return 0;
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.