repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
AnHongMin/pages
node_modules/karma/context/karma.js
4648
// Load our dependencies var stringify = require('../common/stringify') // Define our context Karma constructor var ContextKarma = function (callParentKarmaMethod) { // Define local variables var hasError = false var self = this // Define our loggers // DEV: These are intentionally repeated in client and context this.log = function (type, args) { var values = [] for (var i = 0; i < args.length; i++) { values.push(this.stringify(args[i], 3)) } this.info({log: values.join(', '), type: type}) } this.stringify = stringify // Define our proxy error handler // DEV: We require one in our context to track `hasError` this.error = function () { hasError = true callParentKarmaMethod('error', [].slice.call(arguments)) return false } // Define our start handler var UNIMPLEMENTED_START = function () { this.error('You need to include some adapter that implements __karma__.start method!') } // all files loaded, let's start the execution this.loaded = function () { // has error -> cancel if (!hasError) { this.start(this.config) } // remove reference to child iframe this.start = UNIMPLEMENTED_START } // supposed to be overriden by the context // TODO(vojta): support multiple callbacks (queue) this.start = UNIMPLEMENTED_START // Define proxy methods // DEV: This is a closured `for` loop (same as a `forEach`) for IE support var proxyMethods = ['complete', 'info', 'result'] for (var i = 0; i < proxyMethods.length; i++) { (function bindProxyMethod (methodName) { self[methodName] = function boundProxyMethod () { callParentKarmaMethod(methodName, [].slice.call(arguments)) } }(proxyMethods[i])) } // Define bindings for context window this.setupContext = function (contextWindow) { // If we clear the context after every run and we already had an error // then stop now. Otherwise, carry on. if (self.config.clearContext && hasError) { return } // Perform window level bindings // DEV: We return `self.error` since we want to `return false` to ignore errors contextWindow.onerror = function () { return self.error.apply(self, arguments) } // DEV: We must defined a function since we don't want to pass the event object contextWindow.onbeforeunload = function (e, b) { callParentKarmaMethod('onbeforeunload', []) } contextWindow.dump = function () { self.log('dump', arguments) } var _confirm = contextWindow.confirm var _prompt = contextWindow.prompt contextWindow.alert = function (msg) { self.log('alert', [msg]) } contextWindow.confirm = function (msg) { self.log('confirm', [msg]) _confirm(msg) } contextWindow.prompt = function (msg, defaultVal) { self.log('prompt', [msg, defaultVal]) _prompt(msg, defaultVal) } // If we want to overload our console, then do it var getConsole = function (currentWindow) { return currentWindow.console || { log: function () {}, info: function () {}, warn: function () {}, error: function () {}, debug: function () {} } } if (self.config.captureConsole) { // patch the console var localConsole = contextWindow.console = getConsole(contextWindow) var logMethods = ['log', 'info', 'warn', 'error', 'debug'] var patchConsoleMethod = function (method) { var orig = localConsole[method] if (!orig) { return } localConsole[method] = function () { self.log(method, arguments) return Function.prototype.apply.call(orig, localConsole, arguments) } } for (var i = 0; i < logMethods.length; i++) { patchConsoleMethod(logMethods[i]) } } } } // Define call/proxy methods ContextKarma.getDirectCallParentKarmaMethod = function (parentWindow) { return function directCallParentKarmaMethod (method, args) { // If the method doesn't exist, then error out if (!parentWindow.karma[method]) { parentWindow.karma.error('Expected Karma method "' + method + '" to exist but it doesn\'t') return } // Otherwise, run our method parentWindow.karma[method].apply(parentWindow.karma, args) } } ContextKarma.getPostMessageCallParentKarmaMethod = function (parentWindow) { return function postMessageCallParentKarmaMethod (method, args) { parentWindow.postMessage({__karmaMethod: method, __karmaArguments: args}, window.location.origin) } } // Export our module module.exports = ContextKarma
mit
grubernaut/packer
vendor/github.com/approvals/go-approval-tests/reporters/newbie.go
498
package reporters import ( "fmt" ) type printSupportedDiffPrograms struct{} // NewPrintSupportedDiffProgramsReporter creates a new reporter that states what reporters are supported. func NewPrintSupportedDiffProgramsReporter() Reporter { return &quiet{} } func (s *printSupportedDiffPrograms) Report(approved, received string) bool { fmt.Printf("no diff reporters found on your system\ncurrently supported reporters are [in order of preference]:\nBeyond Compare\nIntelliJ") return false }
mpl-2.0
Godiyos/python-for-android
python-modules/twisted/twisted/conch/ssh/channel.py
9284
# -*- test-case-name: twisted.conch.test.test_channel -*- # Copyright (c) 2001-2008 Twisted Matrix Laboratories. # See LICENSE for details. # """ The parent class for all the SSH Channels. Currently implemented channels are session. direct-tcp, and forwarded-tcp. Maintainer: Paul Swartz """ from twisted.python import log from twisted.internet import interfaces from zope.interface import implements class SSHChannel(log.Logger): """ A class that represents a multiplexed channel over an SSH connection. The channel has a local window which is the maximum amount of data it will receive, and a remote which is the maximum amount of data the remote side will accept. There is also a maximum packet size for any individual data packet going each way. @ivar name: the name of the channel. @type name: C{str} @ivar localWindowSize: the maximum size of the local window in bytes. @type localWindowSize: C{int} @ivar localWindowLeft: how many bytes are left in the local window. @type localWindowLeft: C{int} @ivar localMaxPacket: the maximum size of packet we will accept in bytes. @type localMaxPacket: C{int} @ivar remoteWindowLeft: how many bytes are left in the remote window. @type remoteWindowLeft: C{int} @ivar remoteMaxPacket: the maximum size of a packet the remote side will accept in bytes. @type remoteMaxPacket: C{int} @ivar conn: the connection this channel is multiplexed through. @type conn: L{SSHConnection} @ivar data: any data to send to the other size when the channel is requested. @type data: C{str} @ivar avatar: an avatar for the logged-in user (if a server channel) @ivar localClosed: True if we aren't accepting more data. @type localClosed: C{bool} @ivar remoteClosed: True if the other size isn't accepting more data. @type remoteClosed: C{bool} """ implements(interfaces.ITransport) name = None # only needed for client channels def __init__(self, localWindow = 0, localMaxPacket = 0, remoteWindow = 0, remoteMaxPacket = 0, conn = None, data=None, avatar = None): self.localWindowSize = localWindow or 131072 self.localWindowLeft = self.localWindowSize self.localMaxPacket = localMaxPacket or 32768 self.remoteWindowLeft = remoteWindow self.remoteMaxPacket = remoteMaxPacket self.areWriting = 1 self.conn = conn self.data = data self.avatar = avatar self.specificData = '' self.buf = '' self.extBuf = [] self.closing = 0 self.localClosed = 0 self.remoteClosed = 0 self.id = None # gets set later by SSHConnection def __str__(self): return '<SSHChannel %s (lw %i rw %i)>' % (self.name, self.localWindowLeft, self.remoteWindowLeft) def logPrefix(self): id = (self.id is not None and str(self.id)) or "unknown" return "SSHChannel %s (%s) on %s" % (self.name, id, self.conn.logPrefix()) def channelOpen(self, specificData): """ Called when the channel is opened. specificData is any data that the other side sent us when opening the channel. @type specificData: C{str} """ log.msg('channel open') def openFailed(self, reason): """ Called when the the open failed for some reason. reason.desc is a string descrption, reason.code the the SSH error code. @type reason: L{error.ConchError} """ log.msg('other side refused open\nreason: %s'% reason) def addWindowBytes(self, bytes): """ Called when bytes are added to the remote window. By default it clears the data buffers. @type bytes: C{int} """ self.remoteWindowLeft = self.remoteWindowLeft+bytes if not self.areWriting and not self.closing: self.areWriting = True self.startWriting() if self.buf: b = self.buf self.buf = '' self.write(b) if self.extBuf: b = self.extBuf self.extBuf = [] for (type, data) in b: self.writeExtended(type, data) def requestReceived(self, requestType, data): """ Called when a request is sent to this channel. By default it delegates to self.request_<requestType>. If this function returns true, the request succeeded, otherwise it failed. @type requestType: C{str} @type data: C{str} @rtype: C{bool} """ foo = requestType.replace('-', '_') f = getattr(self, 'request_%s'%foo, None) if f: return f(data) log.msg('unhandled request for %s'%requestType) return 0 def dataReceived(self, data): """ Called when we receive data. @type data: C{str} """ log.msg('got data %s'%repr(data)) def extReceived(self, dataType, data): """ Called when we receive extended data (usually standard error). @type dataType: C{int} @type data: C{str} """ log.msg('got extended data %s %s'%(dataType, repr(data))) def eofReceived(self): """ Called when the other side will send no more data. """ log.msg('remote eof') def closeReceived(self): """ Called when the other side has closed the channel. """ log.msg('remote close') self.loseConnection() def closed(self): """ Called when the channel is closed. This means that both our side and the remote side have closed the channel. """ log.msg('closed') # transport stuff def write(self, data): """ Write some data to the channel. If there is not enough remote window available, buffer until it is. Otherwise, split the data into packets of length remoteMaxPacket and send them. @type data: C{str} """ if self.buf: self.buf += data return top = len(data) if top > self.remoteWindowLeft: data, self.buf = (data[:self.remoteWindowLeft], data[self.remoteWindowLeft:]) self.areWriting = 0 self.stopWriting() top = self.remoteWindowLeft rmp = self.remoteMaxPacket write = self.conn.sendData r = range(0, top, rmp) for offset in r: write(self, data[offset: offset+rmp]) self.remoteWindowLeft -= top if self.closing and not self.buf: self.loseConnection() # try again def writeExtended(self, dataType, data): """ Send extended data to this channel. If there is not enough remote window available, buffer until there is. Otherwise, split the data into packets of length remoteMaxPacket and send them. @type dataType: C{int} @type data: C{str} """ if self.extBuf: if self.extBuf[-1][0] == dataType: self.extBuf[-1][1] += data else: self.extBuf.append([dataType, data]) return if len(data) > self.remoteWindowLeft: data, self.extBuf = (data[:self.remoteWindowLeft], [[dataType, data[self.remoteWindowLeft:]]]) self.areWriting = 0 self.stopWriting() while len(data) > self.remoteMaxPacket: self.conn.sendExtendedData(self, dataType, data[:self.remoteMaxPacket]) data = data[self.remoteMaxPacket:] self.remoteWindowLeft -= self.remoteMaxPacket if data: self.conn.sendExtendedData(self, dataType, data) self.remoteWindowLeft -= len(data) if self.closing: self.loseConnection() # try again def writeSequence(self, data): """ Part of the Transport interface. Write a list of strings to the channel. @type data: C{list} of C{str} """ self.write(''.join(data)) def loseConnection(self): """ Close the channel if there is no buferred data. Otherwise, note the request and return. """ self.closing = 1 if not self.buf and not self.extBuf: self.conn.sendClose(self) def getPeer(self): """ Return a tuple describing the other side of the connection. @rtype: C{tuple} """ return('SSH', )+self.conn.transport.getPeer() def getHost(self): """ Return a tuple describing our side of the connection. @rtype: C{tuple} """ return('SSH', )+self.conn.transport.getHost() def stopWriting(self): """ Called when the remote buffer is full, as a hint to stop writing. This can be ignored, but it can be helpful. """ def startWriting(self): """ Called when the remote buffer has more room, as a hint to continue writing. """
apache-2.0
Piicksarn/cdnjs
ajax/libs/drawer/3.0.0/js/drawer.js
4381
/*! * jquery-drawer v3.0.0 * Flexible drawer menu using jQuery, iScroll and CSS. * http://git.blivesta.com/drawer * License : MIT * Author : blivesta <design@blivesta.com> (http://blivesta.com/) */ ;(function (factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else if (typeof exports === 'object') { module.exports = factory(require('jquery')); } else { factory(jQuery); } }(function($) { 'use strict'; var namespace = 'drawer'; var touches = typeof document.ontouchstart != 'undefined'; var __ = { init: function(options) { options = $.extend({ iscroll: { mouseWheel: true, preventDefault: false } }, options); __.settings = { state: false, class: { nav: 'drawer-nav', toggle: 'drawer-toggle', overlay: 'drawer-overlay', open: 'drawer-open', close: 'drawer-close', dropdown: 'drawer-dropdown' }, events: { opened: 'drawer.opened', closed: 'drawer.closed' }, dropdownEvents: { opened: 'shown.bs.dropdown', closed: 'hidden.bs.dropdown' } }; return this.each(function() { var _this = this; var $this = $(this); var data = $this.data(namespace); if (!data) { options = $.extend({}, options); $this.data(namespace, { options: options }); var iScroll = new IScroll('.' + __.settings.class.nav, options.iscroll); __.addOverlay.call(_this); $('.' + __.settings.class.toggle).on('click.' + namespace, function() { __.toggle.call(_this); return iScroll.refresh(); }); $(window).resize(function() { __.close.call(_this); return iScroll.refresh(); }); $('.' + __.settings.class.dropdown) .on(__.settings.dropdownEvents.opened + ' ' + __.settings.dropdownEvents.closed, function() { return iScroll.refresh(); }); } }); // end each }, addOverlay: function() { var _this = this; var $this = $(this); var $overlay = $('<div>').addClass(__.settings.class.overlay + ' ' + __.settings.class.toggle); return $this.append($overlay); }, toggle: function() { var _this = this; if (__.settings.state){ return __.close.call(_this); } else { return __.open.call(_this); } }, open: function(options) { var $this = $(this); options = $this.data(namespace).options; if (touches) { $this.on('touchmove.' + namespace, function(event) { event.preventDefault(); }); } return $this .removeClass(__.settings.class.close) .addClass(__.settings.class.open) .css({ 'overflow': 'hidden' }) .drawerCallback(function(){ __.settings.state = true; $this.trigger(__.settings.events.opened); }); }, close: function(options) { var $this = $(this); options = $this.data(namespace).options; if (touches) $this.off('touchmove.' + namespace); return $this .removeClass(__.settings.class.open) .addClass(__.settings.class.close) .css({ 'overflow': 'auto' }) .drawerCallback(function(){ __.settings.state = false; $this.trigger(__.settings.events.closed); }); }, destroy: function() { return this.each(function() { var $this = $(this); $(window).off('.' + namespace); $this.removeData(namespace); }); } }; $.fn.drawerCallback = function(callback){ var end = 'transitionend webkitTransitionEnd'; return this.each(function() { var $this = $(this); $this.on(end, function(){ $this.off(end); return callback.call(this); }); }); }; $.fn.drawer = function(method) { if (__[method]) { return __[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return __.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.' + namespace); } }; }));
mit
jakesays/coreclr
src/mscorlib/src/System/Reflection/Emit/SignatureHelper.cs
38843
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // namespace System.Reflection.Emit { using System.Text; using System; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Permissions; [ClassInterface(ClassInterfaceType.None)] [ComDefaultInterface(typeof(_SignatureHelper))] [System.Runtime.InteropServices.ComVisible(true)] public sealed class SignatureHelper : _SignatureHelper { #region Consts Fields private const int NO_SIZE_IN_SIG = -1; #endregion #region Static Members [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, Type returnType, Type[] parameterTypes) { return GetMethodSigHelper(mod, CallingConventions.Standard, returnType, null, null, parameterTypes, null, null); } [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType, int cGenericParam) { return GetMethodSigHelper(mod, callingConvention, cGenericParam, returnType, null, null, null, null, null); } [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, CallingConventions callingConvention, Type returnType) { return GetMethodSigHelper(mod, callingConvention, returnType, null, null, null, null, null); } internal static SignatureHelper GetMethodSpecSigHelper(Module scope, Type[] inst) { SignatureHelper sigHelp = new SignatureHelper(scope, MdSigCallingConvention.GenericInst); sigHelp.AddData(inst.Length); foreach(Type t in inst) sigHelp.AddArgument(t); return sigHelp; } [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper( Module scope, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { return GetMethodSigHelper(scope, callingConvention, 0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetMethodSigHelper( Module scope, CallingConventions callingConvention, int cGenericParam, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { SignatureHelper sigHelp; MdSigCallingConvention intCall; if (returnType == null) { returnType = typeof(void); } intCall = MdSigCallingConvention.Default; if ((callingConvention & CallingConventions.VarArgs) == CallingConventions.VarArgs) intCall = MdSigCallingConvention.Vararg; if (cGenericParam > 0) { intCall |= MdSigCallingConvention.Generic; } if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) intCall |= MdSigCallingConvention.HasThis; sigHelp = new SignatureHelper(scope, intCall, cGenericParam, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers); sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); return sigHelp; } [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetMethodSigHelper(Module mod, CallingConvention unmanagedCallConv, Type returnType) { SignatureHelper sigHelp; MdSigCallingConvention intCall; if (returnType == null) returnType = typeof(void); if (unmanagedCallConv == CallingConvention.Cdecl) { intCall = MdSigCallingConvention.C; } else if (unmanagedCallConv == CallingConvention.StdCall || unmanagedCallConv == CallingConvention.Winapi) { intCall = MdSigCallingConvention.StdCall; } else if (unmanagedCallConv == CallingConvention.ThisCall) { intCall = MdSigCallingConvention.ThisCall; } else if (unmanagedCallConv == CallingConvention.FastCall) { intCall = MdSigCallingConvention.FastCall; } else { throw new ArgumentException(Environment.GetResourceString("Argument_UnknownUnmanagedCallConv"), "unmanagedCallConv"); } sigHelp = new SignatureHelper(mod, intCall, returnType, null, null); return sigHelp; } public static SignatureHelper GetLocalVarSigHelper() { return GetLocalVarSigHelper(null); } public static SignatureHelper GetMethodSigHelper(CallingConventions callingConvention, Type returnType) { return GetMethodSigHelper(null, callingConvention, returnType); } public static SignatureHelper GetMethodSigHelper(CallingConvention unmanagedCallingConvention, Type returnType) { return GetMethodSigHelper(null, unmanagedCallingConvention, returnType); } public static SignatureHelper GetLocalVarSigHelper(Module mod) { return new SignatureHelper(mod, MdSigCallingConvention.LocalSig); } public static SignatureHelper GetFieldSigHelper(Module mod) { return new SignatureHelper(mod, MdSigCallingConvention.Field); } public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] parameterTypes) { return GetPropertySigHelper(mod, returnType, null, null, parameterTypes, null, null); } public static SignatureHelper GetPropertySigHelper(Module mod, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { return GetPropertySigHelper(mod, (CallingConventions)0, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers, parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); } [System.Security.SecuritySafeCritical] // auto-generated public static SignatureHelper GetPropertySigHelper(Module mod, CallingConventions callingConvention, Type returnType, Type[] requiredReturnTypeCustomModifiers, Type[] optionalReturnTypeCustomModifiers, Type[] parameterTypes, Type[][] requiredParameterTypeCustomModifiers, Type[][] optionalParameterTypeCustomModifiers) { SignatureHelper sigHelp; if (returnType == null) { returnType = typeof(void); } MdSigCallingConvention intCall = MdSigCallingConvention.Property; if ((callingConvention & CallingConventions.HasThis) == CallingConventions.HasThis) intCall |= MdSigCallingConvention.HasThis; sigHelp = new SignatureHelper(mod, intCall, returnType, requiredReturnTypeCustomModifiers, optionalReturnTypeCustomModifiers); sigHelp.AddArguments(parameterTypes, requiredParameterTypeCustomModifiers, optionalParameterTypeCustomModifiers); return sigHelp; } [System.Security.SecurityCritical] // auto-generated internal static SignatureHelper GetTypeSigToken(Module mod, Type type) { if (mod == null) throw new ArgumentNullException("module"); if (type == null) throw new ArgumentNullException("type"); return new SignatureHelper(mod, type); } #endregion #region Private Data Members private byte[] m_signature; private int m_currSig; // index into m_signature buffer for next available byte private int m_sizeLoc; // index into m_signature buffer to put m_argCount (will be NO_SIZE_IN_SIG if no arg count is needed) private ModuleBuilder m_module; private bool m_sigDone; private int m_argCount; // tracking number of arguments in the signature #endregion #region Constructor private SignatureHelper(Module mod, MdSigCallingConvention callingConvention) { // Use this constructor to instantiate a local var sig or Field where return type is not applied. Init(mod, callingConvention); } [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, int cGenericParameters, Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { // Use this constructor to instantiate a any signatures that will require a return type. Init(mod, callingConvention, cGenericParameters); if (callingConvention == MdSigCallingConvention.Field) throw new ArgumentException(Environment.GetResourceString("Argument_BadFieldSig")); AddOneArgTypeHelper(returnType, requiredCustomModifiers, optionalCustomModifiers); } [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, MdSigCallingConvention callingConvention, Type returnType, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) : this(mod, callingConvention, 0, returnType, requiredCustomModifiers, optionalCustomModifiers) { } [System.Security.SecurityCritical] // auto-generated private SignatureHelper(Module mod, Type type) { Init(mod); AddOneArgTypeHelper(type); } private void Init(Module mod) { m_signature = new byte[32]; m_currSig = 0; m_module = mod as ModuleBuilder; m_argCount = 0; m_sigDone = false; m_sizeLoc = NO_SIZE_IN_SIG; if (m_module == null && mod != null) throw new ArgumentException(Environment.GetResourceString("NotSupported_MustBeModuleBuilder")); } private void Init(Module mod, MdSigCallingConvention callingConvention) { Init(mod, callingConvention, 0); } private void Init(Module mod, MdSigCallingConvention callingConvention, int cGenericParam) { Init(mod); AddData((byte)callingConvention); if (callingConvention == MdSigCallingConvention.Field || callingConvention == MdSigCallingConvention.GenericInst) { m_sizeLoc = NO_SIZE_IN_SIG; } else { if (cGenericParam > 0) AddData(cGenericParam); m_sizeLoc = m_currSig++; } } #endregion #region Private Members [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type argument, bool pinned) { if (pinned) AddElementType(CorElementType.Pinned); AddOneArgTypeHelper(argument); } [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type clsArgument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { // This function will not increase the argument count. It only fills in bytes // in the signature based on clsArgument. This helper is called for return type. Contract.Requires(clsArgument != null); Contract.Requires((optionalCustomModifiers == null && requiredCustomModifiers == null) || !clsArgument.ContainsGenericParameters); if (optionalCustomModifiers != null) { for (int i = 0; i < optionalCustomModifiers.Length; i++) { Type t = optionalCustomModifiers[i]; if (t == null) throw new ArgumentNullException("optionalCustomModifiers"); if (t.HasElementType) throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "optionalCustomModifiers"); if (t.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "optionalCustomModifiers"); AddElementType(CorElementType.CModOpt); int token = m_module.GetTypeToken(t).Token; Contract.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } } if (requiredCustomModifiers != null) { for (int i = 0; i < requiredCustomModifiers.Length; i++) { Type t = requiredCustomModifiers[i]; if (t == null) throw new ArgumentNullException("requiredCustomModifiers"); if (t.HasElementType) throw new ArgumentException(Environment.GetResourceString("Argument_ArraysInvalid"), "requiredCustomModifiers"); if (t.ContainsGenericParameters) throw new ArgumentException(Environment.GetResourceString("Argument_GenericsInvalid"), "requiredCustomModifiers"); AddElementType(CorElementType.CModReqd); int token = m_module.GetTypeToken(t).Token; Contract.Assert(!MetadataToken.IsNullToken(token)); AddToken(token); } } AddOneArgTypeHelper(clsArgument); } [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelper(Type clsArgument) { AddOneArgTypeHelperWorker(clsArgument, false); } [System.Security.SecurityCritical] // auto-generated private void AddOneArgTypeHelperWorker(Type clsArgument, bool lastWasGenericInst) { if (clsArgument.IsGenericParameter) { if (clsArgument.DeclaringMethod != null) AddElementType(CorElementType.MVar); else AddElementType(CorElementType.Var); AddData(clsArgument.GenericParameterPosition); } else if (clsArgument.IsGenericType && (!clsArgument.IsGenericTypeDefinition || !lastWasGenericInst)) { AddElementType(CorElementType.GenericInst); AddOneArgTypeHelperWorker(clsArgument.GetGenericTypeDefinition(), true); Type[] args = clsArgument.GetGenericArguments(); AddData(args.Length); foreach (Type t in args) AddOneArgTypeHelper(t); } else if (clsArgument is TypeBuilder) { TypeBuilder clsBuilder = (TypeBuilder)clsArgument; TypeToken tkType; if (clsBuilder.Module.Equals(m_module)) { tkType = clsBuilder.TypeToken; } else { tkType = m_module.GetTypeToken(clsArgument); } if (clsArgument.IsValueType) { InternalAddTypeToken(tkType, CorElementType.ValueType); } else { InternalAddTypeToken(tkType, CorElementType.Class); } } else if (clsArgument is EnumBuilder) { TypeBuilder clsBuilder = ((EnumBuilder)clsArgument).m_typeBuilder; TypeToken tkType; if (clsBuilder.Module.Equals(m_module)) { tkType = clsBuilder.TypeToken; } else { tkType = m_module.GetTypeToken(clsArgument); } if (clsArgument.IsValueType) { InternalAddTypeToken(tkType, CorElementType.ValueType); } else { InternalAddTypeToken(tkType, CorElementType.Class); } } else if (clsArgument.IsByRef) { AddElementType(CorElementType.ByRef); clsArgument = clsArgument.GetElementType(); AddOneArgTypeHelper(clsArgument); } else if (clsArgument.IsPointer) { AddElementType(CorElementType.Ptr); AddOneArgTypeHelper(clsArgument.GetElementType()); } else if (clsArgument.IsArray) { if (clsArgument.IsSzArray) { AddElementType(CorElementType.SzArray); AddOneArgTypeHelper(clsArgument.GetElementType()); } else { AddElementType(CorElementType.Array); AddOneArgTypeHelper(clsArgument.GetElementType()); // put the rank information int rank = clsArgument.GetArrayRank(); AddData(rank); // rank AddData(0); // upper bounds AddData(rank); // lower bound for (int i = 0; i < rank; i++) AddData(0); } } else { CorElementType type = CorElementType.Max; if (clsArgument is RuntimeType) { type = RuntimeTypeHandle.GetCorElementType((RuntimeType)clsArgument); //GetCorElementType returns CorElementType.Class for both object and string if (type == CorElementType.Class) { if (clsArgument == typeof(object)) type = CorElementType.Object; else if (clsArgument == typeof(string)) type = CorElementType.String; } } if (IsSimpleType(type)) { AddElementType(type); } else if (m_module == null) { InternalAddRuntimeType(clsArgument); } else if (clsArgument.IsValueType) { InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.ValueType); } else { InternalAddTypeToken(m_module.GetTypeToken(clsArgument), CorElementType.Class); } } } private void AddData(int data) { // A managed representation of CorSigCompressData; if (m_currSig + 4 > m_signature.Length) { m_signature = ExpandArray(m_signature); } if (data <= 0x7F) { m_signature[m_currSig++] = (byte)(data & 0xFF); } else if (data <= 0x3FFF) { m_signature[m_currSig++] = (byte)((data >>8) | 0x80); m_signature[m_currSig++] = (byte)(data & 0xFF); } else if (data <= 0x1FFFFFFF) { m_signature[m_currSig++] = (byte)((data >>24) | 0xC0); m_signature[m_currSig++] = (byte)((data >>16) & 0xFF); m_signature[m_currSig++] = (byte)((data >>8) & 0xFF); m_signature[m_currSig++] = (byte)((data) & 0xFF); } else { throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger")); } } private void AddData(uint data) { if (m_currSig + 4 > m_signature.Length) { m_signature = ExpandArray(m_signature); } m_signature[m_currSig++] = (byte)((data) & 0xFF); m_signature[m_currSig++] = (byte)((data>>8) & 0xFF); m_signature[m_currSig++] = (byte)((data>>16) & 0xFF); m_signature[m_currSig++] = (byte)((data>>24) & 0xFF); } private void AddData(ulong data) { if (m_currSig + 8 > m_signature.Length) { m_signature = ExpandArray(m_signature); } m_signature[m_currSig++] = (byte)((data) & 0xFF); m_signature[m_currSig++] = (byte)((data>>8) & 0xFF); m_signature[m_currSig++] = (byte)((data>>16) & 0xFF); m_signature[m_currSig++] = (byte)((data>>24) & 0xFF); m_signature[m_currSig++] = (byte)((data>>32) & 0xFF); m_signature[m_currSig++] = (byte)((data>>40) & 0xFF); m_signature[m_currSig++] = (byte)((data>>48) & 0xFF); m_signature[m_currSig++] = (byte)((data>>56) & 0xFF); } private void AddElementType(CorElementType cvt) { // Adds an element to the signature. A managed represenation of CorSigCompressElement if (m_currSig + 1 > m_signature.Length) m_signature = ExpandArray(m_signature); m_signature[m_currSig++] = (byte)cvt; } private void AddToken(int token) { // A managed represenation of CompressToken // Pulls the token appart to get a rid, adds some appropriate bits // to the token and then adds this to the signature. int rid = (token & 0x00FFFFFF); //This is RidFromToken; MetadataTokenType type = (MetadataTokenType)(token & unchecked((int)0xFF000000)); //This is TypeFromToken; if (rid > 0x3FFFFFF) { // token is too big to be compressed throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger")); } rid = (rid << 2); // TypeDef is encoded with low bits 00 // TypeRef is encoded with low bits 01 // TypeSpec is encoded with low bits 10 if (type == MetadataTokenType.TypeRef) { //if type is mdtTypeRef rid|=0x1; } else if (type == MetadataTokenType.TypeSpec) { //if type is mdtTypeSpec rid|=0x2; } AddData(rid); } private void InternalAddTypeToken(TypeToken clsToken, CorElementType CorType) { // Add a type token into signature. CorType will be either CorElementType.Class or CorElementType.ValueType AddElementType(CorType); AddToken(clsToken.Token); } [System.Security.SecurityCritical] // auto-generated private unsafe void InternalAddRuntimeType(Type type) { // Add a runtime type into the signature. AddElementType(CorElementType.Internal); IntPtr handle = type.GetTypeHandleInternal().Value; // Internal types must have their pointer written into the signature directly (we don't // want to convert to little-endian format on big-endian machines because the value is // going to be extracted and used directly as a pointer (and only within this process)). if (m_currSig + sizeof(void*) > m_signature.Length) m_signature = ExpandArray(m_signature); byte *phandle = (byte*)&handle; for (int i = 0; i < sizeof(void*); i++) m_signature[m_currSig++] = phandle[i]; } private byte[] ExpandArray(byte[] inArray) { // Expand the signature buffer size return ExpandArray(inArray, inArray.Length * 2); } private byte[] ExpandArray(byte[] inArray, int requiredLength) { // Expand the signature buffer size if (requiredLength < inArray.Length) requiredLength = inArray.Length*2; byte[] outArray = new byte[requiredLength]; Array.Copy(inArray, outArray, inArray.Length); return outArray; } private void IncrementArgCounts() { if (m_sizeLoc == NO_SIZE_IN_SIG) { //We don't have a size if this is a field. return; } m_argCount++; } private void SetNumberOfSignatureElements(bool forceCopy) { // For most signatures, this will set the number of elements in a byte which we have reserved for it. // However, if we have a field signature, we don't set the length and return. // If we have a signature with more than 128 arguments, we can't just set the number of elements, // we actually have to allocate more space (e.g. shift everything in the array one or more spaces to the // right. We do this by making a copy of the array and leaving the correct number of blanks. This new // array is now set to be m_signature and we use the AddData method to set the number of elements properly. // The forceCopy argument can be used to force SetNumberOfSignatureElements to make a copy of // the array. This is useful for GetSignature which promises to trim the array to be the correct size anyway. byte[] temp; int newSigSize; int currSigHolder = m_currSig; if (m_sizeLoc == NO_SIZE_IN_SIG) return; //If we have fewer than 128 arguments and we haven't been told to copy the //array, we can just set the appropriate bit and return. if (m_argCount < 0x80 && !forceCopy) { m_signature[m_sizeLoc] = (byte)m_argCount; return; } //We need to have more bytes for the size. Figure out how many bytes here. //Since we need to copy anyway, we're just going to take the cost of doing a //new allocation. if (m_argCount < 0x80) { newSigSize = 1; } else if (m_argCount < 0x4000) { newSigSize = 2; } else { newSigSize = 4; } //Allocate the new array. temp = new byte[m_currSig + newSigSize - 1]; //Copy the calling convention. The calling convention is always just one byte //so we just copy that byte. Then copy the rest of the array, shifting everything //to make room for the new number of elements. temp[0] = m_signature[0]; Array.Copy(m_signature, m_sizeLoc + 1, temp, m_sizeLoc + newSigSize, currSigHolder - (m_sizeLoc + 1)); m_signature = temp; //Use the AddData method to add the number of elements appropriately compressed. m_currSig = m_sizeLoc; AddData(m_argCount); m_currSig = currSigHolder + (newSigSize - 1); } #endregion #region Internal Members internal int ArgumentCount { get { return m_argCount; } } internal static bool IsSimpleType(CorElementType type) { if (type <= CorElementType.String) return true; if (type == CorElementType.TypedByRef || type == CorElementType.I || type == CorElementType.U || type == CorElementType.Object) return true; return false; } internal byte[] InternalGetSignature(out int length) { // An internal method to return the signature. Does not trim the // array, but passes out the length of the array in an out parameter. // This is the actual array -- not a copy -- so the callee must agree // to not copy it. // // param length : an out param indicating the length of the array. // return : A reference to the internal ubyte array. if (!m_sigDone) { m_sigDone = true; // If we have more than 128 variables, we can't just set the length, we need // to compress it. Unfortunately, this means that we need to copy the entire // array. Bummer, eh? SetNumberOfSignatureElements(false); } length = m_currSig; return m_signature; } internal byte[] InternalGetSignatureArray() { int argCount = m_argCount; int currSigLength = m_currSig; int newSigSize = currSigLength; //Allocate the new array. if (argCount < 0x7F) newSigSize += 1; else if (argCount < 0x3FFF) newSigSize += 2; else newSigSize += 4; byte[] temp = new byte[newSigSize]; // copy the sig int sigCopyIndex = 0; // calling convention temp[sigCopyIndex++] = m_signature[0]; // arg size if (argCount <= 0x7F) temp[sigCopyIndex++] = (byte)(argCount & 0xFF); else if (argCount <= 0x3FFF) { temp[sigCopyIndex++] = (byte)((argCount >>8) | 0x80); temp[sigCopyIndex++] = (byte)(argCount & 0xFF); } else if (argCount <= 0x1FFFFFFF) { temp[sigCopyIndex++] = (byte)((argCount >>24) | 0xC0); temp[sigCopyIndex++] = (byte)((argCount >>16) & 0xFF); temp[sigCopyIndex++] = (byte)((argCount >>8) & 0xFF); temp[sigCopyIndex++] = (byte)((argCount) & 0xFF); } else throw new ArgumentException(Environment.GetResourceString("Argument_LargeInteger")); // copy the sig part of the sig Array.Copy(m_signature, 2, temp, sigCopyIndex, currSigLength - 2); // mark the end of sig temp[newSigSize - 1] = (byte)CorElementType.End; return temp; } #endregion #region Public Methods public void AddArgument(Type clsArgument) { AddArgument(clsArgument, null, null); } [System.Security.SecuritySafeCritical] // auto-generated public void AddArgument(Type argument, bool pinned) { if (argument == null) throw new ArgumentNullException("argument"); IncrementArgCounts(); AddOneArgTypeHelper(argument, pinned); } public void AddArguments(Type[] arguments, Type[][] requiredCustomModifiers, Type[][] optionalCustomModifiers) { if (requiredCustomModifiers != null && (arguments == null || requiredCustomModifiers.Length != arguments.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "requiredCustomModifiers", "arguments")); if (optionalCustomModifiers != null && (arguments == null || optionalCustomModifiers.Length != arguments.Length)) throw new ArgumentException(Environment.GetResourceString("Argument_MismatchedArrays", "optionalCustomModifiers", "arguments")); if (arguments != null) { for (int i =0; i < arguments.Length; i++) { AddArgument(arguments[i], requiredCustomModifiers == null ? null : requiredCustomModifiers[i], optionalCustomModifiers == null ? null : optionalCustomModifiers[i]); } } } [System.Security.SecuritySafeCritical] // auto-generated public void AddArgument(Type argument, Type[] requiredCustomModifiers, Type[] optionalCustomModifiers) { if (m_sigDone) throw new ArgumentException(Environment.GetResourceString("Argument_SigIsFinalized")); if (argument == null) throw new ArgumentNullException("argument"); IncrementArgCounts(); // Add an argument to the signature. Takes a Type and determines whether it // is one of the primitive types of which we have special knowledge or a more // general class. In the former case, we only add the appropriate short cut encoding, // otherwise we will calculate proper description for the type. AddOneArgTypeHelper(argument, requiredCustomModifiers, optionalCustomModifiers); } public void AddSentinel() { AddElementType(CorElementType.Sentinel); } public override bool Equals(Object obj) { if (!(obj is SignatureHelper)) { return false; } SignatureHelper temp = (SignatureHelper)obj; if ( !temp.m_module.Equals(m_module) || temp.m_currSig!=m_currSig || temp.m_sizeLoc!=m_sizeLoc || temp.m_sigDone !=m_sigDone ) { return false; } for (int i=0; i<m_currSig; i++) { if (m_signature[i]!=temp.m_signature[i]) return false; } return true; } public override int GetHashCode() { // Start the hash code with the hash code of the module and the values of the member variables. int HashCode = m_module.GetHashCode() + m_currSig + m_sizeLoc; // Add one if the sig is done. if (m_sigDone) HashCode += 1; // Then add the hash code of all the arguments. for (int i=0; i < m_currSig; i++) HashCode += m_signature[i].GetHashCode(); return HashCode; } public byte[] GetSignature() { return GetSignature(false); } internal byte[] GetSignature(bool appendEndOfSig) { // Chops the internal signature to the appropriate length. Adds the // end token to the signature and marks the signature as finished so that // no further tokens can be added. Return the full signature in a trimmed array. if (!m_sigDone) { if (appendEndOfSig) AddElementType(CorElementType.End); SetNumberOfSignatureElements(true); m_sigDone = true; } // This case will only happen if the user got the signature through // InternalGetSignature first and then called GetSignature. if (m_signature.Length > m_currSig) { byte[] temp = new byte[m_currSig]; Array.Copy(m_signature, temp, m_currSig); m_signature = temp; } return m_signature; } public override String ToString() { StringBuilder sb = new StringBuilder(); sb.Append("Length: " + m_currSig + Environment.NewLine); if (m_sizeLoc != -1) { sb.Append("Arguments: " + m_signature[m_sizeLoc] + Environment.NewLine); } else { sb.Append("Field Signature" + Environment.NewLine); } sb.Append("Signature: " + Environment.NewLine); for (int i=0; i<=m_currSig; i++) { sb.Append(m_signature[i] + " "); } sb.Append(Environment.NewLine); return sb.ToString(); } #endregion #if !FEATURE_CORECLR void _SignatureHelper.GetTypeInfoCount(out uint pcTInfo) { throw new NotImplementedException(); } void _SignatureHelper.GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo) { throw new NotImplementedException(); } void _SignatureHelper.GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId) { throw new NotImplementedException(); } void _SignatureHelper.Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr) { throw new NotImplementedException(); } #endif } }
mit
dongguangming/django-oscar
src/oscar/apps/wishlists/models.py
389
# -*- coding: utf-8 -*- from oscar.core.loading import is_model_registered from .abstract_models import * # noqa __all__ = [] if not is_model_registered('wishlists', 'WishList'): class WishList(AbstractWishList): pass __all__.append('WishList') if not is_model_registered('wishlists', 'Line'): class Line(AbstractLine): pass __all__.append('Line')
bsd-3-clause
jianpingw/sails
errors/fatal.js
8500
/** * Module dependencies */ var nodeutil = require('util'); var nodepath = require('path'); // Build logger using best-available information // when this module is initially required. var log = require('captains-log')(require('../lib/app/configuration/rc')); /** * Fatal Errors */ module.exports = { // Lift-time and load-time errors failedToLoadSails: function(err) { log.error(err); log.error('Could not load Sails.'); log.error('Are you using the latest stable version?'); _terminateProcess(1); }, noPackageJSON: function() { log.error('Cannot read package.json in the current directory (' + process.cwd() + ')'); log.error('Are you sure this is a Sails app?'); _terminateProcess(1); }, notSailsApp: function() { log.error('The package.json in the current directory does not list Sails as a dependency...'); log.error('Are you sure `' + process.cwd() + '` is a Sails app?'); _terminateProcess(1); }, badLocalDependency: function(pathTo_localSails, requiredVersion) { log.error( 'The local Sails dependency installed at `' + pathTo.localSails + '` ' + 'has a corrupted, missing, or un-parsable package.json file.' ); log.error('You may consider running:'); log.error('rm -rf ' + pathTo_localSails + ' && npm install sails@' + app.dependencies.sails); _terminateProcess(1); }, // TODO: replace the inline version of this error // app/loadHooks.js:42 malformedHook: function() { log.error('Malformed hook! (' + id + ')'); log.error('Hooks should be a function with one argument (`sails`)'); _terminateProcess(1); }, // TODO: replace the inline version of this error // app/load.js:146 hooksTookTooLong: function() { var hooksTookTooLongErr = 'Hooks are taking way too long to get ready... ' + 'Something might be amiss.\nAre you using any custom hooks?\nIf so, make sure the hook\'s ' + '`initialize()` method is triggering its callback.'; log.error(hooksTookTooLongErr); process.exit(1); }, // Invalid user module errors invalidCustomResponse: function(responseIdentity) { log.error('Cannot define custom response `' + responseIdentity + '`.'); log.error('`res.' + responseIdentity + '` has special meaning in Connect/Express/Sails.'); log.error('Please remove the `' + responseIdentity + '` file from the `responses` directory.'); _terminateProcess(1); }, // This doesn't technically _need_ to be a fatal error- it just is // because certain grunt modules (e.g. grunt-contrib-watch) don't restart // when an error occurs. __GruntAborted__: function(consoleMsg, stackTrace) { var gruntErr = '\n------------------------------------------------------------------------\n' + consoleMsg + '\n' + (stackTrace || '') + '\n------------------------------------------------------------------------'; log.error(gruntErr); log.blank(); log.error('Looks like a Grunt error occurred--'); log.error('Please fix it, then **restart Sails** to continue running tasks (e.g. watching for changes in assets)'); log.error('Or if you\'re stuck, check out the troubleshooting tips below.'); log.blank(); log.error('Troubleshooting tips:'.underline); var relativePublicPath = (nodepath.resolve(process.cwd(), './.tmp')); var uid = process.getuid && process.getuid() || 'YOUR_COMPUTER_USER_NAME'; log.error(); log.error(' *-> Are "grunt" and related grunt task modules installed locally? Run `npm install` if you\'re not sure.'); log.error(); log.error(' *-> You might have a malformed LESS, SASS, CoffeeScript file, etc.'); log.error(); log.error(' *-> Or maybe you don\'t have permissions to access the `.tmp` directory?'); log.error(' e.g., `' + relativePublicPath + '`', '?'); log.error(); log.error(' If you think this might be the case, try running:'); log.error(' sudo chown -R', uid, relativePublicPath); log.blank(); // See note above this function - for now, this will not // actually terminate the process. The rest of Sails should // continue to run. // return _terminateProcess(1); }, __UnknownPolicy__: function(policy, source, pathToPolicies) { source = source || 'config.policies'; log.error('Unknown policy, "' + policy + '", referenced in `' + source + '`.'); log.error('Are you sure that policy exists?'); log.error('It would be located at: `' + pathToPolicies + '/' + policy + '.js`'); return _terminateProcess(1); }, __InvalidConnection__: function(connection, sourceModelId) { log.error('In model (' + sourceModelId + '), invalid connection ::', connection); log.error('Must contain an `adapter` key referencing the adapter to use.'); return _terminateProcess(1); }, __UnknownConnection__: function(connectionId, sourceModelId) { log.error('Unknown connection, "' + connectionId + '", referenced in model `' + sourceModelId + '`.'); log.error('Are you sure that connection exists? It should be defined in `sails.config.connections`.'); // var probableAdapterModuleName = connectionId.toLowerCase(); // if ( ! probableAdapterModuleName.match(/^(sails-|waterline-)/) ) { // probableAdapterModuleName = 'sails-' + probableAdapterModuleName; // } // log.error('Otherwise, if you\'re trying to use an adapter named `' + connectionId + '`, please run ' + // '`npm install ' + probableAdapterModuleName + '@' + sails.majorVersion + '.' + sails.minorVersion + '.x`'); return _terminateProcess(1); }, __ModelIsMissingConnection__: function(sourceModelId) { log.error(nodeutil.format('One of your models (%s) doesn\'t have a connection.', sourceModelId)); log.error('Do you have a default `connection` in your `config/models.js` file?'); return _terminateProcess(1); }, __UnknownAdapter__: function(adapterId, sourceModelId, sailsMajorV, sailsMinorV) { log.error('Trying to use unknown adapter, "' + adapterId + '", in model `' + sourceModelId + '`.'); log.error('Are you sure that adapter is installed in this Sails app?'); log.error('If you wrote a custom adapter with identity="' + adapterId + '", it should be in this app\'s adapters directory.'); var probableAdapterModuleName = adapterId.toLowerCase(); if (!probableAdapterModuleName.match(/^(sails-|waterline-)/)) { probableAdapterModuleName = 'sails-' + probableAdapterModuleName; } log.error('Otherwise, if you\'re trying to use an adapter named `' + adapterId + '`, please run ' + '`npm install ' + probableAdapterModuleName + ' --save'/*'@' + sailsMajorV + '.' + sailsMinorV + '.x`'*/); return _terminateProcess(1); }, __InvalidAdapter__: function(attemptedModuleName, supplementalErrMsg) { log.error('There was an error attempting to require("' + attemptedModuleName + '")'); log.error('Is this a valid Sails/Waterline adapter? The following error was encountered ::'); log.error(supplementalErrMsg); return _terminateProcess(1); } }; /** * * TODO: Make all of this more elegant. * ======================================================== * + Ideally we don't call `process.exit()` at all. * We should consistently use `sails.lower()` for unhandleable core * errors and just trigger the appropriate callback w/ an error for * core lift/load and any CLI errors. * * + Then we won't have to worry as much about dangling child processes * and things like that. Plus it's more testable that way. * * In practice, the best way to do this may be an error domain or an * event emitted on the sails object (or both!) * ======================================================== * * * * TODO: Merge w/ app/teardown.js * ======================================================== * (probably achievable by doing the aforementioned cleanup) * ======================================================== */ /** * _terminateProcess * * Terminate the process as elegantly as possible. * If process.env is 'test', throw instead. * * @param {[type]} code [console error code] * @param {[type]} opts [currently unused] */ function _terminateProcess(code, opts) { if (process.env.NODE_ENV === 'test') { var Signal = new Error({ type: 'terminate', code: code, options: { todo: 'put the stuff from the original errors in here' } }); throw Signal; } return process.exit(code); }
mit
dannyxx001/cdnjs
ajax/libs/peity/0.3.4/jquery.peity.min.js
2123
// Peity jQuery plugin version 0.3.4 // (c) 2010 Ben Pickles // // http://benpickles.github.com/peity/ // // Released under MIT license. (function(j,m){function l(e,a){var b=m.createElement("canvas");b.setAttribute("width",e);b.setAttribute("height",a);return b}var i=j.fn.peity=function(e,a){m.createElement("canvas").getContext&&this.each(function(){j(this).change(function(){var b=j(this).html();i.graphers[e](j(this),j.extend({},i.defaults[e],a));j(this).trigger("chart:changed",b)}).trigger("change")});return this};i.graphers={};i.defaults={};i.add=function(e,a,b){i.graphers[e]=b;i.defaults[e]=a};i.add("pie",{colours:["#FFF4DD","#FF9900"], delimeter:"/",radius:16},function(e,a){var b=a.radius/2,d=e.text().split(a.delimeter),h=parseFloat(d[0]),k=parseFloat(d[1]);d=-Math.PI/2;h=h/k*Math.PI*2;k=l(a.radius,a.radius);var c=k.getContext("2d");c.beginPath();c.moveTo(b,b);c.arc(b,b,b,h+d,d,false);c.fillStyle=a.colours[0];c.fill();c.beginPath();c.moveTo(b,b);c.arc(b,b,b,d,h+d,false);c.fillStyle=a.colours[1];c.fill();e.wrapInner(j("<span>").hide()).append(k)});i.add("line",{colour:"#c6d9fd",strokeColour:"#4d89f9",strokeWidth:1,delimeter:",", height:16,max:null,width:32},function(e,a){var b=l(a.width,a.height),d=e.text().split(a.delimeter),h=Math.max.apply(Math,d.concat([a.max]));h=a.height/h;var k=a.width/(d.length-1),c=[],f,g=b.getContext("2d");g.beginPath();g.moveTo(0,a.height);for(f=0;f<d.length;f++){var n=f*k,o=a.height-h*d[f];c.push({x:n,y:o});g.lineTo(n,o)}g.lineTo(a.width,a.height);g.fillStyle=a.colour;g.fill();g.beginPath();g.moveTo(0,c[0].y);for(f=0;f<c.length;f++)g.lineTo(c[f].x,c[f].y);g.lineWidth=a.strokeWidth;g.strokeStyle= a.strokeColour;g.stroke();e.wrapInner(j("<span>").hide()).append(b)});i.add("bar",{colour:"#4D89F9",delimeter:",",height:16,max:null,width:32},function(e,a){var b=l(a.width,a.height),d=e.text().split(a.delimeter),h=Math.max.apply(Math,d.concat([a.max]));h=a.height/h;var k=a.width/d.length,c=b.getContext("2d");c.fillStyle=a.colour;for(var f=0;f<d.length;f++){var g=h*d[f];c.fillRect(f*k,a.height-g,k,g)}e.wrapInner(j("<span>").hide()).append(b)})})(jQuery,document);
mit
michaelgallacher/intellij-community
python/lib/Lib/site-packages/django/contrib/auth/management/commands/changepassword.py
1527
from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User import getpass class Command(BaseCommand): help = "Change a user's password for django.contrib.auth." requires_model_validation = False def _get_pass(self, prompt="Password: "): p = getpass.getpass(prompt=prompt) if not p: raise CommandError("aborted") return p def handle(self, *args, **options): if len(args) > 1: raise CommandError("need exactly one or zero arguments for username") if args: username, = args else: username = getpass.getuser() try: u = User.objects.get(username=username) except User.DoesNotExist: raise CommandError("user '%s' does not exist" % username) print "Changing password for user '%s'" % u.username MAX_TRIES = 3 count = 0 p1, p2 = 1, 2 # To make them initially mismatch. while p1 != p2 and count < MAX_TRIES: p1 = self._get_pass() p2 = self._get_pass("Password (again): ") if p1 != p2: print "Passwords do not match. Please try again." count = count + 1 if count == MAX_TRIES: raise CommandError("Aborting password change for user '%s' after %s attempts" % (username, count)) u.set_password(p1) u.save() return "Password changed successfully for user '%s'" % u.username
apache-2.0
matrix-msu/Kora3
vendor/symfony/mime/Tests/Part/Multipart/DigestPartTest.php
836
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Mime\Tests\Part\Multipart; use PHPUnit\Framework\TestCase; use Symfony\Component\Mime\Message; use Symfony\Component\Mime\Part\MessagePart; use Symfony\Component\Mime\Part\Multipart\DigestPart; class DigestPartTest extends TestCase { public function testConstructor() { $r = new DigestPart($a = new MessagePart(new Message()), $b = new MessagePart(new Message())); $this->assertEquals('multipart', $r->getMediaType()); $this->assertEquals('digest', $r->getMediaSubtype()); $this->assertEquals([$a, $b], $r->getParts()); } }
gpl-2.0
whuwxl/kubernetes
pkg/registry/core/configmap/storage/storage.go
1898
/* Copyright 2015 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package storage import ( "k8s.io/apimachinery/pkg/runtime" "k8s.io/apiserver/pkg/registry/generic" genericregistry "k8s.io/apiserver/pkg/registry/generic/registry" "k8s.io/apiserver/pkg/registry/rest" api "k8s.io/kubernetes/pkg/apis/core" "k8s.io/kubernetes/pkg/registry/core/configmap" ) // REST implements a RESTStorage for ConfigMap type REST struct { *genericregistry.Store } // NewREST returns a RESTStorage object that will work with ConfigMap objects. func NewREST(optsGetter generic.RESTOptionsGetter) *REST { store := &genericregistry.Store{ NewFunc: func() runtime.Object { return &api.ConfigMap{} }, NewListFunc: func() runtime.Object { return &api.ConfigMapList{} }, DefaultQualifiedResource: api.Resource("configmaps"), CreateStrategy: configmap.Strategy, UpdateStrategy: configmap.Strategy, DeleteStrategy: configmap.Strategy, } options := &generic.StoreOptions{RESTOptions: optsGetter} if err := store.CompleteWithOptions(options); err != nil { panic(err) // TODO: Propagate error up } return &REST{store} } // Implement ShortNamesProvider var _ rest.ShortNamesProvider = &REST{} // ShortNames implements the ShortNamesProvider interface. Returns a list of short names for a resource. func (r *REST) ShortNames() []string { return []string{"cm"} }
apache-2.0
piquadrat/django
django/conf/locale/ca/formats.py
949
# This file is distributed under the same license as the Django package. # # The *_FORMAT strings use the Django date format syntax, # see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date DATE_FORMAT = r'j \d\e F \d\e Y' TIME_FORMAT = 'G:i' DATETIME_FORMAT = r'j \d\e F \d\e Y \a \l\e\s G:i' YEAR_MONTH_FORMAT = r'F \d\e\l Y' MONTH_DAY_FORMAT = r'j \d\e F' SHORT_DATE_FORMAT = 'd/m/Y' SHORT_DATETIME_FORMAT = 'd/m/Y G:i' FIRST_DAY_OF_WEEK = 1 # Monday # The *_INPUT_FORMATS strings use the Python strftime format syntax, # see http://docs.python.org/library/datetime.html#strftime-strptime-behavior DATE_INPUT_FORMATS = [ # '31/12/2009', '31/12/09' '%d/%m/%Y', '%d/%m/%y' ] DATETIME_INPUT_FORMATS = [ '%d/%m/%Y %H:%M:%S', '%d/%m/%Y %H:%M:%S.%f', '%d/%m/%Y %H:%M', '%d/%m/%y %H:%M:%S', '%d/%m/%y %H:%M:%S.%f', '%d/%m/%y %H:%M', ] DECIMAL_SEPARATOR = ',' THOUSAND_SEPARATOR = '.' NUMBER_GROUPING = 3
bsd-3-clause
marc17/gepi
lib/dojo/dojox/atom/widget/nls/nb/FeedViewerEntry.js.uncompressed.js
86
define( "dojox/atom/widget/nls/nb/FeedViewerEntry", ({ deleteButton: "[Slett]" }) );
gpl-2.0
TaurusTiger/binnavi
src/main/java/com/google/security/zynamics/binnavi/Gui/Debug/Bookmarks/CBookmarkTable.java
3570
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.security.zynamics.binnavi.Gui.Debug.Bookmarks; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import javax.swing.JTable; import javax.swing.ListSelectionModel; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.Gui.Actions.CActionProxy; import com.google.security.zynamics.binnavi.Gui.Debug.Bookmarks.Actions.CDeleteBookmarkAction; import com.google.security.zynamics.binnavi.debug.debugger.BackEndDebuggerProvider; /** * Table control that is used to display memory bookmarks. */ public final class CBookmarkTable extends JTable { /** * Used for serialization. */ private static final long serialVersionUID = 9126742953580510079L; /** * Bookmark table model. */ private final CBookmarkTableModel m_model; /** * Provides the debuggers where breakpoints can be set. */ private final BackEndDebuggerProvider m_debuggerProvider; /** * Creates a new bookmark table. * * @param debuggerProvider Provides the debuggers where breakpoints can be set. */ public CBookmarkTable(final BackEndDebuggerProvider debuggerProvider) { m_debuggerProvider = Preconditions.checkNotNull(debuggerProvider, "IE01321: Bookmark Manager can't be null"); m_model = new CBookmarkTableModel(debuggerProvider); setModel(m_model); getSelectionModel().setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); addMouseListener(new InternalMouseListener()); } /** * Shows a context menu. * * @param event Mouse-event that triggered the context menu. */ private void showPopup(final MouseEvent event) { int[] rows = getSelectedRows(); // If at most one row is selected, select the row // where the click happened. if ((rows.length == 0) || (rows.length == 1)) { final int row = rowAtPoint(event.getPoint()); final int column = columnAtPoint(event.getPoint()); // Apparently no row was properly hit if ((row == -1) || (column == -1)) { return; } changeSelection(row, column, false, false); rows = getSelectedRows(); } final JPopupMenu menu = new JPopupMenu(); menu.add(new JMenuItem(CActionProxy.proxy( new CDeleteBookmarkAction(m_debuggerProvider, rows)))); menu.show(event.getComponent(), event.getX(), event.getY()); } /** * Frees allocated resources. */ public void dispose() { m_model.dispose(); } /** * Listener that shows a context menu when the user right-clicks on the table. */ private class InternalMouseListener extends MouseAdapter { @Override public void mousePressed(final MouseEvent event) { if (event.isPopupTrigger()) { showPopup(event); } } @Override public void mouseReleased(final MouseEvent event) { if (event.isPopupTrigger()) { showPopup(event); } } } }
apache-2.0
aeppert/binnavi
src/main/java/com/google/security/zynamics/binnavi/ZyGraph/Menus/Actions/CUnhideAndSelectAction.java
2265
/* Copyright 2015 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.security.zynamics.binnavi.ZyGraph.Menus.Actions; import java.awt.event.ActionEvent; import javax.swing.AbstractAction; import com.google.common.base.Preconditions; import com.google.security.zynamics.binnavi.ZyGraph.Implementations.CProximityFunctions; import com.google.security.zynamics.binnavi.disassembly.INaviViewNode; import com.google.security.zynamics.binnavi.yfileswrap.zygraph.ZyGraph; import com.google.security.zynamics.zylib.yfileswrap.gui.zygraph.proximity.ZyProximityNode; /** * Action class used to unhide nodes hidden by a proxmity node and to select those nodes exclusively * (unselect all previously selected nodes). */ public final class CUnhideAndSelectAction extends AbstractAction { /** * Used for serialization. */ private static final long serialVersionUID = 3564626106325530429L; /** * Graph where the unhiding operation takes place. */ private final ZyGraph m_graph; /** * Proximity node to remove. */ private final ZyProximityNode<INaviViewNode> m_node; /** * Creates a new action object. * * @param graph Graph where the unhiding operation takes place. * @param node Proximity node to remove. */ public CUnhideAndSelectAction(final ZyGraph graph, final ZyProximityNode<INaviViewNode> node) { super("Unhide and select only"); Preconditions.checkNotNull(graph, "IE00948: Graph argument can't be null"); Preconditions.checkNotNull(node, "IE00949: Node argument can't be null"); m_graph = graph; m_node = node; } @Override public void actionPerformed(final ActionEvent event) { new CProximityFunctions().unhideAndSelectOnly(m_graph, m_node); } }
apache-2.0
erikluo/omaha
common/lang_unittest.cc
13492
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== // #include <map> #include <vector> #include "omaha/base/app_util.h" #include "omaha/base/constants.h" #include "omaha/base/debug.h" #include "omaha/base/file.h" #include "omaha/base/path.h" #include "omaha/base/string.h" #include "omaha/common/config_manager.h" #include "omaha/common/lang.h" #include "omaha/testing/unit_test.h" namespace omaha { namespace { const int kNumberOfLanguages = 56; } // namespace class LanguageManagerTest : public testing::Test { protected: CString GetLang(LANGID langid) { return lang::GetLanguageForLangID(langid); } }; TEST_F(LanguageManagerTest, GetLanguageForLangID_NoLangID) { EXPECT_STREQ(_T("en"), lang::GetLanguageForLangID(0xFFFF)); } TEST_F(LanguageManagerTest, IsLanguageSupported) { EXPECT_TRUE(lang::IsLanguageSupported(_T("en"))); EXPECT_FALSE(lang::IsLanguageSupported(_T(""))); EXPECT_FALSE(lang::IsLanguageSupported(_T("non-existing lang"))); EXPECT_FALSE(lang::IsLanguageSupported(_T("en-US"))); } TEST_F(LanguageManagerTest, GetLanguageForLangID_SupportedIds) { EXPECT_STREQ(_T("am"), GetLang(MAKELANGID(LANG_AMHARIC, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("ar"), GetLang(MAKELANGID(LANG_ARABIC, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("bg"), GetLang(MAKELANGID(LANG_BULGARIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("ca"), GetLang(MAKELANGID(LANG_CATALAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("cs"), GetLang(MAKELANGID(LANG_CZECH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("da"), GetLang(MAKELANGID(LANG_DANISH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("de"), GetLang(MAKELANGID(LANG_GERMAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("el"), GetLang(MAKELANGID(LANG_GREEK, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("en"), GetLang(MAKELANGID(LANG_ENGLISH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("en-GB"), GetLang(MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_UK))); EXPECT_STREQ(_T("es"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("es"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_MEXICAN))); EXPECT_STREQ(_T("es"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_MODERN))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_GUATEMALA))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_COSTA_RICA))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_PANAMA))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID( LANG_SPANISH, SUBLANG_SPANISH_DOMINICAN_REPUBLIC))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_VENEZUELA))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_COLOMBIA))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_PERU))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_ARGENTINA))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_ECUADOR))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_CHILE))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_URUGUAY))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_PARAGUAY))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_BOLIVIA))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_EL_SALVADOR))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_HONDURAS))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_NICARAGUA))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SPANISH_PUERTO_RICO))); EXPECT_STREQ(_T("et"), GetLang(MAKELANGID(LANG_ESTONIAN, SUBLANG_ESTONIAN_ESTONIA))); EXPECT_STREQ(_T("fi"), GetLang(MAKELANGID(LANG_FINNISH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("fil"), GetLang(MAKELANGID(LANG_FILIPINO, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("fr"), GetLang(MAKELANGID(LANG_FRENCH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("hi"), GetLang(MAKELANGID(LANG_HINDI, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("hr"), GetLang(MAKELANGID(LANG_CROATIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("hr"), GetLang(MAKELANGID(LANG_SERBIAN, SUBLANG_SERBIAN_CROATIA))); EXPECT_STREQ(_T("hu"), GetLang(MAKELANGID(LANG_HUNGARIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("id"), GetLang(MAKELANGID(LANG_INDONESIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("it"), GetLang(MAKELANGID(LANG_ITALIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("iw"), GetLang(MAKELANGID(LANG_HEBREW, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("ja"), GetLang(MAKELANGID(LANG_JAPANESE, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("ko"), GetLang(MAKELANGID(LANG_KOREAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("lt"), GetLang(MAKELANGID(LANG_LITHUANIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("lv"), GetLang(MAKELANGID(LANG_LATVIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("nl"), GetLang(MAKELANGID(LANG_DUTCH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("no"), GetLang(MAKELANGID(LANG_NORWEGIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("pl"), GetLang(MAKELANGID(LANG_POLISH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("pt-BR"), GetLang(MAKELANGID(LANG_PORTUGUESE, SUBLANG_PORTUGUESE_BRAZILIAN))); EXPECT_STREQ(_T("pt-PT"), GetLang(MAKELANGID(LANG_PORTUGUESE, SUBLANG_PORTUGUESE))); EXPECT_STREQ(_T("ro"), GetLang(MAKELANGID(LANG_ROMANIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("ru"), GetLang(MAKELANGID(LANG_RUSSIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("sk"), GetLang(MAKELANGID(LANG_SLOVAK, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("sl"), GetLang(MAKELANGID(LANG_SLOVENIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("sr"), GetLang( MAKELANGID(LANG_SERBIAN, SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_CYRILLIC))); EXPECT_STREQ(_T("sr"), GetLang( MAKELANGID(LANG_SERBIAN, SUBLANG_SERBIAN_BOSNIA_HERZEGOVINA_LATIN))); EXPECT_STREQ(_T("sr"), GetLang(MAKELANGID(LANG_SERBIAN, SUBLANG_SERBIAN_CYRILLIC))); EXPECT_STREQ(_T("sr"), GetLang(MAKELANGID(LANG_SERBIAN, SUBLANG_SERBIAN_LATIN))); EXPECT_STREQ(_T("sv"), GetLang(MAKELANGID(LANG_SWEDISH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("sw"), GetLang(MAKELANGID(LANG_SWAHILI, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("th"), GetLang(MAKELANGID(LANG_THAI, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("tr"), GetLang(MAKELANGID(LANG_TURKISH, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("uk"), GetLang(MAKELANGID(LANG_UKRAINIAN, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("vi"), GetLang(MAKELANGID(LANG_VIETNAMESE, SUBLANG_DEFAULT))); EXPECT_STREQ(_T("zh-HK"), GetLang(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_HONGKONG))); EXPECT_STREQ(_T("zh-TW"), GetLang(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_MACAU))); EXPECT_STREQ(_T("zh-CN"), GetLang(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED))); EXPECT_STREQ(_T("zh-CN"), GetLang(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_SINGAPORE))); EXPECT_STREQ(_T("zh-TW"), GetLang(MAKELANGID(LANG_CHINESE, SUBLANG_CHINESE_TRADITIONAL))); } // Unsupported languages and sublanguages fall back to "en". TEST_F(LanguageManagerTest, GetLanguageForLangID_UnsupportedSubLang) { // LANG_NEUTRAL is unsupported. EXPECT_STREQ(_T("en"), GetLang(MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT))); // LANG_AFRIKAANS is unsupported. EXPECT_STREQ(_T("en"), GetLang(MAKELANGID(LANG_AFRIKAANS, SUBLANG_NEUTRAL))); // SUBLANG_NEUTRAL is unsupported. EXPECT_STREQ(_T("en"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_NEUTRAL))); // SUBLANG_SYS_DEFAULT is unsupported. It happens to be 2, which is not // supported for Hungarian but is for English, Spanish, and others/ EXPECT_STREQ(_T("en"), GetLang(MAKELANGID(LANG_HUNGARIAN, SUBLANG_SYS_DEFAULT))); EXPECT_STREQ(_T("es-419"), GetLang(MAKELANGID(LANG_SPANISH, SUBLANG_SYS_DEFAULT))); // 0x3f is an invalid sublang. There is a "es" file. EXPECT_STREQ(_T("en"), GetLang(MAKELANGID(LANG_SPANISH, 0x3f))); // 0x3f is an invalid sublang. There is not a "zh" file. EXPECT_STREQ(_T("en"), GetLang(MAKELANGID(LANG_CHINESE, 0x3f))); } TEST_F(LanguageManagerTest, TestCountLanguagesInTranslationTable) { std::vector<CString> languages; lang::GetSupportedLanguages(&languages); EXPECT_EQ(kNumberOfLanguages, languages.size()); } TEST_F(LanguageManagerTest, TestAppropriateLanguagesInTranslationTable) { EXPECT_TRUE(lang::IsLanguageSupported(_T("am"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ar"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("bg"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("bn"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ca"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("cs"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("da"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("de"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("el"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("en-GB"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("en"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("es-419"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("es"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("et"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("fa"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("fi"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("fil"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("fr"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("gu"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("hi"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("hr"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("hu"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("id"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("is"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("it"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("iw"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ja"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("kn"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ko"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("lt"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("lv"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ml"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("mr"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ms"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("nl"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("no"))); EXPECT_FALSE(lang::IsLanguageSupported(_T("or"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("pl"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("pt-BR"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("pt-PT"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ro"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ru"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("sk"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("sl"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("sr"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("sv"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("sw"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ta"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("te"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("th"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("tr"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("uk"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("ur"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("vi"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("zh-CN"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("zh-HK"))); EXPECT_TRUE(lang::IsLanguageSupported(_T("zh-TW"))); } } // namespace omaha
apache-2.0
eugenpodaru/DefinitelyTyped
sax/sax-tests.ts
2305
/// <reference path="../node/node.d.ts" /> /// <reference path="./sax.d.ts" /> import sax = require("sax"); import fs = require("fs"); (function xmlnsTests() { let opts: sax.SAXOptions = { lowercase: true, normalize: true, xmlns: true, position: true }; let parser = sax.parser(/*strict=*/true, opts); parser.onerror = function(e: Error) { }; parser.ontext = function(text: string) { }; parser.onopentag = function(tag: sax.QualifiedTag) { let prefix: string = tag.prefix; let local: string = tag.local; let uri: string = tag.uri; let name: string = tag.name; let isSelfClosing: boolean = tag.isSelfClosing; let attr: sax.QualifiedAttribute = tag.attributes["name"]; if (attr) { let attrPrefix: string = attr.prefix; let attrLocal: string = attr.local; let attrUri: string = attr.uri; let attrName: string = attr.name; let attrValue: string = attr.value; } }; parser.onattribute = function(attr: { name: string; value: string; }) { }; parser.onend = function() { }; parser.write("<xml>Hello, <who name=\"world\">world</who>!</xml>").close(); let saxStream = sax.createStream(/*strict=*/true, opts); saxStream.on("error", function(e: Error) { this._parser.error = null; this._parser.resume(); }); fs.createReadStream("file.xml") .pipe(saxStream) .pipe(fs.createWriteStream("file-copy.xml")); })(); (function noXmlnsTests() { let opts: sax.SAXOptions = { lowercase: true, normalize: true, xmlns: false, position: true }; let parser = sax.parser(/*strict=*/true, opts); parser.onerror = function(e: Error) { }; parser.ontext = function(text: string) { }; parser.onopentag = function(tag: sax.Tag) { let name: string = tag.name; let isSelfClosing: boolean = tag.isSelfClosing; let attrValue: string = tag.attributes["name"]; }; parser.onattribute = function(attr: { name: string; value: string; }) { }; parser.onend = function() { }; parser.write("<xml>Hello, <who name=\"world\">world</who>!</xml>").close(); })();
mit
tonypartridge/joomla-cms
media/system/js/fields/calendar-locales/de.js
634
window.JoomlaCalLocale = { today : "Heute", weekend : [0, 6], wk : "KW", time : "Uhrzeit:", days : ["Sonntag", "Montag", "Dienstag", "Mittwoch", "Donnerstag", "Freitag", "Samstag"], shortDays : ["Son", "Mon", "Die", "Mit", "Don", "Fre", "Sam"], months : ["Januar", "Februar", "März", "April", "Mai", "Juni", "Juli", "August", "September", "Oktober", "November", "Dezember"], shortMonths : ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"], AM : "AM", PM : "PM", am : "am", pm : "pm", dateType : "gregorian", minYear : 1900, maxYear : 2100, exit: "Schließen", clear: "Leeren" };
gpl-2.0
puppeh/gcc-6502
gcc/testsuite/g++.dg/ipa/devirt-28a.C
295
// PR c++/58678 // { dg-options "-O3 -flto -shared -fPIC -Wl,--no-undefined" } // { dg-do link { target { { gld && fpic } && shared } } } // { dg-require-effective-target lto } struct A { virtual ~A(); }; struct B : A { virtual int m_fn1(); }; void fn1(B* b) { delete b; } int main() {}
gpl-2.0
kpjs4s/AppInventorJavaBridgeCodeGen
appinventor/lib/closure-library/closure/goog/ui/imagelessbuttonrenderer.js
7493
// Copyright 2008 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 An alternative custom button renderer that uses even more CSS * voodoo than the default implementation to render custom buttons with fake * rounded corners and dimensionality (via a subtle flat shadow on the bottom * half of the button) without the use of images. * * Based on the Custom Buttons 3.1 visual specification, see * http://go/custombuttons * * @author eae@google.com (Emil A Eklund) * @see ../demos/imagelessbutton.html */ goog.provide('goog.ui.ImagelessButtonRenderer'); goog.require('goog.dom.classes'); goog.require('goog.ui.Button'); goog.require('goog.ui.Component'); goog.require('goog.ui.CustomButtonRenderer'); goog.require('goog.ui.INLINE_BLOCK_CLASSNAME'); goog.require('goog.ui.registry'); /** * Custom renderer for {@link goog.ui.Button}s. Imageless buttons can contain * almost arbitrary HTML content, will flow like inline elements, but can be * styled like block-level elements. * * @deprecated These contain a lot of unnecessary DOM for modern user agents. * Please use a simpler button renderer like css3buttonrenderer. * @constructor * @extends {goog.ui.CustomButtonRenderer} */ goog.ui.ImagelessButtonRenderer = function() { goog.ui.CustomButtonRenderer.call(this); }; goog.inherits(goog.ui.ImagelessButtonRenderer, goog.ui.CustomButtonRenderer); /** * The singleton instance of this renderer class. * @type {goog.ui.ImagelessButtonRenderer?} * @private */ goog.ui.ImagelessButtonRenderer.instance_ = null; goog.addSingletonGetter(goog.ui.ImagelessButtonRenderer); /** * Default CSS class to be applied to the root element of components rendered * by this renderer. * @type {string} */ goog.ui.ImagelessButtonRenderer.CSS_CLASS = goog.getCssName('goog-imageless-button'); /** * Returns the button's contents wrapped in the following DOM structure: * <div class="goog-inline-block goog-imageless-button"> * <div class="goog-inline-block goog-imageless-button-outer-box"> * <div class="goog-imageless-button-inner-box"> * <div class="goog-imageless-button-pos-box"> * <div class="goog-imageless-button-top-shadow">&nbsp;</div> * <div class="goog-imageless-button-content">Contents...</div> * </div> * </div> * </div> * </div> * @override */ goog.ui.ImagelessButtonRenderer.prototype.createDom; /** @override */ goog.ui.ImagelessButtonRenderer.prototype.getContentElement = function( element) { return /** @type {Element} */ (element && element.firstChild && element.firstChild.firstChild && element.firstChild.firstChild.firstChild.lastChild); }; /** * Takes a text caption or existing DOM structure, and returns the content * wrapped in a pseudo-rounded-corner box. Creates the following DOM structure: * <div class="goog-inline-block goog-imageless-button-outer-box"> * <div class="goog-inline-block goog-imageless-button-inner-box"> * <div class="goog-imageless-button-pos"> * <div class="goog-imageless-button-top-shadow">&nbsp;</div> * <div class="goog-imageless-button-content">Contents...</div> * </div> * </div> * </div> * Used by both {@link #createDom} and {@link #decorate}. To be overridden * by subclasses. * @param {goog.ui.ControlContent} content Text caption or DOM structure to wrap * in a box. * @param {goog.dom.DomHelper} dom DOM helper, used for document interaction. * @return {Element} Pseudo-rounded-corner box containing the content. * @override */ goog.ui.ImagelessButtonRenderer.prototype.createButton = function(content, dom) { var baseClass = this.getCssClass(); var inlineBlock = goog.ui.INLINE_BLOCK_CLASSNAME + ' '; return dom.createDom('div', inlineBlock + goog.getCssName(baseClass, 'outer-box'), dom.createDom('div', inlineBlock + goog.getCssName(baseClass, 'inner-box'), dom.createDom('div', goog.getCssName(baseClass, 'pos'), dom.createDom('div', goog.getCssName(baseClass, 'top-shadow'), '\u00A0'), dom.createDom('div', goog.getCssName(baseClass, 'content'), content)))); }; /** * Check if the button's element has a box structure. * @param {goog.ui.Button} button Button instance whose structure is being * checked. * @param {Element} element Element of the button. * @return {boolean} Whether the element has a box structure. * @protected * @override */ goog.ui.ImagelessButtonRenderer.prototype.hasBoxStructure = function( button, element) { var outer = button.getDomHelper().getFirstElementChild(element); var outerClassName = goog.getCssName(this.getCssClass(), 'outer-box'); if (outer && goog.dom.classes.has(outer, outerClassName)) { var inner = button.getDomHelper().getFirstElementChild(outer); var innerClassName = goog.getCssName(this.getCssClass(), 'inner-box'); if (inner && goog.dom.classes.has(inner, innerClassName)) { var pos = button.getDomHelper().getFirstElementChild(inner); var posClassName = goog.getCssName(this.getCssClass(), 'pos'); if (pos && goog.dom.classes.has(pos, posClassName)) { var shadow = button.getDomHelper().getFirstElementChild(pos); var shadowClassName = goog.getCssName( this.getCssClass(), 'top-shadow'); if (shadow && goog.dom.classes.has(shadow, shadowClassName)) { var content = button.getDomHelper().getNextElementSibling(shadow); var contentClassName = goog.getCssName( this.getCssClass(), 'content'); if (content && goog.dom.classes.has(content, contentClassName)) { // We have a proper box structure. return true; } } } } } return false; }; /** * Returns the CSS class to be applied to the root element of components * rendered using this renderer. * @return {string} Renderer-specific CSS class. * @override */ goog.ui.ImagelessButtonRenderer.prototype.getCssClass = function() { return goog.ui.ImagelessButtonRenderer.CSS_CLASS; }; // Register a decorator factory function for goog.ui.ImagelessButtonRenderer. goog.ui.registry.setDecoratorByClassName( goog.ui.ImagelessButtonRenderer.CSS_CLASS, function() { return new goog.ui.Button(null, goog.ui.ImagelessButtonRenderer.getInstance()); }); // Register a decorator factory function for toggle buttons using the // goog.ui.ImagelessButtonRenderer. goog.ui.registry.setDecoratorByClassName( goog.getCssName('goog-imageless-toggle-button'), function() { var button = new goog.ui.Button(null, goog.ui.ImagelessButtonRenderer.getInstance()); button.setSupportedState(goog.ui.Component.State.CHECKED, true); return button; });
apache-2.0
cgvarela/chef
lib/chef/daemon.rb
4300
# # Author:: AJ Christensen (<aj@junglist.gen.nz>) # Copyright:: Copyright (c) 2008 Opscode, Inc. # License:: Apache License, Version 2.0 # # 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. # I love you Merb (lib/merb-core/server.rb) require 'chef/config' require 'chef/run_lock' require 'etc' class Chef class Daemon class << self attr_accessor :name attr_accessor :runlock # Daemonize the current process, managing pidfiles and process uid/gid # # === Parameters # name<String>:: The name to be used for the pid file # def daemonize(name) @name = name @runlock = RunLock.new(pid_file) if runlock.test # We've acquired the daemon lock. Now daemonize. Chef::Log.info("Daemonizing..") begin exit if fork Process.setsid exit if fork Chef::Log.info("Forked, in #{Process.pid}. Privileges: #{Process.euid} #{Process.egid}") File.umask Chef::Config[:umask] $stdin.reopen("/dev/null") $stdout.reopen("/dev/null", "a") $stderr.reopen($stdout) runlock.save_pid rescue NotImplementedError => e Chef::Application.fatal!("There is no fork: #{e.message}") end else Chef::Application.fatal!("Chef is already running pid #{pid_from_file}") end end # Gets the pid file for @name # ==== Returns # String:: # Location of the pid file for @name def pid_file Chef::Config[:pid_file] or "/tmp/#{@name}.pid" end # Suck the pid out of pid_file # ==== Returns # Integer:: # The PID from pid_file # nil:: # Returned if the pid_file does not exist. # def pid_from_file File.read(pid_file).chomp.to_i rescue Errno::ENOENT, Errno::EACCES nil end # Change process user/group to those specified in Chef::Config # def change_privilege Dir.chdir("/") if Chef::Config[:user] and Chef::Config[:group] Chef::Log.info("About to change privilege to #{Chef::Config[:user]}:#{Chef::Config[:group]}") _change_privilege(Chef::Config[:user], Chef::Config[:group]) elsif Chef::Config[:user] Chef::Log.info("About to change privilege to #{Chef::Config[:user]}") _change_privilege(Chef::Config[:user]) end end # Change privileges of the process to be the specified user and group # # ==== Parameters # user<String>:: The user to change the process to. # group<String>:: The group to change the process to. # # ==== Alternatives # If group is left out, the user will be used (changing to user:user) # def _change_privilege(user, group=user) uid, gid = Process.euid, Process.egid begin target_uid = Etc.getpwnam(user).uid rescue ArgumentError => e Chef::Application.fatal!("Failed to get UID for user #{user}, does it exist? #{e.message}") return false end begin target_gid = Etc.getgrnam(group).gid rescue ArgumentError => e Chef::Application.fatal!("Failed to get GID for group #{group}, does it exist? #{e.message}") return false end if (uid != target_uid) or (gid != target_gid) Process.initgroups(user, target_gid) Process::GID.change_privilege(target_gid) Process::UID.change_privilege(target_uid) end true rescue Errno::EPERM => e Chef::Application.fatal!("Permission denied when trying to change #{uid}:#{gid} to #{target_uid}:#{target_gid}. #{e.message}") end end end end
apache-2.0
ar4s/django
tests/urlpatterns_reverse/urls_without_handlers.py
241
# A URLconf that doesn't define any handlerXXX. from django.urls import path from .views import bad_view, empty_view urlpatterns = [ path('test_view/', empty_view, name="test_view"), path('bad_view/', bad_view, name="bad_view"), ]
bsd-3-clause
JennyCumming/blog
core/modules/system/src/Tests/Menu/MenuTestBase.php
489
<?php namespace Drupal\system\Tests\Menu; @trigger_error(__NAMESPACE__ . '\MenuTestBase is deprecated in Drupal 8.4.0 and will be removed before Drupal 9.0.0. Instead, use \Drupal\Tests\BrowserTestBase', E_USER_DEPRECATED); use Drupal\simpletest\WebTestBase; /** * Base class for Menu tests. * * @deprecated Scheduled for removal in Drupal 9.0.0. * Use \Drupal\Tests\BrowserTestBase instead. */ abstract class MenuTestBase extends WebTestBase { use AssertBreadcrumbTrait; }
gpl-2.0
tmpgit/intellij-community
platform/platform-impl/src/com/intellij/ui/TableViewSpeedSearch.java
2102
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ui; import com.intellij.ui.table.TableView; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * @author Gregory.Shrago */ public abstract class TableViewSpeedSearch<Item> extends SpeedSearchBase<TableView<Item>> { public TableViewSpeedSearch(TableView<Item> component) { super(component); setComparator(new SpeedSearchComparator(false)); } @Override protected int getSelectedIndex() { return getComponent().getSelectedRow(); } @Override protected int convertIndexToModel(int viewIndex) { return myComponent.convertRowIndexToModel(viewIndex); } @Override protected Object[] getAllElements() { return getComponent().getItems().toArray(); } @Nullable @Override protected String getElementText(Object element) { return getItemText((Item)element); } @Nullable protected abstract String getItemText(final @NotNull Item element); @Override protected void selectElement(final Object element, final String selectedText) { final List items = getComponent().getItems(); for (int i = 0, itemsSize = items.size(); i < itemsSize; i++) { final Object o = items.get(i); if (o == element) { final int viewIndex = myComponent.convertRowIndexToView(i); getComponent().getSelectionModel().setSelectionInterval(viewIndex, viewIndex); TableUtil.scrollSelectionToVisible(getComponent()); break; } } } }
apache-2.0
ashwary/RxJava
src/test/java/rx/internal/operators/OperatorOnErrorReturnTest.java
7410
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx.internal.operators; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.concurrent.atomic.AtomicReference; import org.junit.Test; import org.mockito.Mockito; import rx.Observable; import rx.Observer; import rx.Subscriber; import rx.functions.Func1; import rx.observers.TestSubscriber; import rx.schedulers.Schedulers; public class OperatorOnErrorReturnTest { @Test public void testResumeNext() { TestObservable f = new TestObservable("one"); Observable<String> w = Observable.create(f); final AtomicReference<Throwable> capturedException = new AtomicReference<Throwable>(); Observable<String> observable = w.onErrorReturn(new Func1<Throwable, String>() { @Override public String call(Throwable e) { capturedException.set(e); return "failure"; } }); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); observable.subscribe(observer); try { f.t.join(); } catch (InterruptedException e) { fail(e.getMessage()); } verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); verify(observer, times(1)).onNext("one"); verify(observer, times(1)).onNext("failure"); assertNotNull(capturedException.get()); } /** * Test that when a function throws an exception this is propagated through onError */ @Test public void testFunctionThrowsError() { TestObservable f = new TestObservable("one"); Observable<String> w = Observable.create(f); final AtomicReference<Throwable> capturedException = new AtomicReference<Throwable>(); Observable<String> observable = w.onErrorReturn(new Func1<Throwable, String>() { @Override public String call(Throwable e) { capturedException.set(e); throw new RuntimeException("exception from function"); } }); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); observable.subscribe(observer); try { f.t.join(); } catch (InterruptedException e) { fail(e.getMessage()); } // we should get the "one" value before the error verify(observer, times(1)).onNext("one"); // we should have received an onError call on the Observer since the resume function threw an exception verify(observer, times(1)).onError(any(Throwable.class)); verify(observer, times(0)).onCompleted(); assertNotNull(capturedException.get()); } @Test public void testMapResumeAsyncNext() { // Trigger multiple failures Observable<String> w = Observable.just("one", "fail", "two", "three", "fail"); // Introduce map function that fails intermittently (Map does not prevent this when the observer is a // rx.operator incl onErrorResumeNextViaObservable) w = w.map(new Func1<String, String>() { @Override public String call(String s) { if ("fail".equals(s)) throw new RuntimeException("Forced Failure"); System.out.println("BadMapper:" + s); return s; } }); Observable<String> observable = w.onErrorReturn(new Func1<Throwable, String>() { @Override public String call(Throwable t1) { return "resume"; } }); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); TestSubscriber<String> ts = new TestSubscriber<String>(observer); observable.subscribe(ts); ts.awaitTerminalEvent(); verify(observer, Mockito.never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); verify(observer, times(1)).onNext("one"); verify(observer, Mockito.never()).onNext("two"); verify(observer, Mockito.never()).onNext("three"); verify(observer, times(1)).onNext("resume"); } @Test public void testBackpressure() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable.range(0, 100000) .onErrorReturn(new Func1<Throwable, Integer>() { @Override public Integer call(Throwable t1) { return 1; } }) .observeOn(Schedulers.computation()) .map(new Func1<Integer, Integer>() { int c = 0; @Override public Integer call(Integer t1) { if (c++ <= 1) { // slow try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } return t1; } }) .subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); } private static class TestObservable implements Observable.OnSubscribe<String> { final String[] values; Thread t = null; public TestObservable(String... values) { this.values = values; } @Override public void call(final Subscriber<? super String> subscriber) { System.out.println("TestObservable subscribed to ..."); t = new Thread(new Runnable() { @Override public void run() { try { System.out.println("running TestObservable thread"); for (String s : values) { System.out.println("TestObservable onNext: " + s); subscriber.onNext(s); } throw new RuntimeException("Forced Failure"); } catch (Throwable e) { subscriber.onError(e); } } }); System.out.println("starting TestObservable thread"); t.start(); System.out.println("done starting TestObservable thread"); } } }
apache-2.0
SerCeMan/intellij-community
platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemImpl.java
947
/* * Copyright 2000-2014 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.vfs.impl.http; import com.intellij.util.io.URLUtil; /** * @author nik */ public class HttpFileSystemImpl extends HttpFileSystemBase { public HttpFileSystemImpl() { super(URLUtil.HTTP_PROTOCOL); } public static HttpFileSystemImpl getInstanceImpl() { return (HttpFileSystemImpl)getInstance(); } }
apache-2.0
jonobr1/cdnjs
ajax/libs/bootstrap-calendar/0.2.2/js/language/template.js
4498
// If you want to suggest a new language you can use this file as a template. // To reduce the file size you should remove the comment lines (the ones that start with // ) if(!window.calendar_languages) { window.calendar_languages = {}; } // Here you define the language and Country code. Replace en-US with your own. // First letters: the language code (lower case). See http://www.loc.gov/standards/iso639-2/php/code_list.php // Last letters: the Country code (upper case). See http://www.iso.org/iso/home/standards/country_codes/country_names_and_code_elements.htm window.calendar_languages['en-US'] = { error_noview: 'Calendar: View {0} not found', error_dateformat: 'Calendar: Wrong date format {0}. Should be either "now" or "yyyy-mm-dd"', error_loadurl: 'Calendar: Event URL is not set', error_where: 'Calendar: Wrong navigation direction {0}. Can be only "next" or "prev" or "today"', error_timedevide: 'Calendar: Time split parameter should divide 60 without decimals. Something like 10, 15, 30', no_events_in_day: 'No events in this day.', // {0} will be replaced with the year (example: 2013) title_year: '{0}', // {0} will be replaced with the month name (example: September) // {1} will be replaced with the year (example: 2013) title_month: '{0} {1}', // {0} will be replaced with the week number (example: 37) // {1} will be replaced with the year (example: 2013) title_week: 'week {0} of {1}', // {0} will be replaced with the weekday name (example: Thursday) // {1} will be replaced with the day of the month (example: 12) // {2} will be replaced with the month name (example: September) // {3} will be replaced with the year (example: 2013) title_day: '{0} {1} {2}, {3}', week:'Week', all_day: 'All day', time: 'Time', events: 'Events', before_time: 'Ends before timeline', after_time: 'Starts after timeline', m0: 'January', m1: 'February', m2: 'March', m3: 'April', m4: 'May', m5: 'June', m6: 'July', m7: 'August', m8: 'September', m9: 'October', m10: 'November', m11: 'December', ms0: 'Jan', ms1: 'Feb', ms2: 'Mar', ms3: 'Apr', ms4: 'May', ms5: 'Jun', ms6: 'Jul', ms7: 'Aug', ms8: 'Sep', ms9: 'Oct', ms10: 'Nov', ms11: 'Dec', d0: 'Sunday', d1: 'Monday', d2: 'Tuesday', d3: 'Wednesday', d4: 'Thursday', d5: 'Friday', d6: 'Saturday', // Which is the first day of the week (2 for sunday, 1 for monday) first_day: 2, // The list of the holidays. // Each holiday has a date definition and a name (in your language) // For instance: // holidays: { // 'date': 'name', // 'date': 'name', // ... // 'date': 'name' //No ending comma for the last holiday // } // The format of the date may be one of the following: // # For a holiday recurring every year in the same day: 'dd-mm' (dd is the day of the month, mm is the month). For example: '25-12'. // # For a holiday that exists only in one specific year: 'dd-mm-yyyy' (dd is the day of the month, mm is the month, yyyy is the year). For example: '31-01-2013' // # For Easter: use simply 'easter' // # For holidays that are based on the Easter date: 'easter+offset in days'. // Some examples: // - 'easter-2' is Good Friday (2 days before Easter) // - 'easter+1' is Easter Monday (1 day after Easter) // - 'easter+39' is the Ascension Day // - 'easter+49' is Pentecost // # For holidays that are on a specific weekday after the beginning of a month: 'mm+n*w', where 'mm' is the month, 'n' is the ordinal position, 'w' is the weekday being 0: Sunday, 1: Monday, ..., 6: Saturnday // For example: // - Second (2) Monday (1) in October (10): '10+2*1' // # For holidays that are on a specific weekday before the ending of a month: 'mm-n*w', where 'mm' is the month, 'n' is the ordinal position, 'w' is the weekday being 0: Sunday, 1: Monday, ..., 6: Saturnday // For example: // - Last (1) Saturnday (6) in Match (03): '03-1*6' // - Last (1) Monday (1) in May (05): '05-1*1' // # You can also specify a holiday that lasts more than one day. To do that use the format 'start>end' where 'start' and 'end' are specified as above. // For example: // - From 1 January to 6 January: '01-01>06-01' // - Easter and the day after Easter: 'easter>easter+1' // Limitations: currently the multi-day holydays can't cross an year. So, for example, you can't specify a range as '30-12>01-01'; as a workaround you can specify two distinct holidays (for instance '30-12>31-12' and '01-01'). holidays: { } };
mit
djrobson/binnavi
src/test/java/com/google/security/zynamics/binnavi/disassembly/AddressSpaces/MockAddressSpaceContentListener.java
1541
/* Copyright 2014 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.google.security.zynamics.binnavi.disassembly.AddressSpaces; import com.google.security.zynamics.binnavi.disassembly.INaviAddressSpace; import com.google.security.zynamics.binnavi.disassembly.INaviModule; import com.google.security.zynamics.binnavi.disassembly.AddressSpaces.IAddressSpaceContentListener; import com.google.security.zynamics.zylib.disassembly.IAddress; public class MockAddressSpaceContentListener implements IAddressSpaceContentListener { public String events = ""; @Override public void addedModule(final INaviAddressSpace addressSpace, final INaviModule module) { events += "addedModule;"; } @Override public void changedImageBase(final INaviAddressSpace addressSpace, final INaviModule module, final IAddress address) { events += "changedImageBase;"; } @Override public void removedModule(final INaviAddressSpace addressSpace, final INaviModule module) { events += "removedModule;"; } }
apache-2.0
MisterAndersen/elasticsearch
core/src/main/java/org/elasticsearch/common/lucene/index/ElasticsearchLeafReader.java
2678
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.common.lucene.index; import org.apache.lucene.index.FilterLeafReader; import org.apache.lucene.index.LeafReader; import org.elasticsearch.index.shard.ShardId; /** * A {@link org.apache.lucene.index.FilterLeafReader} that exposes * Elasticsearch internal per shard / index information like the shard ID. */ public final class ElasticsearchLeafReader extends FilterLeafReader { private final ShardId shardId; /** * <p>Construct a FilterLeafReader based on the specified base reader. * <p>Note that base reader is closed if this FilterLeafReader is closed.</p> * * @param in specified base reader. */ public ElasticsearchLeafReader(LeafReader in, ShardId shardId) { super(in); this.shardId = shardId; } /** * Returns the shard id this segment belongs to. */ public ShardId shardId() { return this.shardId; } @Override public Object getCoreCacheKey() { return in.getCoreCacheKey(); } public static ElasticsearchLeafReader getElasticsearchLeafReader(LeafReader reader) { if (reader instanceof FilterLeafReader) { if (reader instanceof ElasticsearchLeafReader) { return (ElasticsearchLeafReader) reader; } else { // We need to use FilterLeafReader#getDelegate and not FilterLeafReader#unwrap, because // If there are multiple levels of filtered leaf readers then with the unwrap() method it immediately // returns the most inner leaf reader and thus skipping of over any other filtered leaf reader that // may be instance of ElasticsearchLeafReader. This can cause us to miss the shardId. return getElasticsearchLeafReader(((FilterLeafReader) reader).getDelegate()); } } return null; } }
apache-2.0
bonitadecker77/python-for-android
android/Common/src/com/googlecode/android_scripting/trigger/Trigger.java
1438
/* * Copyright (C) 2010 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.googlecode.android_scripting.trigger; import android.content.Context; import com.googlecode.android_scripting.event.Event; import java.io.Serializable; /** * Interface implemented by objects listening to events on the event queue inside of the * {@link SerivceManager}. * * @author Felix Arends (felix.arends@gmail.com) */ public interface Trigger extends Serializable { /** * Handles an event from the event queue. * * @param event * Event to handle * @param context * TODO */ void handleEvent(Event event, Context context); /** * Returns the event name that this {@link Trigger} is interested in. */ // TODO(damonkohler): This could be removed by maintaining a reverse mapping from Trigger to event // name in the TriggerRespository. String getEventName(); }
apache-2.0
khchine5/lino
lino/modlib/openui5/static/openui5/openui5-CKEditor/ckeditor/plugins/a11yhelp/dialogs/lang/mk.js
4382
/* Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang("a11yhelp","mk",{title:"Инструкции за пристапност",contents:"Содржина на делот за помош. За да го затворите овој дијалог притиснете ESC.",legend:[{name:"Општо",items:[{name:"Мени за уредувачот",legend:"Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT+TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button."},{name:"Дијалот за едиторот", legend:"Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively."},{name:"Контекст-мени на уредувачот",legend:"Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."}, {name:"Editor List Box",legend:"Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."},{name:"Editor Element Path Bar",legend:"Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."}]}, {name:"Наредби",items:[{name:" Undo command",legend:"Press ${undo}"},{name:" Redo command",legend:"Press ${redo}"},{name:" Bold command",legend:"Press ${bold}"},{name:" Italic command",legend:"Press ${italic}"},{name:" Underline command",legend:"Press ${underline}"},{name:" Link command",legend:"Press ${link}"},{name:" Toolbar Collapse command",legend:"Press ${toolbarCollapse}"},{name:" Access previous focus space command",legend:"Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."}, {name:" Access next focus space command",legend:"Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."},{name:" Accessibility Help",legend:"Press ${a11yHelp}"},{name:" Paste as plain text",legend:"Press ${pastetext}",legendEdge:"Press ${pastetext}, followed by ${paste}"}]}],tab:"Tab",pause:"Пауза",capslock:"Caps Lock",escape:"Escape",pageUp:"Page Up",pageDown:"Page Up", leftArrow:"Стрелка лево",upArrow:"Стрелка горе",rightArrow:"Стрелка десно",downArrow:"Стрелка доле",insert:"Insert",leftWindowKey:"Лево Windows копче",rightWindowKey:"Десно Windows копче",selectKey:"Select копче",numpad0:"Нум. таст. 0",numpad1:"Нум. таст. 1",numpad2:"Нум. таст. 2",numpad3:"Нум. таст. 3",numpad4:"Нум. таст. 4",numpad5:"Нум. таст. 5",numpad6:"Нум. таст. 6",numpad7:"Нум. таст. 7",numpad8:"Нум. таст. 8",numpad9:"Нум. таст. 9",multiply:"Multiply",add:"Add",subtract:"Subtract",decimalPoint:"Decimal Point", divide:"Divide",f1:"F1",f2:"F2",f3:"F3",f4:"F4",f5:"F5",f6:"F6",f7:"F7",f8:"F8",f9:"F9",f10:"F10",f11:"F11",f12:"F12",numLock:"Num Lock",scrollLock:"Scroll Lock",semiColon:"Semicolon",equalSign:"Equal Sign",comma:"Comma",dash:"Dash",period:"Period",forwardSlash:"Forward Slash",graveAccent:"Grave Accent",openBracket:"Open Bracket",backSlash:"Backslash",closeBracket:"Close Bracket",singleQuote:"Single Quote"});
bsd-2-clause
helenst/django
tests/admin_registration/models.py
354
""" Tests for various ways of registering models with the admin site. """ from django.db import models class Person(models.Model): name = models.CharField(max_length=200) class Traveler(Person): pass class Location(models.Model): class Meta: abstract = True class Place(Location): name = models.CharField(max_length=200)
bsd-3-clause
jameseggers/docker
integration-cli/docker_cli_diff_test.go
2581
package main import ( "strings" "github.com/docker/docker/pkg/integration/checker" "github.com/go-check/check" ) // ensure that an added file shows up in docker diff func (s *DockerSuite) TestDiffFilenameShownInOutput(c *check.C) { testRequires(c, DaemonIsLinux) containerCmd := `echo foo > /root/bar` out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", containerCmd) cleanCID := strings.TrimSpace(out) out, _ = dockerCmd(c, "diff", cleanCID) found := false for _, line := range strings.Split(out, "\n") { if strings.Contains("A /root/bar", line) { found = true break } } c.Assert(found, checker.True) } // test to ensure GH #3840 doesn't occur any more func (s *DockerSuite) TestDiffEnsureDockerinitFilesAreIgnored(c *check.C) { testRequires(c, DaemonIsLinux) // this is a list of files which shouldn't show up in `docker diff` dockerinitFiles := []string{"/etc/resolv.conf", "/etc/hostname", "/etc/hosts", "/.dockerinit", "/.dockerenv"} containerCount := 5 // we might not run into this problem from the first run, so start a few containers for i := 0; i < containerCount; i++ { containerCmd := `echo foo > /root/bar` out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", containerCmd) cleanCID := strings.TrimSpace(out) out, _ = dockerCmd(c, "diff", cleanCID) for _, filename := range dockerinitFiles { c.Assert(out, checker.Not(checker.Contains), filename) } } } func (s *DockerSuite) TestDiffEnsureOnlyKmsgAndPtmx(c *check.C) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "busybox", "sleep", "0") cleanCID := strings.TrimSpace(out) out, _ = dockerCmd(c, "diff", cleanCID) expected := map[string]bool{ "C /dev": true, "A /dev/full": true, // busybox "C /dev/ptmx": true, // libcontainer "A /dev/mqueue": true, "A /dev/kmsg": true, "A /dev/fd": true, "A /dev/fuse": true, "A /dev/ptmx": true, "A /dev/null": true, "A /dev/random": true, "A /dev/stdout": true, "A /dev/stderr": true, "A /dev/tty1": true, "A /dev/stdin": true, "A /dev/tty": true, "A /dev/urandom": true, "A /dev/zero": true, } for _, line := range strings.Split(out, "\n") { c.Assert(line == "" || expected[line], checker.True) } } // https://github.com/docker/docker/pull/14381#discussion_r33859347 func (s *DockerSuite) TestDiffEmptyArgClientError(c *check.C) { out, _, err := dockerCmdWithError("diff", "") c.Assert(err, checker.NotNil) c.Assert(strings.TrimSpace(out), checker.Equals, "Container name cannot be empty") }
apache-2.0
aveshagarwal/origin
vendor/golang.org/x/tools/imports/fastwalk_test.go
4259
// Copyright 2016 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package imports import ( "bytes" "flag" "fmt" "os" "path/filepath" "reflect" "runtime" "sort" "strings" "sync" "testing" ) func formatFileModes(m map[string]os.FileMode) string { var keys []string for k := range m { keys = append(keys, k) } sort.Strings(keys) var buf bytes.Buffer for _, k := range keys { fmt.Fprintf(&buf, "%-20s: %v\n", k, m[k]) } return buf.String() } func testFastWalk(t *testing.T, files map[string]string, callback func(path string, typ os.FileMode) error, want map[string]os.FileMode) { testConfig{ gopathFiles: files, }.test(t, func(t *goimportTest) { got := map[string]os.FileMode{} var mu sync.Mutex if err := fastWalk(t.gopath, func(path string, typ os.FileMode) error { mu.Lock() defer mu.Unlock() if !strings.HasPrefix(path, t.gopath) { t.Fatalf("bogus prefix on %q, expect %q", path, t.gopath) } key := filepath.ToSlash(strings.TrimPrefix(path, t.gopath)) if old, dup := got[key]; dup { t.Fatalf("callback called twice for key %q: %v -> %v", key, old, typ) } got[key] = typ return callback(path, typ) }); err != nil { t.Fatalf("callback returned: %v", err) } if !reflect.DeepEqual(got, want) { t.Errorf("walk mismatch.\n got:\n%v\nwant:\n%v", formatFileModes(got), formatFileModes(want)) } }) } func TestFastWalk_Basic(t *testing.T) { testFastWalk(t, map[string]string{ "foo/foo.go": "one", "bar/bar.go": "two", "skip/skip.go": "skip", }, func(path string, typ os.FileMode) error { return nil }, map[string]os.FileMode{ "": os.ModeDir, "/src": os.ModeDir, "/src/bar": os.ModeDir, "/src/bar/bar.go": 0, "/src/foo": os.ModeDir, "/src/foo/foo.go": 0, "/src/skip": os.ModeDir, "/src/skip/skip.go": 0, }) } func TestFastWalk_Symlink(t *testing.T) { switch runtime.GOOS { case "windows", "plan9": t.Skipf("skipping on %s", runtime.GOOS) } testFastWalk(t, map[string]string{ "foo/foo.go": "one", "bar/bar.go": "LINK:../foo.go", "symdir": "LINK:foo", }, func(path string, typ os.FileMode) error { return nil }, map[string]os.FileMode{ "": os.ModeDir, "/src": os.ModeDir, "/src/bar": os.ModeDir, "/src/bar/bar.go": os.ModeSymlink, "/src/foo": os.ModeDir, "/src/foo/foo.go": 0, "/src/symdir": os.ModeSymlink, }) } func TestFastWalk_SkipDir(t *testing.T) { testFastWalk(t, map[string]string{ "foo/foo.go": "one", "bar/bar.go": "two", "skip/skip.go": "skip", }, func(path string, typ os.FileMode) error { if typ == os.ModeDir && strings.HasSuffix(path, "skip") { return filepath.SkipDir } return nil }, map[string]os.FileMode{ "": os.ModeDir, "/src": os.ModeDir, "/src/bar": os.ModeDir, "/src/bar/bar.go": 0, "/src/foo": os.ModeDir, "/src/foo/foo.go": 0, "/src/skip": os.ModeDir, }) } func TestFastWalk_TraverseSymlink(t *testing.T) { switch runtime.GOOS { case "windows", "plan9": t.Skipf("skipping on %s", runtime.GOOS) } testFastWalk(t, map[string]string{ "foo/foo.go": "one", "bar/bar.go": "two", "skip/skip.go": "skip", "symdir": "LINK:foo", }, func(path string, typ os.FileMode) error { if typ == os.ModeSymlink { return traverseLink } return nil }, map[string]os.FileMode{ "": os.ModeDir, "/src": os.ModeDir, "/src/bar": os.ModeDir, "/src/bar/bar.go": 0, "/src/foo": os.ModeDir, "/src/foo/foo.go": 0, "/src/skip": os.ModeDir, "/src/skip/skip.go": 0, "/src/symdir": os.ModeSymlink, "/src/symdir/foo.go": 0, }) } var benchDir = flag.String("benchdir", runtime.GOROOT(), "The directory to scan for BenchmarkFastWalk") func BenchmarkFastWalk(b *testing.B) { b.ReportAllocs() for i := 0; i < b.N; i++ { err := fastWalk(*benchDir, func(path string, typ os.FileMode) error { return nil }) if err != nil { b.Fatal(err) } } }
apache-2.0
billti/TypeScript
tests/baselines/reference/declarationEmitDefaultExport8.js
385
//// [declarationEmitDefaultExport8.ts] var _default = 1; export {_default as d} export default 1 + 2; //// [declarationEmitDefaultExport8.js] var _default = 1; export { _default as d }; export default 1 + 2; //// [declarationEmitDefaultExport8.d.ts] declare var _default: number; export { _default as d }; declare var _default_1: number; export default _default_1;
apache-2.0
sufuf3/cdnjs
ajax/libs/svg4everybody/2.1.2/svg4everybody.legacy.js
6853
!function(root, factory) { "function" == typeof define && define.amd ? // AMD. Register as an anonymous module unless amdModuleId is set define([], function() { return root.svg4everybody = factory(); }) : "object" == typeof exports ? // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory() : root.svg4everybody = factory(); }(this, function() { /*! svg4everybody v2.1.0 | github.com/jonathantneal/svg4everybody */ function embed(svg, target) { // if the target exists if (target) { // create a document fragment to hold the contents of the target var fragment = document.createDocumentFragment(), viewBox = !svg.getAttribute("viewBox") && target.getAttribute("viewBox"); // conditionally set the viewBox on the svg viewBox && svg.setAttribute("viewBox", viewBox); // copy the contents of the clone into the fragment for (// clone the target var clone = target.cloneNode(!0); clone.childNodes.length; ) { fragment.appendChild(clone.firstChild); } // append the fragment into the svg svg.appendChild(fragment); } } function loadreadystatechange(xhr) { // listen to changes in the request xhr.onreadystatechange = function() { // if the request is ready if (4 === xhr.readyState) { // get the cached html document var cachedDocument = xhr._cachedDocument; // ensure the cached html document based on the xhr response cachedDocument || (cachedDocument = xhr._cachedDocument = document.implementation.createHTMLDocument(""), cachedDocument.body.innerHTML = xhr.responseText, xhr._cachedTarget = {}), // clear the xhr embeds list and embed each item xhr._embeds.splice(0).map(function(item) { // get the cached target var target = xhr._cachedTarget[item.id]; // ensure the cached target target || (target = xhr._cachedTarget[item.id] = cachedDocument.getElementById(item.id)), // embed the target into the svg embed(item.svg, target); }); } }, // test the ready state change immediately xhr.onreadystatechange(); } function svg4everybody(rawopts) { function oninterval() { // while the index exists in the live <use> collection for (// get the cached <use> index var index = 0; index < uses.length; ) { // get the current <use> var use = uses[index], svg = use.parentNode; if (svg && /svg/i.test(svg.nodeName)) { var src = use.getAttribute("xlink:href"); // if running with legacy support if (nosvg) { // create a new fallback image var img = document.createElement("img"); // force display in older IE img.style.cssText = "display:inline-block;height:100%;width:100%", // set the fallback size using the svg size img.setAttribute("width", svg.getAttribute("width") || svg.clientWidth), img.setAttribute("height", svg.getAttribute("height") || svg.clientHeight), // set the fallback src img.src = fallback(src, svg, use), // replace the <use> with the fallback image svg.replaceChild(img, use); } else { if (polyfill && (!opts.validate || opts.validate(src, svg, use))) { // remove the <use> element svg.removeChild(use); // parse the src and get the url and id var srcSplit = src.split("#"), url = srcSplit.shift(), id = srcSplit.join("#"); // if the link is external if (url.length) { // get the cached xhr request var xhr = requests[url]; // ensure the xhr request exists xhr || (xhr = requests[url] = new XMLHttpRequest(), xhr.open("GET", url), xhr.send(), xhr._embeds = []), // add the svg and id as an item to the xhr embeds list xhr._embeds.push({ svg: svg, id: id }), // prepare the xhr ready state change event loadreadystatechange(xhr); } else { // embed the local id into the svg embed(svg, document.getElementById(id)); } } } } else { // increase the index when the previous value was not "valid" ++index; } } // continue the interval requestAnimationFrame(oninterval, 67); } var nosvg, fallback, opts = Object(rawopts); // configure the fallback method fallback = opts.fallback || function(src) { return src.replace(/\?[^#]+/, "").replace("#", ".").replace(/^\./, "") + ".png" + (/\?[^#]+/.exec(src) || [ "" ])[0]; }, // set whether to shiv <svg> and <use> elements and use image fallbacks nosvg = "nosvg" in opts ? opts.nosvg : /\bMSIE [1-8]\b/.test(navigator.userAgent), // conditionally shiv <svg> and <use> nosvg && (document.createElement("svg"), document.createElement("use")); // set whether the polyfill will be activated or not var polyfill, olderIEUA = /\bMSIE [1-8]\.0\b/, newerIEUA = /\bTrident\/[567]\b|\bMSIE (?:9|10)\.0\b/, webkitUA = /\bAppleWebKit\/(\d+)\b/, olderEdgeUA = /\bEdge\/12\.(\d+)\b/; polyfill = "polyfill" in opts ? opts.polyfill : olderIEUA.test(navigator.userAgent) || newerIEUA.test(navigator.userAgent) || (navigator.userAgent.match(olderEdgeUA) || [])[1] < 10547 || (navigator.userAgent.match(webkitUA) || [])[1] < 537; // create xhr requests object var requests = {}, requestAnimationFrame = window.requestAnimationFrame || setTimeout, uses = document.getElementsByTagName("use"); // conditionally start the interval if the polyfill is active polyfill && oninterval(); } return svg4everybody; });
mit
puppeh/gcc-6502
libstdc++-v3/include/ext/pb_ds/detail/rb_tree_map_/rb_tree_.hpp
7962
// -*- C++ -*- // Copyright (C) 2005-2015 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, or (at your option) any later // version. // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file rb_tree_map_/rb_tree_.hpp * Contains an implementation for Red Black trees. */ #include <ext/pb_ds/detail/standard_policies.hpp> #include <utility> #include <vector> #include <assert.h> #include <debug/debug.h> namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template<typename Key, typename Mapped, typename Cmp_Fn, \ typename Node_And_It_Traits, typename _Alloc> #ifdef PB_DS_DATA_TRUE_INDICATOR # define PB_DS_RB_TREE_NAME rb_tree_map # define PB_DS_RB_TREE_BASE_NAME bin_search_tree_map #endif #ifdef PB_DS_DATA_FALSE_INDICATOR # define PB_DS_RB_TREE_NAME rb_tree_set # define PB_DS_RB_TREE_BASE_NAME bin_search_tree_set #endif #define PB_DS_CLASS_C_DEC \ PB_DS_RB_TREE_NAME<Key, Mapped, Cmp_Fn, Node_And_It_Traits, _Alloc> #define PB_DS_RB_TREE_BASE \ PB_DS_RB_TREE_BASE_NAME<Key, Mapped, Cmp_Fn, Node_And_It_Traits, _Alloc> /** * @brief Red-Black tree. * @ingroup branch-detail * * This implementation uses an idea from the SGI STL (using a * @a header node which is needed for efficient iteration). */ template<typename Key, typename Mapped, typename Cmp_Fn, typename Node_And_It_Traits, typename _Alloc> class PB_DS_RB_TREE_NAME : public PB_DS_RB_TREE_BASE { private: typedef PB_DS_RB_TREE_BASE base_type; typedef typename base_type::node_pointer node_pointer; public: typedef rb_tree_tag container_category; typedef Cmp_Fn cmp_fn; typedef _Alloc allocator_type; typedef typename _Alloc::size_type size_type; typedef typename _Alloc::difference_type difference_type; typedef typename base_type::key_type key_type; typedef typename base_type::key_pointer key_pointer; typedef typename base_type::key_const_pointer key_const_pointer; typedef typename base_type::key_reference key_reference; typedef typename base_type::key_const_reference key_const_reference; typedef typename base_type::mapped_type mapped_type; typedef typename base_type::mapped_pointer mapped_pointer; typedef typename base_type::mapped_const_pointer mapped_const_pointer; typedef typename base_type::mapped_reference mapped_reference; typedef typename base_type::mapped_const_reference mapped_const_reference; typedef typename base_type::value_type value_type; typedef typename base_type::pointer pointer; typedef typename base_type::const_pointer const_pointer; typedef typename base_type::reference reference; typedef typename base_type::const_reference const_reference; typedef typename base_type::point_iterator point_iterator; typedef typename base_type::const_iterator point_const_iterator; typedef typename base_type::iterator iterator; typedef typename base_type::const_iterator const_iterator; typedef typename base_type::reverse_iterator reverse_iterator; typedef typename base_type::const_reverse_iterator const_reverse_iterator; typedef typename base_type::node_update node_update; PB_DS_RB_TREE_NAME(); PB_DS_RB_TREE_NAME(const Cmp_Fn&); PB_DS_RB_TREE_NAME(const Cmp_Fn&, const node_update&); PB_DS_RB_TREE_NAME(const PB_DS_CLASS_C_DEC&); void swap(PB_DS_CLASS_C_DEC&); template<typename It> void copy_from_range(It, It); inline std::pair<point_iterator, bool> insert(const_reference); inline mapped_reference operator[](key_const_reference r_key) { #ifdef PB_DS_DATA_TRUE_INDICATOR _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) std::pair<point_iterator, bool> ins_pair = base_type::insert_leaf(value_type(r_key, mapped_type())); if (ins_pair.second == true) { ins_pair.first.m_p_nd->m_red = true; _GLIBCXX_DEBUG_ONLY(this->structure_only_assert_valid(__FILE__, __LINE__);) insert_fixup(ins_pair.first.m_p_nd); } _GLIBCXX_DEBUG_ONLY(assert_valid(__FILE__, __LINE__);) return ins_pair.first.m_p_nd->m_value.second; #else insert(r_key); return base_type::s_null_type; #endif } inline bool erase(key_const_reference); inline iterator erase(iterator); inline reverse_iterator erase(reverse_iterator); template<typename Pred> inline size_type erase_if(Pred); void join(PB_DS_CLASS_C_DEC&); void split(key_const_reference, PB_DS_CLASS_C_DEC&); private: #ifdef _GLIBCXX_DEBUG void assert_valid(const char*, int) const; size_type assert_node_consistent(const node_pointer, const char*, int) const; #endif inline static bool is_effectively_black(const node_pointer); void initialize(); void insert_fixup(node_pointer); void erase_node(node_pointer); void remove_node(node_pointer); void remove_fixup(node_pointer, node_pointer); void split_imp(node_pointer, PB_DS_CLASS_C_DEC&); inline node_pointer split_min(); std::pair<node_pointer, node_pointer> split_min_imp(); void join_imp(node_pointer, node_pointer); std::pair<node_pointer, node_pointer> find_join_pos_right(node_pointer, size_type, size_type); std::pair<node_pointer, node_pointer> find_join_pos_left(node_pointer, size_type, size_type); inline size_type black_height(node_pointer); void split_at_node(node_pointer, PB_DS_CLASS_C_DEC&); }; #define PB_DS_STRUCT_ONLY_ASSERT_VALID(X) \ _GLIBCXX_DEBUG_ONLY(X.structure_only_assert_valid(__FILE__, __LINE__);) #include <ext/pb_ds/detail/rb_tree_map_/constructors_destructor_fn_imps.hpp> #include <ext/pb_ds/detail/rb_tree_map_/insert_fn_imps.hpp> #include <ext/pb_ds/detail/rb_tree_map_/erase_fn_imps.hpp> #include <ext/pb_ds/detail/rb_tree_map_/debug_fn_imps.hpp> #include <ext/pb_ds/detail/rb_tree_map_/split_join_fn_imps.hpp> #include <ext/pb_ds/detail/rb_tree_map_/info_fn_imps.hpp> #undef PB_DS_STRUCT_ONLY_ASSERT_VALID #undef PB_DS_CLASS_T_DEC #undef PB_DS_CLASS_C_DEC #undef PB_DS_RB_TREE_NAME #undef PB_DS_RB_TREE_BASE_NAME #undef PB_DS_RB_TREE_BASE } // namespace detail } // namespace __gnu_pbds
gpl-2.0
pshc/rust
src/test/run-fail/assert-macro-fmt.rs
594
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // error-pattern:panicked at 'test-assert-fmt 42 rust' fn main() { assert!(false, "test-assert-fmt {} {}", 42, "rust"); }
apache-2.0
jeanregisser/homebrew-cask
Casks/yemuzip.rb
427
cask 'yemuzip' do version '2.4.3' sha256 'f554c0ef41fe3fa0aa9d13663a8346db99c95e7108a200474918fe390076ca9c' url "http://yellowmug.com/download/YemuZip_#{version}.dmg" appcast 'http://yellowmug.com/yemuzip/appcast.xml', checkpoint: '2ede15a2a242f583876e6e5f5957368819435adff6347431862c5a45ee7b2a42' name 'YemuZip' homepage 'http://www.yellowmug.com/yemuzip' license :commercial app 'YemuZip.app' end
bsd-2-clause
useiichi/spree
backend/app/controllers/spree/admin/customer_returns_controller.rb
2392
module Spree module Admin class CustomerReturnsController < ResourceController belongs_to 'spree/order', find_by: :number before_action :parent # ensure order gets loaded to support our pseudo parent-child relationship before_action :load_form_data, only: [:new, :edit] create.before :build_return_items_from_params create.fails :load_form_data def edit @pending_return_items = @customer_return.return_items.select(&:pending?) @accepted_return_items = @customer_return.return_items.select(&:accepted?) @rejected_return_items = @customer_return.return_items.select(&:rejected?) @manual_intervention_return_items = @customer_return.return_items.select(&:manual_intervention_required?) @pending_reimbursements = @customer_return.reimbursements.select(&:pending?) super end private def location_after_save url_for([:edit, :admin, @order, @customer_return]) end def build_resource Spree::CustomerReturn.new end def find_resource Spree::CustomerReturn.accessible_by(current_ability, :read).find(params[:id]) end def collection parent # trigger loading the order @collection ||= Spree::ReturnItem .accessible_by(current_ability, :read) .where(inventory_unit_id: @order.inventory_units.pluck(:id)) .map(&:customer_return).uniq.compact @customer_returns = @collection end def load_form_data return_items = @order.inventory_units.map(&:current_or_new_return_item).reject(&:customer_return_id) @rma_return_items = return_items.select(&:return_authorization_id) end def permitted_resource_params @permitted_resource_params ||= params.require('customer_return').permit(permitted_customer_return_attributes) end def build_return_items_from_params return_items_params = permitted_resource_params.delete(:return_items_attributes).values @customer_return.return_items = return_items_params.map do |item_params| next unless item_params.delete('returned') == '1' return_item = item_params[:id] ? Spree::ReturnItem.find(item_params[:id]) : Spree::ReturnItem.new return_item.attributes = item_params return_item end.compact end end end end
bsd-3-clause
franksun/wp
components/com_config/view/templates/html.php
677
<?php /** * @package Joomla.Site * @subpackage com_config * * @copyright Copyright (C) 2005 - 2015 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; /** * View to edit a template style. * * @since 3.2 */ class ConfigViewTemplatesHtml extends ConfigViewCmsHtml { public $item; public $form; /** * Method to render the view. * * @return string The rendered view. * * @since 3.2 */ public function render() { $user = JFactory::getUser(); $this->userIsSuperAdmin = $user->authorise('core.admin'); return parent::render(); } }
gpl-2.0
abhinay100/openerm_app
library/classes/rulesets/Cqm/reports/NFQ_0024/PopulationCriteria3.php
1040
<?php // Copyright (C) 2011 Ken Chapple <ken@mi-squared.com> // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // class NFQ_0024_PopulationCriteria3 implements CqmPopulationCrtiteriaFactory { public function getTitle() { return "Population Criteria 3"; } public function createInitialPatientPopulation() { return new NFQ_0024_InitialPatientPopulation3(); } public function createNumerators() { $nums = array(); $nums[]= new NFQ_0024_Numerator1(); $nums[]= new NFQ_0024_Numerator2(); $nums[]= new NFQ_0024_Numerator3(); return $nums; } public function createDenominator() { return new NFQ_0024_Denominator(); } public function createExclusion() { return new ExclusionsNone(); } }
gpl-3.0
udogan/baklavaborekmatik
vendor/gedmo/doctrine-extensions/tests/Gedmo/Translatable/Fixture/Document/Personal/ArticleTranslation.php
446
<?php namespace Translatable\Fixture\Document\Personal; use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoODM; use Gedmo\Translatable\Document\MappedSuperclass\AbstractPersonalTranslation; /** * @MongoODM\Document(collection="article_translations") */ class ArticleTranslation extends AbstractPersonalTranslation { /** * @MongoODM\ReferenceOne(targetDocument="Article", inversedBy="translations") */ protected $object; }
gpl-3.0
priyawadhwa/runtimes-common
vendor/golang.org/x/oauth2/google/doc_not_go19.go
2101
// Copyright 2018 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build !go1.9 // Package google provides support for making OAuth2 authorized and authenticated // HTTP requests to Google APIs. It supports the Web server flow, client-side // credentials, service accounts, Google Compute Engine service accounts, and Google // App Engine service accounts. // // A brief overview of the package follows. For more information, please read // https://developers.google.com/accounts/docs/OAuth2 // and // https://developers.google.com/accounts/docs/application-default-credentials. // // OAuth2 Configs // // Two functions in this package return golang.org/x/oauth2.Config values from Google credential // data. Google supports two JSON formats for OAuth2 credentials: one is handled by ConfigFromJSON, // the other by JWTConfigFromJSON. The returned Config can be used to obtain a TokenSource or // create an http.Client. // // // Credentials // // The DefaultCredentials type represents Google Application Default Credentials, as // well as other forms of credential. // // Use FindDefaultCredentials to obtain Application Default Credentials. // FindDefaultCredentials looks in some well-known places for a credentials file, and // will call AppEngineTokenSource or ComputeTokenSource as needed. // // DefaultClient and DefaultTokenSource are convenience methods. They first call FindDefaultCredentials, // then use the credentials to construct an http.Client or an oauth2.TokenSource. // // Use CredentialsFromJSON to obtain credentials from either of the two JSON // formats described in OAuth2 Configs, above. (The DefaultCredentials returned may // not be "Application Default Credentials".) The TokenSource in the returned value // is the same as the one obtained from the oauth2.Config returned from // ConfigFromJSON or JWTConfigFromJSON, but the DefaultCredentials may contain // additional information that is useful is some circumstances. package google // import "golang.org/x/oauth2/google"
apache-2.0
stefanbirkner/junit
src/main/java/org/junit/internal/RealSystem.java
323
package org.junit.internal; import java.io.PrintStream; public class RealSystem implements JUnitSystem { /** * Will be removed in the next major release */ @Deprecated public void exit(int code) { System.exit(code); } public PrintStream out() { return System.out; } }
epl-1.0
GunoH/intellij-community
python/testData/completion/weakQualifierBoundMethodAttributes.py
139
class MyClass(object): def method(self): pass if True: inst = MyClass() else: inst = unresolved inst.method.__<caret>
apache-2.0
mikeusry/BLG6
sites/all/modules/panels/plugins/export_ui/panels_layouts_ui.class.php
9012
<?php // $Id: panels_layouts_ui.class.php,v 1.1.2.8 2010/07/23 21:49:03 merlinofchaos Exp $ class panels_layouts_ui extends ctools_export_ui { var $lipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam egestas congue nibh, vel dictum ante posuere vitae. Cras gravida massa tempor metus eleifend sed elementum tortor scelerisque. Vivamus egestas, tortor quis luctus tristique, sem velit adipiscing risus, et tempus enim felis in massa. Morbi viverra, nisl quis rhoncus imperdiet, turpis massa vestibulum turpis, egestas faucibus nibh metus vel nunc. In hac habitasse platea dictumst. Nunc sit amet nisi quis ipsum tincidunt semper. Donec ac urna enim, et placerat arcu. Morbi eu laoreet justo. Nullam nec velit eu neque mattis pulvinar sed non libero. Sed sed vulputate erat. Fusce sit amet dui nibh."; function hook_menu(&$items) { // During updates, this can run before our schema is set up, so our // plugin can be empty. if (empty($this->plugin['menu']['items']['add'])) { return; } // Change the item to a tab on the Panels page. $this->plugin['menu']['items']['list callback']['type'] = MENU_LOCAL_TASK; // Establish a base for adding plugins $base = $this->plugin['menu']['items']['add']; // Remove the default 'add' menu item. unset($this->plugin['menu']['items']['add']); ctools_include('plugins', 'panels'); $this->builders = panels_get_layout_builders(); asort($this->builders); foreach ($this->builders as $name => $builder) { // Create a new menu item for the builder $item = $base; $item['title'] = !empty($builder['builder tab title']) ? $builder['builder tab title'] : 'Add ' . $builder['title']; $item['page arguments'][] = $name; $item['path'] = 'add-' . $name; $this->plugin['menu']['items']['add ' . $name] = $item; } parent::hook_menu($items); } function edit_form(&$form, &$form_state) { ctools_include('plugins', 'panels'); // If the plugin is not set, then it should be provided as an argument: if (!isset($form_state['item']->plugin)) { $form_state['item']->plugin = $form_state['function args'][2]; } parent::edit_form($form, $form_state); $form['category'] = array( '#type' => 'textfield', '#title' => t('Category'), '#description' => t('What category this layout should appear in. If left blank the category will be "Miscellaneous".'), '#default_value' => $form_state['item']->category, ); ctools_include('context'); ctools_include('display-edit', 'panels'); ctools_include('content'); // Provide actual layout admin UI here. // Create a display for editing: $cache_key = 'builder-' . $form_state['item']->name; // Load the display being edited from cache, if possible. if (!empty($_POST) && is_object($cache = panels_edit_cache_get($cache_key))) { $display = &$cache->display; } else { $content_types = ctools_content_get_available_types(); $display->cache_key = $cache_key; panels_cache_clear('display', $cache_key); $cache = new stdClass(); $display = panels_new_display(); $display->did = $form_state['item']->name; $display->layout = $form_state['item']->plugin; $display->layout_settings = $form_state['item']->settings; $display->cache_key = $cache_key; $display->editing_layout = TRUE; $cache->display = $display; $cache->content_types = $content_types; $cache->display_title = FALSE; panels_edit_cache_set($cache); } // Set up lipsum content in all of the existing panel regions: $display->content = array(); $display->panels = array(); $custom = ctools_get_content_type('custom'); $layout = panels_get_layout($display->layout); $regions = panels_get_regions($layout, $display); foreach ($regions as $id => $title) { $pane = panels_new_pane('custom', 'custom'); $pane->pid = $id; $pane->panel = $id; $pane->configuration = ctools_content_get_defaults($custom, 'custom'); $pane->configuration['title'] = 'Lorem Ipsum'; $pane->configuration['body'] = $this->lipsum; $display->content[$id] = $pane; $display->panels[$id] = array($id); } $form_state['display'] = &$display; // Tell the Panels form not to display buttons. $form_state['no buttons'] = TRUE; $form_state['no display settings'] = TRUE; $form_state['cache_key'] = $cache_key; $form_state['content_types'] = $cache->content_types; $form_state['display_title'] = FALSE; $form_state['renderer'] = panels_get_renderer_handler('editor', $cache->display); $form_state['renderer']->cache = &$cache; $form = array_merge($form, panels_edit_display_form($form_state)); // Make sure the theme will work since our form id is different. $form['#theme'] = 'panels_edit_display_form'; // If we leave the standard submit handler, it'll try to reconcile // content from the input, but we've not exposed that to the user. This // makes previews work with the content we forced in. $form['preview']['button']['#submit'] = array('panels_edit_display_form_preview'); } function edit_form_submit(&$form, &$form_state) { parent::edit_form_submit($form, $form_state); $form_state['item']->settings = $form_state['display']->layout_settings; } function list_form(&$form, &$form_state) { ctools_include('plugins', 'panels'); $this->builders = panels_get_layout_builders(); parent::list_form($form, $form_state); $categories = $plugins = array('all' => t('- All -')); foreach ($this->items as $item) { $categories[$item->category] = $item->category ? $item->category : t('Miscellaneous'); } $form['top row']['category'] = array( '#type' => 'select', '#title' => t('Category'), '#options' => $categories, '#default_value' => 'all', '#weight' => -10, ); foreach ($this->builders as $name => $plugin) { $plugins[$name] = $plugin['title']; } $form['top row']['plugin'] = array( '#type' => 'select', '#title' => t('Type'), '#options' => $plugins, '#default_value' => 'all', '#weight' => -9, ); } function list_filter($form_state, $item) { if ($form_state['values']['category'] != 'all' && $form_state['values']['category'] != $item->category) { return TRUE; } if ($form_state['values']['plugin'] != 'all' && $form_state['values']['plugin'] != $item->plugin) { return TRUE; } return parent::list_filter($form_state, $item); } function list_sort_options() { return array( 'disabled' => t('Enabled, title'), 'title' => t('Title'), 'name' => t('Name'), 'category' => t('Category'), 'storage' => t('Storage'), 'plugin' => t('Type'), ); } function list_build_row($item, &$form_state, $operations) { // Set up sorting switch ($form_state['values']['order']) { case 'disabled': $this->sorts[$item->name] = empty($item->disabled) . $item->admin_title; break; case 'title': $this->sorts[$item->name] = $item->admin_title; break; case 'name': $this->sorts[$item->name] = $item->name; break; case 'category': $this->sorts[$item->name] = ($item->category ? $item->category : t('Miscellaneous')) . $item->admin_title; break; case 'plugin': $this->sorts[$item->name] = $item->plugin; break; case 'storage': $this->sorts[$item->name] = $item->type . $item->admin_title; break; } $type = !empty($this->builders[$item->plugin]) ? $this->builders[$item->plugin]['title'] : t('Broken/missing plugin'); $category = $item->category ? check_plain($item->category) : t('Miscellaneous'); $this->rows[$item->name] = array( 'data' => array( array('data' => check_plain($type), 'class' => 'ctools-export-ui-type'), array('data' => check_plain($item->name), 'class' => 'ctools-export-ui-name'), array('data' => check_plain($item->admin_title), 'class' => 'ctools-export-ui-title'), array('data' => $category, 'class' => 'ctools-export-ui-category'), array('data' => theme('links', $operations), 'class' => 'ctools-export-ui-operations'), ), 'title' => check_plain($item->admin_description), 'class' => !empty($item->disabled) ? 'ctools-export-ui-disabled' : 'ctools-export-ui-enabled', ); } function list_table_header() { return array( array('data' => t('Type'), 'class' => 'ctools-export-ui-type'), array('data' => t('Name'), 'class' => 'ctools-export-ui-name'), array('data' => t('Title'), 'class' => 'ctools-export-ui-title'), array('data' => t('Category'), 'class' => 'ctools-export-ui-category'), array('data' => t('Operations'), 'class' => 'ctools-export-ui-operations'), ); } }
gpl-2.0
rodriguezdevera/sakai
signup/tool/src/java/org/sakaiproject/signup/tool/jsf/signupFilter.java
3379
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Educational * Community 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://opensource.org/licenses/ecl2.txt * * 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.sakaiproject.signup.tool.jsf; import java.util.Date; import java.util.List; import org.sakaiproject.signup.model.SignupAttendee; import org.sakaiproject.signup.model.SignupTimeslot; import org.sakaiproject.signup.tool.util.SignupBeanConstants; /** * * * <p> * This class will provide filter logic for Sign-up tool main page. * </P> * * @author gl256 * */ public class signupFilter implements SignupBeanConstants { private final String currentUserId; private final String filterChoice; public signupFilter(String currentUserId, String filterChoice) { this.currentUserId = currentUserId; this.filterChoice = filterChoice; } /** * Filter out the signupMeeting list according to the filter-choice. * * @param sMeetings * a list of SignupMeeting objects */ public void filterSignupMeetings(List<SignupMeetingWrapper> sMeetingWrps) { if (VIEW_MY_SIGNED_UP.equals(filterChoice)) getMySignedUpOnes(sMeetingWrps); else if (VIEW_IMMEDIATE_AVAIL.equals(filterChoice)) getImmediateAvailOnes(sMeetingWrps); } private void getImmediateAvailOnes(List<SignupMeetingWrapper> sMeetingWrps) { if (sMeetingWrps != null && !sMeetingWrps.isEmpty()) { for (int i = sMeetingWrps.size(); i > 0; i--) { if ((new Date()).before(sMeetingWrps.get(i - 1).getMeeting().getSignupBegins()) || (new Date()).after(sMeetingWrps.get(i - 1).getMeeting().getSignupDeadline())) { sMeetingWrps.remove(i - 1); } } } } private void getMySignedUpOnes(List<SignupMeetingWrapper> sMeetingWrps) { if (sMeetingWrps != null && !sMeetingWrps.isEmpty()) { for (int i = sMeetingWrps.size(); i > 0; i--) { SignupMeetingWrapper wrpOne = sMeetingWrps.get(i - 1); List<SignupTimeslot> signupTimeSlots = wrpOne.getMeeting().getSignupTimeSlots(); boolean found = false; for (SignupTimeslot timeslot : signupTimeSlots) { List<SignupAttendee> attendees = timeslot.getAttendees(); for (SignupAttendee attendee : attendees) { if (attendee.getAttendeeUserId().equals(currentUserId)) { found = true; break; } } if (found) { /* * set attendee's appointment time frame and set up for * the first schedule if multiple exists */ if (!wrpOne.isShowMyAppointmentTimeFrame()) { wrpOne.setStartTime(timeslot.getStartTime()); wrpOne.setEndTime(timeslot.getEndTime()); wrpOne.setShowMyAppointmentTimeFrame(true); } break; } } if (!found) { sMeetingWrps.remove(i - 1); } } } } }
apache-2.0
gregorypratt/jsdelivr
files/rxjs/2.5.0/rx.all.compat.js
386502
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { var len = arr.length, a = new Array(len); for(var i = 0; i < len; i++) { a[i] = arr[i]; } return a; } Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Fix for Tessel if (!Object.prototype.propertyIsEnumerable) { Object.prototype.propertyIsEnumerable = function (key) { for (var k in this) { if (k === key) { return true; } } return false; }; } if (!Object.keys) { Object.keys = (function() { 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty, hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'); return function(obj) { if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) { throw new TypeError('Object.keys called on non-object'); } var result = [], prop, i; for (prop in obj) { if (hasOwnProperty.call(obj, prop)) { result.push(prop); } } if (hasDontEnumBug) { for (i = 0; i < dontEnumsLength; i++) { if (hasOwnProperty.call(obj, dontEnums[i])) { result.push(dontEnums[i]); } } } return result; }; }()); } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); } recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle) }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { return thrower(result.e); } } } } var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(null, function () { observer.onCompleted(); }); }); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { return o.onError(e); } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (o) { return scheduler.scheduleWithState(value, function(_,v) { o.onNext(v); o.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }, source); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (o) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { o.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { o.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, function (e) { o.onError(e); }, function () { o.onNext(list); o.onCompleted(); }); }, source); } function firstOnly(x) { if (x.length === 0) { throw new EmptyError(); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @deprecated Use #reduce instead * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var hasSeed = false, accumulator, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var hasSeed = false, seed, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { return o.onError(e); } }, function (e) { o.onError(e); }, function () { hasValue && o.onNext(accumulation); !hasValue && hasSeed && o.onNext(seed); !hasValue && !hasSeed && o.onError(new EmptyError()); o.onCompleted(); } ); }, source); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = function (predicate, thisArg) { var source = this; return predicate ? source.filter(predicate, thisArg).some() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, function (e) { observer.onError(e); }, function () { observer.onNext(false); observer.onCompleted(); }); }, source); }; /** @deprecated use #some instead */ observableProto.any = function () { //deprecate('any', 'some'); return this.some.apply(this, arguments); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = function (predicate, thisArg) { return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not); }; /** @deprecated use #every instead */ observableProto.all = function () { //deprecate('all', 'every'); return this.every.apply(this, arguments); }; /** * Determines whether an observable sequence includes a specified element with an optional equality comparer. * @param searchElement The value to locate in the source sequence. * @param {Number} [fromIndex] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index. */ observableProto.includes = function (searchElement, fromIndex) { var source = this; function comparer(a, b) { return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b))); } return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(false); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i++ >= n && comparer(x, searchElement)) { o.onNext(true); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onNext(false); o.onCompleted(); }); }, this); }; /** * @deprecated use #includes instead. */ observableProto.contains = function (searchElement, fromIndex) { //deprecate('contains', 'includes'); observableProto.includes(searchElement, fromIndex); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.filter(predicate, thisArg).count() : this.reduce(function (count) { return count + 1; }, 0); }; /** * Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present. * @param {Any} searchElement Element to locate in the array. * @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0. * @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present. */ observableProto.indexOf = function(searchElement, fromIndex) { var source = this; return new AnonymousObservable(function (o) { var i = 0, n = +fromIndex || 0; Math.abs(n) === Infinity && (n = 0); if (n < 0) { o.onNext(-1); o.onCompleted(); return disposableEmpty; } return source.subscribe( function (x) { if (i >= n && x === searchElement) { o.onNext(i); o.onCompleted(); } i++; }, function (e) { o.onError(e); }, function () { o.onNext(-1); o.onCompleted(); }); }, source); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).sum() : this.reduce(function (prev, curr) { return prev + curr; }, 0); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector && isFunction(keySelector) ? this.map(keySelector, thisArg).average() : this.reduce(function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }, {sum: 0, count: 0 }).map(function (s) { if (s.count === 0) { throw new EmptyError(); } return s.sum / s.count; }); }; /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { o.onError(e); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (doner) { o.onNext(false); o.onCompleted(); } else { ql.push(x); } }, function(e) { o.onError(e); }, function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { o.onNext(false); o.onCompleted(); } else if (doner) { o.onNext(true); o.onCompleted(); } } }); (isArrayLike(second) || isIterable(second)) && (second = observableFrom(second)); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal; if (ql.length > 0) { var v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { o.onError(exception); return; } if (!equal) { o.onNext(false); o.onCompleted(); } } else if (donel) { o.onNext(false); o.onCompleted(); } else { qr.push(x); } }, function(e) { o.onError(e); }, function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { o.onNext(false); o.onCompleted(); } else if (donel) { o.onNext(true); o.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }, first); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (o) { var i = index; return source.subscribe(function (x) { if (i-- === 0) { o.onNext(x); o.onCompleted(); } }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new ArgumentOutOfRangeError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { o.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate && isFunction(predicate) ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate && isFunction(predicate) ? this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue); }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { return source.subscribe(function (x) { o.onNext(x); o.onCompleted(); }, function (e) { o.onError(e); }, function () { if (!hasDefault) { o.onError(new EmptyError()); } else { o.onNext(defaultValue); o.onCompleted(); } }); }, source); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (o) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, function (e) { o.onError(e); }, function () { if (!seenValue && !hasDefault) { o.onError(new EmptyError()); } else { o.onNext(value); o.onCompleted(); } }); }, source); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { var callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = callback(x, i, source); } catch (e) { o.onError(e); return; } if (shouldRun) { o.onNext(yieldIndex ? i : x); o.onCompleted(); } else { i++; } }, function (e) { o.onError(e); }, function () { o.onNext(yieldIndex ? -1 : undefined); o.onCompleted(); }); }, source); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Converts the observable sequence to a Set if it exists. * @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence. */ observableProto.toSet = function () { if (typeof root.Set === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var s = new root.Set(); return source.subscribe( function (x) { s.add(x); }, function (e) { o.onError(e); }, function () { o.onNext(s); o.onCompleted(); }); }, source); }; /** * Converts the observable sequence to a Map if it exists. * @param {Function} keySelector A function which produces the key for the Map. * @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence. * @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence. */ observableProto.toMap = function (keySelector, elementSelector) { if (typeof root.Map === 'undefined') { throw new TypeError(); } var source = this; return new AnonymousObservable(function (o) { var m = new root.Map(); return source.subscribe( function (x) { var key; try { key = keySelector(x); } catch (e) { o.onError(e); return; } var element = x; if (elementSelector) { try { element = elementSelector(x); } catch (e) { o.onError(e); return; } } m.set(key, element); }, function (e) { o.onError(e); }, function () { o.onNext(m); o.onCompleted(); }); }, source); }; var fnString = 'function', throwString = 'throw', isObject = Rx.internals.isObject; function toThunk(obj, ctx) { if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); } if (isGenerator(obj)) { return observableSpawn(obj); } if (isObservable(obj)) { return observableToThunk(obj); } if (isPromise(obj)) { return promiseToThunk(obj); } if (typeof obj === fnString) { return obj; } if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); } return obj; } function objectToThunk(obj) { var ctx = this; return function (done) { var keys = Object.keys(obj), pending = keys.length, results = new obj.constructor(), finished; if (!pending) { timeoutScheduler.schedule(function () { done(null, results); }); return; } for (var i = 0, len = keys.length; i < len; i++) { run(obj[keys[i]], keys[i]); } function run(fn, key) { if (finished) { return; } try { fn = toThunk(fn, ctx); if (typeof fn !== fnString) { results[key] = fn; return --pending || done(null, results); } fn.call(ctx, function(err, res) { if (finished) { return; } if (err) { finished = true; return done(err); } results[key] = res; --pending || done(null, results); }); } catch (e) { finished = true; done(e); } } } } function observableToThunk(observable) { return function (fn) { var value, hasValue = false; observable.subscribe( function (v) { value = v; hasValue = true; }, fn, function () { hasValue && fn(null, value); }); } } function promiseToThunk(promise) { return function(fn) { promise.then(function(res) { fn(null, res); }, fn); } } function isObservable(obj) { return obj && typeof obj.subscribe === fnString; } function isGeneratorFunction(obj) { return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction'; } function isGenerator(obj) { return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString; } /* * Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions. * @param {Function} The spawning function. * @returns {Function} a function which has a done continuation. */ var observableSpawn = Rx.spawn = function (fn) { var isGenFun = isGeneratorFunction(fn); return function (done) { var ctx = this, gen = fn; if (isGenFun) { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } var len = args.length, hasCallback = len && typeof args[len - 1] === fnString; done = hasCallback ? args.pop() : handleError; gen = fn.apply(this, args); } else { done = done || handleError; } next(); function exit(err, res) { timeoutScheduler.schedule(done.bind(ctx, err, res)); } function next(err, res) { var ret; // multiple args if (arguments.length > 2) { for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); } } if (err) { try { ret = gen[throwString](err); } catch (e) { return exit(e); } } if (!err) { try { ret = gen.next(res); } catch (e) { return exit(e); } } if (ret.done) { return exit(null, ret.value); } ret.value = toThunk(ret.value, ctx); if (typeof ret.value === fnString) { var called = false; try { ret.value.call(ctx, function() { if (called) { return; } called = true; next.apply(ctx, arguments); }); } catch (e) { timeoutScheduler.schedule(function () { if (called) { return; } called = true; next.call(ctx, e); }); } return; } // Not supported next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.')); } } }; function handleError(err) { if (!err) { return; } timeoutScheduler.schedule(function() { throw err; }); } /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler() { var len = arguments.length, results = new Array(len); for(var i = 0; i < len; i++) { results[i] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var len = arguments.length, results = []; for(var i = 1; i < len; i++) { results[i - 1] = arguments[i]; } if (selector) { try { results = selector.apply(context, results); } catch (e) { return observer.onError(e); } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation) { event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch (event.type) { case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { // Handles jq, Angular.js, Zepto, Marionette, Ember.js if (typeof element.on === 'function' && typeof element.off === 'function') { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { return observer.onError(err); } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (__super__) { inherits(PausableObservable, __super__); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (o) { var hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(2), err; function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { if (err) { o.onError(err); return; } try { res = resultSelector.apply(null, values); } catch (ex) { o.onError(ex); return; } o.onNext(res); } if (isDone && values[1]) { o.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, function (e) { if (values[1]) { o.onError(e); } else { err = e; } }, function () { isDone = true; values[1] && o.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, function (e) { o.onError(e); }, function () { isDone = true; next(true, 1); }) ); }, source); } var PausableBufferedObservable = (function (__super__) { inherits(PausableBufferedObservable, __super__); function subscribe(o) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { o.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { o.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { o.onNext(q.shift()); } o.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } __super__.call(this, subscribe, source); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; var ControlledObservable = (function (__super__) { inherits(ControlledObservable, __super__); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { __super__.call(this, subscribe, source); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = (function (__super__) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, __super__); function ControlledSubject(enableQueue) { enableQueue == null && (enableQueue = true); __super__.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) this.subject.onCompleted(); else this.queue.push(Rx.Notification.createOnCompleted()); }, onError: function (error) { this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) this.subject.onError(error); else this.queue.push(Rx.Notification.createOnError(error)); }, onNext: function (value) { var hasRequested = false; if (this.requestedCount === 0) { this.enableQueue && this.queue.push(Rx.Notification.createOnNext(value)); } else { (this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest(); hasRequested = true; } hasRequested && this.subject.onNext(value); }, _processRequest: function (numberOfItems) { if (this.enableQueue) { while ((this.queue.length >= numberOfItems && numberOfItems > 0) || (this.queue.length > 0 && this.queue[0].kind !== 'N')) { var first = this.queue.shift(); first.accept(this.subject); if (first.kind === 'N') numberOfItems--; else { this.disposeCurrentRequest(); this.queue = []; } } return { numberOfItems : numberOfItems, returnValue: this.queue.length !== 0}; } //TODO I don't think this is ever necessary, since termination of a sequence without a queue occurs in the onCompletion or onError function //if (this.hasFailed) { // this.subject.onError(this.error); //} else if (this.hasCompleted) { // this.subject.onCompleted(); //} return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); var number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable; } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; } }); return ControlledSubject; }(Observable)); /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var StopAndWaitObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(1); }); return this.subscription; } inherits(StopAndWaitObservable, __super__); function StopAndWaitObservable (source) { __super__.call(this, subscribe, source); this.source = source; } var StopAndWaitObserver = (function (__sub__) { inherits(StopAndWaitObserver, __sub__); function StopAndWaitObserver (observer, observable, cancel) { __sub__.call(this); this.observer = observer; this.observable = observable; this.cancel = cancel; } var stopAndWaitObserverProto = StopAndWaitObserver.prototype; stopAndWaitObserverProto.completed = function () { this.observer.onCompleted(); this.dispose(); }; stopAndWaitObserverProto.error = function (error) { this.observer.onError(error); this.dispose(); } stopAndWaitObserverProto.next = function (value) { this.observer.onNext(value); var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(1); }); }; stopAndWaitObserverProto.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return StopAndWaitObserver; }(AbstractObserver)); return StopAndWaitObservable; }(Observable)); /** * Attaches a stop and wait observable to the current observable. * @returns {Observable} A stop and wait observable. */ ControlledObservable.prototype.stopAndWait = function () { return new StopAndWaitObservable(this); }; var WindowedObservable = (function (__super__) { function subscribe (observer) { this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription)); var self = this; timeoutScheduler.schedule(function () { self.source.request(self.windowSize); }); return this.subscription; } inherits(WindowedObservable, __super__); function WindowedObservable(source, windowSize) { __super__.call(this, subscribe, source); this.source = source; this.windowSize = windowSize; } var WindowedObserver = (function (__sub__) { inherits(WindowedObserver, __sub__); function WindowedObserver(observer, observable, cancel) { this.observer = observer; this.observable = observable; this.cancel = cancel; this.received = 0; } var windowedObserverPrototype = WindowedObserver.prototype; windowedObserverPrototype.completed = function () { this.observer.onCompleted(); this.dispose(); }; windowedObserverPrototype.error = function (error) { this.observer.onError(error); this.dispose(); }; windowedObserverPrototype.next = function (value) { this.observer.onNext(value); this.received = ++this.received % this.observable.windowSize; if (this.received === 0) { var self = this; timeoutScheduler.schedule(function () { self.observable.source.request(self.observable.windowSize); }); } }; windowedObserverPrototype.dispose = function () { this.observer = null; if (this.cancel) { this.cancel.dispose(); this.cancel = null; } __sub__.prototype.dispose.call(this); }; return WindowedObserver; }(AbstractObserver)); return WindowedObservable; }(Observable)); /** * Creates a sliding windowed observable based upon the window size. * @param {Number} windowSize The number of items in the window * @returns {Observable} A windowed observable based upon the window size. */ ControlledObservable.prototype.windowed = function (windowSize) { return new WindowedObservable(this, windowSize); }; /** * Pipes the existing Observable sequence into a Node.js Stream. * @param {Stream} dest The destination Node.js stream. * @returns {Stream} The destination stream. */ observableProto.pipe = function (dest) { var source = this.pausableBuffered(); function onDrain() { source.resume(); } dest.addListener('drain', onDrain); source.subscribe( function (x) { !dest.write(String(x)) && source.pause(); }, function (err) { dest.emit('error', err); }, function () { // Hack check because STDIO is not closable !dest._isStdio && dest.end(); dest.removeListener('drain', onDrain); }); source.resume(); return dest; }; /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }, source) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param windowSize [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, windowSize, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, windowSize, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, windowSize, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, windowSize, scheduler) { return this.replay(null, bufferSize, windowSize, scheduler).refCount(); }; var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.hasError = false; } addProperties(BehaviorSubject.prototype, Observer, { /** * Gets the current value or throws an exception. * Value is frozen after onCompleted is called. * After onError is called always throws the specified exception. * An exception is always thrown after dispose is called. * @returns {Mixed} The initial value passed to the constructor until onNext is called; after which, the last value passed to onNext. */ getValue: function () { checkDisposed(this); if (this.hasError) { throw this.error; } return this.value; }, /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { var maxSafeInteger = Math.pow(2, 53) - 1; function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed(this); this._trim(this.scheduler.now()); this.observers.push(so); for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { so.onError(this.error); } else if (this.isStopped) { so.onCompleted(); } so.ensureActive(); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? maxSafeInteger : bufferSize; this.windowSize = windowSize == null ? maxSafeInteger : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onError(error); observer.ensureActive(); } this.observers.length = 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { var observer = os[i]; observer.onCompleted(); observer.ensureActive(); } this.observers.length = 0; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, function (o) { return subject.subscribe(o); }); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if ((candidate & 1) === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash << 5) - hash) + character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof valueOf === 'string') { return stringHashFn(valueOf); } } if (obj.hashCode) { return obj.hashCode(); } var id = 17 * uniqueIdCounter++; obj.hashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new ArgumentOutOfRangeError(); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }, left); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }, left); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) { return win; }); } function observableWindowWithBoundaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var win = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries)); d.add(windowBoundaries.subscribe(function (w) { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); return r; }, source); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), win = new Subject(); observer.onNext(addRef(win, r)); d.add(source.subscribe(function (x) { win.onNext(x); }, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); observer.onCompleted(); })); function createWindowClose () { var windowClose; try { windowClose = windowClosingSelector(); } catch (e) { observer.onError(e); return; } isPromise(windowClose) && (windowClose = observableFromPromise(windowClose)); var m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) { win.onError(err); observer.onError(err); }, function () { win.onCompleted(); win = new Subject(); observer.onNext(addRef(win, r)); createWindowClose(); })); } createWindowClose(); return r; }, source); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }, source); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { return [ this.filter(predicate, thisArg), this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) { return enumerableOf(sources, resultSelector, thisArg).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }, this); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = []; if (Array.isArray(arguments[0])) { allSources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); } } return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }, first); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }, source); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeAll().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwError(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = root.Map || (function () { function Map() { this._keys = []; this._values = []; } Map.prototype.get = function (key) { var i = this._keys.indexOf(key); return i !== -1 ? this._values[i] : undefined; }; Map.prototype.set = function (key, value) { var i = this._keys.indexOf(key); i !== -1 && (this._values[i] = value); this._values[this._keys.push(key) - 1] = value; }; Map.prototype.forEach = function (callback, thisArg) { for (var i = 0, len = this._keys.length; i < len; i++) { callback.call(thisArg, this._values[i], this._keys[i]); } }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * @param other Observable sequence to match in addition to the current pattern. * @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { return new Pattern(this.patterns.concat(other)); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } function ActivePlan(joinObserverArray, onNext, onCompleted) { this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (var i = 0, len = this.joinObserverArray.length; i < len; i++) { var joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { this.joinObservers.forEach(function (v) { v.queue.shift(); }); }; ActivePlan.prototype.match = function () { var i, len, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { var firstValues = [], isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true); } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); var values = []; for (i = 0, len = firstValues.length; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; var JoinObserver = (function (__super__) { inherits(JoinObserver, __super__); function JoinObserver(source, onError) { __super__.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { return this.onError(notification.exception); } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; JoinObserverPrototype.error = noop; JoinObserverPrototype.completed = noop; JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; JoinObserverPrototype.removeActivePlan = function (activePlan) { this.activePlans.splice(this.activePlans.indexOf(activePlan), 1); this.activePlans.length === 0 && this.dispose(); }; JoinObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param {Function} selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var len = arguments.length, plans; if (Array.isArray(arguments[0])) { plans = arguments[0]; } else { plans = new Array(len); for(var i = 0; i < len; i++) { plans[i] = arguments[i]; } } return new AnonymousObservable(function (o) { var activePlans = [], externalSubscriptions = new Map(); var outObserver = observerCreate( function (x) { o.onNext(x); }, function (err) { externalSubscriptions.forEach(function (v) { v.onError(err); }); o.onError(err); }, function (x) { o.onCompleted(); } ); try { for (var i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); activePlans.length === 0 && o.onCompleted(); })); } } catch (e) { observableThrow(e).subscribe(o); } var group = new CompositeDisposable(); externalSubscriptions.forEach(function (joinObserver) { joinObserver.subscribe(); group.add(joinObserver); }); return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count); self(count + 1, d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }, source); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The debounced sequence. */ observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, this); }; /** * @deprecated use #debounce or #throttleWithTimeout instead. */ observableProto.throttle = function(dueTime, scheduler) { //deprecate('throttle', 'debounce or throttleWithTimeout'); return this.debounce(dueTime, scheduler); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (isScheduler(timeShiftOrScheduler)) { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { if (isShift) { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } isSpan && q.shift().onCompleted(); createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var timerD = new SerialDisposable(), groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable), n = 0, windowId = 0, s = new Subject(); function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { if (id !== windowId) { return; } n = 0; var newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe( function (x) { var newId = 0, newWindow = false; s.onNext(x); if (++n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }, source); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(start, observer.onError.bind(observer), start)); } return new CompositeDisposable(subscription, delays); }, this); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false; function setTimer(timeout) { var myId = id; function timerWins () { return id === myId; } var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); d.dispose(); }, function (e) { timerWins() && observer.onError(e); }, function () { timerWins() && subscription.setDisposable(other.subscribe(observer)); })); }; setTimer(firstTimeout); function observerWins() { var res = !switched; if (res) { id++; } return res; } original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout); } }, function (e) { observerWins() && observer.onError(e); }, function () { observerWins() && observer.onCompleted(); })); return new CompositeDisposable(subscription, timer); }, source); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The debounced sequence. */ observableProto.debounceWithSelector = function (durationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0; var subscription = source.subscribe(function (x) { var throttle; try { throttle = durationSelector(x); } catch (e) { observer.onError(e); return; } isPromise(throttle) && (throttle = observableFromPromise(throttle)); hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { hasValue && id === currentid && observer.onNext(value); hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); hasValue && observer.onNext(value); observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }, source); }; /** * @deprecated use #debounceWithSelector instead. */ observableProto.throttleWithSelector = function (durationSelector) { //deprecate('throttleWithSelector', 'debounceWithSelector'); return this.debounceWithSelector(durationSelector); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { o.onNext(q.shift().value); } o.onCompleted(); }); }, source); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { o.onNext(next.value); } } o.onCompleted(); }); }, source); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, function (e) { o.onError(e); }, function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); now - next.interval <= duration && res.push(next.value); } o.onNext(res); o.onCompleted(); }); }, source); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (o) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }, source); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [scheduler]); * 2 - res = source.skipUntilWithTime(5000, [scheduler]); * @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); })); }, source); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} [scheduler] Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (o) { return new CompositeDisposable( scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }), source.subscribe(o)); }, source); }; /** * Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration. * @param {Number} windowDuration time to wait before emitting another item after emitting the last item * @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout. * @returns {Observable} An Observable that performs the throttle operation. */ observableProto.throttleFirst = function (windowDuration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var duration = +windowDuration || 0; if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); } var source = this; return new AnonymousObservable(function (o) { var lastOnNext = 0; return source.subscribe( function (x) { var now = scheduler.now(); if (lastOnNext === 0 || now - lastOnNext >= duration) { lastOnNext = now; o.onNext(x); } },function (e) { o.onError(e); }, function () { o.onCompleted(); } ); }, source); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }, this); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this, selectorFunc = bindCallback(selector, thisArg, 3); return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selectorFunc(x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, function (e) { observer.onError(e); }, function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, function (e) { observer.onError(e); }, function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }, this); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new ArgumentOutOfRangeError(); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new ArgumentOutOfRangeError(); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var GroupedObservable = (function (__super__) { inherits(GroupedObservable, __super__); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } function GroupedObservable(key, underlyingObservable, mergedDisposable) { __super__.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Used to pause and resume streams. */ Rx.Pauser = (function (__super__) { inherits(Pauser, __super__); function Pauser() { __super__.call(this); } /** * Pauses the underlying sequence. */ Pauser.prototype.pause = function () { this.onNext(false); }; /** * Resumes the underlying sequence. */ Pauser.prototype.resume = function () { this.onNext(true); }; return Pauser; }(Subject)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
mit
ashwinr/DefinitelyTyped
types/react-icons/fa/fighter-jet.d.ts
158
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class FaFighterJet extends React.Component<IconBaseProps> { }
mit
ashwinr/DefinitelyTyped
types/react-icons/io/ios-download-outline.d.ts
166
import * as React from 'react'; import { IconBaseProps } from 'react-icon-base'; export default class IoIosDownloadOutline extends React.Component<IconBaseProps> { }
mit
bgold09/azure-powershell
src/ServiceManagement/Storage/Commands.Storage.ScenarioTest/StorageObjectType.cs
909
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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. // ---------------------------------------------------------------------------------- namespace Commands.Storage.ScenarioTest { public enum StorageObjectType { Container, Blob, Queue, Table }; }
apache-2.0
dalinhuang/cameras
includes/modules/pages/create_account/jscript_addr_pulldowns.php
2765
<?php /** * jscript_addr_pulldowns * * handles pulldown menu dependencies for state/country selection * * @package page * @copyright Copyright 2003-2006 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: jscript_addr_pulldowns.php 4830 2006-10-24 21:58:27Z drbyte $ */ ?> <script language="javascript" type="text/javascript"><!-- function update_zone(theForm) { // if there is no zone_id field to update, or if it is hidden from display, then exit performing no updates if (!theForm || !theForm.elements["zone_id"]) return; if (theForm.zone_id.type == "hidden") return; // set initial values var SelectedCountry = theForm.zone_country_id.options[theForm.zone_country_id.selectedIndex].value; var SelectedZone = theForm.elements["zone_id"].value; // reset the array of pulldown options so it can be repopulated var NumState = theForm.zone_id.options.length; while(NumState > 0) { NumState = NumState - 1; theForm.zone_id.options[NumState] = null; } // build dynamic list of countries/zones for pulldown <?php echo zen_js_zone_list('SelectedCountry', 'theForm', 'zone_id'); ?> // if we had a value before reset, set it again if (SelectedZone != "") theForm.elements["zone_id"].value = SelectedZone; } function hideStateField(theForm) { theForm.state.disabled = true; theForm.state.className = 'hiddenField'; theForm.state.setAttribute('className', 'hiddenField'); document.getElementById("stateLabel").className = 'hiddenField'; document.getElementById("stateLabel").setAttribute('className', 'hiddenField'); document.getElementById("stText").className = 'hiddenField'; document.getElementById("stText").setAttribute('className', 'hiddenField'); document.getElementById("stBreak").className = 'hiddenField'; document.getElementById("stBreak").setAttribute('className', 'hiddenField'); } function showStateField(theForm) { theForm.state.disabled = false; theForm.state.className = 'inputLabel visibleField'; theForm.state.setAttribute('className', 'visibleField'); document.getElementById("stateLabel").className = 'inputLabel visibleField'; document.getElementById("stateLabel").setAttribute('className', 'inputLabel visibleField'); document.getElementById("stText").className = 'alert visibleField'; document.getElementById("stText").setAttribute('className', 'alert visibleField'); document.getElementById("stBreak").className = 'clearBoth visibleField'; document.getElementById("stBreak").setAttribute('className', 'clearBoth visibleField'); } //--></script>
gpl-2.0
YaDelivery/yii
build/generate_accessors_phpdoc.php
4205
<?php $nFiles = 0; $nFilesTotal = 0; $nClasses = 0; $nClassesTotal = 0; file_put_contents( dirname(__FILE__) . '/phpdoc.txt', getPhpDocForDir(dirname(dirname(__FILE__)) . '/framework') . getPhpDocStats() // getPhpDocForDir(dirname(dirname(__FILE__)) . '/framework/caching') . getPhpDocStats() // getPhpDocForDir(dirname(dirname(__FILE__)) . '/framework/base/CModel.php') . getPhpDocStats() ); function getPhpDocStats() { global $nFiles, $nFilesTotal, $nClasses, $nClassesTotal; return "\n\nComments for $nClasses classes in $nFiles files (processed $nClassesTotal classes in $nFilesTotal files)\n"; } function getPhpDocForDir($dirName) { global $nFiles, $nFilesTotal; $phpdocDir = ""; $files = new RegexIterator( new RecursiveIteratorIterator( new RecursiveDirectoryIterator($dirName) ), '#^.+\.php$#i', RecursiveRegexIterator::GET_MATCH); foreach ($files as $file) { $phpdocFile = getPhpDocForFile($file[0]); if ($phpdocFile != "") { $phpdocDir .= "\n[ " . $file[0] . " ]\n"; $phpdocDir .= $phpdocFile; $nFiles++; } $nFilesTotal++; } return $phpdocDir; } function getPhpDocForFile($fileName) { global $nClasses, $nClassesTotal; $phpdoc = ""; $file = str_replace("\r", "", str_replace("\t", " ", file_get_contents($fileName, true))); $classes = match('#\n(?:abstract )?class (?<name>\w+) extends .+\{(?<content>.+)\n\}(\n|$)#', $file); foreach ($classes as &$class) { $gets = match( '#\* @return (?<type>\w+)(?: (?<comment>(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' . '[\s\n]{2,}public function (?<kind>get)(?<name>\w+)\((?:,? ?\$\w+ ?= ?[^,]+)*\)#', $class['content']); $sets = match( '#\* @param (?<type>\w+) \$\w+(?: (?<comment>(?:(?!\*/|\* @).)+?)(?:(?!\*/).)+|[\s\n]*)\*/' . '[\s\n]{2,}public function (?<kind>set)(?<name>\w+)\(\$\w+(?:, ?\$\w+ ?= ?[^,]+)*\)#', $class['content']); $acrs = array_merge($gets, $sets); //print_r($acrs); continue; $props = array(); foreach ($acrs as &$acr) { $acr['name'] = camelCase($acr['name']); $acr['comment'] = trim(preg_replace('#(^|\n)\s+\*\s?#', '$1 * ', $acr['comment'])); $props[$acr['name']][$acr['kind']] = array( 'type' => $acr['type'], 'comment' => fixSentence($acr['comment']), ); } /*foreach ($props as $propName => &$prop) // I don't like write-only props... if (!isset($prop['get'])) unset($props[$propName]);*/ if (count($props) > 0) { $phpdoc .= "\n" . $class['name'] . ":\n"; $phpdoc .= " *\n"; foreach ($props as $propName => &$prop) { $phpdoc .= ' * @'; /*if (isset($prop['get']) && isset($prop['set'])) // Few IDEs support complex syntax $phpdoc .= 'property'; elseif (isset($prop['get'])) $phpdoc .= 'property-read'; elseif (isset($prop['set'])) $phpdoc .= 'property-write';*/ $phpdoc .= 'property'; $phpdoc .= ' ' . getPropParam($prop, 'type') . " $$propName " . getPropParam($prop, 'comment') . "\n"; } $phpdoc .= " *\n"; $nClasses++; } $nClassesTotal++; } return $phpdoc; } function match($pattern, $subject) { $sets = array(); preg_match_all($pattern . 'suU', $subject, $sets, PREG_SET_ORDER); foreach ($sets as &$set) foreach ($set as $i => $match) if (is_numeric($i) /*&& $i != 0*/) unset($set[$i]); return $sets; } function camelCase($str) { return strtolower(substr($str, 0, 1)) . substr($str, 1); } function fixSentence($str) { if ($str == '') return ''; return strtoupper(substr($str, 0, 1)) . substr($str, 1) . ($str[strlen($str) - 1] != '.' ? '.' : ''); } function getPropParam($prop, $param) { return isset($prop['get']) ? $prop['get'][$param] : $prop['set'][$param]; } ?>
bsd-3-clause
SerCeMan/intellij-community
java/java-tests/testData/compileServer/incremental/markDirty/recompileDependent/src/Client.java
104
class Client { public static void main(String[] args) { System.out.println(Server.CONSTANT); } }
apache-2.0
tylerball/homebrew
Library/Formula/dnsmasq.rb
2313
class Dnsmasq < Formula homepage "http://www.thekelleys.org.uk/dnsmasq/doc.html" url "http://www.thekelleys.org.uk/dnsmasq/dnsmasq-2.72.tar.gz" sha1 "c2dc54b142ec5676d6e22951bc5b61863b0503fe" bottle do revision 1 sha1 "68baa9fab86c8f30738984f2d734d537a0e815e5" => :yosemite sha1 "926b6cf81ecd09011a64ded5922231cb13aae7d8" => :mavericks sha1 "86e05946e01f650595ea72332fcce61e5e489ed4" => :mountain_lion end option "with-libidn", "Compile with IDN support" option "with-dnssec", "Compile with DNSSEC support" deprecated_option "with-idn" => "with-libidn" depends_on "pkg-config" => :build depends_on "libidn" => :optional depends_on "nettle" if build.with? "dnssec" def install ENV.deparallelize # Fix etc location inreplace "src/config.h", "/etc/dnsmasq.conf", "#{etc}/dnsmasq.conf" # Optional IDN support if build.with? "libidn" inreplace "src/config.h", "/* #define HAVE_IDN */", "#define HAVE_IDN" end # Optional DNSSEC support if build.with? "dnssec" inreplace "src/config.h", "/* #define HAVE_DNSSEC */", "#define HAVE_DNSSEC" end # Fix compilation on Lion ENV.append_to_cflags "-D__APPLE_USE_RFC_3542" if MacOS.version >= :lion inreplace "Makefile" do |s| s.change_make_var! "CFLAGS", ENV.cflags end system "make", "install", "PREFIX=#{prefix}" prefix.install "dnsmasq.conf.example" end def caveats; <<-EOS.undent To configure dnsmasq, copy the example configuration to #{etc}/dnsmasq.conf and edit to taste. cp #{opt_prefix}/dnsmasq.conf.example #{etc}/dnsmasq.conf EOS end plist_options :startup => true def plist; <<-EOS.undent <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>Label</key> <string>#{plist_name}</string> <key>ProgramArguments</key> <array> <string>#{opt_sbin}/dnsmasq</string> <string>--keep-in-foreground</string> </array> <key>RunAtLoad</key> <true/> <key>KeepAlive</key> <true/> </dict> </plist> EOS end test do system "#{bin}/dnsmasq", "--test" end end
bsd-2-clause
mdaniel/intellij-community
java/java-psi-impl/src/com/intellij/psi/impl/java/stubs/PsiImportListStub.java
823
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author max */ package com.intellij.psi.impl.java.stubs; import com.intellij.psi.PsiImportList; import com.intellij.psi.stubs.StubElement; public interface PsiImportListStub extends StubElement<PsiImportList> { }
apache-2.0
chbfiv/fabric-engine-old
Native/ThirdParty/Private/include/boost/boost/xpressive/regex_constants.hpp
16829
/////////////////////////////////////////////////////////////////////////////// /// \file regex_constants.hpp /// Contains definitions for the syntax_option_type, match_flag_type and /// error_type enumerations. // // Copyright 2008 Eric Niebler. 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) #ifndef BOOST_XPRESSIVE_REGEX_CONSTANTS_HPP_EAN_10_04_2005 #define BOOST_XPRESSIVE_REGEX_CONSTANTS_HPP_EAN_10_04_2005 // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif #include <boost/mpl/identity.hpp> #ifndef BOOST_XPRESSIVE_DOXYGEN_INVOKED # define icase icase_ #endif namespace boost { namespace xpressive { namespace regex_constants { /// Flags used to customize the regex syntax /// enum syntax_option_type { // these flags are required: ECMAScript = 0, ///< Specifies that the grammar recognized by the regular expression ///< engine uses its normal semantics: that is the same as that given ///< in the ECMA-262, ECMAScript Language Specification, Chapter 15 ///< part 10, RegExp (Regular Expression) Objects (FWD.1). ///< icase = 1 << 1, ///< Specifies that matching of regular expressions against a character ///< container sequence shall be performed without regard to case. ///< nosubs = 1 << 2, ///< Specifies that when a regular expression is matched against a ///< character container sequence, then no sub-expression matches are to ///< be stored in the supplied match_results structure. ///< optimize = 1 << 3, ///< Specifies that the regular expression engine should pay more ///< attention to the speed with which regular expressions are matched, ///< and less to the speed with which regular expression objects are ///< constructed. Otherwise it has no detectable effect on the program ///< output. ///< collate = 1 << 4, ///< Specifies that character ranges of the form "[a-b]" should be ///< locale sensitive. ///< // These flags are optional. If the functionality is supported // then the flags shall take these names. //basic = 1 << 5, ///< Specifies that the grammar recognized by the regular expression // ///< engine is the same as that used by POSIX basic regular expressions // ///< in IEEE Std 1003.1-2001, Portable Operating System Interface // ///< (POSIX), Base Definitions and Headers, Section 9, Regular // ///< Expressions (FWD.1). // ///< //extended = 1 << 6, ///< Specifies that the grammar recognized by the regular expression // ///< engine is the same as that used by POSIX extended regular // ///< expressions in IEEE Std 1003.1-2001, Portable Operating System // ///< Interface (POSIX), Base Definitions and Headers, Section 9, // ///< Regular Expressions (FWD.1). // ///< //awk = 1 << 7, ///< Specifies that the grammar recognized by the regular expression // ///< engine is the same as that used by POSIX utility awk in IEEE Std // ///< 1003.1-2001, Portable Operating System Interface (POSIX), Shells // ///< and Utilities, Section 4, awk (FWD.1). // ///< //grep = 1 << 8, ///< Specifies that the grammar recognized by the regular expression // ///< engine is the same as that used by POSIX utility grep in IEEE Std // ///< 1003.1-2001, Portable Operating System Interface (POSIX), // ///< Shells and Utilities, Section 4, Utilities, grep (FWD.1). // ///< //egrep = 1 << 9, ///< Specifies that the grammar recognized by the regular expression // ///< engine is the same as that used by POSIX utility grep when given // ///< the -E option in IEEE Std 1003.1-2001, Portable Operating System // ///< Interface (POSIX), Shells and Utilities, Section 4, Utilities, // ///< grep (FWD.1). // ///< // these flags are specific to xpressive, and they help with perl compliance. single_line = 1 << 10, ///< Specifies that the ^ and \$ metacharacters DO NOT match at ///< internal line breaks. Note that this is the opposite of the ///< perl default. It is the inverse of perl's /m (multi-line) ///< modifier. ///< not_dot_null = 1 << 11, ///< Specifies that the . metacharacter does not match the null ///< character \\0. ///< not_dot_newline = 1 << 12, ///< Specifies that the . metacharacter does not match the ///< newline character \\n. ///< ignore_white_space = 1 << 13 ///< Specifies that non-escaped white-space is not significant. ///< }; /// Flags used to customize the behavior of the regex algorithms /// enum match_flag_type { match_default = 0, ///< Specifies that matching of regular expressions proceeds ///< without any modification of the normal rules used in ///< ECMA-262, ECMAScript Language Specification, Chapter 15 ///< part 10, RegExp (Regular Expression) Objects (FWD.1) ///< match_not_bol = 1 << 1, ///< Specifies that the expression "^" should not be matched ///< against the sub-sequence [first,first). ///< match_not_eol = 1 << 2, ///< Specifies that the expression "\$" should not be ///< matched against the sub-sequence [last,last). ///< match_not_bow = 1 << 3, ///< Specifies that the expression "\\b" should not be ///< matched against the sub-sequence [first,first). ///< match_not_eow = 1 << 4, ///< Specifies that the expression "\\b" should not be ///< matched against the sub-sequence [last,last). ///< match_any = 1 << 7, ///< Specifies that if more than one match is possible then ///< any match is an acceptable result. ///< match_not_null = 1 << 8, ///< Specifies that the expression can not be matched ///< against an empty sequence. ///< match_continuous = 1 << 10, ///< Specifies that the expression must match a sub-sequence ///< that begins at first. ///< match_partial = 1 << 11, ///< Specifies that if no match can be found, then it is ///< acceptable to return a match [from, last) where ///< from != last, if there exists some sequence of characters ///< [from,to) of which [from,last) is a prefix, and which ///< would result in a full match. ///< match_prev_avail = 1 << 12, ///< Specifies that --first is a valid iterator position, ///< when this flag is set then the flags match_not_bol ///< and match_not_bow are ignored by the regular expression ///< algorithms (RE.7) and iterators (RE.8). ///< format_default = 0, ///< Specifies that when a regular expression match is to be ///< replaced by a new string, that the new string is ///< constructed using the rules used by the ECMAScript ///< replace function in ECMA-262, ECMAScript Language ///< Specification, Chapter 15 part 5.4.11 ///< String.prototype.replace. (FWD.1). In addition during ///< search and replace operations then all non-overlapping ///< occurrences of the regular expression are located and ///< replaced, and sections of the input that did not match ///< the expression, are copied unchanged to the output ///< string. ///< format_sed = 1 << 13, ///< Specifies that when a regular expression match is to be ///< replaced by a new string, that the new string is ///< constructed using the rules used by the Unix sed ///< utility in IEEE Std 1003.1-2001, Portable Operating ///< SystemInterface (POSIX), Shells and Utilities. ///< format_perl = 1 << 14, ///< Specifies that when a regular expression match is to be ///< replaced by a new string, that the new string is ///< constructed using an implementation defined superset ///< of the rules used by the ECMAScript replace function in ///< ECMA-262, ECMAScript Language Specification, Chapter 15 ///< part 5.4.11 String.prototype.replace (FWD.1). ///< format_no_copy = 1 << 15, ///< When specified during a search and replace operation, ///< then sections of the character container sequence being ///< searched that do match the regular expression, are not ///< copied to the output string. ///< format_first_only = 1 << 16, ///< When specified during a search and replace operation, ///< then only the first occurrence of the regular ///< expression is replaced. ///< format_literal = 1 << 17, ///< Treat the format string as a literal. ///< format_all = 1 << 18 ///< Specifies that all syntax extensions are enabled, ///< including conditional (?ddexpression1:expression2) ///< replacements. ///< }; /// Error codes used by the regex_error type /// enum error_type { error_collate, ///< The expression contained an invalid collating element name. ///< error_ctype, ///< The expression contained an invalid character class name. ///< error_escape, ///< The expression contained an invalid escaped character, ///< or a trailing escape. ///< error_subreg, ///< The expression contained an invalid back-reference. ///< error_brack, ///< The expression contained mismatched [ and ]. ///< error_paren, ///< The expression contained mismatched ( and ). ///< error_brace, ///< The expression contained mismatched { and }. ///< error_badbrace, ///< The expression contained an invalid range in a {} expression. ///< error_range, ///< The expression contained an invalid character range, for ///< example [b-a]. ///< error_space, ///< There was insufficient memory to convert the expression into a ///< finite state machine. ///< error_badrepeat, ///< One of *?+{ was not preceded by a valid regular expression. ///< error_complexity, ///< The complexity of an attempted match against a regular ///< expression exceeded a pre-set level. ///< error_stack, ///< There was insufficient memory to determine whether the regular ///< expression could match the specified character sequence. ///< error_badref, ///< An nested regex is uninitialized. ///< error_badmark, ///< An invalid use of a named capture. ///< error_badlookbehind, ///< An attempt to create a variable-width look-behind assertion ///< was detected. ///< error_badrule, ///< An invalid use of a rule was detected. ///< error_badarg, ///< An argument to an action was unbound. ///< error_badattr, ///< Tried to read from an uninitialized attribute. ///< error_internal ///< An internal error has occured. ///< }; /// INTERNAL ONLY inline syntax_option_type operator &(syntax_option_type b1, syntax_option_type b2) { return static_cast<syntax_option_type>( static_cast<int>(b1) & static_cast<int>(b2)); } /// INTERNAL ONLY inline syntax_option_type operator |(syntax_option_type b1, syntax_option_type b2) { return static_cast<syntax_option_type>(static_cast<int>(b1) | static_cast<int>(b2)); } /// INTERNAL ONLY inline syntax_option_type operator ^(syntax_option_type b1, syntax_option_type b2) { return static_cast<syntax_option_type>(static_cast<int>(b1) ^ static_cast<int>(b2)); } /// INTERNAL ONLY inline syntax_option_type operator ~(syntax_option_type b) { return static_cast<syntax_option_type>(~static_cast<int>(b)); } /// INTERNAL ONLY inline match_flag_type operator &(match_flag_type b1, match_flag_type b2) { return static_cast<match_flag_type>(static_cast<int>(b1) & static_cast<int>(b2)); } /// INTERNAL ONLY inline match_flag_type operator |(match_flag_type b1, match_flag_type b2) { return static_cast<match_flag_type>(static_cast<int>(b1) | static_cast<int>(b2)); } /// INTERNAL ONLY inline match_flag_type operator ^(match_flag_type b1, match_flag_type b2) { return static_cast<match_flag_type>(static_cast<int>(b1) ^ static_cast<int>(b2)); } /// INTERNAL ONLY inline match_flag_type operator ~(match_flag_type b) { return static_cast<match_flag_type>(~static_cast<int>(b)); } }}} // namespace boost::xpressive::regex_constants #ifndef BOOST_XPRESSIVE_DOXYGEN_INVOKED # undef icase #endif #endif
agpl-3.0
nhoobin/moodle
lib/horde/framework/Horde/Mail/Rfc822/Object.php
2676
<?php /** * Copyright 2012-2017 Horde LLC (http://www.horde.org/) * * See the enclosed file LICENSE for license information (BSD). If you * did not receive this file, see http://www.horde.org/licenses/bsd. * * @category Horde * @copyright 2012-2017 Horde LLC * @license http://www.horde.org/licenses/bsd New BSD License * @package Mail */ /** * Object representation of an RFC 822 element. * * @author Michael Slusarz <slusarz@horde.org> * @category Horde * @copyright 2012-2017 Horde LLC * @license http://www.horde.org/licenses/bsd New BSD License * @package Mail */ abstract class Horde_Mail_Rfc822_Object { /** * String representation of object. * * @return string Returns the full e-mail address. */ public function __toString() { return $this->writeAddress(); } /** * Write an address given information in this part. * * @param mixed $opts If boolean true, is equivalent to passing true for * both 'encode' and 'idn'. If an array, these * keys are supported: * - comment: (boolean) If true, include comment(s) in output? * @since 2.6.0 * DEFAULT: false * - encode: (mixed) MIME encode the personal/groupname parts? * If boolean true, encodes in 'UTF-8'. * If a string, encodes using this charset. * DEFAULT: false * - idn: (boolean) If true, encodes IDN domain names (RFC 3490). * DEFAULT: false * - noquote: (boolean) If true, don't quote personal part. [@since * 2.4.0] * DEFAULT: false * * @return string The correctly escaped/quoted address. */ public function writeAddress($opts = array()) { if ($opts === true) { $opts = array( 'encode' => 'UTF-8', 'idn' => true ); } elseif (!empty($opts['encode']) && ($opts['encode'] === true)) { $opts['encode'] = 'UTF-8'; } return $this->_writeAddress($opts); } /** * Class-specific implementation of writeAddress(). * * @see writeAddress() * * @param array $opts See writeAddress(). * * @return string The correctly escaped/quoted address. */ abstract protected function _writeAddress($opts); /** * Compare this object against other data. * * @param mixed $ob Address data. * * @return boolean True if the data reflects the same canonical address. */ abstract public function match($ob); }
gpl-3.0
KonaTeam/DefinitelyTyped
jquerymobile/jquerymobile.d.ts
11922
// Type definitions for jQuery Mobile 1.4 // Project: http://jquerymobile.com/ // Definitions by: Boris Yankov <https://github.com/borisyankov/> // Definitions: https://github.com/borisyankov/DefinitelyTyped /// <reference path="../jquery/jquery.d.ts"/> interface JQueryMobileEvent { (event: Event, ui: any): void; } interface DialogOptions { closeBtn?: string; closeBtnText?: string; corners?: boolean; initSelector?: string; overlayTheme?: string; } interface DialogEvents { create?: JQueryMobileEvent; } interface PopupOptions { corners?: boolean; history?: boolean; initSelector?: string; overlayTheme?: string; positionTo?: string; shadow?: boolean; theme?: string; tolerance?: string; transition?: string; } interface PopupEvents { popupbeforeposition?: JQueryMobileEvent; popupafteropen?: JQueryMobileEvent; popupafterclose?: JQueryMobileEvent; } interface FixedToolbarOptions { visibleOnPageShow?: boolean; disablePageZoom?: boolean; transition?: string; fullscreen?: boolean; tapToggle?: boolean; tapToggleBlacklist?: string; hideDuringFocus?: string; updatePagePadding?: boolean; supportBlacklist?: Function; initSelector?: string; } interface FixedToolbarEvents { create?: JQueryMobileEvent; } interface ButtonOptions { corners?: boolean; icon?: string; iconpos?: string; iconshadow?: boolean; inline?: boolean; mini?: boolean; shadow?: boolean; theme?: string; initSelector?: string; } interface ButtonEvents { create?: JQueryMobileEvent; } interface CollapsibleOptions { collapsed?: boolean; collapseCueText?: string; collapsedIcon?: string; contentTheme?: string; expandCueText?: string; expandedIcon?: string; heading?: string; iconpos?: string; initSelector?: string; inset?: boolean; mini?: boolean; theme?: string; } interface CollapsibleEvents { create?: JQueryMobileEvent; collapse?: JQueryMobileEvent; expand?: JQueryMobileEvent; } interface CollapsibleSetOptions { collapsedIcon?: string; expandedIcon?: string; iconpos?: string; initSelector?: string; inset?: boolean; mini?: boolean; theme?: string; } interface CollapsibleSetEvents { create?: JQueryMobileEvent; } interface TextInputOptions { clearBtn?: boolean; clearBtnText?: string; disabled?: boolean; initSelector?: string; mini?: boolean; preventFocusZoom?: boolean; theme?: string; } interface TextInputEvents { create?: JQueryMobileEvent; } interface SearchInputOptions { clearSearchButtonText?: string; disabled?: boolean; initSelector?: string; mini?: boolean; theme?: string; } interface SliderOptions { disabled?: boolean; highlight?: boolean; initSelector?: string; mini?: boolean; theme?: string; trackTheme?: string; } interface SliderEvents { create?: JQueryMobileEvent; slidestart?: JQueryMobileEvent; slidestop?: JQueryMobileEvent; } interface FlipswitchOptions { corners?: boolean; defaults?: boolean; disabled?: boolean; enhanced?: boolean; mini?: boolean; offText?: string; onText?: string; theme?: string; wrapperClass?: string; } interface CheckboxRadioOptions { mini?: boolean; theme?: string; } interface CheckboxRadioEvents { create?: JQueryMobileEvent; } interface SelectMenuOptions { corners?: boolean; icon?: string; iconpos?: string; iconshadow?: boolean; initSelector?: string; inline?: boolean; hidePlaceholderMenuItems: boolean; mini?: boolean; nativeMenu?: boolean; overlayTheme?: string; preventFocusZoom?: boolean; shadow?: boolean; theme?: string; } interface SelectMenuEvents { create?: JQueryMobileEvent; } interface ListViewOptions { autodividers?: boolean; autodividersSelector?: (jq?: JQuery) => string; countTheme?: string; defaults?: boolean; disabled?: boolean; dividerTheme?: string; filter?: boolean; filterCallback?: Function; filterPlaceholder?: string; filterTheme?: string; headerTheme?: string; initSelector?: string; inset?: boolean; splitIcon?: string; splitTheme?: string; theme?: string; } interface ListViewEvents { create?: JQueryMobileEvent; } interface FilterableOptions { children?: any; defaults?: boolean; disabled?: boolean; enhanced?: boolean; filterCallback?: {(index: number, searchValue?: string): boolean; }; filterPlaceholder?: string; filterReveal?: boolean; filterTheme?: string; input: any; } interface NavbarOptions { iconpos: string; } interface ControlgroupOptions { corners?: boolean; excludeInvisible?: boolean; mini?: boolean; shadow?: boolean; type?: string; } interface JQueryMobileOptions { activeBtnClass?: string; activePageClass?: string; ajaxEnabled?: boolean; allowCrossDomainPages?: boolean; autoInitializePage?: boolean; buttonMarkup: any; defaultDialogTransition?: string; defaultPageTransition?: string; getMaxScrollForTransition?: number; gradeA?: Function; hashListeningEnabled?: boolean; ignoreContentEnabled?: boolean; linkBindingEnabled?: boolean; loadingMessageTextVisible?: boolean; loadingMessageTheme?: string; maxTransitionWidth?: number; minScrollBack?: number; ns?: number; pageLoadErrorMessage?: string; pageLoadErrorMessageTheme?: string; phonegapNavigationEnabled?: boolean; pushStateEnabled?: boolean; subPageUrlKey?: string; touchOverflowEnabled?: boolean; transitionFallbacks: any; } interface JQueryMobileEvents { tap: any; taphold: any; swipe: any; swipeleft: any; swiperight: any; vmouseover: any; vmouseout: any; vmousedown: any; vmousemove: any; vmouseup: any; vclick: any; vmousecancel: any; orientationchange: any; scrollstart: any; scrollstop: any; pagebeforeload: any; pageload: any; pageloadfailed: any; pagebeforechange: any; pagechange: any; pagechangefailed: any; pagebeforeshow: any; pagebeforehide: any; pageshow: any; pagehide: any; pagebeforecreate: any; pagecreate: any; pageinit: any; pageremove: any; updatelayout: any; } interface ChangePageOptions { allowSamePageTransition?: boolean; changeHash?: boolean; data?: any; dataUrl?: string; pageContainer?: JQuery; reloadPage?: boolean; reverse?: boolean; role?: string; showLoadMsg?: boolean; transition?: string; type?: string; } interface LoadPageOptions { data?: any; loadMsgDelay?: number; pageContainer?: JQuery; reloadPage?: boolean; role?: string; showLoadMsg?: boolean; type?: string; } interface LoaderOptions { theme?: string; textVisible?: boolean; html?: string; text?: string; textonly?: boolean; } interface JQueryMobilePath { get(url: string): string; getDocumentBase(asParsedObject?: boolean): any; getDocumentUrl(asParsedObject?: boolean): any; getLocation(): string; isAbsoluteUrl(url: string): boolean; isRelativeUrl(url: string): boolean; makeUrlAbsolute(relUrl: string, absUrl: string): string; parseLocation(): ParsedPath; parseUrl(url: string): ParsedPath; } interface ParsedPath { authority: string; directory: string; domain: string; doubleSlash: string; filename: string; hash: string; host: string; hostname: string; href: string; hrefNoHash: string; hrefNoSearch: string; password: string; pathname: string; port: string; protocol: string; search: string; username: string; } interface JQueryMobile extends JQueryMobileOptions { version: string; changePage(to: any, options?: ChangePageOptions): void; initializePage(): void; loadPage(url: any, options?: LoadPageOptions): void; loading(): JQuery; loading(command: string, options?: LoaderOptions): JQuery; pageContainer: any; base: any; silentScroll(yPos: number): void; activePage: JQuery; options: JQueryMobileOptions; transitionFallbacks: any; loader: any; page: any; touchOverflow: any; showCategory: any; path: JQueryMobilePath; dialog: any; popup: any; fixedtoolbar: any; button: any; collapsible: any; collapsibleset: any; textinput: any; slider: any; flipswitch: any; checkboxradio: any; selectmenu: any; listview: any; filterable: any; defaultHomeScroll: number; } interface JQuerySupport { touchOverflow: any; } interface JQuery { enhanceWithin(): JQuery; dialog(): JQuery; dialog(command: string): JQuery; dialog(options: DialogOptions): JQuery; dialog(events: DialogEvents): JQuery; popup(): JQuery; popup(command: string): JQuery; popup(options: PopupOptions): JQuery; popup(command: string, options: PopupOptions): JQuery; popup(events: PopupEvents): JQuery; fixedtoolbar(): JQuery; fixedtoolbar(command: string): JQuery; fixedtoolbar(options: FixedToolbarOptions): JQuery; fixedtoolbar(events: FixedToolbarEvents): JQuery; button(): JQuery; button(command: string): JQuery; button(options?: ButtonOptions): JQuery; button(events: ButtonEvents): JQuery; buttonMarkup(options?: ButtonOptions): JQuery; collapsible(): JQuery; collapsible(command: string): JQuery; collapsible(options: CollapsibleOptions): JQuery; collapsible(events: CollapsibleEvents): JQuery; collapsibleSet(): JQuery; collapsibleSet(command: string): JQuery; collapsibleset(options: CollapsibleSetOptions): JQuery; collapsibleset(events: CollapsibleSetEvents): JQuery; textinput(): JQuery; textinput(command: string): JQuery; textinput(options: TextInputOptions): JQuery; textinput(events: TextInputEvents): JQuery; textinput(options: SearchInputOptions): JQuery; slider(): JQuery; slider(command: string): JQuery; slider(options: SliderOptions): JQuery; slider(events: SliderEvents): JQuery; flipswitch(): JQuery; flipswitch(command: string): JQuery; flipswitch(options: FlipswitchOptions): JQuery; checkboxradio(): JQuery; checkboxradio(command: string): JQuery; checkboxradio(options: CheckboxRadioOptions): JQuery; checkboxradio(events: CheckboxRadioEvents): JQuery; selectmenu(): JQuery; selectmenu(command: string): JQuery; selectmenu(command: string, update: boolean): JQuery; selectmenu(options: SelectMenuOptions): JQuery; selectmenu(events: SelectMenuEvents): JQuery; listview(): JQuery; listview(command: string): JQuery; listview(options: ListViewOptions): JQuery; listview(events: ListViewEvents): JQuery; filterable(): JQuery; filterable(command: string): JQuery; filterable(options: FilterableOptions): JQuery; navbar(options?: NavbarOptions): JQuery; table(): JQuery; table(command: string): JQuery; controlgroup(): JQuery; controlgroup(command: string): JQuery; controlgroup(options: ControlgroupOptions): JQuery; } interface JQueryStatic { mobile: JQueryMobile; }
mit
psykidellic/appengine-flask-skeleton
lib/werkzeug/debug/__init__.py
17271
# -*- coding: utf-8 -*- """ werkzeug.debug ~~~~~~~~~~~~~~ WSGI application traceback debugger. :copyright: (c) 2014 by the Werkzeug Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ import os import re import sys import uuid import json import time import getpass import hashlib import mimetypes from itertools import chain from os.path import join, dirname, basename, isfile from werkzeug.wrappers import BaseRequest as Request, BaseResponse as Response from werkzeug.http import parse_cookie from werkzeug.debug.tbtools import get_current_traceback, render_console_html from werkzeug.debug.console import Console from werkzeug.security import gen_salt from werkzeug._internal import _log from werkzeug._compat import text_type # DEPRECATED #: import this here because it once was documented as being available #: from this module. In case there are users left ... from werkzeug.debug.repr import debug_repr # noqa # A week PIN_TIME = 60 * 60 * 24 * 7 def hash_pin(pin): if isinstance(pin, text_type): pin = pin.encode('utf-8', 'replace') return hashlib.md5(pin + b'shittysalt').hexdigest()[:12] _machine_id = None def get_machine_id(): global _machine_id rv = _machine_id if rv is not None: return rv def _generate(): # Potential sources of secret information on linux. The machine-id # is stable across boots, the boot id is not for filename in '/etc/machine-id', '/proc/sys/kernel/random/boot_id': try: with open(filename, 'rb') as f: return f.readline().strip() except IOError: continue # On OS X we can use the computer's serial number assuming that # ioreg exists and can spit out that information. try: # Also catch import errors: subprocess may not be available, e.g. # Google App Engine # See https://github.com/pallets/werkzeug/issues/925 from subprocess import Popen, PIPE dump = Popen(['ioreg', '-c', 'IOPlatformExpertDevice', '-d', '2'], stdout=PIPE).communicate()[0] match = re.search(b'"serial-number" = <([^>]+)', dump) if match is not None: return match.group(1) except (OSError, ImportError): pass # On Windows we can use winreg to get the machine guid wr = None try: import winreg as wr except ImportError: try: import _winreg as wr except ImportError: pass if wr is not None: try: with wr.OpenKey(wr.HKEY_LOCAL_MACHINE, 'SOFTWARE\\Microsoft\\Cryptography', 0, wr.KEY_READ | wr.KEY_WOW64_64KEY) as rk: return wr.QueryValueEx(rk, 'MachineGuid')[0] except WindowsError: pass _machine_id = rv = _generate() return rv class _ConsoleFrame(object): """Helper class so that we can reuse the frame console code for the standalone console. """ def __init__(self, namespace): self.console = Console(namespace) self.id = 0 def get_pin_and_cookie_name(app): """Given an application object this returns a semi-stable 9 digit pin code and a random key. The hope is that this is stable between restarts to not make debugging particularly frustrating. If the pin was forcefully disabled this returns `None`. Second item in the resulting tuple is the cookie name for remembering. """ pin = os.environ.get('WERKZEUG_DEBUG_PIN') rv = None num = None # Pin was explicitly disabled if pin == 'off': return None, None # Pin was provided explicitly if pin is not None and pin.replace('-', '').isdigit(): # If there are separators in the pin, return it directly if '-' in pin: rv = pin else: num = pin modname = getattr(app, '__module__', getattr(app.__class__, '__module__')) try: # `getpass.getuser()` imports the `pwd` module, # which does not exist in the Google App Engine sandbox. username = getpass.getuser() except ImportError: username = None mod = sys.modules.get(modname) # This information only exists to make the cookie unique on the # computer, not as a security feature. probably_public_bits = [ username, modname, getattr(app, '__name__', getattr(app.__class__, '__name__')), getattr(mod, '__file__', None), ] # This information is here to make it harder for an attacker to # guess the cookie name. They are unlikely to be contained anywhere # within the unauthenticated debug page. private_bits = [ str(uuid.getnode()), get_machine_id(), ] h = hashlib.md5() for bit in chain(probably_public_bits, private_bits): if not bit: continue if isinstance(bit, text_type): bit = bit.encode('utf-8') h.update(bit) h.update(b'cookiesalt') cookie_name = '__wzd' + h.hexdigest()[:20] # If we need to generate a pin we salt it a bit more so that we don't # end up with the same value and generate out 9 digits if num is None: h.update(b'pinsalt') num = ('%09d' % int(h.hexdigest(), 16))[:9] # Format the pincode in groups of digits for easier remembering if # we don't have a result yet. if rv is None: for group_size in 5, 4, 3: if len(num) % group_size == 0: rv = '-'.join(num[x:x + group_size].rjust(group_size, '0') for x in range(0, len(num), group_size)) break else: rv = num return rv, cookie_name class DebuggedApplication(object): """Enables debugging support for a given application:: from werkzeug.debug import DebuggedApplication from myapp import app app = DebuggedApplication(app, evalex=True) The `evalex` keyword argument allows evaluating expressions in a traceback's frame context. .. versionadded:: 0.9 The `lodgeit_url` parameter was deprecated. :param app: the WSGI application to run debugged. :param evalex: enable exception evaluation feature (interactive debugging). This requires a non-forking server. :param request_key: The key that points to the request object in ths environment. This parameter is ignored in current versions. :param console_path: the URL for a general purpose console. :param console_init_func: the function that is executed before starting the general purpose console. The return value is used as initial namespace. :param show_hidden_frames: by default hidden traceback frames are skipped. You can show them by setting this parameter to `True`. :param pin_security: can be used to disable the pin based security system. :param pin_logging: enables the logging of the pin system. """ def __init__(self, app, evalex=False, request_key='werkzeug.request', console_path='/console', console_init_func=None, show_hidden_frames=False, lodgeit_url=None, pin_security=True, pin_logging=True): if lodgeit_url is not None: from warnings import warn warn(DeprecationWarning('Werkzeug now pastes into gists.')) if not console_init_func: console_init_func = None self.app = app self.evalex = evalex self.frames = {} self.tracebacks = {} self.request_key = request_key self.console_path = console_path self.console_init_func = console_init_func self.show_hidden_frames = show_hidden_frames self.secret = gen_salt(20) self._failed_pin_auth = 0 self.pin_logging = pin_logging if pin_security: # Print out the pin for the debugger on standard out. if os.environ.get('WERKZEUG_RUN_MAIN') == 'true' and \ pin_logging: _log('warning', ' * Debugger is active!') if self.pin is None: _log('warning', ' * Debugger pin disabled. ' 'DEBUGGER UNSECURED!') else: _log('info', ' * Debugger pin code: %s' % self.pin) else: self.pin = None def _get_pin(self): if not hasattr(self, '_pin'): self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app) return self._pin def _set_pin(self, value): self._pin = value pin = property(_get_pin, _set_pin) del _get_pin, _set_pin @property def pin_cookie_name(self): """The name of the pin cookie.""" if not hasattr(self, '_pin_cookie'): self._pin, self._pin_cookie = get_pin_and_cookie_name(self.app) return self._pin_cookie def debug_application(self, environ, start_response): """Run the application and conserve the traceback frames.""" app_iter = None try: app_iter = self.app(environ, start_response) for item in app_iter: yield item if hasattr(app_iter, 'close'): app_iter.close() except Exception: if hasattr(app_iter, 'close'): app_iter.close() traceback = get_current_traceback( skip=1, show_hidden_frames=self.show_hidden_frames, ignore_system_exceptions=True) for frame in traceback.frames: self.frames[frame.id] = frame self.tracebacks[traceback.id] = traceback try: start_response('500 INTERNAL SERVER ERROR', [ ('Content-Type', 'text/html; charset=utf-8'), # Disable Chrome's XSS protection, the debug # output can cause false-positives. ('X-XSS-Protection', '0'), ]) except Exception: # if we end up here there has been output but an error # occurred. in that situation we can do nothing fancy any # more, better log something into the error log and fall # back gracefully. environ['wsgi.errors'].write( 'Debugging middleware caught exception in streamed ' 'response at a point where response headers were already ' 'sent.\n') else: is_trusted = bool(self.check_pin_trust(environ)) yield traceback.render_full(evalex=self.evalex, evalex_trusted=is_trusted, secret=self.secret) \ .encode('utf-8', 'replace') traceback.log(environ['wsgi.errors']) def execute_command(self, request, command, frame): """Execute a command in a console.""" return Response(frame.console.eval(command), mimetype='text/html') def display_console(self, request): """Display a standalone shell.""" if 0 not in self.frames: if self.console_init_func is None: ns = {} else: ns = dict(self.console_init_func()) ns.setdefault('app', self.app) self.frames[0] = _ConsoleFrame(ns) is_trusted = bool(self.check_pin_trust(request.environ)) return Response(render_console_html(secret=self.secret, evalex_trusted=is_trusted), mimetype='text/html') def paste_traceback(self, request, traceback): """Paste the traceback and return a JSON response.""" rv = traceback.paste() return Response(json.dumps(rv), mimetype='application/json') def get_resource(self, request, filename): """Return a static resource from the shared folder.""" filename = join(dirname(__file__), 'shared', basename(filename)) if isfile(filename): mimetype = mimetypes.guess_type(filename)[0] \ or 'application/octet-stream' f = open(filename, 'rb') try: return Response(f.read(), mimetype=mimetype) finally: f.close() return Response('Not Found', status=404) def check_pin_trust(self, environ): """Checks if the request passed the pin test. This returns `True` if the request is trusted on a pin/cookie basis and returns `False` if not. Additionally if the cookie's stored pin hash is wrong it will return `None` so that appropriate action can be taken. """ if self.pin is None: return True val = parse_cookie(environ).get(self.pin_cookie_name) if not val or '|' not in val: return False ts, pin_hash = val.split('|', 1) if not ts.isdigit(): return False if pin_hash != hash_pin(self.pin): return None return (time.time() - PIN_TIME) < int(ts) def _fail_pin_auth(self): time.sleep(self._failed_pin_auth > 5 and 5.0 or 0.5) self._failed_pin_auth += 1 def pin_auth(self, request): """Authenticates with the pin.""" exhausted = False auth = False trust = self.check_pin_trust(request.environ) # If the trust return value is `None` it means that the cookie is # set but the stored pin hash value is bad. This means that the # pin was changed. In this case we count a bad auth and unset the # cookie. This way it becomes harder to guess the cookie name # instead of the pin as we still count up failures. bad_cookie = False if trust is None: self._fail_pin_auth() bad_cookie = True # If we're trusted, we're authenticated. elif trust: auth = True # If we failed too many times, then we're locked out. elif self._failed_pin_auth > 10: exhausted = True # Otherwise go through pin based authentication else: entered_pin = request.args.get('pin') if entered_pin.strip().replace('-', '') == \ self.pin.replace('-', ''): self._failed_pin_auth = 0 auth = True else: self._fail_pin_auth() rv = Response(json.dumps({ 'auth': auth, 'exhausted': exhausted, }), mimetype='application/json') if auth: rv.set_cookie(self.pin_cookie_name, '%s|%s' % ( int(time.time()), hash_pin(self.pin) ), httponly=True) elif bad_cookie: rv.delete_cookie(self.pin_cookie_name) return rv def log_pin_request(self): """Log the pin if needed.""" if self.pin_logging and self.pin is not None: _log('info', ' * To enable the debugger you need to ' 'enter the security pin:') _log('info', ' * Debugger pin code: %s' % self.pin) return Response('') def __call__(self, environ, start_response): """Dispatch the requests.""" # important: don't ever access a function here that reads the incoming # form data! Otherwise the application won't have access to that data # any more! request = Request(environ) response = self.debug_application if request.args.get('__debugger__') == 'yes': cmd = request.args.get('cmd') arg = request.args.get('f') secret = request.args.get('s') traceback = self.tracebacks.get(request.args.get('tb', type=int)) frame = self.frames.get(request.args.get('frm', type=int)) if cmd == 'resource' and arg: response = self.get_resource(request, arg) elif cmd == 'paste' and traceback is not None and \ secret == self.secret: response = self.paste_traceback(request, traceback) elif cmd == 'pinauth' and secret == self.secret: response = self.pin_auth(request) elif cmd == 'printpin' and secret == self.secret: response = self.log_pin_request() elif self.evalex and cmd is not None and frame is not None \ and self.secret == secret and \ self.check_pin_trust(environ): response = self.execute_command(request, cmd, frame) elif self.evalex and self.console_path is not None and \ request.path == self.console_path: response = self.display_console(request) return response(environ, start_response)
apache-2.0
vchandev/conversation
node_modules/eslint/lib/rules/space-unary-ops.js
11158
/** * @fileoverview This rule shoud require or disallow spaces before or after unary operations. * @author Marcin Kumorek */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "enforce consistent spacing before or after unary operators", category: "Stylistic Issues", recommended: false }, fixable: "whitespace", schema: [ { type: "object", properties: { words: { type: "boolean" }, nonwords: { type: "boolean" }, overrides: { type: "object", additionalProperties: { type: "boolean" } } }, additionalProperties: false } ] }, create: function(context) { var options = context.options && Array.isArray(context.options) && context.options[0] || { words: true, nonwords: false }; var sourceCode = context.getSourceCode(); //-------------------------------------------------------------------------- // Helpers //-------------------------------------------------------------------------- /** * Check if the node is the first "!" in a "!!" convert to Boolean expression * @param {ASTnode} node AST node * @returns {boolean} Whether or not the node is first "!" in "!!" */ function isFirstBangInBangBangExpression(node) { return node && node.type === "UnaryExpression" && node.argument.operator === "!" && node.argument && node.argument.type === "UnaryExpression" && node.argument.operator === "!"; } /** * Check if the node's child argument is an "ObjectExpression" * @param {ASTnode} node AST node * @returns {boolean} Whether or not the argument's type is "ObjectExpression" */ function isArgumentObjectExpression(node) { return node.argument && node.argument.type && node.argument.type === "ObjectExpression"; } /** * Checks if an override exists for a given operator. * @param {ASTnode} node AST node * @param {string} operator Operator * @returns {boolean} Whether or not an override has been provided for the operator */ function overrideExistsForOperator(node, operator) { return options.overrides && options.overrides.hasOwnProperty(operator); } /** * Gets the value that the override was set to for this operator * @param {ASTnode} node AST node * @param {string} operator Operator * @returns {boolean} Whether or not an override enforces a space with this operator */ function overrideEnforcesSpaces(node, operator) { return options.overrides[operator]; } /** * Verify Unary Word Operator has spaces after the word operator * @param {ASTnode} node AST node * @param {object} firstToken first token from the AST node * @param {object} secondToken second token from the AST node * @param {string} word The word to be used for reporting * @returns {void} */ function verifyWordHasSpaces(node, firstToken, secondToken, word) { if (secondToken.range[0] === firstToken.range[1]) { context.report({ node: node, message: "Unary word operator '" + word + "' must be followed by whitespace.", fix: function(fixer) { return fixer.insertTextAfter(firstToken, " "); } }); } } /** * Verify Unary Word Operator doesn't have spaces after the word operator * @param {ASTnode} node AST node * @param {object} firstToken first token from the AST node * @param {object} secondToken second token from the AST node * @param {string} word The word to be used for reporting * @returns {void} */ function verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word) { if (isArgumentObjectExpression(node)) { if (secondToken.range[0] > firstToken.range[1]) { context.report({ node: node, message: "Unexpected space after unary word operator '" + word + "'.", fix: function(fixer) { return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); } }); } } } /** * Check Unary Word Operators for spaces after the word operator * @param {ASTnode} node AST node * @param {object} firstToken first token from the AST node * @param {object} secondToken second token from the AST node * @param {string} word The word to be used for reporting * @returns {void} */ function checkUnaryWordOperatorForSpaces(node, firstToken, secondToken, word) { word = word || firstToken.value; if (overrideExistsForOperator(node, word)) { if (overrideEnforcesSpaces(node, word)) { verifyWordHasSpaces(node, firstToken, secondToken, word); } else { verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); } } else if (options.words) { verifyWordHasSpaces(node, firstToken, secondToken, word); } else { verifyWordDoesntHaveSpaces(node, firstToken, secondToken, word); } } /** * Verifies YieldExpressions satisfy spacing requirements * @param {ASTnode} node AST node * @returns {void} */ function checkForSpacesAfterYield(node) { var tokens = sourceCode.getFirstTokens(node, 3), word = "yield"; if (!node.argument || node.delegate) { return; } checkUnaryWordOperatorForSpaces(node, tokens[0], tokens[1], word); } /** * Verifies UnaryExpression, UpdateExpression and NewExpression have spaces before or after the operator * @param {ASTnode} node AST node * @param {object} firstToken First token in the expression * @param {object} secondToken Second token in the expression * @returns {void} */ function verifyNonWordsHaveSpaces(node, firstToken, secondToken) { if (node.prefix) { if (isFirstBangInBangBangExpression(node)) { return; } if (firstToken.range[1] === secondToken.range[0]) { context.report({ node: node, message: "Unary operator '" + firstToken.value + "' must be followed by whitespace.", fix: function(fixer) { return fixer.insertTextAfter(firstToken, " "); } }); } } else { if (firstToken.range[1] === secondToken.range[0]) { context.report({ node: node, message: "Space is required before unary expressions '" + secondToken.value + "'.", fix: function(fixer) { return fixer.insertTextBefore(secondToken, " "); } }); } } } /** * Verifies UnaryExpression, UpdateExpression and NewExpression don't have spaces before or after the operator * @param {ASTnode} node AST node * @param {object} firstToken First token in the expression * @param {object} secondToken Second token in the expression * @returns {void} */ function verifyNonWordsDontHaveSpaces(node, firstToken, secondToken) { if (node.prefix) { if (secondToken.range[0] > firstToken.range[1]) { context.report({ node: node, message: "Unexpected space after unary operator '" + firstToken.value + "'.", fix: function(fixer) { return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); } }); } } else { if (secondToken.range[0] > firstToken.range[1]) { context.report({ node: node, message: "Unexpected space before unary operator '" + secondToken.value + "'.", fix: function(fixer) { return fixer.removeRange([firstToken.range[1], secondToken.range[0]]); } }); } } } /** * Verifies UnaryExpression, UpdateExpression and NewExpression satisfy spacing requirements * @param {ASTnode} node AST node * @returns {void} */ function checkForSpaces(node) { var tokens = sourceCode.getFirstTokens(node, 2), firstToken = tokens[0], secondToken = tokens[1]; if ((node.type === "NewExpression" || node.prefix) && firstToken.type === "Keyword") { checkUnaryWordOperatorForSpaces(node, firstToken, secondToken); return; } var operator = node.prefix ? tokens[0].value : tokens[1].value; if (overrideExistsForOperator(node, operator)) { if (overrideEnforcesSpaces(node, operator)) { verifyNonWordsHaveSpaces(node, firstToken, secondToken); } else { verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); } } else if (options.nonwords) { verifyNonWordsHaveSpaces(node, firstToken, secondToken); } else { verifyNonWordsDontHaveSpaces(node, firstToken, secondToken); } } //-------------------------------------------------------------------------- // Public //-------------------------------------------------------------------------- return { UnaryExpression: checkForSpaces, UpdateExpression: checkForSpaces, NewExpression: checkForSpaces, YieldExpression: checkForSpacesAfterYield }; } };
apache-2.0
LeChuck42/or1k-gcc
gcc/testsuite/g++.dg/cpp0x/constexpr-ice10.C
150
// PR c++/60225 // { dg-do compile { target c++11 } } struct A { constexpr A() {} static constexpr A a[2] = {}; // { dg-error "incomplete" } };
gpl-2.0
nolsherry/cdnjs
ajax/libs/react-virtualized/5.2.4/react-virtualized.js
118978
!function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory(require("react"), require("react-dom")) : "function" == typeof define && define.amd ? define([ "react", "react-dom" ], factory) : "object" == typeof exports ? exports.ReactVirtualized = factory(require("react"), require("react-dom")) : root.ReactVirtualized = factory(root.React, root.ReactDOM); }(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_21__) { /******/ return function(modules) { /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if (installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: !1 }; /******/ /******/ // Return the exports of the module /******/ /******/ /******/ // Execute the module function /******/ /******/ /******/ // Flag the module as loaded /******/ return modules[moduleId].call(module.exports, module, module.exports, __webpack_require__), module.loaded = !0, module.exports; } // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // Load entry module and return exports /******/ /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ /******/ /******/ // expose the module cache /******/ /******/ /******/ // __webpack_public_path__ /******/ return __webpack_require__.m = modules, __webpack_require__.c = installedModules, __webpack_require__.p = "", __webpack_require__(0); }([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var _AutoSizer = __webpack_require__(1); Object.defineProperty(exports, "AutoSizer", { enumerable: !0, get: function() { return _AutoSizer.AutoSizer; } }); var _ColumnSizer = __webpack_require__(7); Object.defineProperty(exports, "ColumnSizer", { enumerable: !0, get: function() { return _ColumnSizer.ColumnSizer; } }); var _FlexTable = __webpack_require__(18); Object.defineProperty(exports, "FlexTable", { enumerable: !0, get: function() { return _FlexTable.FlexTable; } }), Object.defineProperty(exports, "FlexColumn", { enumerable: !0, get: function() { return _FlexTable.FlexColumn; } }), Object.defineProperty(exports, "SortDirection", { enumerable: !0, get: function() { return _FlexTable.SortDirection; } }), Object.defineProperty(exports, "SortIndicator", { enumerable: !0, get: function() { return _FlexTable.SortIndicator; } }); var _Grid = __webpack_require__(9); Object.defineProperty(exports, "Grid", { enumerable: !0, get: function() { return _Grid.Grid; } }); var _InfiniteLoader = __webpack_require__(22); Object.defineProperty(exports, "InfiniteLoader", { enumerable: !0, get: function() { return _InfiniteLoader.InfiniteLoader; } }); var _ScrollSync = __webpack_require__(24); Object.defineProperty(exports, "ScrollSync", { enumerable: !0, get: function() { return _ScrollSync.ScrollSync; } }); var _VirtualScroll = __webpack_require__(26); Object.defineProperty(exports, "VirtualScroll", { enumerable: !0, get: function() { return _VirtualScroll.VirtualScroll; } }); }, /* 1 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.AutoSizer = exports["default"] = void 0; var _AutoSizer2 = __webpack_require__(2), _AutoSizer3 = _interopRequireDefault(_AutoSizer2); exports["default"] = _AutoSizer3["default"], exports.AutoSizer = _AutoSizer3["default"]; }, /* 2 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _function = __webpack_require__(4), _function2 = _interopRequireDefault(_function), AutoSizer = function(_Component) { function AutoSizer(props) { _classCallCheck(this, AutoSizer); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(AutoSizer).call(this, props)); return _this.shouldComponentUpdate = _function2["default"], _this.state = { height: 0, width: 0 }, _this._onResize = _this._onResize.bind(_this), _this._setRef = _this._setRef.bind(_this), _this; } return _inherits(AutoSizer, _Component), _createClass(AutoSizer, [ { key: "componentDidMount", value: function() { this._detectElementResize = __webpack_require__(6), this._detectElementResize.addResizeListener(this._parentNode, this._onResize), this._onResize(); } }, { key: "componentWillUnmount", value: function() { this._detectElementResize.removeResizeListener(this._parentNode, this._onResize); } }, { key: "render", value: function() { var _props = this.props, children = _props.children, disableHeight = _props.disableHeight, disableWidth = _props.disableWidth, _state = this.state, height = _state.height, width = _state.width, outerStyle = { overflow: "visible" }; return disableHeight || (outerStyle.height = 0), disableWidth || (outerStyle.width = 0), _react2["default"].createElement("div", { ref: this._setRef, style: outerStyle }, children({ height: height, width: width })); } }, { key: "_onResize", value: function() { var onResize = this.props.onResize, _parentNode$getBoundi = this._parentNode.getBoundingClientRect(), height = _parentNode$getBoundi.height, width = _parentNode$getBoundi.width, style = getComputedStyle(this._parentNode), paddingLeft = parseInt(style.paddingLeft, 10), paddingRight = parseInt(style.paddingRight, 10), paddingTop = parseInt(style.paddingTop, 10), paddingBottom = parseInt(style.paddingBottom, 10); this.setState({ height: height - paddingTop - paddingBottom, width: width - paddingLeft - paddingRight }), onResize({ height: height, width: width }); } }, { key: "_setRef", value: function(autoSizer) { this._parentNode = autoSizer && autoSizer.parentNode; } } ]), AutoSizer; }(_react.Component); AutoSizer.propTypes = { children: _react.PropTypes.func.isRequired, disableHeight: _react.PropTypes.bool, disableWidth: _react.PropTypes.bool, onResize: _react.PropTypes.func.isRequired }, AutoSizer.defaultProps = { onResize: function() {} }, exports["default"] = AutoSizer; }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; }, /* 4 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function shouldPureComponentUpdate(nextProps, nextState) { return !(0, _shallowEqual2["default"])(this.props, nextProps) || !(0, _shallowEqual2["default"])(this.state, nextState); } exports.__esModule = !0, exports["default"] = shouldPureComponentUpdate; var _shallowEqual = __webpack_require__(5), _shallowEqual2 = _interopRequireDefault(_shallowEqual); module.exports = exports["default"]; }, /* 5 */ /***/ function(module, exports) { "use strict"; function shallowEqual(objA, objB) { if (objA === objB) return !0; if ("object" != typeof objA || null === objA || "object" != typeof objB || null === objB) return !1; var keysA = Object.keys(objA), keysB = Object.keys(objB); if (keysA.length !== keysB.length) return !1; for (var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB), i = 0; i < keysA.length; i++) if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) return !1; return !0; } exports.__esModule = !0, exports["default"] = shallowEqual, module.exports = exports["default"]; }, /* 6 */ /***/ function(module, exports) { "use strict"; var _window; _window = "undefined" != typeof window ? window : "undefined" != typeof self ? self : void 0; var attachEvent = "undefined" != typeof document && document.attachEvent, stylesCreated = !1; if (!attachEvent) { var requestFrame = function() { var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function(fn) { return _window.setTimeout(fn, 20); }; return function(fn) { return raf(fn); }; }(), cancelFrame = function() { var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout; return function(id) { return cancel(id); }; }(), resetTriggers = function(element) { var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild; contract.scrollLeft = contract.scrollWidth, contract.scrollTop = contract.scrollHeight, expandChild.style.width = expand.offsetWidth + 1 + "px", expandChild.style.height = expand.offsetHeight + 1 + "px", expand.scrollLeft = expand.scrollWidth, expand.scrollTop = expand.scrollHeight; }, checkTriggers = function(element) { return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height; }, scrollListener = function(e) { var element = this; resetTriggers(this), this.__resizeRAF__ && cancelFrame(this.__resizeRAF__), this.__resizeRAF__ = requestFrame(function() { checkTriggers(element) && (element.__resizeLast__.width = element.offsetWidth, element.__resizeLast__.height = element.offsetHeight, element.__resizeListeners__.forEach(function(fn) { fn.call(element, e); })); }); }, animation = !1, animationstring = "animation", keyframeprefix = "", animationstartevent = "animationstart", domPrefixes = "Webkit Moz O ms".split(" "), startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "), pfx = "", elm = document.createElement("fakeelement"); if (void 0 !== elm.style.animationName && (animation = !0), animation === !1) for (var i = 0; i < domPrefixes.length; i++) if (void 0 !== elm.style[domPrefixes[i] + "AnimationName"]) { pfx = domPrefixes[i], animationstring = pfx + "Animation", keyframeprefix = "-" + pfx.toLowerCase() + "-", animationstartevent = startEvents[i], animation = !0; break; } var animationName = "resizeanim", animationKeyframes = "@" + keyframeprefix + "keyframes " + animationName + " { from { opacity: 0; } to { opacity: 0; } } ", animationStyle = keyframeprefix + "animation: 1ms " + animationName + "; "; } var createStyles = function() { if (!stylesCreated) { var css = (animationKeyframes ? animationKeyframes : "") + ".resize-triggers { " + (animationStyle ? animationStyle : "") + 'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.head || document.getElementsByTagName("head")[0], style = document.createElement("style"); style.type = "text/css", style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)), head.appendChild(style), stylesCreated = !0; } }, addResizeListener = function(element, fn) { attachEvent ? element.attachEvent("onresize", fn) : (element.__resizeTriggers__ || ("static" == getComputedStyle(element).position && (element.style.position = "relative"), createStyles(), element.__resizeLast__ = {}, element.__resizeListeners__ = [], (element.__resizeTriggers__ = document.createElement("div")).className = "resize-triggers", element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>', element.appendChild(element.__resizeTriggers__), resetTriggers(element), element.addEventListener("scroll", scrollListener, !0), animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function(e) { e.animationName == animationName && resetTriggers(element); })), element.__resizeListeners__.push(fn)); }, removeResizeListener = function(element, fn) { attachEvent ? element.detachEvent("onresize", fn) : (element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1), element.__resizeListeners__.length || (element.removeEventListener("scroll", scrollListener), element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__))); }; module.exports = { addResizeListener: addResizeListener, removeResizeListener: removeResizeListener }; }, /* 7 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ColumnSizer = exports["default"] = void 0; var _ColumnSizer2 = __webpack_require__(8), _ColumnSizer3 = _interopRequireDefault(_ColumnSizer2); exports["default"] = _ColumnSizer3["default"], exports.ColumnSizer = _ColumnSizer3["default"]; }, /* 8 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _function = __webpack_require__(4), _function2 = _interopRequireDefault(_function), _Grid = __webpack_require__(9), _Grid2 = _interopRequireDefault(_Grid), ColumnSizer = function(_Component) { function ColumnSizer(props, context) { _classCallCheck(this, ColumnSizer); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ColumnSizer).call(this, props, context)); return _this.shouldComponentUpdate = _function2["default"], _this._registerChild = _this._registerChild.bind(_this), _this; } return _inherits(ColumnSizer, _Component), _createClass(ColumnSizer, [ { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props = this.props, columnMaxWidth = _props.columnMaxWidth, columnMinWidth = _props.columnMinWidth, columnsCount = _props.columnsCount, width = _props.width; columnMaxWidth === prevProps.columnMaxWidth && columnMinWidth === prevProps.columnMinWidth && columnsCount === prevProps.columnsCount && width === prevProps.width || this._registeredChild && this._registeredChild.recomputeGridSize(); } }, { key: "render", value: function() { var _props2 = this.props, children = _props2.children, columnMaxWidth = _props2.columnMaxWidth, columnMinWidth = _props2.columnMinWidth, columnsCount = _props2.columnsCount, width = _props2.width, safeColumnMinWidth = columnMinWidth || 1, safeColumnMaxWidth = columnMaxWidth ? Math.min(columnMaxWidth, width) : width, columnWidth = width / columnsCount; columnWidth = Math.max(safeColumnMinWidth, columnWidth), columnWidth = Math.min(safeColumnMaxWidth, columnWidth), columnWidth = Math.floor(columnWidth); var adjustedWidth = Math.min(width, columnWidth * columnsCount); return children({ adjustedWidth: adjustedWidth, getColumnWidth: function() { return columnWidth; }, registerChild: this._registerChild }); } }, { key: "_registerChild", value: function(child) { if (null !== child && !(child instanceof _Grid2["default"])) throw Error("Unexpected child type registered; only Grid children are supported."); this._registeredChild = child, this._registeredChild && this._registeredChild.recomputeGridSize(); } } ]), ColumnSizer; }(_react.Component); ColumnSizer.propTypes = { children: _react.PropTypes.func.isRequired, columnMaxWidth: _react.PropTypes.number, columnMinWidth: _react.PropTypes.number, columnsCount: _react.PropTypes.number.isRequired, width: _react.PropTypes.number.isRequired }, exports["default"] = ColumnSizer; }, /* 9 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.Grid = exports["default"] = void 0; var _Grid2 = __webpack_require__(10), _Grid3 = _interopRequireDefault(_Grid2); exports["default"] = _Grid3["default"], exports.Grid = _Grid3["default"]; }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(setImmediate, clearImmediate) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _utils = __webpack_require__(13), _classnames = __webpack_require__(14), _classnames2 = _interopRequireDefault(_classnames), _raf = __webpack_require__(15), _raf2 = _interopRequireDefault(_raf), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _function = __webpack_require__(4), _function2 = _interopRequireDefault(_function), IS_SCROLLING_TIMEOUT = 150, SCROLL_POSITION_CHANGE_REASONS = { OBSERVED: "observed", REQUESTED: "requested" }, Grid = function(_Component) { function Grid(props, context) { _classCallCheck(this, Grid); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Grid).call(this, props, context)); return _this.shouldComponentUpdate = _function2["default"], _this.state = { computeGridMetadataOnNextUpdate: !1, isScrolling: !1, scrollLeft: 0, scrollTop: 0 }, _this._onGridRenderedMemoizer = (0, _utils.createCallbackMemoizer)(), _this._onScrollMemoizer = (0, _utils.createCallbackMemoizer)(!1), _this._computeGridMetadata = _this._computeGridMetadata.bind(_this), _this._invokeOnGridRenderedHelper = _this._invokeOnGridRenderedHelper.bind(_this), _this._onKeyPress = _this._onKeyPress.bind(_this), _this._onScroll = _this._onScroll.bind(_this), _this._updateScrollLeftForScrollToColumn = _this._updateScrollLeftForScrollToColumn.bind(_this), _this._updateScrollTopForScrollToRow = _this._updateScrollTopForScrollToRow.bind(_this), _this; } return _inherits(Grid, _Component), _createClass(Grid, [ { key: "recomputeGridSize", value: function() { this.setState({ computeGridMetadataOnNextUpdate: !0 }); } }, { key: "scrollToCell", value: function(_ref) { var scrollToColumn = _ref.scrollToColumn, scrollToRow = _ref.scrollToRow; this._updateScrollLeftForScrollToColumn(scrollToColumn), this._updateScrollTopForScrollToRow(scrollToRow); } }, { key: "setScrollPosition", value: function(_ref2) { var scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, newState = { scrollPositionChangeReason: SCROLL_POSITION_CHANGE_REASONS.REQUESTED }; scrollLeft >= 0 && (newState.scrollLeft = scrollLeft), scrollTop >= 0 && (newState.scrollTop = scrollTop), (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(newState); } }, { key: "componentDidMount", value: function() { var _this2 = this, _props = this.props, scrollLeft = _props.scrollLeft, scrollToColumn = _props.scrollToColumn, scrollTop = _props.scrollTop, scrollToRow = _props.scrollToRow; (scrollLeft >= 0 || scrollTop >= 0) && this.setScrollPosition({ scrollLeft: scrollLeft, scrollTop: scrollTop }), (scrollToColumn >= 0 || scrollToRow >= 0) && (this._setImmediateId = setImmediate(function() { _this2._setImmediateId = null, _this2._updateScrollLeftForScrollToColumn(), _this2._updateScrollTopForScrollToRow(); })), this._invokeOnGridRenderedHelper(); } }, { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props2 = this.props, columnsCount = _props2.columnsCount, columnWidth = _props2.columnWidth, height = _props2.height, rowHeight = _props2.rowHeight, rowsCount = _props2.rowsCount, scrollToColumn = _props2.scrollToColumn, scrollToRow = _props2.scrollToRow, width = _props2.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollPositionChangeReason = _state.scrollPositionChangeReason, scrollTop = _state.scrollTop; scrollPositionChangeReason === SCROLL_POSITION_CHANGE_REASONS.REQUESTED && (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft && scrollLeft !== this.refs.scrollingContainer.scrollLeft && (this.refs.scrollingContainer.scrollLeft = scrollLeft), scrollTop >= 0 && scrollTop !== prevState.scrollTop && scrollTop !== this.refs.scrollingContainer.scrollTop && (this.refs.scrollingContainer.scrollTop = scrollTop)), (0, _utils.updateScrollIndexHelper)({ cellsCount: columnsCount, cellMetadata: this._columnMetadata, cellSize: columnWidth, previousCellsCount: prevProps.columnsCount, previousCellSize: prevProps.columnWidth, previousScrollToIndex: prevProps.scrollToColumn, previousSize: prevProps.width, scrollOffset: scrollLeft, scrollToIndex: scrollToColumn, size: width, updateScrollIndexCallback: this._updateScrollLeftForScrollToColumn }), (0, _utils.updateScrollIndexHelper)({ cellsCount: rowsCount, cellMetadata: this._rowMetadata, cellSize: rowHeight, previousCellsCount: prevProps.rowsCount, previousCellSize: prevProps.rowHeight, previousScrollToIndex: prevProps.scrollToRow, previousSize: prevProps.height, scrollOffset: scrollTop, scrollToIndex: scrollToRow, size: height, updateScrollIndexCallback: this._updateScrollTopForScrollToRow }), this._invokeOnGridRenderedHelper(); } }, { key: "componentWillMount", value: function() { this._computeGridMetadata(this.props); } }, { key: "componentWillUnmount", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._setImmediateId && clearImmediate(this._setImmediateId), this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { 0 === nextProps.columnsCount && 0 !== nextState.scrollLeft && this.setScrollPosition({ scrollLeft: 0 }), 0 === nextProps.rowsCount && 0 !== nextState.scrollTop && this.setScrollPosition({ scrollTop: 0 }), nextProps.scrollLeft !== this.props.scrollLeft && this.setScrollPosition({ scrollLeft: nextProps.scrollLeft }), nextProps.scrollTop !== this.props.scrollTop && this.setScrollPosition({ scrollTop: nextProps.scrollTop }), (0, _utils.computeCellMetadataAndUpdateScrollOffsetHelper)({ cellsCount: this.props.columnsCount, cellSize: this.props.columnWidth, computeMetadataCallback: this._computeGridMetadata, computeMetadataCallbackProps: nextProps, computeMetadataOnNextUpdate: nextState.computeGridMetadataOnNextUpdate, nextCellsCount: nextProps.columnsCount, nextCellSize: nextProps.columnWidth, nextScrollToIndex: nextProps.scrollToColumn, scrollToIndex: this.props.scrollToColumn, updateScrollOffsetForScrollToIndex: this._updateScrollLeftForScrollToColumn }), (0, _utils.computeCellMetadataAndUpdateScrollOffsetHelper)({ cellsCount: this.props.rowsCount, cellSize: this.props.rowHeight, computeMetadataCallback: this._computeGridMetadata, computeMetadataCallbackProps: nextProps, computeMetadataOnNextUpdate: nextState.computeGridMetadataOnNextUpdate, nextCellsCount: nextProps.rowsCount, nextCellSize: nextProps.rowHeight, nextScrollToIndex: nextProps.scrollToRow, scrollToIndex: this.props.scrollToRow, updateScrollOffsetForScrollToIndex: this._updateScrollTopForScrollToRow }), this.setState({ computeGridMetadataOnNextUpdate: !1 }); } }, { key: "render", value: function() { var _props3 = this.props, className = _props3.className, columnsCount = _props3.columnsCount, height = _props3.height, noContentRenderer = _props3.noContentRenderer, overscanColumnsCount = _props3.overscanColumnsCount, overscanRowsCount = _props3.overscanRowsCount, renderCell = _props3.renderCell, rowsCount = _props3.rowsCount, width = _props3.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, childrenToDisplay = []; if (height > 0 && width > 0) { var _getVisibleCellIndice = (0, _utils.getVisibleCellIndices)({ cellsCount: columnsCount, cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft }), columnStartIndex = _getVisibleCellIndice.start, columnStopIndex = _getVisibleCellIndice.stop, _getVisibleCellIndice2 = (0, _utils.getVisibleCellIndices)({ cellsCount: rowsCount, cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop }), rowStartIndex = _getVisibleCellIndice2.start, rowStopIndex = _getVisibleCellIndice2.stop; this._renderedColumnStartIndex = columnStartIndex, this._renderedColumnStopIndex = columnStopIndex, this._renderedRowStartIndex = rowStartIndex, this._renderedRowStopIndex = rowStopIndex; var overscanColumnIndices = (0, _utils.getOverscanIndices)({ cellsCount: columnsCount, overscanCellsCount: overscanColumnsCount, startIndex: columnStartIndex, stopIndex: columnStopIndex }), overscanRowIndices = (0, _utils.getOverscanIndices)({ cellsCount: rowsCount, overscanCellsCount: overscanRowsCount, startIndex: rowStartIndex, stopIndex: rowStopIndex }); columnStartIndex = overscanColumnIndices.overscanStartIndex, columnStopIndex = overscanColumnIndices.overscanStopIndex, rowStartIndex = overscanRowIndices.overscanStartIndex, rowStopIndex = overscanRowIndices.overscanStopIndex; for (var rowIndex = rowStartIndex; rowStopIndex >= rowIndex; rowIndex++) for (var rowDatum = this._rowMetadata[rowIndex], columnIndex = columnStartIndex; columnStopIndex >= columnIndex; columnIndex++) { var columnDatum = this._columnMetadata[columnIndex], renderedCell = renderCell({ columnIndex: columnIndex, rowIndex: rowIndex }), key = rowIndex + "-" + columnIndex, child = _react2["default"].createElement("div", { key: key, className: "Grid__cell", style: { height: this._getRowHeight(rowIndex), left: columnDatum.offset + "px", top: rowDatum.offset + "px", width: this._getColumnWidth(columnIndex) } }, renderedCell); childrenToDisplay.push(child); } } return _react2["default"].createElement("div", { ref: "scrollingContainer", className: (0, _classnames2["default"])("Grid", className), onKeyDown: this._onKeyPress, onScroll: this._onScroll, tabIndex: 0, style: { height: height, width: width } }, childrenToDisplay.length > 0 && _react2["default"].createElement("div", { className: "Grid__innerScrollContainer", style: { width: this._getTotalColumnsWidth(), height: this._getTotalRowsHeight(), maxWidth: this._getTotalColumnsWidth(), maxHeight: this._getTotalRowsHeight(), pointerEvents: isScrolling ? "none" : "auto" } }, childrenToDisplay), 0 === childrenToDisplay.length && noContentRenderer()); } }, { key: "_computeGridMetadata", value: function(props) { var columnsCount = props.columnsCount, columnWidth = props.columnWidth, rowHeight = props.rowHeight, rowsCount = props.rowsCount; this._columnMetadata = (0, _utils.initCellMetadata)({ cellsCount: columnsCount, size: columnWidth }), this._rowMetadata = (0, _utils.initCellMetadata)({ cellsCount: rowsCount, size: rowHeight }); } }, { key: "_enablePointerEventsAfterDelay", value: function() { var _this3 = this; this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(function() { _this3._disablePointerEventsTimeoutId = null, _this3.setState({ isScrolling: !1 }); }, IS_SCROLLING_TIMEOUT); } }, { key: "_getColumnWidth", value: function(index) { var columnWidth = this.props.columnWidth; return columnWidth instanceof Function ? columnWidth(index) : columnWidth; } }, { key: "_getRowHeight", value: function(index) { var rowHeight = this.props.rowHeight; return rowHeight instanceof Function ? rowHeight(index) : rowHeight; } }, { key: "_getTotalColumnsWidth", value: function() { if (0 === this._columnMetadata.length) return 0; var datum = this._columnMetadata[this._columnMetadata.length - 1]; return datum.offset + datum.size; } }, { key: "_getTotalRowsHeight", value: function() { if (0 === this._rowMetadata.length) return 0; var datum = this._rowMetadata[this._rowMetadata.length - 1]; return datum.offset + datum.size; } }, { key: "_invokeOnGridRenderedHelper", value: function() { var _props4 = this.props, columnsCount = _props4.columnsCount, onSectionRendered = _props4.onSectionRendered, overscanColumnsCount = _props4.overscanColumnsCount, overscanRowsCount = _props4.overscanRowsCount, rowsCount = _props4.rowsCount, _getOverscanIndices = (0, _utils.getOverscanIndices)({ cellsCount: columnsCount, overscanCellsCount: overscanColumnsCount, startIndex: this._renderedColumnStartIndex, stopIndex: this._renderedColumnStopIndex }), columnOverscanStartIndex = _getOverscanIndices.overscanStartIndex, columnOverscanStopIndex = _getOverscanIndices.overscanStopIndex, _getOverscanIndices2 = (0, _utils.getOverscanIndices)({ cellsCount: rowsCount, overscanCellsCount: overscanRowsCount, startIndex: this._renderedRowStartIndex, stopIndex: this._renderedRowStopIndex }), rowOverscanStartIndex = _getOverscanIndices2.overscanStartIndex, rowOverscanStopIndex = _getOverscanIndices2.overscanStopIndex; this._onGridRenderedMemoizer({ callback: onSectionRendered, indices: { columnOverscanStartIndex: columnOverscanStartIndex, columnOverscanStopIndex: columnOverscanStopIndex, columnStartIndex: this._renderedColumnStartIndex, columnStopIndex: this._renderedColumnStopIndex, rowOverscanStartIndex: rowOverscanStartIndex, rowOverscanStopIndex: rowOverscanStopIndex, rowStartIndex: this._renderedRowStartIndex, rowStopIndex: this._renderedRowStopIndex } }); } }, { key: "_setNextState", value: function(state) { var _this4 = this; this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId), this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() { _this4._setNextStateAnimationFrameId = null, _this4.setState(state); }); } }, { key: "_stopEvent", value: function(event) { event.preventDefault(); } }, { key: "_updateScrollLeftForScrollToColumn", value: function(scrollToColumnOverride) { var scrollToColumn = null != scrollToColumnOverride ? scrollToColumnOverride : this.props.scrollToColumn, width = this.props.width, scrollLeft = this.state.scrollLeft; if (scrollToColumn >= 0) { var calculatedScrollLeft = (0, _utils.getUpdatedOffsetForIndex)({ cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft, targetIndex: scrollToColumn }); scrollLeft !== calculatedScrollLeft && this.setScrollPosition({ scrollLeft: calculatedScrollLeft }); } } }, { key: "_updateScrollTopForScrollToRow", value: function(scrollToRowOverride) { var scrollToRow = null != scrollToRowOverride ? scrollToRowOverride : this.props.scrollToRow, height = this.props.height, scrollTop = this.state.scrollTop; if (scrollToRow >= 0) { var calculatedScrollTop = (0, _utils.getUpdatedOffsetForIndex)({ cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop, targetIndex: scrollToRow }); scrollTop !== calculatedScrollTop && this.setScrollPosition({ scrollTop: calculatedScrollTop }); } } }, { key: "_onKeyPress", value: function(event) { var _props5 = this.props, columnsCount = _props5.columnsCount, height = _props5.height, rowsCount = _props5.rowsCount, width = _props5.width, _state3 = this.state, scrollLeft = _state3.scrollLeft, scrollTop = _state3.scrollTop, start = void 0, datum = void 0, newScrollLeft = void 0, newScrollTop = void 0; if (0 !== columnsCount && 0 !== rowsCount) switch (event.key) { case "ArrowDown": this._stopEvent(event), start = (0, _utils.getVisibleCellIndices)({ cellsCount: rowsCount, cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop }).start, datum = this._rowMetadata[start], newScrollTop = Math.min(this._getTotalRowsHeight() - height, scrollTop + datum.size), this.setScrollPosition({ scrollTop: newScrollTop }); break; case "ArrowLeft": this._stopEvent(event), start = (0, _utils.getVisibleCellIndices)({ cellsCount: columnsCount, cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft }).start, this.scrollToCell({ scrollToColumn: Math.max(0, start - 1), scrollToRow: this.props.scrollToRow }); break; case "ArrowRight": this._stopEvent(event), start = (0, _utils.getVisibleCellIndices)({ cellsCount: columnsCount, cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft }).start, datum = this._columnMetadata[start], newScrollLeft = Math.min(this._getTotalColumnsWidth() - width, scrollLeft + datum.size), this.setScrollPosition({ scrollLeft: newScrollLeft }); break; case "ArrowUp": this._stopEvent(event), start = (0, _utils.getVisibleCellIndices)({ cellsCount: rowsCount, cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop }).start, this.scrollToCell({ scrollToColumn: this.props.scrollToColumn, scrollToRow: Math.max(0, start - 1) }); } } }, { key: "_onScroll", value: function(event) { if (event.target === this.refs.scrollingContainer) { this._enablePointerEventsAfterDelay(); var _props6 = this.props, height = _props6.height, onScroll = _props6.onScroll, width = _props6.width, totalRowsHeight = this._getTotalRowsHeight(), totalColumnsWidth = this._getTotalColumnsWidth(), scrollLeft = Math.min(totalColumnsWidth - width, event.target.scrollLeft), scrollTop = Math.min(totalRowsHeight - height, event.target.scrollTop); if (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) { var scrollPositionChangeReason = event.cancelable ? SCROLL_POSITION_CHANGE_REASONS.OBSERVED : SCROLL_POSITION_CHANGE_REASONS.REQUESTED; this.state.isScrolling || this.setState({ isScrolling: !0 }), this._setNextState({ isScrolling: !0, scrollLeft: scrollLeft, scrollPositionChangeReason: scrollPositionChangeReason, scrollTop: scrollTop }); } this._onScrollMemoizer({ callback: function(_ref3) { var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop; onScroll({ clientHeight: height, clientWidth: width, scrollHeight: totalRowsHeight, scrollLeft: scrollLeft, scrollTop: scrollTop, scrollWidth: totalColumnsWidth }); }, indices: { scrollLeft: scrollLeft, scrollTop: scrollTop } }); } } } ]), Grid; }(_react.Component); Grid.propTypes = { className: _react.PropTypes.string, columnsCount: _react.PropTypes.number.isRequired, columnWidth: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, height: _react.PropTypes.number.isRequired, noContentRenderer: _react.PropTypes.func.isRequired, onScroll: _react.PropTypes.func.isRequired, onSectionRendered: _react.PropTypes.func.isRequired, overscanColumnsCount: _react.PropTypes.number.isRequired, overscanRowsCount: _react.PropTypes.number.isRequired, renderCell: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowsCount: _react.PropTypes.number.isRequired, scrollLeft: _react.PropTypes.number, scrollToColumn: _react.PropTypes.number, scrollTop: _react.PropTypes.number, scrollToRow: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, Grid.defaultProps = { noContentRenderer: function() { return null; }, onScroll: function() { return null; }, onSectionRendered: function() { return null; }, overscanColumnsCount: 0, overscanRowsCount: 10 }, exports["default"] = Grid; }).call(exports, __webpack_require__(11).setImmediate, __webpack_require__(11).clearImmediate); }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(setImmediate, clearImmediate) { function Timeout(id, clearFn) { this._id = id, this._clearFn = clearFn; } var nextTick = __webpack_require__(12).nextTick, apply = Function.prototype.apply, slice = Array.prototype.slice, immediateIds = {}, nextImmediateId = 0; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }, exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }, exports.clearTimeout = exports.clearInterval = function(timeout) { timeout.close(); }, Timeout.prototype.unref = Timeout.prototype.ref = function() {}, Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }, // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId), item._idleTimeout = msecs; }, exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId), item._idleTimeout = -1; }, exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; msecs >= 0 && (item._idleTimeoutId = setTimeout(function() { item._onTimeout && item._onTimeout(); }, msecs)); }, // That's not how node.js implements it but the exposed api is the same. exports.setImmediate = "function" == typeof setImmediate ? setImmediate : function(fn) { var id = nextImmediateId++, args = arguments.length < 2 ? !1 : slice.call(arguments, 1); return immediateIds[id] = !0, nextTick(function() { immediateIds[id] && (// fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu args ? fn.apply(null, args) : fn.call(null), // Prevent ids from leaking exports.clearImmediate(id)); }), id; }, exports.clearImmediate = "function" == typeof clearImmediate ? clearImmediate : function(id) { delete immediateIds[id]; }; }).call(exports, __webpack_require__(11).setImmediate, __webpack_require__(11).clearImmediate); }, /* 12 */ /***/ function(module, exports) { function cleanUpNextTick() { draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1, queue.length && drainQueue(); } function drainQueue() { if (!draining) { var timeout = setTimeout(cleanUpNextTick); draining = !0; for (var len = queue.length; len; ) { for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run(); queueIndex = -1, len = queue.length; } currentQueue = null, draining = !1, clearTimeout(timeout); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun, this.array = array; } function noop() {} // shim for using process in browser var currentQueue, process = module.exports = {}, queue = [], draining = !1, queueIndex = -1; process.nextTick = function(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i]; queue.push(new Item(fun, args)), 1 !== queue.length || draining || setTimeout(drainQueue, 0); }, Item.prototype.run = function() { this.fun.apply(null, this.array); }, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [], process.version = "", // empty string to avoid regexp issues process.versions = {}, process.on = noop, process.addListener = noop, process.once = noop, process.off = noop, process.removeListener = noop, process.removeAllListeners = noop, process.emit = noop, process.binding = function(name) { throw new Error("process.binding is not supported"); }, process.cwd = function() { return "/"; }, process.chdir = function(dir) { throw new Error("process.chdir is not supported"); }, process.umask = function() { return 0; }; }, /* 13 */ /***/ function(module, exports) { "use strict"; function computeCellMetadataAndUpdateScrollOffsetHelper(_ref) { var cellsCount = _ref.cellsCount, cellSize = _ref.cellSize, computeMetadataCallback = _ref.computeMetadataCallback, computeMetadataCallbackProps = _ref.computeMetadataCallbackProps, computeMetadataOnNextUpdate = _ref.computeMetadataOnNextUpdate, nextCellsCount = _ref.nextCellsCount, nextCellSize = _ref.nextCellSize, nextScrollToIndex = _ref.nextScrollToIndex, scrollToIndex = _ref.scrollToIndex, updateScrollOffsetForScrollToIndex = _ref.updateScrollOffsetForScrollToIndex; (computeMetadataOnNextUpdate || cellsCount !== nextCellsCount || ("number" == typeof cellSize || "number" == typeof nextCellSize) && cellSize !== nextCellSize) && (computeMetadataCallback(computeMetadataCallbackProps), scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex && updateScrollOffsetForScrollToIndex()); } function createCallbackMemoizer() { var requireAllKeys = arguments.length <= 0 || void 0 === arguments[0] ? !0 : arguments[0], cachedIndices = {}; return function(_ref2) { var callback = _ref2.callback, indices = _ref2.indices, keys = Object.keys(indices), allInitialized = !requireAllKeys || keys.every(function(key) { return indices[key] >= 0; }), indexChanged = keys.some(function(key) { return cachedIndices[key] !== indices[key]; }); cachedIndices = indices, allInitialized && indexChanged && callback(indices); }; } function findNearestCell(_ref3) { for (var cellMetadata = _ref3.cellMetadata, mode = _ref3.mode, offset = _ref3.offset, high = cellMetadata.length - 1, low = 0, middle = void 0, currentOffset = void 0; high >= low; ) { if (middle = low + Math.floor((high - low) / 2), currentOffset = cellMetadata[middle].offset, currentOffset === offset) return middle; offset > currentOffset ? low = middle + 1 : currentOffset > offset && (high = middle - 1); } return mode === findNearestCell.EQUAL_OR_LOWER && low > 0 ? low - 1 : mode === findNearestCell.EQUAL_OR_HIGHER && high < cellMetadata.length - 1 ? high + 1 : void 0; } function getOverscanIndices(_ref4) { var cellsCount = _ref4.cellsCount, overscanCellsCount = _ref4.overscanCellsCount, startIndex = _ref4.startIndex, stopIndex = _ref4.stopIndex; return { overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), overscanStopIndex: Math.min(cellsCount - 1, stopIndex + overscanCellsCount) }; } function getUpdatedOffsetForIndex(_ref5) { var cellMetadata = _ref5.cellMetadata, containerSize = _ref5.containerSize, currentOffset = _ref5.currentOffset, targetIndex = _ref5.targetIndex; if (0 === cellMetadata.length) return 0; targetIndex = Math.max(0, Math.min(cellMetadata.length - 1, targetIndex)); var datum = cellMetadata[targetIndex], maxOffset = datum.offset, minOffset = maxOffset - containerSize + datum.size, newOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset)); return newOffset; } function getVisibleCellIndices(_ref6) { var cellsCount = _ref6.cellsCount, cellMetadata = _ref6.cellMetadata, containerSize = _ref6.containerSize, currentOffset = _ref6.currentOffset; if (0 === cellsCount) return {}; currentOffset = Math.max(0, currentOffset); var maxOffset = currentOffset + containerSize, start = findNearestCell({ cellMetadata: cellMetadata, mode: findNearestCell.EQUAL_OR_LOWER, offset: currentOffset }), datum = cellMetadata[start]; currentOffset = datum.offset + datum.size; for (var stop = start; maxOffset > currentOffset && cellsCount - 1 > stop; ) stop++, currentOffset += cellMetadata[stop].size; return { start: start, stop: stop }; } function initCellMetadata(_ref7) { for (var cellsCount = _ref7.cellsCount, size = _ref7.size, sizeGetter = size instanceof Function ? size : function(index) { return size; }, cellMetadata = [], offset = 0, i = 0; cellsCount > i; i++) { var _size = sizeGetter(i); if (null == _size || isNaN(_size)) throw Error("Invalid size returned for cell " + i + " of value " + _size); cellMetadata[i] = { size: _size, offset: offset }, offset += _size; } return cellMetadata; } function updateScrollIndexHelper(_ref8) { var cellMetadata = _ref8.cellMetadata, cellsCount = _ref8.cellsCount, cellSize = _ref8.cellSize, previousCellsCount = _ref8.previousCellsCount, previousCellSize = _ref8.previousCellSize, previousScrollToIndex = _ref8.previousScrollToIndex, previousSize = _ref8.previousSize, scrollOffset = _ref8.scrollOffset, scrollToIndex = _ref8.scrollToIndex, size = _ref8.size, updateScrollIndexCallback = _ref8.updateScrollIndexCallback, hasScrollToIndex = scrollToIndex >= 0 && cellsCount > scrollToIndex, sizeHasChanged = size !== previousSize || !previousCellSize || "number" == typeof cellSize && cellSize !== previousCellSize; if (hasScrollToIndex && (sizeHasChanged || scrollToIndex !== previousScrollToIndex)) updateScrollIndexCallback(); else if (!hasScrollToIndex && (previousSize > size || previousCellsCount > cellsCount)) { var calculatedScrollOffset = getUpdatedOffsetForIndex({ cellMetadata: cellMetadata, containerSize: size, currentOffset: scrollOffset, targetIndex: cellsCount - 1 }); scrollOffset > calculatedScrollOffset && updateScrollIndexCallback(cellsCount - 1); } } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.computeCellMetadataAndUpdateScrollOffsetHelper = computeCellMetadataAndUpdateScrollOffsetHelper, exports.createCallbackMemoizer = createCallbackMemoizer, exports.findNearestCell = findNearestCell, exports.getOverscanIndices = getOverscanIndices, exports.getUpdatedOffsetForIndex = getUpdatedOffsetForIndex, exports.getVisibleCellIndices = getVisibleCellIndices, exports.initCellMetadata = initCellMetadata, exports.updateScrollIndexHelper = updateScrollIndexHelper, findNearestCell.EQUAL_OR_LOWER = 1, findNearestCell.EQUAL_OR_HIGHER = 2; }, /* 14 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__; /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ !function() { "use strict"; function classNames() { for (var classes = [], i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { var argType = typeof arg; if ("string" === argType || "number" === argType) classes.push(arg); else if (Array.isArray(arg)) classes.push(classNames.apply(null, arg)); else if ("object" === argType) for (var key in arg) hasOwn.call(arg, key) && arg[key] && classes.push(key); } } return classes.join(" "); } var hasOwn = {}.hasOwnProperty; "undefined" != typeof module && module.exports ? module.exports = classNames : (__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), !(void 0 !== __WEBPACK_AMD_DEFINE_RESULT__ && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))); }(); }, /* 15 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(global) { for (var now = __webpack_require__(16), root = "undefined" == typeof window ? global : window, vendors = [ "moz", "webkit" ], suffix = "AnimationFrame", raf = root["request" + suffix], caf = root["cancel" + suffix] || root["cancelRequest" + suffix], i = 0; !raf && i < vendors.length; i++) raf = root[vendors[i] + "Request" + suffix], caf = root[vendors[i] + "Cancel" + suffix] || root[vendors[i] + "CancelRequest" + suffix]; // Some versions of FF have rAF but not cAF if (!raf || !caf) { var last = 0, id = 0, queue = [], frameDuration = 1e3 / 60; raf = function(callback) { if (0 === queue.length) { var _now = now(), next = Math.max(0, frameDuration - (_now - last)); last = next + _now, setTimeout(function() { var cp = queue.slice(0); // Clear queue here to prevent // callbacks from appending listeners // to the current frame's queue queue.length = 0; for (var i = 0; i < cp.length; i++) if (!cp[i].cancelled) try { cp[i].callback(last); } catch (e) { setTimeout(function() { throw e; }, 0); } }, Math.round(next)); } return queue.push({ handle: ++id, callback: callback, cancelled: !1 }), id; }, caf = function(handle) { for (var i = 0; i < queue.length; i++) queue[i].handle === handle && (queue[i].cancelled = !0); }; } module.exports = function(fn) { // Wrap in a new function to prevent // `cancel` potentially being assigned // to the native rAF function return raf.call(root, fn); }, module.exports.cancel = function() { caf.apply(root, arguments); }, module.exports.polyfill = function() { root.requestAnimationFrame = raf, root.cancelAnimationFrame = caf; }; }).call(exports, function() { return this; }()); }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { // Generated by CoffeeScript 1.7.1 (function() { var getNanoSeconds, hrtime, loadTime; "undefined" != typeof performance && null !== performance && performance.now ? module.exports = function() { return performance.now(); } : "undefined" != typeof process && null !== process && process.hrtime ? (module.exports = function() { return (getNanoSeconds() - loadTime) / 1e6; }, hrtime = process.hrtime, getNanoSeconds = function() { var hr; return hr = hrtime(), 1e9 * hr[0] + hr[1]; }, loadTime = getNanoSeconds()) : Date.now ? (module.exports = function() { return Date.now() - loadTime; }, loadTime = Date.now()) : (module.exports = function() { return new Date().getTime() - loadTime; }, loadTime = new Date().getTime()); }).call(this); }).call(exports, __webpack_require__(17)); }, /* 17 */ /***/ function(module, exports) { function cleanUpNextTick() { draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1, queue.length && drainQueue(); } function drainQueue() { if (!draining) { var timeout = setTimeout(cleanUpNextTick); draining = !0; for (var len = queue.length; len; ) { for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run(); queueIndex = -1, len = queue.length; } currentQueue = null, draining = !1, clearTimeout(timeout); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun, this.array = array; } function noop() {} // shim for using process in browser var currentQueue, process = module.exports = {}, queue = [], draining = !1, queueIndex = -1; process.nextTick = function(fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) for (var i = 1; i < arguments.length; i++) args[i - 1] = arguments[i]; queue.push(new Item(fun, args)), 1 !== queue.length || draining || setTimeout(drainQueue, 0); }, Item.prototype.run = function() { this.fun.apply(null, this.array); }, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [], process.version = "", // empty string to avoid regexp issues process.versions = {}, process.on = noop, process.addListener = noop, process.once = noop, process.off = noop, process.removeListener = noop, process.removeAllListeners = noop, process.emit = noop, process.binding = function(name) { throw new Error("process.binding is not supported"); }, process.cwd = function() { return "/"; }, process.chdir = function(dir) { throw new Error("process.chdir is not supported"); }, process.umask = function() { return 0; }; }, /* 18 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.FlexColumn = exports.SortIndicator = exports.SortDirection = exports.FlexTable = exports["default"] = void 0; var _FlexTable2 = __webpack_require__(19); Object.defineProperty(exports, "SortDirection", { enumerable: !0, get: function() { return _FlexTable2.SortDirection; } }), Object.defineProperty(exports, "SortIndicator", { enumerable: !0, get: function() { return _FlexTable2.SortIndicator; } }); var _FlexTable3 = _interopRequireDefault(_FlexTable2), _FlexColumn2 = __webpack_require__(20), _FlexColumn3 = _interopRequireDefault(_FlexColumn2); exports["default"] = _FlexTable3["default"], exports.FlexTable = _FlexTable3["default"], exports.FlexColumn = _FlexColumn3["default"]; }, /* 19 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function SortIndicator(_ref4) { var sortDirection = _ref4.sortDirection, classNames = (0, _classnames2["default"])("FlexTable__sortableHeaderIcon", { "FlexTable__sortableHeaderIcon--ASC": sortDirection === SortDirection.ASC, "FlexTable__sortableHeaderIcon--DESC": sortDirection === SortDirection.DESC }); return _react2["default"].createElement("svg", { className: classNames, width: 18, height: 18, viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg" }, sortDirection === SortDirection.ASC ? _react2["default"].createElement("path", { d: "M7 14l5-5 5 5z" }) : _react2["default"].createElement("path", { d: "M7 10l5 5 5-5z" }), _react2["default"].createElement("path", { d: "M0 0h24v24H0z", fill: "none" })); } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.SortDirection = void 0; var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(); exports.SortIndicator = SortIndicator; var _classnames = __webpack_require__(14), _classnames2 = _interopRequireDefault(_classnames), _FlexColumn = __webpack_require__(20), _FlexColumn2 = _interopRequireDefault(_FlexColumn), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _reactDom = __webpack_require__(21), _function = __webpack_require__(4), _function2 = _interopRequireDefault(_function), _Grid = __webpack_require__(9), _Grid2 = _interopRequireDefault(_Grid), SortDirection = exports.SortDirection = { ASC: "ASC", DESC: "DESC" }, FlexTable = function(_Component) { function FlexTable(props) { _classCallCheck(this, FlexTable); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(FlexTable).call(this, props)); return _initialiseProps.call(_this), _this.state = { scrollbarWidth: 0 }, _this._createRow = _this._createRow.bind(_this), _this; } return _inherits(FlexTable, _Component), _createClass(FlexTable, [ { key: "recomputeRowHeights", value: function() { this.refs.Grid.recomputeGridSize(); } }, { key: "scrollToRow", value: function(scrollToIndex) { this.refs.Grid.scrollToCell({ scrollToColumn: 0, scrollToRow: scrollToIndex }); } }, { key: "setScrollTop", value: function(scrollTop) { this.refs.Grid.setScrollPosition({ scrollLeft: 0, scrollTop: scrollTop }); } }, { key: "componentDidMount", value: function() { var scrollTop = this.props.scrollTop; scrollTop >= 0 && this.setScrollTop(scrollTop), this._setScrollbarWidth(); } }, { key: "componentDidUpdate", value: function() { this._setScrollbarWidth(); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { nextProps.scrollTop !== this.props.scrollTop && this.setScrollTop(nextProps.scrollTop); } }, { key: "render", value: function() { var _this2 = this, _props = this.props, className = _props.className, disableHeader = _props.disableHeader, headerHeight = _props.headerHeight, height = _props.height, noRowsRenderer = _props.noRowsRenderer, onRowsRendered = _props.onRowsRendered, _onScroll = _props.onScroll, overscanRowsCount = _props.overscanRowsCount, rowClassName = _props.rowClassName, rowHeight = _props.rowHeight, rowsCount = _props.rowsCount, scrollToIndex = _props.scrollToIndex, width = _props.width, scrollbarWidth = this.state.scrollbarWidth, availableRowsHeight = height - headerHeight, rowRenderer = function(index) { return _this2._createRow(index); }, rowClass = rowClassName instanceof Function ? rowClassName(-1) : rowClassName; return _react2["default"].createElement("div", { className: (0, _classnames2["default"])("FlexTable", className) }, !disableHeader && _react2["default"].createElement("div", { className: (0, _classnames2["default"])("FlexTable__headerRow", rowClass), style: { height: headerHeight, paddingRight: scrollbarWidth, width: width } }, this._getRenderedHeaderRow()), _react2["default"].createElement(_Grid2["default"], { ref: "Grid", className: "FlexTable__Grid", columnWidth: width, columnsCount: 1, height: availableRowsHeight, noContentRenderer: noRowsRenderer, onScroll: function(_ref) { var clientHeight = _ref.clientHeight, scrollHeight = _ref.scrollHeight, scrollTop = _ref.scrollTop; return _onScroll({ clientHeight: clientHeight, scrollHeight: scrollHeight, scrollTop: scrollTop }); }, onSectionRendered: function(_ref2) { var rowOverscanStartIndex = _ref2.rowOverscanStartIndex, rowOverscanStopIndex = _ref2.rowOverscanStopIndex, rowStartIndex = _ref2.rowStartIndex, rowStopIndex = _ref2.rowStopIndex; return onRowsRendered({ overscanStartIndex: rowOverscanStartIndex, overscanStopIndex: rowOverscanStopIndex, startIndex: rowStartIndex, stopIndex: rowStopIndex }); }, overscanRowsCount: overscanRowsCount, renderCell: function(_ref3) { var rowIndex = (_ref3.columnIndex, _ref3.rowIndex); return rowRenderer(rowIndex); }, rowHeight: rowHeight, rowsCount: rowsCount, scrollToRow: scrollToIndex, width: width })); } }, { key: "_createColumn", value: function(column, columnIndex, rowData, rowIndex) { var _column$props = column.props, cellClassName = _column$props.cellClassName, cellDataGetter = _column$props.cellDataGetter, columnData = _column$props.columnData, dataKey = _column$props.dataKey, cellRenderer = _column$props.cellRenderer, cellData = cellDataGetter(dataKey, rowData, columnData), renderedCell = cellRenderer(cellData, dataKey, rowData, rowIndex, columnData), style = this._getFlexStyleForColumn(column), title = "string" == typeof renderedCell ? renderedCell : null; return _react2["default"].createElement("div", { key: "Row" + rowIndex + "-Col" + columnIndex, className: (0, _classnames2["default"])("FlexTable__rowColumn", cellClassName), style: style }, _react2["default"].createElement("div", { className: "FlexTable__truncatedColumnText", title: title }, renderedCell)); } }, { key: "_createHeader", value: function(column, columnIndex) { var _props2 = this.props, headerClassName = _props2.headerClassName, onHeaderClick = _props2.onHeaderClick, sort = _props2.sort, sortBy = _props2.sortBy, sortDirection = _props2.sortDirection, _column$props2 = column.props, dataKey = _column$props2.dataKey, disableSort = _column$props2.disableSort, label = _column$props2.label, columnData = _column$props2.columnData, showSortIndicator = sortBy === dataKey, sortEnabled = !disableSort && sort, classNames = (0, _classnames2["default"])("FlexTable__headerColumn", headerClassName, column.props.headerClassName, { FlexTable__sortableHeaderColumn: sortEnabled }), style = this._getFlexStyleForColumn(column), newSortDirection = sortBy !== dataKey || sortDirection === SortDirection.DESC ? SortDirection.ASC : SortDirection.DESC, onClick = function() { sortEnabled && sort(dataKey, newSortDirection), onHeaderClick(dataKey, columnData); }; return _react2["default"].createElement("div", { key: "Header-Col" + columnIndex, className: classNames, style: style, onClick: onClick }, _react2["default"].createElement("div", { className: "FlexTable__headerTruncatedText", title: label }, label), showSortIndicator && _react2["default"].createElement(SortIndicator, { sortDirection: sortDirection })); } }, { key: "_createRow", value: function(rowIndex) { var _this3 = this, _props3 = this.props, children = _props3.children, onRowClick = _props3.onRowClick, rowClassName = _props3.rowClassName, rowGetter = _props3.rowGetter, scrollbarWidth = this.state.scrollbarWidth, rowClass = rowClassName instanceof Function ? rowClassName(rowIndex) : rowClassName, renderedRow = _react2["default"].Children.map(children, function(column, columnIndex) { return _this3._createColumn(column, columnIndex, rowGetter(rowIndex), rowIndex); }); return _react2["default"].createElement("div", { key: rowIndex, className: (0, _classnames2["default"])("FlexTable__row", rowClass), onClick: function() { return onRowClick(rowIndex); }, style: { height: this._getRowHeight(rowIndex), paddingRight: scrollbarWidth } }, renderedRow); } }, { key: "_getFlexStyleForColumn", value: function(column) { var flexValue = column.props.flexGrow + " " + column.props.flexShrink + " " + column.props.width + "px", style = { flex: flexValue, msFlex: flexValue, WebkitFlex: flexValue }; return column.props.maxWidth && (style.maxWidth = column.props.maxWidth), column.props.minWidth && (style.minWidth = column.props.minWidth), style; } }, { key: "_getRenderedHeaderRow", value: function() { var _this4 = this, _props4 = this.props, children = _props4.children, disableHeader = _props4.disableHeader, items = disableHeader ? [] : children; return _react2["default"].Children.map(items, function(column, columnIndex) { return _this4._createHeader(column, columnIndex); }); } }, { key: "_getRowHeight", value: function(rowIndex) { var rowHeight = this.props.rowHeight; return rowHeight instanceof Function ? rowHeight(rowIndex) : rowHeight; } }, { key: "_setScrollbarWidth", value: function() { var Grid = (0, _reactDom.findDOMNode)(this.refs.Grid), clientWidth = Grid.clientWidth || 0, offsetWidth = Grid.offsetWidth || 0, scrollbarWidth = offsetWidth - clientWidth; this.setState({ scrollbarWidth: scrollbarWidth }); } } ]), FlexTable; }(_react.Component); FlexTable.propTypes = { children: function children(props, propName, componentName) { for (var children = _react2["default"].Children.toArray(props.children), i = 0; i < children.length; i++) if (children[i].type !== _FlexColumn2["default"]) return new Error("FlexTable only accepts children of type FlexColumn"); }, className: _react.PropTypes.string, disableHeader: _react.PropTypes.bool, headerClassName: _react.PropTypes.string, headerHeight: _react.PropTypes.number.isRequired, height: _react.PropTypes.number.isRequired, noRowsRenderer: _react.PropTypes.func, onHeaderClick: _react.PropTypes.func, onRowClick: _react.PropTypes.func, onRowsRendered: _react.PropTypes.func, onScroll: _react.PropTypes.func.isRequired, overscanRowsCount: _react.PropTypes.number.isRequired, rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), rowGetter: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowsCount: _react.PropTypes.number.isRequired, scrollToIndex: _react.PropTypes.number, scrollTop: _react.PropTypes.number, sort: _react.PropTypes.func, sortBy: _react.PropTypes.string, sortDirection: _react.PropTypes.oneOf([ SortDirection.ASC, SortDirection.DESC ]), width: _react.PropTypes.number.isRequired }, FlexTable.defaultProps = { disableHeader: !1, headerHeight: 0, noRowsRenderer: function() { return null; }, onHeaderClick: function() { return null; }, onRowClick: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, overscanRowsCount: 10 }; var _initialiseProps = function() { this.shouldComponentUpdate = _function2["default"]; }; exports["default"] = FlexTable, SortIndicator.propTypes = { sortDirection: _react.PropTypes.oneOf([ SortDirection.ASC, SortDirection.DESC ]) }; }, /* 20 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function defaultCellRenderer(cellData, cellDataKey, rowData, rowIndex, columnData) { return null === cellData || void 0 === cellData ? "" : String(cellData); } function defaultCellDataGetter(dataKey, rowData, columnData) { return rowData.get instanceof Function ? rowData.get(dataKey) : rowData[dataKey]; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.defaultCellRenderer = defaultCellRenderer, exports.defaultCellDataGetter = defaultCellDataGetter; var _react = __webpack_require__(3), Column = function(_Component) { function Column() { return _classCallCheck(this, Column), _possibleConstructorReturn(this, Object.getPrototypeOf(Column).apply(this, arguments)); } return _inherits(Column, _Component), Column; }(_react.Component); Column.defaultProps = { cellDataGetter: defaultCellDataGetter, cellRenderer: defaultCellRenderer, flexGrow: 0, flexShrink: 1 }, Column.propTypes = { cellClassName: _react.PropTypes.string, cellDataGetter: _react.PropTypes.func, cellRenderer: _react.PropTypes.func, columnData: _react.PropTypes.object, dataKey: _react.PropTypes.any.isRequired, disableSort: _react.PropTypes.bool, flexGrow: _react.PropTypes.number, flexShrink: _react.PropTypes.number, headerClassName: _react.PropTypes.string, label: _react.PropTypes.string, maxWidth: _react.PropTypes.number, minWidth: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, exports["default"] = Column; }, /* 21 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_21__; }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.InfiniteLoader = exports["default"] = void 0; var _InfiniteLoader2 = __webpack_require__(23), _InfiniteLoader3 = _interopRequireDefault(_InfiniteLoader2); exports["default"] = _InfiniteLoader3["default"], exports.InfiniteLoader = _InfiniteLoader3["default"]; }, /* 23 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function isRangeVisible(_ref2) { var lastRenderedStartIndex = _ref2.lastRenderedStartIndex, lastRenderedStopIndex = _ref2.lastRenderedStopIndex, startIndex = _ref2.startIndex, stopIndex = _ref2.stopIndex; return !(startIndex > lastRenderedStopIndex || lastRenderedStartIndex > stopIndex); } function scanForUnloadedRanges(_ref3) { for (var isRowLoaded = _ref3.isRowLoaded, startIndex = _ref3.startIndex, stopIndex = _ref3.stopIndex, unloadedRanges = [], rangeStartIndex = null, rangeStopIndex = null, i = startIndex; stopIndex >= i; i++) { var loaded = isRowLoaded(i); loaded ? null !== rangeStopIndex && (unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }), rangeStartIndex = rangeStopIndex = null) : (rangeStopIndex = i, null === rangeStartIndex && (rangeStartIndex = i)); } return null !== rangeStopIndex && unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }), unloadedRanges; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(); exports.isRangeVisible = isRangeVisible, exports.scanForUnloadedRanges = scanForUnloadedRanges; var _react = __webpack_require__(3), _function = __webpack_require__(4), _function2 = _interopRequireDefault(_function), InfiniteLoader = function(_Component) { function InfiniteLoader(props, context) { _classCallCheck(this, InfiniteLoader); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(InfiniteLoader).call(this, props, context)); return _this.shouldComponentUpdate = _function2["default"], _this._onRowsRendered = _this._onRowsRendered.bind(_this), _this._registerChild = _this._registerChild.bind(_this), _this; } return _inherits(InfiniteLoader, _Component), _createClass(InfiniteLoader, [ { key: "render", value: function() { var children = this.props.children; return children({ onRowsRendered: this._onRowsRendered, registerChild: this._registerChild }); } }, { key: "_onRowsRendered", value: function(_ref) { var _this2 = this, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, _props = this.props, isRowLoaded = _props.isRowLoaded, loadMoreRows = _props.loadMoreRows, rowsCount = _props.rowsCount, threshold = _props.threshold; this._lastRenderedStartIndex = startIndex, this._lastRenderedStopIndex = stopIndex; var unloadedRanges = scanForUnloadedRanges({ isRowLoaded: isRowLoaded, startIndex: Math.max(0, startIndex - threshold), stopIndex: Math.min(rowsCount, stopIndex + threshold) }); unloadedRanges.forEach(function(unloadedRange) { var promise = loadMoreRows(unloadedRange); promise && promise.then(function() { isRangeVisible({ lastRenderedStartIndex: _this2._lastRenderedStartIndex, lastRenderedStopIndex: _this2._lastRenderedStopIndex, startIndex: unloadedRange.startIndex, stopIndex: unloadedRange.stopIndex }) && _this2._registeredChild && _this2._registeredChild.forceUpdate(); }); }); } }, { key: "_registerChild", value: function(registeredChild) { this._registeredChild = registeredChild; } } ]), InfiniteLoader; }(_react.Component); InfiniteLoader.propTypes = { children: _react.PropTypes.func.isRequired, isRowLoaded: _react.PropTypes.func.isRequired, loadMoreRows: _react.PropTypes.func.isRequired, rowsCount: _react.PropTypes.number.isRequired, threshold: _react.PropTypes.number.isRequired }, InfiniteLoader.defaultProps = { rowsCount: 0, threshold: 15 }, exports["default"] = InfiniteLoader; }, /* 24 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.ScrollSync = exports["default"] = void 0; var _ScrollSync2 = __webpack_require__(25), _ScrollSync3 = _interopRequireDefault(_ScrollSync2); exports["default"] = _ScrollSync3["default"], exports.ScrollSync = _ScrollSync3["default"]; }, /* 25 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _react = __webpack_require__(3), _function = __webpack_require__(4), _function2 = _interopRequireDefault(_function), ScrollSync = function(_Component) { function ScrollSync(props, context) { _classCallCheck(this, ScrollSync); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(ScrollSync).call(this, props, context)); return _this.shouldComponentUpdate = _function2["default"], _this.state = { scrollLeft: 0, scrollTop: 0 }, _this._onScroll = _this._onScroll.bind(_this), _this; } return _inherits(ScrollSync, _Component), _createClass(ScrollSync, [ { key: "render", value: function() { var children = this.props.children, _state = this.state, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop; return children({ onScroll: this._onScroll, scrollLeft: scrollLeft, scrollTop: scrollTop }); } }, { key: "_onScroll", value: function(_ref) { var scrollLeft = _ref.scrollLeft, scrollTop = _ref.scrollTop; this.setState({ scrollLeft: scrollLeft, scrollTop: scrollTop }); } } ]), ScrollSync; }(_react.Component); ScrollSync.propTypes = { children: _react.PropTypes.func.isRequired }, exports["default"] = ScrollSync; }, /* 26 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.VirtualScroll = exports["default"] = void 0; var _VirtualScroll2 = __webpack_require__(27), _VirtualScroll3 = _interopRequireDefault(_VirtualScroll2); exports["default"] = _VirtualScroll3["default"], exports.VirtualScroll = _VirtualScroll3["default"]; }, /* 27 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _possibleConstructorReturn(self, call) { if (!self) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return !call || "object" != typeof call && "function" != typeof call ? self : call; } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _Grid = __webpack_require__(9), _Grid2 = _interopRequireDefault(_Grid), _react = __webpack_require__(3), _react2 = _interopRequireDefault(_react), _classnames = __webpack_require__(14), _classnames2 = _interopRequireDefault(_classnames), _function = __webpack_require__(4), _function2 = _interopRequireDefault(_function), VirtualScroll = function(_Component) { function VirtualScroll() { var _Object$getPrototypeO, _temp, _this, _ret; _classCallCheck(this, VirtualScroll); for (var _len = arguments.length, args = Array(_len), _key = 0; _len > _key; _key++) args[_key] = arguments[_key]; return _temp = _this = _possibleConstructorReturn(this, (_Object$getPrototypeO = Object.getPrototypeOf(VirtualScroll)).call.apply(_Object$getPrototypeO, [ this ].concat(args))), _this.shouldComponentUpdate = _function2["default"], _ret = _temp, _possibleConstructorReturn(_this, _ret); } return _inherits(VirtualScroll, _Component), _createClass(VirtualScroll, [ { key: "componentDidMount", value: function() { var scrollTop = this.props.scrollTop; scrollTop >= 0 && this.setScrollTop(scrollTop); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { nextProps.scrollTop !== this.props.scrollTop && this.setScrollTop(nextProps.scrollTop); } }, { key: "recomputeRowHeights", value: function() { this.refs.Grid.recomputeGridSize(); } }, { key: "scrollToRow", value: function(scrollToIndex) { this.refs.Grid.scrollToCell({ scrollToColumn: 0, scrollToRow: scrollToIndex }); } }, { key: "setScrollTop", value: function(scrollTop) { this.refs.Grid.setScrollPosition({ scrollLeft: 0, scrollTop: scrollTop }); } }, { key: "render", value: function() { var _props = this.props, className = _props.className, height = _props.height, noRowsRenderer = _props.noRowsRenderer, onRowsRendered = _props.onRowsRendered, _onScroll = _props.onScroll, rowHeight = _props.rowHeight, rowRenderer = _props.rowRenderer, overscanRowsCount = _props.overscanRowsCount, rowsCount = _props.rowsCount, scrollToIndex = _props.scrollToIndex, width = _props.width, classNames = (0, _classnames2["default"])("VirtualScroll", className); return _react2["default"].createElement(_Grid2["default"], { ref: "Grid", className: classNames, columnWidth: width, columnsCount: 1, height: height, noContentRenderer: noRowsRenderer, onScroll: function(_ref) { var clientHeight = _ref.clientHeight, scrollHeight = _ref.scrollHeight, scrollTop = _ref.scrollTop; return _onScroll({ clientHeight: clientHeight, scrollHeight: scrollHeight, scrollTop: scrollTop }); }, onSectionRendered: function(_ref2) { var rowOverscanStartIndex = _ref2.rowOverscanStartIndex, rowOverscanStopIndex = _ref2.rowOverscanStopIndex, rowStartIndex = _ref2.rowStartIndex, rowStopIndex = _ref2.rowStopIndex; return onRowsRendered({ overscanStartIndex: rowOverscanStartIndex, overscanStopIndex: rowOverscanStopIndex, startIndex: rowStartIndex, stopIndex: rowStopIndex }); }, overscanRowsCount: overscanRowsCount, renderCell: function(_ref3) { var rowIndex = (_ref3.columnIndex, _ref3.rowIndex); return rowRenderer(rowIndex); }, rowHeight: rowHeight, rowsCount: rowsCount, scrollToRow: scrollToIndex, width: width }); } } ]), VirtualScroll; }(_react.Component); VirtualScroll.propTypes = { className: _react.PropTypes.string, height: _react.PropTypes.number.isRequired, noRowsRenderer: _react.PropTypes.func.isRequired, onRowsRendered: _react.PropTypes.func.isRequired, overscanRowsCount: _react.PropTypes.number.isRequired, onScroll: _react.PropTypes.func.isRequired, rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, rowRenderer: _react.PropTypes.func.isRequired, rowsCount: _react.PropTypes.number.isRequired, scrollToIndex: _react.PropTypes.number, scrollTop: _react.PropTypes.number, width: _react.PropTypes.number.isRequired }, VirtualScroll.defaultProps = { noRowsRenderer: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, overscanRowsCount: 10 }, exports["default"] = VirtualScroll; } ]); }); //# sourceMappingURL=react-virtualized.js.map
mit
joseroes/altura_hotel
administrator/components/com_content/content.php
642
<?php /** * @package Joomla.Administrator * @subpackage com_content * * @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die; if (!JFactory::getUser()->authorise('core.manage', 'com_content')) { return JError::raiseWarning(404, JText::_('JERROR_ALERTNOAUTHOR')); } JLoader::register('ContentHelper', __DIR__ . '/helpers/content.php'); $controller = JControllerLegacy::getInstance('Content'); $controller->execute(JFactory::getApplication()->input->get('task')); $controller->redirect();
gpl-2.0
snkrishnan1/PivotGridSample
node_modules/browser-sync-ui/lib/plugins/remote-debug/overlay-grid/overlay-grid.client.js
1427
(function (angular) { const SECTION_NAME = "remote-debug"; /** * Display the snippet when in snippet mode */ angular .module("BrowserSync") .directive("cssGrid", function () { return { restrict: "E", replace: true, scope: { "options": "=" }, templateUrl: "overlay-grid.html", controller: ["$scope", "Socket", overlayGridDirectiveControlller], controllerAs: "ctrl" }; }); /** * @param $scope * @param Socket */ function overlayGridDirectiveControlller($scope, Socket) { var ctrl = this; ctrl.overlayGrid = $scope.options[SECTION_NAME]["overlay-grid"]; ctrl.size = ctrl.overlayGrid.size; var ns = SECTION_NAME + ":overlay-grid"; ctrl.alter = function (value) { Socket.emit("ui", { namespace: ns, event: "adjust", data: value }); }; ctrl.toggleAxis = function (axis, value) { Socket.emit("ui", { namespace: ns, event: "toggle:axis", data: { axis: axis, value: value } }); }; } })(angular);
mit
mquandalle/rethinkdb
external/v8_3.30.33.16/test/webkit/dfg-intrinsic-unused-this-method-check.js
2037
// Copyright 2013 the V8 project authors. All rights reserved. // Copyright (C) 2005, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 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. // // THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY // DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. description( "This tests that doing intrinsic function optimization does not result in this being lost entirely, if method check optimizations succeed." ); function bar(a, b) { return this.f + Math.max(a, b); } function baz(o, a, b) { return o.stuff(a, b); } var functionToCall = Math.max; var offset = 0; for (var i = 0; i < 1000; ++i) { if (i == 600) { functionToCall = bar; offset = 42; } var object = {}; object.stuff = functionToCall; object.f = 42; shouldBe("baz(object, " + i + ", " + (i * 2) + ")", "" + (offset + Math.max(i, i * 2))); }
agpl-3.0
cunningt/camel
camel-core/src/test/java/org/apache/camel/management/BacklogDebuggerTest.java
28774
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.management; import java.util.Set; import javax.management.MBeanServer; import javax.management.ObjectName; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.mock.MockEndpoint; public class BacklogDebuggerTest extends ManagementTestSupport { @SuppressWarnings("unchecked") public void testBacklogDebugger() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogDebugger"); assertNotNull(on); mbeanServer.isRegistered(on); Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should not be enabled", Boolean.FALSE, enabled); // enable debugger mbeanServer.invoke(on, "enableDebugger", null, null); enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should be enabled", Boolean.TRUE, enabled); // add breakpoint at bar mbeanServer.invoke(on, "addBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); mock.setSleepForEmptyTest(1000); template.sendBody("seda:start", "Hello World"); assertMockEndpointsSatisfied(); // add breakpoint at bar Set<String> nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("bar", nodes.iterator().next()); // the message should be ours String xml = (String) mbeanServer.invoke(on, "dumpTracedMessagesAsXml", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertNotNull(xml); log.info(xml); assertTrue("Should contain our body", xml.contains("Hello World")); assertTrue("Should contain bar node", xml.contains("<toNode>bar</toNode>")); resetMocks(); mock.expectedMessageCount(1); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertMockEndpointsSatisfied(); // and no suspended anymore nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); } @SuppressWarnings("unchecked") public void testBacklogDebuggerUpdateBodyAndHeader() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogDebugger"); assertNotNull(on); mbeanServer.isRegistered(on); Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should not be enabled", Boolean.FALSE, enabled); // enable debugger mbeanServer.invoke(on, "enableDebugger", null, null); enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should be enabled", Boolean.TRUE, enabled); // add breakpoint at bar mbeanServer.invoke(on, "addBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); mbeanServer.invoke(on, "addBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); mock.setSleepForEmptyTest(1000); template.sendBody("seda:start", "Hello World"); assertMockEndpointsSatisfied(); // add breakpoint at bar Set<String> nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("foo", nodes.iterator().next()); // update body and header mbeanServer.invoke(on, "setMessageBodyOnBreakpoint", new Object[]{"foo", "Changed body"}, new String[]{"java.lang.String", "java.lang.Object"}); mbeanServer.invoke(on, "setMessageHeaderOnBreakpoint", new Object[]{"foo", "beer", "Carlsberg"}, new String[]{"java.lang.String", "java.lang.String", "java.lang.Object"}); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); Thread.sleep(1000); // add breakpoint at bar nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("bar", nodes.iterator().next()); // the message should be ours String xml = (String) mbeanServer.invoke(on, "dumpTracedMessagesAsXml", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertNotNull(xml); log.info(xml); assertTrue("Should contain our body", xml.contains("Changed body")); assertTrue("Should contain bar node", xml.contains("<toNode>bar</toNode>")); assertTrue("Should contain our added header", xml.contains("<header key=\"beer\" type=\"java.lang.String\">Carlsberg</header>")); resetMocks(); mock.expectedMessageCount(1); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertMockEndpointsSatisfied(); // and no suspended anymore nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); } @SuppressWarnings("unchecked") public void testBacklogDebuggerUpdateBodyAndHeaderType() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogDebugger"); assertNotNull(on); mbeanServer.isRegistered(on); Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should not be enabled", Boolean.FALSE, enabled); // enable debugger mbeanServer.invoke(on, "enableDebugger", null, null); enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should be enabled", Boolean.TRUE, enabled); // add breakpoint at bar mbeanServer.invoke(on, "addBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); mbeanServer.invoke(on, "addBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); mock.setSleepForEmptyTest(1000); template.sendBody("seda:start", "Hello World"); assertMockEndpointsSatisfied(); // add breakpoint at bar Set<String> nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("foo", nodes.iterator().next()); // update body and header mbeanServer.invoke(on, "setMessageBodyOnBreakpoint", new Object[]{"foo", "444", "java.lang.Integer"}, new String[]{"java.lang.String", "java.lang.Object", "java.lang.String"}); mbeanServer.invoke(on, "setMessageHeaderOnBreakpoint", new Object[]{"foo", "beer", "123", "java.lang.Integer"}, new String[]{"java.lang.String", "java.lang.String", "java.lang.Object", "java.lang.String"}); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); Thread.sleep(1000); // add breakpoint at bar nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("bar", nodes.iterator().next()); // the message should be ours String xml = (String) mbeanServer.invoke(on, "dumpTracedMessagesAsXml", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertNotNull(xml); log.info(xml); assertTrue("Should contain our body", xml.contains("444")); assertTrue("Should contain bar node", xml.contains("<toNode>bar</toNode>")); assertTrue("Should contain our added header", xml.contains("<header key=\"beer\" type=\"java.lang.Integer\">123</header>")); resetMocks(); mock.expectedMessageCount(1); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertMockEndpointsSatisfied(); // and no suspended anymore nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); } @SuppressWarnings("unchecked") public void testBacklogDebuggerRemoveBodyAndHeader() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogDebugger"); assertNotNull(on); mbeanServer.isRegistered(on); Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should not be enabled", Boolean.FALSE, enabled); // enable debugger mbeanServer.invoke(on, "enableDebugger", null, null); enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should be enabled", Boolean.TRUE, enabled); // add breakpoint at bar mbeanServer.invoke(on, "addBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); mbeanServer.invoke(on, "addBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); mock.setSleepForEmptyTest(1000); template.sendBody("seda:start", "Hello World"); assertMockEndpointsSatisfied(); // add breakpoint at bar Set<String> nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("foo", nodes.iterator().next()); // update body and header mbeanServer.invoke(on, "removeMessageBodyOnBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); mbeanServer.invoke(on, "removeMessageHeaderOnBreakpoint", new Object[]{"foo", "beer"}, new String[]{"java.lang.String", "java.lang.String"}); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); Thread.sleep(1000); // add breakpoint at bar nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("bar", nodes.iterator().next()); // the message should be ours String xml = (String) mbeanServer.invoke(on, "dumpTracedMessagesAsXml", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertNotNull(xml); log.info(xml); assertTrue("Should not contain our body", xml.contains("<body>[Body is null]</body>")); assertTrue("Should contain bar node", xml.contains("<toNode>bar</toNode>")); assertFalse("Should not contain any headers", xml.contains("<header")); resetMocks(); mock.expectedMessageCount(1); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertMockEndpointsSatisfied(); // and no suspended anymore nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); } @SuppressWarnings("unchecked") public void testBacklogDebuggerSuspendOnlyOneAtBreakpoint() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogDebugger"); assertNotNull(on); mbeanServer.isRegistered(on); Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should not be enabled", Boolean.FALSE, enabled); // enable debugger mbeanServer.invoke(on, "enableDebugger", null, null); enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should be enabled", Boolean.TRUE, enabled); // add breakpoint at bar mbeanServer.invoke(on, "addBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(2); // only one of them is suspended template.sendBody("seda:start", "Hello World"); template.sendBody("seda:start", "Hello Camel"); template.sendBody("seda:start", "Hello Earth"); assertMockEndpointsSatisfied(); // add breakpoint at bar Set<String> nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("bar", nodes.iterator().next()); // the message should be ours String xml = (String) mbeanServer.invoke(on, "dumpTracedMessagesAsXml", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertNotNull(xml); log.info(xml); assertTrue("Should contain bar node", xml.contains("<toNode>bar</toNode>")); resetMocks(); mock.expectedMessageCount(1); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertMockEndpointsSatisfied(); // and no suspended anymore nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); } @SuppressWarnings("unchecked") public void testBacklogDebuggerConditional() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogDebugger"); assertNotNull(on); mbeanServer.isRegistered(on); Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should not be enabled", Boolean.FALSE, enabled); // enable debugger mbeanServer.invoke(on, "enableDebugger", null, null); enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should be enabled", Boolean.TRUE, enabled); // validate conditional breakpoint (mistake on purpose) Object out = mbeanServer.invoke(on, "validateConditionalBreakpoint", new Object[]{"unknown", "${body contains 'Camel'"}, new String[]{"java.lang.String", "java.lang.String"}); assertEquals("No language could be found for: unknown", out); // validate conditional breakpoint (mistake on purpose) out = mbeanServer.invoke(on, "validateConditionalBreakpoint", new Object[]{"simple", "${body contains 'Camel'"}, new String[]{"java.lang.String", "java.lang.String"}); assertNotNull(out); assertTrue(out.toString().startsWith("Invalid syntax ${body contains 'Camel'")); // validate conditional breakpoint (is correct) out = mbeanServer.invoke(on, "validateConditionalBreakpoint", new Object[]{"simple", "${body} contains 'Camel'"}, new String[]{"java.lang.String", "java.lang.String"}); assertNull(out); // add breakpoint at bar mbeanServer.invoke(on, "addConditionalBreakpoint", new Object[]{"bar", "simple", "${body} contains 'Camel'"}, new String[]{"java.lang.String", "java.lang.String", "java.lang.String"}); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); template.sendBody("seda:start", "Hello World"); assertMockEndpointsSatisfied(); // add not breakpoint at bar as condition did not match Set<String> nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); resetMocks(); mock.expectedMessageCount(0); mock.setSleepForEmptyTest(1000); template.sendBody("seda:start", "Hello Camel"); assertMockEndpointsSatisfied(); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("bar", nodes.iterator().next()); // the message should be ours String xml = (String) mbeanServer.invoke(on, "dumpTracedMessagesAsXml", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertNotNull(xml); log.info(xml); assertTrue("Should contain our body", xml.contains("Hello Camel")); assertTrue("Should contain bar node", xml.contains("<toNode>bar</toNode>")); resetMocks(); mock.expectedMessageCount(1); // resume breakpoint mbeanServer.invoke(on, "resumeBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); assertMockEndpointsSatisfied(); // and no suspended anymore nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); } @SuppressWarnings("unchecked") public void testBacklogDebuggerStep() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogDebugger"); assertNotNull(on); mbeanServer.isRegistered(on); Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should not be enabled", Boolean.FALSE, enabled); // enable debugger mbeanServer.invoke(on, "enableDebugger", null, null); enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should be enabled", Boolean.TRUE, enabled); // add breakpoint at bar mbeanServer.invoke(on, "addBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); mock.setSleepForEmptyTest(1000); template.sendBody("seda:start", "Hello World"); assertMockEndpointsSatisfied(); // add breakpoint at bar Set<String> nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("foo", nodes.iterator().next()); Boolean stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should not be in step mode", Boolean.FALSE, stepMode); // step breakpoint mbeanServer.invoke(on, "stepBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); // then at bar now Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("bar", nodes.iterator().next()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should be in step mode", Boolean.TRUE, stepMode); // step mbeanServer.invoke(on, "step", null, null); // then at transform now Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("transform", nodes.iterator().next()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should be in step mode", Boolean.TRUE, stepMode); // step mbeanServer.invoke(on, "step", null, null); // then at cheese now Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("cheese", nodes.iterator().next()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should be in step mode", Boolean.TRUE, stepMode); // step mbeanServer.invoke(on, "step", null, null); // then at result now Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("result", nodes.iterator().next()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should be in step mode", Boolean.TRUE, stepMode); // step mbeanServer.invoke(on, "step", null, null); // then the exchange is completed Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should not be in step mode", Boolean.FALSE, stepMode); } @SuppressWarnings("unchecked") public void testBacklogDebuggerStepCurrentNode() throws Exception { // JMX tests dont work well on AIX CI servers (hangs them) if (isPlatform("aix")) { return; } MBeanServer mbeanServer = getMBeanServer(); ObjectName on = new ObjectName("org.apache.camel:context=camel-1,type=tracer,name=BacklogDebugger"); assertNotNull(on); mbeanServer.isRegistered(on); Boolean enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should not be enabled", Boolean.FALSE, enabled); // enable debugger mbeanServer.invoke(on, "enableDebugger", null, null); enabled = (Boolean) mbeanServer.getAttribute(on, "Enabled"); assertEquals("Should be enabled", Boolean.TRUE, enabled); // add breakpoint at bar mbeanServer.invoke(on, "addBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(0); mock.setSleepForEmptyTest(1000); template.sendBody("seda:start", "Hello World"); assertMockEndpointsSatisfied(); // add breakpoint at bar Set<String> nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("foo", nodes.iterator().next()); Boolean stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should not be in step mode", Boolean.FALSE, stepMode); // step breakpoint mbeanServer.invoke(on, "stepBreakpoint", new Object[]{"foo"}, new String[]{"java.lang.String"}); // then at bar now Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("bar", nodes.iterator().next()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should be in step mode", Boolean.TRUE, stepMode); // step mbeanServer.invoke(on, "stepBreakpoint", new Object[]{"bar"}, new String[]{"java.lang.String"}); // then at transform now Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("transform", nodes.iterator().next()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should be in step mode", Boolean.TRUE, stepMode); // step mbeanServer.invoke(on, "stepBreakpoint", new Object[]{"transform"}, new String[]{"java.lang.String"}); // then at cheese now Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("cheese", nodes.iterator().next()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should be in step mode", Boolean.TRUE, stepMode); // step mbeanServer.invoke(on, "stepBreakpoint", new Object[]{"cheese"}, new String[]{"java.lang.String"}); // then at result now Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(1, nodes.size()); assertEquals("result", nodes.iterator().next()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should be in step mode", Boolean.TRUE, stepMode); // step mbeanServer.invoke(on, "stepBreakpoint", new Object[]{"result"}, new String[]{"java.lang.String"}); // then the exchange is completed Thread.sleep(1000); nodes = (Set<String>) mbeanServer.invoke(on, "getSuspendedBreakpointNodeIds", null, null); assertNotNull(nodes); assertEquals(0, nodes.size()); stepMode = (Boolean) mbeanServer.getAttribute(on, "SingleStepMode"); assertEquals("Should not be in step mode", Boolean.FALSE, stepMode); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { context.setUseBreadcrumb(false); from("seda:start?concurrentConsumers=2") .to("log:foo").id("foo") .to("log:bar").id("bar") .transform().constant("Bye World").id("transform") .to("log:cheese?showExchangeId=true").id("cheese") .to("mock:result").id("result"); } }; } }
apache-2.0
DLehenbauer/TypeScript
tests/baselines/reference/parserRegularExpression4.js
676
//// [parserRegularExpression4.ts] if (Ca.test(c.href) || Ba.test(c.href) && /(\\?|&)adurl=/.test(c.href) && !/(\\?|&)q=/.test(c.href)) / (\\ ? | & ) rct = j / .test(c.href) || (d += "&rct=j"), /(\\?|&)q=/.test(c.href) || (d += "&q=" + encodeURIComponent(W("q") || W("as_q") || A), d = d.substring(0, 1948 - c.href.length)), b = !0; //// [parserRegularExpression4.js] if (Ca.test(c.href) || Ba.test(c.href) && /(\\?|&)adurl=/.test(c.href) && !/(\\?|&)q=/.test(c.href)) / (\\ ? | & ) rct = j /.test(c.href) || (d += "&rct=j"), /(\\?|&)q=/.test(c.href) || (d += "&q=" + encodeURIComponent(W("q") || W("as_q") || A), d = d.substring(0, 1948 - c.href.length)), b = !0;
apache-2.0
noraesae/cdnjs
ajax/libs/jinplace/1.1.0/jinplace.min.js
4380
/* Copyright ? 2013, 2014 the jinplace team and contributors. MIT Licence */ (function(d,s,n,h){function k(b,a){var c=this.element=d(b),c=this.elementOptions(c);c.activator=d(c.activator||b);this.opts=c=d.extend({},d.fn[f].defaults,a,c);this.bindElement(c)}var f="jinplace",p="type url data loadurl elementId object attribute okButton cancelButton inputClass activator textOnly placeholder submitFunction".split(" ");k.prototype={elementOptions:function(b){function a(a){return"-"+a.toLowerCase()}var c={};d.each(p,function(d,g){c[g]=b.attr("data-"+g.replace(/[A-Z]/g,a))});c.elementId= b.attr("id");c.textOnly&&(c.textOnly="false"!==c.textOnly);return c},bindElement:function(b){b.activator.off("click.jip").on("click.jip",d.proxy(this.clickHandler,this));var a=this.element;""==d.trim(a.html())&&(a.html(b.placeholder),b.placeholder=a.html())},clickHandler:function(b){b.preventDefault();b.stopPropagation();d(b.currentTarget).off("click.jip").on("click.jip",function(a){a.preventDefault()});var a=this,c=a.opts,e=d.extend({},l,d.fn[f].editors[c.type]);a.origValue=a.element.html();a.fetchData(c).done(function(b){b= e.makeField(a.element,b);e.inputField||(e.inputField=b);b.addClass(c.inputClass);var d=q(c,b,e.buttonsAllowed);a.element.html(d);d.on("jip:submit submit",function(b){a.submit(e,c);return!1}).on("jip:cancel",function(b){a.cancel(e);return!1}).on("keyup",function(b){27==b.keyCode&&a.cancel(e)});e.activate(d,b);e.blurEvent(b,d,e.blurAction||(c.okButton?c.cancelButton?h:"jip:cancel":"submit"))})},fetchData:function(b){var a;a=b.data?b.data:b.loadurl?b.loadFunction(b):d.trim(this.element.html());var c= function(a){return a==b.placeholder?"":a};a=d.when(a);return a.pipe?a.pipe(c):a.then(c)},cancel:function(b){this.element.html(this.origValue);b.finish();this.bindElement(this.opts)},submit:function(b,a){var c=this,e,g=d.Deferred().reject();try{e=a.submitFunction.call(h,a,b.value()),e===h&&(e=g)}catch(f){e=g}d.when(e).done(function(d,e,g){c.element.trigger("jinplace:done",[d,e,g]);c.onUpdate(b,a,d)}).fail(function(a,d,e){c.element.trigger("jinplace:fail",[a,d,e]);c.cancel(b)}).always(function(a,b, d){c.element.trigger("jinplace:always",[a,b,d])})},onUpdate:function(b,a,c){this.setContent(c);b.finish();this.bindElement(a)},setContent:function(b){var a=this.element;b?this.opts.textOnly?a.text(b):a.html(b):a.html(this.opts.placeholder)}};var m=function(b,a){var c={id:b.elementId,object:b.object,attribute:b.attribute};d.isPlainObject(a)?d.extend(c,a):a!==h&&(c.value=a);return c};d.fn[f]=function(b){return this.each(function(){d.data(this,"plugin_"+f)||d.data(this,"plugin_"+f,new k(this,b))})}; d.fn[f].defaults={url:n.location.pathname,type:"input",textOnly:2,placeholder:"[ --- ]",submitFunction:function(b,a){return d.ajax(b.url,{type:"post",data:m(b,a),dataType:"text",headers:{"Cache-Control":"no-cache"}})},loadFunction:function(b){return d.ajax(b.loadurl,{data:m(b)})}};var q=function(b,a,c){a=d("<form>").attr("style","display: inline;").attr("action","javascript:void(0);").append(a);c&&r(a,b);return a},r=function(b,a){var c=function(a,c){b.append(a);a.one("click",function(a){a.stopPropagation(); b.trigger(c)})},e=a.okButton;e&&(e=d("<input>").attr("type","button").attr("value",e).addClass("jip-button jip-ok-button"),c(e,"submit"));if(e=a.cancelButton)e=d("<input>").attr("type","button").attr("value",e).addClass("jip-button jip-cancel-button"),c(e,"jip:cancel")},l={makeField:function(b,a){return d("<input>").attr("type","text").val(a)},activate:function(b,a){a.focus()},value:function(){return this.inputField.val()},blurEvent:function(b,a,c){if(c&&"ignore"!=c)b.on("blur",function(d){var g= setTimeout(function(){b.trigger(c)},300);a.on("click",function(){clearTimeout(g)})})},finish:function(){}};d.fn[f].editorBase=l;d.fn[f].editors={input:{buttonsAllowed:!0},textarea:{buttonsAllowed:!0,makeField:function(b,a){return d("<textarea>").css({"min-width":b.width(),"min-height":b.height()}).val(a)},activate:function(b,a){a.focus();a.elastic&&a.elastic()}},select:{makeField:function(b,a){var c=d("<select>"),e=d.parseJSON(a),g=!1,f=null;d.each(e,function(a,e){var h=d("<option>").val(e[0]).html(e[1]); e[2]&&(h.attr("selected","1"),g=!0);e[1]==b.text()&&(f=h);c.append(h)});!g&&f&&f.attr("selected","1");return c},activate:function(b,a){a.focus();a.on("change",function(){a.trigger("jip:submit")})}}}})(jQuery,window,document);
mit
Sribalaji1004/Angular-form
node_modules/rxjs/scheduler/AsapAction.d.ts
573
import { AsyncAction } from './AsyncAction'; import { AsapScheduler } from './AsapScheduler'; /** * We need this JSDoc comment for affecting ESDoc. * @ignore * @extends {Ignored} */ export declare class AsapAction<T> extends AsyncAction<T> { protected scheduler: AsapScheduler; protected work: (state?: T) => void; constructor(scheduler: AsapScheduler, work: (state?: T) => void); protected requestAsyncId(scheduler: AsapScheduler, id?: any, delay?: number): any; protected recycleAsyncId(scheduler: AsapScheduler, id?: any, delay?: number): any; }
mit
miguel250/vagrant
plugins/commands/plugin/command/update.rb
681
require 'optparse' require_relative "base" require_relative "mixin_install_opts" module VagrantPlugins module CommandPlugin module Command class Update < Base include MixinInstallOpts def execute opts = OptionParser.new do |o| o.banner = "Usage: vagrant plugin update [names...] [-h]" o.separator "" end # Parse the options argv = parse_options(opts) return if !argv # Update the gem action(Action.action_update, { plugin_name: argv, }) # Success, exit status 0 0 end end end end end
mit
mposolda/keycloak
examples/broker/saml-broker-authentication/src/main/webapp/js/lib/angular/angular-loader.js
15140
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @license AngularJS v1.2.13 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function() {'use strict'; /** * @description * * This object provides a utility for producing rich Error messages within * Angular. It can be called as follows: * * var exampleMinErr = minErr('example'); * throw exampleMinErr('one', 'This {0} is {1}', foo, bar); * * The above creates an instance of minErr in the example namespace. The * resulting error will have a namespaced error code of example.one. The * resulting error will replace {0} with the value of foo, and {1} with the * value of bar. The object is not restricted in the number of arguments it can * take. * * If fewer arguments are specified than necessary for interpolation, the extra * interpolation markers will be preserved in the final string. * * Since data will be parsed statically during a build step, some restrictions * are applied with respect to how minErr instances are created and called. * Instances should have names of the form namespaceMinErr for a minErr created * using minErr('namespace') . Error codes, namespaces and template strings * should all be static strings, not variables or general expressions. * * @param {string} module The namespace to use for the new minErr instance. * @returns {function(string, string, ...): Error} instance */ function minErr(module) { return function () { var code = arguments[0], prefix = '[' + (module ? module + ':' : '') + code + '] ', template = arguments[1], templateArgs = arguments, stringify = function (obj) { if (typeof obj === 'function') { return obj.toString().replace(/ \{[\s\S]*$/, ''); } else if (typeof obj === 'undefined') { return 'undefined'; } else if (typeof obj !== 'string') { return JSON.stringify(obj); } return obj; }, message, i; message = prefix + template.replace(/\{\d+\}/g, function (match) { var index = +match.slice(1, -1), arg; if (index + 2 < templateArgs.length) { arg = templateArgs[index + 2]; if (typeof arg === 'function') { return arg.toString().replace(/ ?\{[\s\S]*$/, ''); } else if (typeof arg === 'undefined') { return 'undefined'; } else if (typeof arg !== 'string') { return toJson(arg); } return arg; } return match; }); message = message + '\nhttp://errors.angularjs.org/1.2.13/' + (module ? module + '/' : '') + code; for (i = 2; i < arguments.length; i++) { message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' + encodeURIComponent(stringify(arguments[i])); } return new Error(message); }; } /** * @ngdoc interface * @name angular.Module * @description * * Interface for configuring angular {@link angular.module modules}. */ function setupModuleLoader(window) { var $injectorMinErr = minErr('$injector'); var ngMinErr = minErr('ng'); function ensure(obj, name, factory) { return obj[name] || (obj[name] = factory()); } var angular = ensure(window, 'angular', Object); // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap angular.$$minErr = angular.$$minErr || minErr; return ensure(angular, 'module', function() { /** @type {Object.<string, angular.Module>} */ var modules = {}; /** * @ngdoc function * @name angular.module * @description * * The `angular.module` is a global place for creating, registering and retrieving Angular * modules. * All modules (angular core or 3rd party) that should be available to an application must be * registered using this mechanism. * * When passed two or more arguments, a new module is created. If passed only one argument, an * existing module (the name passed as the first argument to `module`) is retrieved. * * * # Module * * A module is a collection of services, directives, filters, and configuration information. * `angular.module` is used to configure the {@link AUTO.$injector $injector}. * * <pre> * // Create a new module * var myModule = angular.module('myModule', []); * * // register a new service * myModule.value('appName', 'MyCoolApp'); * * // configure existing services inside initialization blocks. * myModule.config(function($locationProvider) { * // Configure existing providers * $locationProvider.hashPrefix('!'); * }); * </pre> * * Then you can create an injector and load your modules like this: * * <pre> * var injector = angular.injector(['ng', 'MyModule']) * </pre> * * However it's more likely that you'll just use * {@link ng.directive:ngApp ngApp} or * {@link angular.bootstrap} to simplify this process for you. * * @param {!string} name The name of the module to create or retrieve. * @param {Array.<string>=} requires If specified then new module is being created. If * unspecified then the the module is being retrieved for further configuration. * @param {Function} configFn Optional configuration function for the module. Same as * {@link angular.Module#methods_config Module#config()}. * @returns {module} new module with the {@link angular.Module} api. */ return function module(name, requires, configFn) { var assertNotHasOwnProperty = function(name, context) { if (name === 'hasOwnProperty') { throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context); } }; assertNotHasOwnProperty(name, 'module'); if (requires && modules.hasOwnProperty(name)) { modules[name] = null; } return ensure(modules, name, function() { if (!requires) { throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " + "the module name or forgot to load it. If registering a module ensure that you " + "specify the dependencies as the second argument.", name); } /** @type {!Array.<Array.<*>>} */ var invokeQueue = []; /** @type {!Array.<Function>} */ var runBlocks = []; var config = invokeLater('$injector', 'invoke'); /** @type {angular.Module} */ var moduleInstance = { // Private state _invokeQueue: invokeQueue, _runBlocks: runBlocks, /** * @ngdoc property * @name angular.Module#requires * @propertyOf angular.Module * @returns {Array.<string>} List of module names which must be loaded before this module. * @description * Holds the list of modules which the injector will load before the current module is * loaded. */ requires: requires, /** * @ngdoc property * @name angular.Module#name * @propertyOf angular.Module * @returns {string} Name of the module. * @description */ name: name, /** * @ngdoc method * @name angular.Module#provider * @methodOf angular.Module * @param {string} name service name * @param {Function} providerType Construction function for creating new instance of the * service. * @description * See {@link AUTO.$provide#provider $provide.provider()}. */ provider: invokeLater('$provide', 'provider'), /** * @ngdoc method * @name angular.Module#factory * @methodOf angular.Module * @param {string} name service name * @param {Function} providerFunction Function for creating new instance of the service. * @description * See {@link AUTO.$provide#factory $provide.factory()}. */ factory: invokeLater('$provide', 'factory'), /** * @ngdoc method * @name angular.Module#service * @methodOf angular.Module * @param {string} name service name * @param {Function} constructor A constructor function that will be instantiated. * @description * See {@link AUTO.$provide#service $provide.service()}. */ service: invokeLater('$provide', 'service'), /** * @ngdoc method * @name angular.Module#value * @methodOf angular.Module * @param {string} name service name * @param {*} object Service instance object. * @description * See {@link AUTO.$provide#value $provide.value()}. */ value: invokeLater('$provide', 'value'), /** * @ngdoc method * @name angular.Module#constant * @methodOf angular.Module * @param {string} name constant name * @param {*} object Constant value. * @description * Because the constant are fixed, they get applied before other provide methods. * See {@link AUTO.$provide#constant $provide.constant()}. */ constant: invokeLater('$provide', 'constant', 'unshift'), /** * @ngdoc method * @name angular.Module#animation * @methodOf angular.Module * @param {string} name animation name * @param {Function} animationFactory Factory function for creating new instance of an * animation. * @description * * **NOTE**: animations take effect only if the **ngAnimate** module is loaded. * * * Defines an animation hook that can be later used with * {@link ngAnimate.$animate $animate} service and directives that use this service. * * <pre> * module.animation('.animation-name', function($inject1, $inject2) { * return { * eventName : function(element, done) { * //code to run the animation * //once complete, then run done() * return function cancellationFunction(element) { * //code to cancel the animation * } * } * } * }) * </pre> * * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and * {@link ngAnimate ngAnimate module} for more information. */ animation: invokeLater('$animateProvider', 'register'), /** * @ngdoc method * @name angular.Module#filter * @methodOf angular.Module * @param {string} name Filter name. * @param {Function} filterFactory Factory function for creating new instance of filter. * @description * See {@link ng.$filterProvider#register $filterProvider.register()}. */ filter: invokeLater('$filterProvider', 'register'), /** * @ngdoc method * @name angular.Module#controller * @methodOf angular.Module * @param {string|Object} name Controller name, or an object map of controllers where the * keys are the names and the values are the constructors. * @param {Function} constructor Controller constructor function. * @description * See {@link ng.$controllerProvider#register $controllerProvider.register()}. */ controller: invokeLater('$controllerProvider', 'register'), /** * @ngdoc method * @name angular.Module#directive * @methodOf angular.Module * @param {string|Object} name Directive name, or an object map of directives where the * keys are the names and the values are the factories. * @param {Function} directiveFactory Factory function for creating new instance of * directives. * @description * See {@link ng.$compileProvider#methods_directive $compileProvider.directive()}. */ directive: invokeLater('$compileProvider', 'directive'), /** * @ngdoc method * @name angular.Module#config * @methodOf angular.Module * @param {Function} configFn Execute this function on module load. Useful for service * configuration. * @description * Use this method to register work which needs to be performed on module loading. */ config: config, /** * @ngdoc method * @name angular.Module#run * @methodOf angular.Module * @param {Function} initializationFn Execute this function after injector creation. * Useful for application initialization. * @description * Use this method to register work which should be performed when the injector is done * loading all modules. */ run: function(block) { runBlocks.push(block); return this; } }; if (configFn) { config(configFn); } return moduleInstance; /** * @param {string} provider * @param {string} method * @param {String=} insertMethod * @returns {angular.Module} */ function invokeLater(provider, method, insertMethod) { return function() { invokeQueue[insertMethod || 'push']([provider, method, arguments]); return moduleInstance; }; } }); }; }); } setupModuleLoader(window); })(window); /** * Closure compiler type information * * @typedef { { * requires: !Array.<string>, * invokeQueue: !Array.<Array.<*>>, * * service: function(string, Function):angular.Module, * factory: function(string, Function):angular.Module, * value: function(string, *):angular.Module, * * filter: function(string, Function):angular.Module, * * init: function(Function):angular.Module * } } */ angular.Module;
apache-2.0
cherryhill/playatyourlibrary
tests/behat/vendor/symfony/console/Symfony/Component/Console/Helper/TableSeparator.php
405
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Console\Helper; /** * Marks a row as being a separator. * * @author Fabien Potencier <fabien@symfony.com> */ class TableSeparator { }
gpl-2.0
tinganho/TypeScript
tests/cases/conformance/classes/indexMemberDeclarations/privateIndexer.ts
179
// private indexers not allowed class C { private [x: string]: string; } class D { private [x: number]: string; } class E<T> { private [x: string]: T; }
apache-2.0
notdol/mongodb_lecture
crud/node_modules/mongoose/node_modules/hooks/hooks.js
5385
// TODO Add in pre and post skipping options module.exports = { /** * Declares a new hook to which you can add pres and posts * @param {String} name of the function * @param {Function} the method * @param {Function} the error handler callback */ hook: function (name, fn, errorCb) { if (arguments.length === 1 && typeof name === 'object') { for (var k in name) { // `name` is a hash of hookName->hookFn this.hook(k, name[k]); } return; } var proto = this.prototype || this , pres = proto._pres = proto._pres || {} , posts = proto._posts = proto._posts || {}; pres[name] = pres[name] || []; posts[name] = posts[name] || []; proto[name] = function () { var self = this , hookArgs // arguments eventually passed to the hook - are mutable , lastArg = arguments[arguments.length-1] , pres = this._pres[name] , posts = this._posts[name] , _total = pres.length , _current = -1 , _asyncsLeft = proto[name].numAsyncPres , _next = function () { if (arguments[0] instanceof Error) { return handleError(arguments[0]); } var _args = Array.prototype.slice.call(arguments) , currPre , preArgs; if (_args.length && !(arguments[0] == null && typeof lastArg === 'function')) hookArgs = _args; if (++_current < _total) { currPre = pres[_current] if (currPre.isAsync && currPre.length < 2) throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)"); if (currPre.length < 1) throw new Error("Your pre must have a next argument -- e.g., function (next, ...)"); preArgs = (currPre.isAsync ? [once(_next), once(_asyncsDone)] : [once(_next)]).concat(hookArgs); return currPre.apply(self, preArgs); } else if (!proto[name].numAsyncPres) { return _done.apply(self, hookArgs); } } , _done = function () { var args_ = Array.prototype.slice.call(arguments) , ret, total_, current_, next_, done_, postArgs; if (_current === _total) { ret = fn.apply(self, args_); total_ = posts.length; current_ = -1; next_ = function () { if (arguments[0] instanceof Error) { return handleError(arguments[0]); } var args_ = Array.prototype.slice.call(arguments, 1) , currPost , postArgs; if (args_.length) hookArgs = args_; if (++current_ < total_) { currPost = posts[current_] if (currPost.length < 1) throw new Error("Your post must have a next argument -- e.g., function (next, ...)"); postArgs = [once(next_)].concat(hookArgs); return currPost.apply(self, postArgs); } }; if (total_) return next_(); return ret; } }; if (_asyncsLeft) { function _asyncsDone (err) { if (err && err instanceof Error) { return handleError(err); } --_asyncsLeft || _done.apply(self, hookArgs); } } function handleError (err) { if ('function' == typeof lastArg) return lastArg(err); if (errorCb) return errorCb.call(self, err); throw err; } return _next.apply(this, arguments); }; proto[name].numAsyncPres = 0; return this; }, pre: function (name, isAsync, fn, errorCb) { if ('boolean' !== typeof arguments[1]) { errorCb = fn; fn = isAsync; isAsync = false; } var proto = this.prototype || this , pres = proto._pres = proto._pres || {}; this._lazySetupHooks(proto, name, errorCb); if (fn.isAsync = isAsync) { proto[name].numAsyncPres++; } (pres[name] = pres[name] || []).push(fn); return this; }, post: function (name, isAsync, fn) { if (arguments.length === 2) { fn = isAsync; isAsync = false; } var proto = this.prototype || this , posts = proto._posts = proto._posts || {}; this._lazySetupHooks(proto, name); (posts[name] = posts[name] || []).push(fn); return this; }, removePre: function (name, fnToRemove) { var proto = this.prototype || this , pres = proto._pres || (proto._pres || {}); if (!pres[name]) return this; if (arguments.length === 1) { // Remove all pre callbacks for hook `name` pres[name].length = 0; } else { pres[name] = pres[name].filter( function (currFn) { return currFn !== fnToRemove; }); } return this; }, _lazySetupHooks: function (proto, methodName, errorCb) { if ('undefined' === typeof proto[methodName].numAsyncPres) { this.hook(methodName, proto[methodName], errorCb); } } }; function once (fn, scope) { return function fnWrapper () { if (fnWrapper.hookCalled) return; fnWrapper.hookCalled = true; fn.apply(scope, arguments); }; }
mit
emelleme/PhillyOpen
sapphire/thirdparty/tinymce/themes/simple/langs/pl.js
384
tinyMCE.addI18n('pl.simple',{ bold_desc:"Pogrubienie (Ctrl+B)", italic_desc:"Kursywa (Ctrl+I)", underline_desc:"Podkre\u015Blenie (Ctrl+U)", striketrough_desc:"Przekre\u015Blenie", bullist_desc:"Lista nienumerowana", numlist_desc:"Lista numerowana", undo_desc:"Cofnij (Ctrl+Z)", redo_desc:"Pon\u00F3w (Ctrl+Y)", cleanup_desc:"Wyczy\u015B\u0107 nieuporz\u0105dkowany kod" });
bsd-3-clause
AdoHe/libnetwork
Godeps/_workspace/src/github.com/docker/docker/pkg/term/term_windows.go
6069
// +build windows package term import ( "fmt" "io" "os" "os/signal" "github.com/Azure/go-ansiterm/winterm" "github.com/Sirupsen/logrus" "github.com/docker/docker/pkg/term/windows" ) // State holds the console mode for the terminal. type State struct { mode uint32 } // Winsize is used for window size. type Winsize struct { Height uint16 Width uint16 x uint16 y uint16 } // StdStreams returns the standard streams (stdin, stdout, stedrr). func StdStreams() (stdIn io.ReadCloser, stdOut, stdErr io.Writer) { switch { case os.Getenv("ConEmuANSI") == "ON": // The ConEmu shell emulates ANSI well by default. return os.Stdin, os.Stdout, os.Stderr case os.Getenv("MSYSTEM") != "": // MSYS (mingw) does not emulate ANSI well. return windows.ConsoleStreams() default: return windows.ConsoleStreams() } } // GetFdInfo returns the file descriptor for an os.File and indicates whether the file represents a terminal. func GetFdInfo(in interface{}) (uintptr, bool) { return windows.GetHandleInfo(in) } // GetWinsize returns the window size based on the specified file descriptor. func GetWinsize(fd uintptr) (*Winsize, error) { info, err := winterm.GetConsoleScreenBufferInfo(fd) if err != nil { return nil, err } winsize := &Winsize{ Width: uint16(info.Window.Right - info.Window.Left + 1), Height: uint16(info.Window.Bottom - info.Window.Top + 1), x: 0, y: 0} // Note: GetWinsize is called frequently -- uncomment only for excessive details // logrus.Debugf("[windows] GetWinsize: Console(%v)", info.String()) // logrus.Debugf("[windows] GetWinsize: Width(%v), Height(%v), x(%v), y(%v)", winsize.Width, winsize.Height, winsize.x, winsize.y) return winsize, nil } // SetWinsize tries to set the specified window size for the specified file descriptor. func SetWinsize(fd uintptr, ws *Winsize) error { // Ensure the requested dimensions are no larger than the maximum window size info, err := winterm.GetConsoleScreenBufferInfo(fd) if err != nil { return err } if ws.Width == 0 || ws.Height == 0 || ws.Width > uint16(info.MaximumWindowSize.X) || ws.Height > uint16(info.MaximumWindowSize.Y) { return fmt.Errorf("Illegal window size: (%v,%v) -- Maximum allow: (%v,%v)", ws.Width, ws.Height, info.MaximumWindowSize.X, info.MaximumWindowSize.Y) } // Narrow the sizes to that used by Windows width := winterm.SHORT(ws.Width) height := winterm.SHORT(ws.Height) // Set the dimensions while ensuring they remain within the bounds of the backing console buffer // -- Shrinking will always succeed. Growing may push the edges past the buffer boundary. When that occurs, // shift the upper left just enough to keep the new window within the buffer. rect := info.Window if width < rect.Right-rect.Left+1 { rect.Right = rect.Left + width - 1 } else if width > rect.Right-rect.Left+1 { rect.Right = rect.Left + width - 1 if rect.Right >= info.Size.X { rect.Left = info.Size.X - width rect.Right = info.Size.X - 1 } } if height < rect.Bottom-rect.Top+1 { rect.Bottom = rect.Top + height - 1 } else if height > rect.Bottom-rect.Top+1 { rect.Bottom = rect.Top + height - 1 if rect.Bottom >= info.Size.Y { rect.Top = info.Size.Y - height rect.Bottom = info.Size.Y - 1 } } logrus.Debugf("[windows] SetWinsize: Requested((%v,%v)) Actual(%v)", ws.Width, ws.Height, rect) return winterm.SetConsoleWindowInfo(fd, true, rect) } // IsTerminal returns true if the given file descriptor is a terminal. func IsTerminal(fd uintptr) bool { return windows.IsConsole(fd) } // RestoreTerminal restores the terminal connected to the given file descriptor // to a previous state. func RestoreTerminal(fd uintptr, state *State) error { return winterm.SetConsoleMode(fd, state.mode) } // SaveState saves the state of the terminal connected to the given file descriptor. func SaveState(fd uintptr) (*State, error) { mode, e := winterm.GetConsoleMode(fd) if e != nil { return nil, e } return &State{mode}, nil } // DisableEcho disables echo for the terminal connected to the given file descriptor. // -- See https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx func DisableEcho(fd uintptr, state *State) error { mode := state.mode mode &^= winterm.ENABLE_ECHO_INPUT mode |= winterm.ENABLE_PROCESSED_INPUT | winterm.ENABLE_LINE_INPUT err := winterm.SetConsoleMode(fd, mode) if err != nil { return err } // Register an interrupt handler to catch and restore prior state restoreAtInterrupt(fd, state) return nil } // SetRawTerminal puts the terminal connected to the given file descriptor into raw // mode and returns the previous state. func SetRawTerminal(fd uintptr) (*State, error) { state, err := MakeRaw(fd) if err != nil { return nil, err } // Register an interrupt handler to catch and restore prior state restoreAtInterrupt(fd, state) return state, err } // MakeRaw puts the terminal (Windows Console) connected to the given file descriptor into raw // mode and returns the previous state of the terminal so that it can be restored. func MakeRaw(fd uintptr) (*State, error) { state, err := SaveState(fd) if err != nil { return nil, err } // See // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms686033(v=vs.85).aspx // -- https://msdn.microsoft.com/en-us/library/windows/desktop/ms683462(v=vs.85).aspx mode := state.mode // Disable these modes mode &^= winterm.ENABLE_ECHO_INPUT mode &^= winterm.ENABLE_LINE_INPUT mode &^= winterm.ENABLE_MOUSE_INPUT mode &^= winterm.ENABLE_WINDOW_INPUT mode &^= winterm.ENABLE_PROCESSED_INPUT // Enable these modes mode |= winterm.ENABLE_EXTENDED_FLAGS mode |= winterm.ENABLE_INSERT_MODE mode |= winterm.ENABLE_QUICK_EDIT_MODE err = winterm.SetConsoleMode(fd, mode) if err != nil { return nil, err } return state, nil } func restoreAtInterrupt(fd uintptr, state *State) { sigchan := make(chan os.Signal, 1) signal.Notify(sigchan, os.Interrupt) go func() { _ = <-sigchan RestoreTerminal(fd, state) os.Exit(0) }() }
apache-2.0
stripe/smokescreen
vendor/golang.org/x/sys/unix/syscall_darwin.1_12.go
846
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // +build darwin,go1.12,!go1.13 package unix import ( "unsafe" ) const _SYS_GETDIRENTRIES64 = 344 func Getdirentries(fd int, buf []byte, basep *uintptr) (n int, err error) { // To implement this using libSystem we'd need syscall_syscallPtr for // fdopendir. However, syscallPtr was only added in Go 1.13, so we fall // back to raw syscalls for this func on Go 1.12. var p unsafe.Pointer if len(buf) > 0 { p = unsafe.Pointer(&buf[0]) } else { p = unsafe.Pointer(&_zero) } r0, _, e1 := Syscall6(_SYS_GETDIRENTRIES64, uintptr(fd), uintptr(p), uintptr(len(buf)), uintptr(unsafe.Pointer(basep)), 0, 0) n = int(r0) if e1 != 0 { return n, errnoErr(e1) } return n, nil }
mit
anhredweb/togtejendomme.dk
libraries/joomla/base/observer.php
1218
<?php /** * @package Joomla.Platform * @subpackage Base * * @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE */ defined('JPATH_PLATFORM') or die; /** * Abstract observer class to implement the observer design pattern * * @package Joomla.Platform * @subpackage Base * @since 11.1 * @deprecated 12.3 * @codeCoverageIgnore */ abstract class JObserver extends JObject { /** * Event object to observe. * * @var object * @since 11.1 * @deprecated 12.3 */ protected $_subject = null; /** * Constructor * * @param object &$subject The object to observe. * * @since 11.1 * @deprecated 12.3 */ public function __construct(&$subject) { // Register the observer ($this) so we can be notified $subject->attach($this); // Set the subject to observe $this->_subject = &$subject; } /** * Method to update the state of observable objects * * @param array &$args An array of arguments to pass to the listener. * * @return mixed * * @since 11.1 * @deprecated 12.3 */ public abstract function update(&$args); }
gpl-2.0
davidni/Windows-universal-samples
Samples/Notifications/cs/Notifications/ScenarioPages/Badges/Local/PrimaryTile/SetBadgeGlyph/ScenarioElement.xaml.cs
1514
using Windows.Data.Xml.Dom; using Windows.UI.Notifications; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace Notifications.ScenarioPages.Badges.Local.PrimaryTile.SetBadgeGlyph { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class ScenarioElement : UserControl { public ScenarioElement() { this.InitializeComponent(); } private void ButtonUpdateBadgeGlyph_Click(object sender, RoutedEventArgs e) { string badgeGlyphValue = ComboBoxBadgeGlyph.SelectedItem as string; // Get the blank badge XML payload for a badge glyph XmlDocument badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeGlyph); // Set the value of the badge in the XML to our glyph value XmlElement badgeElement = badgeXml.SelectSingleNode("/badge") as XmlElement; badgeElement.SetAttribute("value", badgeGlyphValue); // Create the badge notification BadgeNotification badge = new BadgeNotification(badgeXml); // Create the badge updater for the application BadgeUpdater badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication(); // And update the badge badgeUpdater.Update(badge); } } }
mit
HENM1415/henm1415g2
NodeJS/node_modules/mongoose/lib/utils.js
15080
/*! * Module dependencies. */ var ReadPref = require('mongodb').ReadPreference , ObjectId = require('./types/objectid') , cloneRegExp = require('regexp-clone') , sliced = require('sliced') , mpath = require('mpath') , ms = require('ms') , MongooseBuffer , MongooseArray , Document /*! * Produces a collection name from model `name`. * * @param {String} name a model name * @return {String} a collection name * @api private */ exports.toCollectionName = function (name, options) { options = options || {}; if ('system.profile' === name) return name; if ('system.indexes' === name) return name; if (options.pluralization === false) return name; return pluralize(name.toLowerCase()); }; /** * Pluralization rules. * * These rules are applied while processing the argument to `toCollectionName`. * * @deprecated remove in 4.x gh-1350 */ exports.pluralization = [ [/(m)an$/gi, '$1en'], [/(pe)rson$/gi, '$1ople'], [/(child)$/gi, '$1ren'], [/^(ox)$/gi, '$1en'], [/(ax|test)is$/gi, '$1es'], [/(octop|vir)us$/gi, '$1i'], [/(alias|status)$/gi, '$1es'], [/(bu)s$/gi, '$1ses'], [/(buffal|tomat|potat)o$/gi, '$1oes'], [/([ti])um$/gi, '$1a'], [/sis$/gi, 'ses'], [/(?:([^f])fe|([lr])f)$/gi, '$1$2ves'], [/(hive)$/gi, '$1s'], [/([^aeiouy]|qu)y$/gi, '$1ies'], [/(x|ch|ss|sh)$/gi, '$1es'], [/(matr|vert|ind)ix|ex$/gi, '$1ices'], [/([m|l])ouse$/gi, '$1ice'], [/(quiz)$/gi, '$1zes'], [/s$/gi, 's'], [/([^a-z])$/, '$1'], [/$/gi, 's'] ]; var rules = exports.pluralization; /** * Uncountable words. * * These words are applied while processing the argument to `toCollectionName`. * @api public */ exports.uncountables = [ 'advice', 'energy', 'excretion', 'digestion', 'cooperation', 'health', 'justice', 'labour', 'machinery', 'equipment', 'information', 'pollution', 'sewage', 'paper', 'money', 'species', 'series', 'rain', 'rice', 'fish', 'sheep', 'moose', 'deer', 'news', 'expertise', 'status', 'media' ]; var uncountables = exports.uncountables; /*! * Pluralize function. * * @author TJ Holowaychuk (extracted from _ext.js_) * @param {String} string to pluralize * @api private */ function pluralize (str) { var rule, found; if (!~uncountables.indexOf(str.toLowerCase())){ found = rules.filter(function(rule){ return str.match(rule[0]); }); if (found[0]) return str.replace(found[0][0], found[0][1]); } return str; }; /*! * Determines if `a` and `b` are deep equal. * * Modified from node/lib/assert.js * * @param {any} a a value to compare to `b` * @param {any} b a value to compare to `a` * @return {Boolean} * @api private */ exports.deepEqual = function deepEqual (a, b) { if (a === b) return true; if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime(); if (a instanceof ObjectId && b instanceof ObjectId) { return a.toString() === b.toString(); } if (a instanceof RegExp && b instanceof RegExp) { return a.source == b.source && a.ignoreCase == b.ignoreCase && a.multiline == b.multiline && a.global == b.global; } if (typeof a !== 'object' && typeof b !== 'object') return a == b; if (a === null || b === null || a === undefined || b === undefined) return false if (a.prototype !== b.prototype) return false; // Handle MongooseNumbers if (a instanceof Number && b instanceof Number) { return a.valueOf() === b.valueOf(); } if (Buffer.isBuffer(a)) { return exports.buffer.areEqual(a, b); } if (isMongooseObject(a)) a = a.toObject(); if (isMongooseObject(b)) b = b.toObject(); try { var ka = Object.keys(a), kb = Object.keys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!deepEqual(a[key], b[key])) return false; } return true; }; /*! * Object clone with Mongoose natives support. * * If options.minimize is true, creates a minimal data object. Empty objects and undefined values will not be cloned. This makes the data payload sent to MongoDB as small as possible. * * Functions are never cloned. * * @param {Object} obj the object to clone * @param {Object} options * @return {Object} the cloned object * @api private */ exports.clone = function clone (obj, options) { if (obj === undefined || obj === null) return obj; if (Array.isArray(obj)) return cloneArray(obj, options); if (isMongooseObject(obj)) { if (options && options.json && 'function' === typeof obj.toJSON) { return obj.toJSON(options); } else { return obj.toObject(options); } } if (obj.constructor) { switch (obj.constructor.name) { case 'Object': return cloneObject(obj, options); case 'Date': return new obj.constructor(+obj); case 'RegExp': return cloneRegExp(obj); default: // ignore break; } } if (obj instanceof ObjectId) return new ObjectId(obj.id); if (!obj.constructor && exports.isObject(obj)) { // object created with Object.create(null) return cloneObject(obj, options); } if (obj.valueOf) return obj.valueOf(); }; var clone = exports.clone; /*! * ignore */ function cloneObject (obj, options) { var retainKeyOrder = options && options.retainKeyOrder , minimize = options && options.minimize , ret = {} , hasKeys , keys , val , k , i if (retainKeyOrder) { for (k in obj) { val = clone(obj[k], options); if (!minimize || ('undefined' !== typeof val)) { hasKeys || (hasKeys = true); ret[k] = val; } } } else { // faster keys = Object.keys(obj); i = keys.length; while (i--) { k = keys[i]; val = clone(obj[k], options); if (!minimize || ('undefined' !== typeof val)) { if (!hasKeys) hasKeys = true; ret[k] = val; } } } return minimize ? hasKeys && ret : ret; }; function cloneArray (arr, options) { var ret = []; for (var i = 0, l = arr.length; i < l; i++) ret.push(clone(arr[i], options)); return ret; }; /*! * Shallow copies defaults into options. * * @param {Object} defaults * @param {Object} options * @return {Object} the merged object * @api private */ exports.options = function (defaults, options) { var keys = Object.keys(defaults) , i = keys.length , k ; options = options || {}; while (i--) { k = keys[i]; if (!(k in options)) { options[k] = defaults[k]; } } return options; }; /*! * Generates a random string * * @api private */ exports.random = function () { return Math.random().toString().substr(3); }; /*! * Merges `from` into `to` without overwriting existing properties. * * @param {Object} to * @param {Object} from * @api private */ exports.merge = function merge (to, from) { var keys = Object.keys(from) , i = keys.length , key; while (i--) { key = keys[i]; if ('undefined' === typeof to[key]) { to[key] = from[key]; } else if (exports.isObject(from[key])) { merge(to[key], from[key]); } } }; /*! * toString helper */ var toString = Object.prototype.toString; /*! * Determines if `arg` is an object. * * @param {Object|Array|String|Function|RegExp|any} arg * @api private * @return {Boolean} */ exports.isObject = function (arg) { return '[object Object]' == toString.call(arg); } /*! * A faster Array.prototype.slice.call(arguments) alternative * @api private */ exports.args = sliced; /*! * process.nextTick helper. * * Wraps `callback` in a try/catch + nextTick. * * node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback. * * @param {Function} callback * @api private */ exports.tick = function tick (callback) { if ('function' !== typeof callback) return; return function () { try { callback.apply(this, arguments); } catch (err) { // only nextTick on err to get out of // the event loop and avoid state corruption. process.nextTick(function () { throw err; }); } } } /*! * Returns if `v` is a mongoose object that has a `toObject()` method we can use. * * This is for compatibility with libs like Date.js which do foolish things to Natives. * * @param {any} v * @api private */ exports.isMongooseObject = function (v) { Document || (Document = require('./document')); MongooseArray || (MongooseArray = require('./types').Array); MongooseBuffer || (MongooseBuffer = require('./types').Buffer); return v instanceof Document || v instanceof MongooseArray || v instanceof MongooseBuffer } var isMongooseObject = exports.isMongooseObject; /*! * Converts `expires` options of index objects to `expiresAfterSeconds` options for MongoDB. * * @param {Object} object * @api private */ exports.expires = function expires (object) { if (!(object && 'Object' == object.constructor.name)) return; if (!('expires' in object)) return; var when; if ('string' != typeof object.expires) { when = object.expires; } else { when = Math.round(ms(object.expires) / 1000); } object.expireAfterSeconds = when; delete object.expires; } /*! * Converts arguments to ReadPrefs the driver * can understand. * * @TODO move this into the driver layer * @param {String|Array} pref * @param {Array} [tags] */ exports.readPref = function readPref (pref, tags) { if (Array.isArray(pref)) { tags = pref[1]; pref = pref[0]; } switch (pref) { case 'p': pref = 'primary'; break; case 'pp': pref = 'primaryPreferred'; break; case 's': pref = 'secondary'; break; case 'sp': pref = 'secondaryPreferred'; break; case 'n': pref = 'nearest'; break; } return new ReadPref(pref, tags); } /*! * Populate options constructor */ function PopulateOptions (path, select, match, options, model) { this.path = path; this.match = match; this.select = select; this.options = options; this.model = model; this._docs = {}; } // make it compatible with utils.clone PopulateOptions.prototype.constructor = Object; // expose exports.PopulateOptions = PopulateOptions; /*! * populate helper */ exports.populate = function populate (path, select, model, match, options) { // The order of select/conditions args is opposite Model.find but // necessary to keep backward compatibility (select could be // an array, string, or object literal). // might have passed an object specifying all arguments if (1 === arguments.length) { if (path instanceof PopulateOptions) { return [path]; } if (Array.isArray(path)) { return path.map(function(o){ return exports.populate(o)[0]; }); } if (exports.isObject(path)) { match = path.match; options = path.options; select = path.select; model = path.model; path = path.path; } } else if ('string' !== typeof model) { options = match; match = model; model = undefined; } if ('string' != typeof path) { throw new TypeError('utils.populate: invalid path. Expected string. Got typeof `' + typeof path + '`'); } var ret = []; var paths = path.split(' '); for (var i = 0; i < paths.length; ++i) { ret.push(new PopulateOptions(paths[i], select, match, options, model)); } return ret; } /*! * Return the value of `obj` at the given `path`. * * @param {String} path * @param {Object} obj */ exports.getValue = function (path, obj, map) { return mpath.get(path, obj, '_doc', map); } /*! * Sets the value of `obj` at the given `path`. * * @param {String} path * @param {Anything} val * @param {Object} obj */ exports.setValue = function (path, val, obj, map) { mpath.set(path, val, obj, '_doc', map); } /*! * Returns an array of values from object `o`. * * @param {Object} o * @return {Array} * @private */ exports.object = {}; exports.object.vals = function vals (o) { var keys = Object.keys(o) , i = keys.length , ret = []; while (i--) { ret.push(o[keys[i]]); } return ret; } /*! * @see exports.options */ exports.object.shallowCopy = exports.options; /*! * Safer helper for hasOwnProperty checks * * @param {Object} obj * @param {String} prop */ var hop = Object.prototype.hasOwnProperty; exports.object.hasOwnProperty = function (obj, prop) { return hop.call(obj, prop); } /*! * Determine if `val` is null or undefined * * @return {Boolean} */ exports.isNullOrUndefined = function (val) { return null == val } /*! * ignore */ exports.array = {}; /*! * Flattens an array. * * [ 1, [ 2, 3, [4] ]] -> [1,2,3,4] * * @param {Array} arr * @param {Function} [filter] If passed, will be invoked with each item in the array. If `filter` returns a falsey value, the item will not be included in the results. * @return {Array} * @private */ exports.array.flatten = function flatten (arr, filter, ret) { ret || (ret = []); arr.forEach(function (item) { if (Array.isArray(item)) { flatten(item, filter, ret); } else { if (!filter || filter(item)) { ret.push(item); } } }); return ret; } /*! * Determines if two buffers are equal. * * @param {Buffer} a * @param {Object} b */ exports.buffer = {}; exports.buffer.areEqual = function (a, b) { if (!Buffer.isBuffer(a)) return false; if (!Buffer.isBuffer(b)) return false; if (a.length !== b.length) return false; for (var i = 0, len = a.length; i < len; ++i) { if (a[i] !== b[i]) return false; } return true; } /** * merges to with a copy of from * * @param {Object} to * @param {Object} from * @api private */ exports.mergeClone = function(to, from) { var keys = Object.keys(from) , i = keys.length , key while (i--) { key = keys[i]; if ('undefined' === typeof to[key]) { // make sure to retain key order here because of a bug handling the $each // operator in mongodb 2.4.4 to[key] = exports.clone(from[key], { retainKeyOrder : 1}); } else { if (exports.isObject(from[key])) { exports.mergeClone(to[key], from[key]); } else { // make sure to retain key order here because of a bug handling the // $each operator in mongodb 2.4.4 to[key] = exports.clone(from[key], { retainKeyOrder : 1}); } } } }
apache-2.0
jaybenzz/homebrew
Library/Formula/vault-cli.rb
598
require "formula" class VaultCli < Formula homepage "http://jackrabbit.apache.org/filevault/index.html" url "http://search.maven.org/remotecontent?filepath=org/apache/jackrabbit/vault/vault-cli/3.1.6/vault-cli-3.1.6-bin.tar.gz" sha1 "3dd2c596ce8936c983e95b6cc868885f51b02992" def install # Remove windows files rm_f Dir["bin/*.bat"] prefix.install_metafiles libexec.install Dir['*'] bin.install_symlink Dir["#{libexec}/bin/*"] end test do # Bad test, but we're limited without a Jackrabbit repo to speak to... system "#{bin}/vlt", '--version' end end
bsd-2-clause
jspahrsummers/homebrew
Library/Formula/libhid.rb
1787
require "formula" class Libhid < Formula homepage "http://libhid.alioth.debian.org/" url "http://distcache.freebsd.org/ports-distfiles/libhid-0.2.16.tar.gz" sha1 "9a25fef674e8f20f97fea6700eb91c21ebbbcc02" bottle do cellar :any revision 1 sha1 "906bbdb53b10becc5fa7662513ac7ee98bef5b24" => :yosemite sha1 "fcd7fdf048247a5ecb01abbd56f7c03e330c62ca" => :mavericks end depends_on "libusb" depends_on "libusb-compat" # Fix compilation error on 10.9 patch :DATA def install system "./configure", "--disable-debug", "--disable-dependency-tracking", "--prefix=#{prefix}", "--disable-swig" system "make install" end end __END__ --- libhid-0.2.16/src/Makefile.am.org 2014-01-02 19:20:33.000000000 +0200 +++ libhid-0.2.16/src/Makefile.am 2014-01-02 19:21:15.000000000 +0200 @@ -17,7 +17,7 @@ else if OS_DARWIN OS_SUPPORT_SOURCE = darwin.c AM_CFLAGS += -no-cpp-precomp -AM_LDFLAGS += -lIOKit -framework "CoreFoundation" +AM_LDFLAGS += -framework IOKit -framework "CoreFoundation" else OS_SUPPORT = endif --- libhid-0.2.16/src/Makefile.in.org 2014-01-02 19:20:35.000000000 +0200 +++ libhid-0.2.16/src/Makefile.in 2014-01-02 19:21:24.000000000 +0200 @@ -39,7 +39,7 @@ POST_UNINSTALL = : build_triplet = @build@ host_triplet = @host@ @OS_BSD_FALSE@@OS_DARWIN_TRUE@@OS_LINUX_FALSE@@OS_SOLARIS_FALSE@am__append_1 = -no-cpp-precomp -@OS_BSD_FALSE@@OS_DARWIN_TRUE@@OS_LINUX_FALSE@@OS_SOLARIS_FALSE@am__append_2 = -lIOKit -framework "CoreFoundation" +@OS_BSD_FALSE@@OS_DARWIN_TRUE@@OS_LINUX_FALSE@@OS_SOLARIS_FALSE@am__append_2 = -framework IOKit -framework "CoreFoundation" bin_PROGRAMS = libhid-detach-device$(EXEEXT) subdir = src DIST_COMMON = $(include_HEADERS) $(srcdir)/Makefile.am \
bsd-2-clause
kaikiai/kimai
libraries/zendframework/zendframework1/library/Zend/Measure/Energy.php
14412
<?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 license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Measure * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id$ */ /** * Implement needed classes */ require_once 'Zend/Measure/Abstract.php'; require_once 'Zend/Locale.php'; /** * Class for handling energy conversions * * @category Zend * @package Zend_Measure * @subpackage Zend_Measure_Energy * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ class Zend_Measure_Energy extends Zend_Measure_Abstract { const STANDARD = 'JOULE'; const ATTOJOULE = 'ATTOJOULE'; const BOARD_OF_TRADE_UNIT = 'BOARD_OF_TRADE_UNIT'; const BTU = 'BTU'; const BTU_THERMOCHEMICAL = 'BTU_TERMOCHEMICAL'; const CALORIE = 'CALORIE'; const CALORIE_15C = 'CALORIE_15C'; const CALORIE_NUTRITIONAL = 'CALORIE_NUTRITIONAL'; const CALORIE_THERMOCHEMICAL = 'CALORIE_THERMOCHEMICAL'; const CELSIUS_HEAT_UNIT = 'CELSIUS_HEAT_UNIT'; const CENTIJOULE = 'CENTIJOULE'; const CHEVAL_VAPEUR_HEURE = 'CHEVAL_VAPEUR_HEURE'; const DECIJOULE = 'DECIJOULE'; const DEKAJOULE = 'DEKAJOULE'; const DEKAWATT_HOUR = 'DEKAWATT_HOUR'; const DEKATHERM = 'DEKATHERM'; const ELECTRONVOLT = 'ELECTRONVOLT'; const ERG = 'ERG'; const EXAJOULE = 'EXAJOULE'; const EXAWATT_HOUR = 'EXAWATT_HOUR'; const FEMTOJOULE = 'FEMTOJOULE'; const FOOT_POUND = 'FOOT_POUND'; const FOOT_POUNDAL = 'FOOT_POUNDAL'; const GALLON_UK_AUTOMOTIVE = 'GALLON_UK_AUTOMOTIVE'; const GALLON_US_AUTOMOTIVE = 'GALLON_US_AUTOMOTIVE'; const GALLON_UK_AVIATION = 'GALLON_UK_AVIATION'; const GALLON_US_AVIATION = 'GALLON_US_AVIATION'; const GALLON_UK_DIESEL = 'GALLON_UK_DIESEL'; const GALLON_US_DIESEL = 'GALLON_US_DIESEL'; const GALLON_UK_DISTILATE = 'GALLON_UK_DISTILATE'; const GALLON_US_DISTILATE = 'GALLON_US_DISTILATE'; const GALLON_UK_KEROSINE_JET = 'GALLON_UK_KEROSINE_JET'; const GALLON_US_KEROSINE_JET = 'GALLON_US_KEROSINE_JET'; const GALLON_UK_LPG = 'GALLON_UK_LPG'; const GALLON_US_LPG = 'GALLON_US_LPG'; const GALLON_UK_NAPHTA = 'GALLON_UK_NAPHTA'; const GALLON_US_NAPHTA = 'GALLON_US_NAPHTA'; const GALLON_UK_KEROSENE = 'GALLON_UK_KEROSINE'; const GALLON_US_KEROSENE = 'GALLON_US_KEROSINE'; const GALLON_UK_RESIDUAL = 'GALLON_UK_RESIDUAL'; const GALLON_US_RESIDUAL = 'GALLON_US_RESIDUAL'; const GIGAELECTRONVOLT = 'GIGAELECTRONVOLT'; const GIGACALORIE = 'GIGACALORIE'; const GIGACALORIE_15C = 'GIGACALORIE_15C'; const GIGAJOULE = 'GIGAJOULE'; const GIGAWATT_HOUR = 'GIGAWATT_HOUR'; const GRAM_CALORIE = 'GRAM_CALORIE'; const HARTREE = 'HARTREE'; const HECTOJOULE = 'HECTOJOULE'; const HECTOWATT_HOUR = 'HECTOWATT_HOUR'; const HORSEPOWER_HOUR = 'HORSEPOWER_HOUR'; const HUNDRED_CUBIC_FOOT_GAS = 'HUNDRED_CUBIC_FOOT_GAS'; const INCH_OUNCE = 'INCH_OUNCE'; const INCH_POUND = 'INCH_POUND'; const JOULE = 'JOULE'; const KILOCALORIE_15C = 'KILOCALORIE_15C'; const KILOCALORIE = 'KILOCALORIE'; const KILOCALORIE_THERMOCHEMICAL = 'KILOCALORIE_THERMOCHEMICAL'; const KILOELECTRONVOLT = 'KILOELECTRONVOLT'; const KILOGRAM_CALORIE = 'KILOGRAM_CALORIE'; const KILOGRAM_FORCE_METER = 'KILOGRAM_FORCE_METER'; const KILOJOULE = 'KILOJOULE'; const KILOPOND_METER = 'KILOPOND_METER'; const KILOTON = 'KILOTON'; const KILOWATT_HOUR = 'KILOWATT_HOUR'; const LITER_ATMOSPHERE = 'LITER_ATMOSPHERE'; const MEGAELECTRONVOLT = 'MEGAELECTRONVOLT'; const MEGACALORIE = 'MEGACALORIE'; const MEGACALORIE_15C = 'MEGACALORIE_15C'; const MEGAJOULE = 'MEGAJOULE'; const MEGALERG = 'MEGALERG'; const MEGATON = 'MEGATON'; const MEGAWATTHOUR = 'MEGAWATTHOUR'; const METER_KILOGRAM_FORCE = 'METER_KILOGRAM_FORCE'; const MICROJOULE = 'MICROJOULE'; const MILLIJOULE = 'MILLIJOULE'; const MYRIAWATT_HOUR = 'MYRIAWATT_HOUR'; const NANOJOULE = 'NANOJOULE'; const NEWTON_METER = 'NEWTON_METER'; const PETAJOULE = 'PETAJOULE'; const PETAWATTHOUR = 'PETAWATTHOUR'; const PFERDESTAERKENSTUNDE = 'PFERDESTAERKENSTUNDE'; const PICOJOULE = 'PICOJOULE'; const Q_UNIT = 'Q_UNIT'; const QUAD = 'QUAD'; const TERAELECTRONVOLT = 'TERAELECTRONVOLT'; const TERAJOULE = 'TERAJOULE'; const TERAWATTHOUR = 'TERAWATTHOUR'; const THERM = 'THERM'; const THERM_US = 'THERM_US'; const THERMIE = 'THERMIE'; const TON = 'TON'; const TONNE_COAL = 'TONNE_COAL'; const TONNE_OIL = 'TONNE_OIL'; const WATTHOUR = 'WATTHOUR'; const WATTSECOND = 'WATTSECOND'; const YOCTOJOULE = 'YOCTOJOULE'; const YOTTAJOULE = 'YOTTAJOULE'; const YOTTAWATTHOUR = 'YOTTAWATTHOUR'; const ZEPTOJOULE = 'ZEPTOJOULE'; const ZETTAJOULE = 'ZETTAJOULE'; const ZETTAWATTHOUR = 'ZETTAWATTHOUR'; /** * Calculations for all energy units * * @var array */ protected $_units = array( 'ATTOJOULE' => array('1.0e-18', 'aJ'), 'BOARD_OF_TRADE_UNIT' => array('3600000', 'BOTU'), 'BTU' => array('1055.0559', 'Btu'), 'BTU_TERMOCHEMICAL' => array('1054.3503', 'Btu'), 'CALORIE' => array('4.1868', 'cal'), 'CALORIE_15C' => array('6.1858', 'cal'), 'CALORIE_NUTRITIONAL' => array('4186.8', 'cal'), 'CALORIE_THERMOCHEMICAL' => array('4.184', 'cal'), 'CELSIUS_HEAT_UNIT' => array('1899.1005', 'Chu'), 'CENTIJOULE' => array('0.01', 'cJ'), 'CHEVAL_VAPEUR_HEURE' => array('2647795.5', 'cv heure'), 'DECIJOULE' => array('0.1', 'dJ'), 'DEKAJOULE' => array('10', 'daJ'), 'DEKAWATT_HOUR' => array('36000', 'daWh'), 'DEKATHERM' => array('1.055057e+9', 'dathm'), 'ELECTRONVOLT' => array('1.6021773e-19', 'eV'), 'ERG' => array('0.0000001', 'erg'), 'EXAJOULE' => array('1.0e+18', 'EJ'), 'EXAWATT_HOUR' => array('3.6e+21', 'EWh'), 'FEMTOJOULE' => array('1.0e-15', 'fJ'), 'FOOT_POUND' => array('1.3558179', 'ft lb'), 'FOOT_POUNDAL' => array('0.04214011', 'ft poundal'), 'GALLON_UK_AUTOMOTIVE' => array('158237172', 'gal car gasoline'), 'GALLON_US_AUTOMOTIVE' => array('131760000', 'gal car gasoline'), 'GALLON_UK_AVIATION' => array('158237172', 'gal jet gasoline'), 'GALLON_US_AVIATION' => array('131760000', 'gal jet gasoline'), 'GALLON_UK_DIESEL' => array('175963194', 'gal diesel'), 'GALLON_US_DIESEL' => array('146520000', 'gal diesel'), 'GALLON_UK_DISTILATE' => array('175963194', 'gal destilate fuel'), 'GALLON_US_DISTILATE' => array('146520000', 'gal destilate fuel'), 'GALLON_UK_KEROSINE_JET' => array('170775090', 'gal jet kerosine'), 'GALLON_US_KEROSINE_JET' => array('142200000', 'gal jet kerosine'), 'GALLON_UK_LPG' => array('121005126.0865275', 'gal lpg'), 'GALLON_US_LPG' => array('100757838.45', 'gal lpg'), 'GALLON_UK_NAPHTA' => array('160831224', 'gal jet fuel'), 'GALLON_US_NAPHTA' => array('133920000', 'gal jet fuel'), 'GALLON_UK_KEROSINE' => array('170775090', 'gal kerosine'), 'GALLON_US_KEROSINE' => array('142200000', 'gal kerosine'), 'GALLON_UK_RESIDUAL' => array('189798138', 'gal residual fuel'), 'GALLON_US_RESIDUAL' => array('158040000', 'gal residual fuel'), 'GIGAELECTRONVOLT' => array('1.6021773e-10', 'GeV'), 'GIGACALORIE' => array('4186800000', 'Gcal'), 'GIGACALORIE_15C' => array('4185800000', 'Gcal'), 'GIGAJOULE' => array('1.0e+9', 'GJ'), 'GIGAWATT_HOUR' => array('3.6e+12', 'GWh'), 'GRAM_CALORIE' => array('4.1858', 'g cal'), 'HARTREE' => array('4.3597482e-18', 'Eh'), 'HECTOJOULE' => array('100', 'hJ'), 'HECTOWATT_HOUR' => array('360000', 'hWh'), 'HORSEPOWER_HOUR' => array('2684519.5', 'hph'), 'HUNDRED_CUBIC_FOOT_GAS' => array('108720000', 'hundred ft� gas'), 'INCH_OUNCE' => array('0.0070615518', 'in oc'), 'INCH_POUND' => array('0.112984825', 'in lb'), 'JOULE' => array('1', 'J'), 'KILOCALORIE_15C' => array('4185.8', 'kcal'), 'KILOCALORIE' => array('4186','8', 'kcal'), 'KILOCALORIE_THERMOCHEMICAL' => array('4184', 'kcal'), 'KILOELECTRONVOLT' => array('1.6021773e-16', 'keV'), 'KILOGRAM_CALORIE' => array('4185.8', 'kg cal'), 'KILOGRAM_FORCE_METER' => array('9.80665', 'kgf m'), 'KILOJOULE' => array('1000', 'kJ'), 'KILOPOND_METER' => array('9.80665', 'kp m'), 'KILOTON' => array('4.184e+12', 'kt'), 'KILOWATT_HOUR' => array('3600000', 'kWh'), 'LITER_ATMOSPHERE' => array('101.325', 'l atm'), 'MEGAELECTRONVOLT' => array('1.6021773e-13', 'MeV'), 'MEGACALORIE' => array('4186800', 'Mcal'), 'MEGACALORIE_15C' => array('4185800', 'Mcal'), 'MEGAJOULE' => array('1000000', 'MJ'), 'MEGALERG' => array('0.1', 'megalerg'), 'MEGATON' => array('4.184e+15', 'Mt'), 'MEGAWATTHOUR' => array('3.6e+9', 'MWh'), 'METER_KILOGRAM_FORCE' => array('9.80665', 'm kgf'), 'MICROJOULE' => array('0.000001', '�J'), 'MILLIJOULE' => array('0.001', 'mJ'), 'MYRIAWATT_HOUR' => array('3.6e+7', 'myWh'), 'NANOJOULE' => array('1.0e-9', 'nJ'), 'NEWTON_METER' => array('1', 'Nm'), 'PETAJOULE' => array('1.0e+15', 'PJ'), 'PETAWATTHOUR' => array('3.6e+18', 'PWh'), 'PFERDESTAERKENSTUNDE' => array('2647795.5', 'ps h'), 'PICOJOULE' => array('1.0e-12', 'pJ'), 'Q_UNIT' => array('1.0550559e+21', 'Q unit'), 'QUAD' => array('1.0550559e+18', 'quad'), 'TERAELECTRONVOLT' => array('1.6021773e-7', 'TeV'), 'TERAJOULE' => array('1.0e+12', 'TJ'), 'TERAWATTHOUR' => array('3.6e+15', 'TWh'), 'THERM' => array('1.0550559e+8', 'thm'), 'THERM_US' => array('1.054804e+8', 'thm'), 'THERMIE' => array('4185800', 'th'), 'TON' => array('4.184e+9', 'T explosive'), 'TONNE_COAL' => array('2.93076e+10', 'T coal'), 'TONNE_OIL' => array('4.1868e+10', 'T oil'), 'WATTHOUR' => array('3600', 'Wh'), 'WATTSECOND' => array('1', 'Ws'), 'YOCTOJOULE' => array('1.0e-24', 'yJ'), 'YOTTAJOULE' => array('1.0e+24', 'YJ'), 'YOTTAWATTHOUR' => array('3.6e+27', 'YWh'), 'ZEPTOJOULE' => array('1.0e-21', 'zJ'), 'ZETTAJOULE' => array('1.0e+21', 'ZJ'), 'ZETTAWATTHOUR' => array('3.6e+24', 'ZWh'), 'STANDARD' => 'JOULE' ); }
gpl-3.0
chipironcin/opencart
upload/catalog/controller/payment/paypoint.php
7189
<?php class ControllerPaymentPaypoint extends Controller { public function index() { $data['button_confirm'] = $this->language->get('button_confirm'); $this->load->model('checkout/order'); $order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']); $data['merchant'] = $this->config->get('paypoint_merchant'); $data['trans_id'] = $this->session->data['order_id']; $data['amount'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false); if ($this->config->get('paypoint_password')) { $data['digest'] = md5($this->session->data['order_id'] . $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false) . $this->config->get('paypoint_password')); } else { $data['digest'] = ''; } $data['bill_name'] = $order_info['payment_firstname'] . ' ' . $order_info['payment_lastname']; $data['bill_addr_1'] = $order_info['payment_address_1']; $data['bill_addr_2'] = $order_info['payment_address_2']; $data['bill_city'] = $order_info['payment_city']; $data['bill_state'] = $order_info['payment_zone']; $data['bill_post_code'] = $order_info['payment_postcode']; $data['bill_country'] = $order_info['payment_country']; $data['bill_tel'] = $order_info['telephone']; $data['bill_email'] = $order_info['email']; if ($this->cart->hasShipping()) { $data['ship_name'] = $order_info['shipping_firstname'] . ' ' . $order_info['shipping_lastname']; $data['ship_addr_1'] = $order_info['shipping_address_1']; $data['ship_addr_2'] = $order_info['shipping_address_2']; $data['ship_city'] = $order_info['shipping_city']; $data['ship_state'] = $order_info['shipping_zone']; $data['ship_post_code'] = $order_info['shipping_postcode']; $data['ship_country'] = $order_info['shipping_country']; } else { $data['ship_name'] = ''; $data['ship_addr_1'] = ''; $data['ship_addr_2'] = ''; $data['ship_city'] = ''; $data['ship_state'] = ''; $data['ship_post_code'] = ''; $data['ship_country'] = ''; } $data['currency'] = $this->currency->getCode(); $data['callback'] = $this->url->link('payment/paypoint/callback', '', 'SSL'); switch ($this->config->get('paypoint_test')) { case 'live': $status = 'live'; break; case 'successful': default: $status = 'true'; break; case 'fail': $status = 'false'; break; } $data['options'] = 'test_status=' . $status . ',dups=false,cb_post=false'; if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/paypoint.tpl')) { return $this->load->view($this->config->get('config_template') . '/template/payment/paypoint.tpl', $data); } else { return $this->load->view('default/template/payment/paypoint.tpl', $data); } } public function callback() { if (isset($this->request->get['trans_id'])) { $order_id = $this->request->get['trans_id']; } else { $order_id = 0; } $this->load->model('checkout/order'); $order_info = $this->model_checkout_order->getOrder($order_id); // Validate the request is from PayPoint if ($this->config->get('paypoint_password')) { if (!empty($this->request->get['hash'])) { $status = ($this->request->get['hash'] == md5(str_replace('hash=' . $this->request->get['hash'], '', htmlspecialchars_decode($this->request->server['REQUEST_URI'], ENT_COMPAT)) . $this->config->get('paypoint_password'))); } else { $status = false; } } else { $status = true; } if ($order_info) { $this->load->language('payment/paypoint'); $data['title'] = sprintf($this->language->get('heading_title'), $this->config->get('config_name')); if (!$this->request->server['HTTPS']) { $data['base'] = HTTP_SERVER; } else { $data['base'] = HTTPS_SERVER; } $data['language'] = $this->language->get('code'); $data['direction'] = $this->language->get('direction'); $data['heading_title'] = sprintf($this->language->get('heading_title'), $this->config->get('config_name')); $data['text_response'] = $this->language->get('text_response'); $data['text_success'] = $this->language->get('text_success'); $data['text_success_wait'] = sprintf($this->language->get('text_success_wait'), $this->url->link('checkout/success')); $data['text_failure'] = $this->language->get('text_failure'); $data['text_failure_wait'] = sprintf($this->language->get('text_failure_wait'), $this->url->link('checkout/cart')); if (isset($this->request->get['code']) && $this->request->get['code'] == 'A' && $status) { $message = ''; if (isset($this->request->get['code'])) { $message .= 'code: ' . $this->request->get['code'] . "\n"; } if (isset($this->request->get['auth_code'])) { $message .= 'auth_code: ' . $this->request->get['auth_code'] . "\n"; } if (isset($this->request->get['ip'])) { $message .= 'ip: ' . $this->request->get['ip'] . "\n"; } if (isset($this->request->get['cv2avs'])) { $message .= 'cv2avs: ' . $this->request->get['cv2avs'] . "\n"; } if (isset($this->request->get['valid'])) { $message .= 'valid: ' . $this->request->get['valid'] . "\n"; } $this->load->model('checkout/order'); $this->model_checkout_order->addOrderHistory($order_id, $this->config->get('paypoint_order_status_id'), $message, false); $data['continue'] = $this->url->link('checkout/success'); $data['column_left'] = $this->load->controller('common/column_left'); $data['column_right'] = $this->load->controller('common/column_right'); $data['content_top'] = $this->load->controller('common/content_top'); $data['content_bottom'] = $this->load->controller('common/content_bottom'); $data['footer'] = $this->load->controller('common/footer'); $data['header'] = $this->load->controller('common/header'); if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/paypoint_success.tpl')) { $this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/payment/paypoint_success.tpl', $data)); } else { $this->response->setOutput($this->load->view('default/template/payment/paypoint_success.tpl', $data)); } } else { $data['continue'] = $this->url->link('checkout/cart'); $data['column_left'] = $this->load->controller('common/column_left'); $data['column_right'] = $this->load->controller('common/column_right'); $data['content_top'] = $this->load->controller('common/content_top'); $data['content_bottom'] = $this->load->controller('common/content_bottom'); $data['footer'] = $this->load->controller('common/footer'); $data['header'] = $this->load->controller('common/header'); if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/paypoint_failure.tpl')) { $this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/payment/paypoint_failure.tpl', $data)); } else { $this->response->setOutput($this->load->view('default/template/payment/paypoint_failure.tpl', $data)); } } } } }
gpl-3.0
jollygeorge/camel
components/camel-soap/src/test/java/org/apache/camel/dataformat/soap/MultiPartCxfServerTest.java
8191
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.dataformat.soap; import java.util.List; import javax.xml.ws.Endpoint; import javax.xml.ws.Holder; import com.example.customerservice.multipart.Company; import com.example.customerservice.multipart.Customer; import com.example.customerservice.multipart.GetCustomersByName; import com.example.customerservice.multipart.GetCustomersByNameResponse; import com.example.customerservice.multipart.MultiPartCustomerService; import com.example.customerservice.multipart.Product; import com.example.customerservice.multipart.SaveCustomer; import org.apache.camel.Exchange; import org.apache.camel.Processor; import org.apache.camel.Produce; import org.apache.camel.ProducerTemplate; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.component.bean.BeanInvocation; import org.apache.camel.dataformat.soap.name.ServiceInterfaceStrategy; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.junit.Assert.assertTrue; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration public class MultiPartCxfServerTest extends RouteBuilder { protected static Endpoint endpoint; @Produce(uri = "direct:start") ProducerTemplate producerTemplate; @Override public void configure() throws Exception { ServiceInterfaceStrategy strat = new ServiceInterfaceStrategy(com.example.customerservice.multipart.MultiPartCustomerService.class, true); SoapJaxbDataFormat soapDataFormat = new SoapJaxbDataFormat("com.example.customerservice.multipart", strat); from("direct:start") .marshal(soapDataFormat) .log("marshal to: ${body}") .to("direct:cxfEndpoint") .unmarshal(soapDataFormat) .end(); } @Test public void testSendRequestWithInPart() throws Exception { Exchange exchange = producerTemplate.send("direct:start", new Processor() { public void process(Exchange exchange) throws Exception { BeanInvocation beanInvocation = new BeanInvocation(); GetCustomersByName getCustomersByName = new GetCustomersByName(); getCustomersByName.setName("Dr. Multipart"); beanInvocation.setMethod(MultiPartCustomerService.class.getMethod("getCustomersByName", GetCustomersByName.class, com.example.customerservice.multipart.Product.class)); Product product = new Product(); product.setName("Multipart Product"); product.setDescription("Useful for lots of things."); Object[] args = new Object[] {getCustomersByName, product}; beanInvocation.setArgs(args); exchange.getIn().setBody(beanInvocation); } }); if (exchange.getException() != null) { throw exchange.getException(); } Object responseObj = exchange.getOut().getBody(); assertTrue(responseObj instanceof GetCustomersByNameResponse); GetCustomersByNameResponse response = (GetCustomersByNameResponse) responseObj; assertTrue(response.getReturn().get(0).getName().equals("Multipart Product")); } @Test public void testSendRequestWithInAndInOutParts() throws Exception { Exchange exchange = producerTemplate.send("direct:start", new Processor() { public void process(Exchange exchange) throws Exception { BeanInvocation beanInvocation = new BeanInvocation(); beanInvocation.setMethod(MultiPartCustomerService.class.getMethod("saveCustomer", SaveCustomer.class, Product.class, Holder.class)); Customer customer = new Customer(); customer.setName("TestCustomer"); customer.setRevenue(50000); SaveCustomer saveCustomer = new SaveCustomer(); saveCustomer.setCustomer(customer); Product product = new Product(); product.setName("Multiuse Product"); product.setDescription("Useful for lots of things."); Holder<Company> holder = new Holder<Company>(); Object[] args = new Object[] {saveCustomer, product, holder}; beanInvocation.setArgs(args); exchange.getIn().setBody(beanInvocation); } }); if (exchange.getException() != null) { throw exchange.getException(); } @SuppressWarnings("unchecked") List<Object> headers = (List<Object>) exchange.getOut().getHeader(SoapJaxbDataFormat.SOAP_UNMARSHALLED_HEADER_LIST); assertTrue(headers.size() == 1); Object companyHeaderObj = headers.get(0); assertTrue(companyHeaderObj instanceof Company); assertTrue(((Company)companyHeaderObj).getName().equals("MultipartSoft")); } /** * This test validates the end-to-end behavior of the service interface mapping when a parameter type * is defined with a different QName in two different Web method. It also tests the case where a * QName and type are directly reused across methods. */ @Test public void testSendRequestWithReusedInAndInOutParts() throws Exception { Exchange exchange = producerTemplate.send("direct:start", new Processor() { public void process(Exchange exchange) throws Exception { BeanInvocation beanInvocation = new BeanInvocation(); beanInvocation.setMethod(MultiPartCustomerService.class.getMethod("saveCustomerToo", SaveCustomer.class, Product.class, Holder.class)); Customer customer = new Customer(); customer.setName("TestCustomerToo"); customer.setRevenue(50000); SaveCustomer saveCustomer = new SaveCustomer(); saveCustomer.setCustomer(customer); Product product = new Product(); product.setName("Multiuse Product"); product.setDescription("Useful for lots of things."); Holder<Company> holder = new Holder<Company>(); Object[] args = new Object[] {saveCustomer, product, holder}; beanInvocation.setArgs(args); exchange.getIn().setBody(beanInvocation); } }); if (exchange.getException() != null) { throw exchange.getException(); } @SuppressWarnings("unchecked") List<Object> headers = (List<Object>) exchange.getOut().getHeader(SoapJaxbDataFormat.SOAP_UNMARSHALLED_HEADER_LIST); assertTrue(headers.size() == 1); Object companyHeaderObj = headers.get(0); assertTrue(companyHeaderObj instanceof Company); assertTrue(((Company)companyHeaderObj).getName().equals("MultipartSoft")); } }
apache-2.0
pplatek/camel
components/camel-netty4/src/main/java/org/apache/camel/component/netty4/ChannelHandlerFactories.java
6773
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.netty4; import java.nio.charset.Charset; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandler; import io.netty.handler.codec.LengthFieldBasedFrameDecoder; import io.netty.handler.codec.bytes.ByteArrayDecoder; import io.netty.handler.codec.bytes.ByteArrayEncoder; import io.netty.handler.codec.serialization.ClassResolvers; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; import org.apache.camel.component.netty4.codec.DatagramPacketByteArrayDecoder; import org.apache.camel.component.netty4.codec.DatagramPacketByteArrayEncoder; import org.apache.camel.component.netty4.codec.DatagramPacketDecoder; import org.apache.camel.component.netty4.codec.DatagramPacketDelimiterDecoder; import org.apache.camel.component.netty4.codec.DatagramPacketEncoder; import org.apache.camel.component.netty4.codec.DatagramPacketObjectDecoder; import org.apache.camel.component.netty4.codec.DatagramPacketObjectEncoder; import org.apache.camel.component.netty4.codec.DatagramPacketStringDecoder; import org.apache.camel.component.netty4.codec.DatagramPacketStringEncoder; import org.apache.camel.component.netty4.codec.DelimiterBasedFrameDecoder; import org.apache.camel.component.netty4.codec.ObjectDecoder; import org.apache.camel.component.netty4.codec.ObjectEncoder; /** * Helper to create commonly used {@link ChannelHandlerFactory} instances. */ public final class ChannelHandlerFactories { private ChannelHandlerFactories() { } public static ChannelHandlerFactory newStringEncoder(Charset charset, String protocol) { if ("udp".equalsIgnoreCase(protocol)) { return new ShareableChannelHandlerFactory(new DatagramPacketStringEncoder(charset)); } else { return new ShareableChannelHandlerFactory(new StringEncoder(charset)); } } public static ChannelHandlerFactory newStringDecoder(Charset charset, String protocol) { if ("udp".equalsIgnoreCase(protocol)) { return new ShareableChannelHandlerFactory(new DatagramPacketStringDecoder(charset)); } else { return new ShareableChannelHandlerFactory(new StringDecoder(charset)); } } public static ChannelHandlerFactory newObjectDecoder(String protocol) { if ("udp".equalsIgnoreCase(protocol)) { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } else { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new ObjectDecoder(ClassResolvers.weakCachingResolver(null)); } }; } } public static ChannelHandlerFactory newObjectEncoder(String protocol) { if ("udp".equals(protocol)) { return new ShareableChannelHandlerFactory(new DatagramPacketObjectEncoder()); } else { return new ShareableChannelHandlerFactory(new ObjectEncoder()); } } public static ChannelHandlerFactory newDelimiterBasedFrameDecoder(final int maxFrameLength, final ByteBuf[] delimiters, String protocol) { return newDelimiterBasedFrameDecoder(maxFrameLength, delimiters, true, protocol); } public static ChannelHandlerFactory newDelimiterBasedFrameDecoder(final int maxFrameLength, final ByteBuf[] delimiters, final boolean stripDelimiter, String protocol) { if ("udp".equals(protocol)) { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DatagramPacketDelimiterDecoder(maxFrameLength, stripDelimiter, delimiters); } }; } else { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new DelimiterBasedFrameDecoder(maxFrameLength, stripDelimiter, delimiters); } }; } } public static ChannelHandlerFactory newDatagramPacketDecoder() { return new ShareableChannelHandlerFactory(new DatagramPacketDecoder()); } public static ChannelHandlerFactory newDatagramPacketEncoder() { return new ShareableChannelHandlerFactory(new DatagramPacketEncoder()); } public static ChannelHandlerFactory newLengthFieldBasedFrameDecoder(final int maxFrameLength, final int lengthFieldOffset, final int lengthFieldLength, final int lengthAdjustment, final int initialBytesToStrip) { return new DefaultChannelHandlerFactory() { @Override public ChannelHandler newChannelHandler() { return new LengthFieldBasedFrameDecoder(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip); } }; } public static ChannelHandlerFactory newByteArrayDecoder(String protocol) { if ("udp".equals(protocol)) { return new ShareableChannelHandlerFactory(new DatagramPacketByteArrayDecoder()); } else { return new ShareableChannelHandlerFactory(new ByteArrayDecoder()); } } public static ChannelHandlerFactory newByteArrayEncoder(String protocol) { if ("udp".equals(protocol)) { return new ShareableChannelHandlerFactory(new DatagramPacketByteArrayEncoder()); } else { return new ShareableChannelHandlerFactory(new ByteArrayEncoder()); } } }
apache-2.0
SamirSouzaSys/zendf2napratica
vendor/zendframework/zendframework/resources/languages/ar/Zend_Validate.php
21692
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ /** * EN-Revision: 25.Jul.2011 */ return array( // Zend_Validate_Alnum "Invalid type given. String, integer or float expected" => "خطأ في المدخلة. يجب ادخال أرقام أو حروف فقط", "'%value%' contains characters which are non alphabetic and no digits" => "'%value%' تحتوي على رموز ليست حروف أو أرقام", "'%value%' is an empty string" => "'%value%' فارغ", // Zend_Validate_Alpha "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال حروف فقط", "'%value%' contains non alphabetic characters" => "'%value%' تحتوي على رموز ليست حروف", "'%value%' is an empty string" => "'%value%' فارغ", // Zend_Validate_Barcode "'%value%' failed checksum validation" => "'%value%' لم يجتز فحص الصحة", "'%value%' contains invalid characters" => "'%value%' يحتوي على رموز خاطئة", "'%value%' should have a length of %length% characters" => "طول '%value%' يجب أن يكون %length% حرف", "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", // Zend_Validate_Between "'%value%' is not between '%min%' and '%max%', inclusively" => "قيمة '%value%' يجب أن تكون بين '%min%' و '%max%'", "'%value%' is not strictly between '%min%' and '%max%'" => "قيمة '%value%' ليست بين '%min%' و '%max%'", // Zend_Validate_Callback "'%value%' is not valid" => "'%value%' خاطئ", "An exception has been raised within the callback" => "حصل خطأ داخلي أثناء تنفيذ العملية", // Zend_Validate_Ccnum "'%value%' must contain between 13 and 19 digits" => "'%value%' يجب أن تحتوي على ما بين 13 إلى 19 رقم", "Luhn algorithm (mod-10 checksum) failed on '%value%'" => "فشل اختبار Luhn algorithm (mod-10 checksum) على '%value%'", // Zend_Validate_CreditCard "'%value%' seems to contain an invalid checksum" => "'%value%' لم يجتز فحص الصحة", "'%value%' must contain only digits" => "'%value%' يجب أن تحتوي على أرقام فقط", "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", "'%value%' contains an invalid amount of digits" => "'%value%' تحتوي على عدد خاطئ من الأرقام", "'%value%' is not from an allowed institute" => "قيمة '%value%' ليست من مؤسسة مسموحة أو مقبولة", "'%value%' seems to be an invalid creditcard number" => "'%value%' ليس رقم بطاقة إئتمان", "An exception has been raised while validating '%value%'" => "حصل خطأ أثناء التحقق من صحة '%value%'", // Zend_Validate_Date "Invalid type given. String, integer, array or Zend_Date expected" => "خطأ في المدخلة. يجب ادخال حروف، أرقام، متسلسلات، أو Zend_Date", "'%value%' does not appear to be a valid date" => "'%value%' ليس تاريخ صحيح", "'%value%' does not fit the date format '%format%'" => "'%value%' لا يطابق شكل التاريخ '%format%'", // Zend_Validate_Db_Abstract "No record matching '%value%' was found" => "لم يتم العثور على سجل مطابق لـ '%value%'", "A record matching '%value%' was found" => "السجل '%value%' موجود", // Zend_Validate_Digits "Invalid type given. String, integer or float expected" => "خطأ في المدخلة. يجب ادخال أرقام أو حروف فقط", "'%value%' must contain only digits" => "'%value%' يجب أن يحتوي على أرقام فقط", "'%value%' is an empty string" => "'%value%' فارغ", // Zend_Validate_EmailAddress "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", "'%value%' is not a valid email address in the basic format local-part@hostname" => "قيمة '%value%' ليست بريد الكتروني صحيح يطابق نمط local-part@hostname", "'%hostname%' is not a valid hostname for email address '%value%'" => "قيمة '%hostname%' للبريد الإلكتروني '%value%' ليس صحيح", "'%hostname%' does not appear to have a valid MX record for the email address '%value%'" => "لا يوجد مدخلة MX صحيحة لـ'%hostname%' للبريد الإلكتروني '%value%'", "'%hostname%' is not in a routable network segment. The email address '%value%' should not be resolved from public network" => "'%hostname%' غير موجود في مكان يمكن الوصول إليه. البريد الإلكتروني '%value%' لا يمكن الوصول إليه من شبكة عامة", "'%localPart%' can not be matched against dot-atom format" => "'%localPart%' لا يمكن مطابقته مع شكل dot-atom", "'%localPart%' can not be matched against quoted-string format" => "'%localPart%' لا يمكن مطابقته مع شكل quoted-string", "'%localPart%' is not a valid local part for email address '%value%'" => "'%localPart%' ليس بريد الكتروني صحيح لقيمة '%value%'", "'%value%' exceeds the allowed length" => "طول '%value%' تعدى الطول المسموح", // Zend_Validate_File_Count "Too many files, maximum '%max%' are allowed but '%count%' are given" => "'%count%' ملف/ملفات هو عدد أكبر من العدد المسموح به وهو '%max%'", "Too few files, minimum '%min%' are expected but '%count%' are given" => "'%count%' ملف/ملفات هو عدد أقل من العدد المطلوب وهو '%min%'", // Zend_Validate_File_Crc32 "File '%value%' does not match the given crc32 hashes" => "لم يطابق تشفير crc32 للملف '%value%' التشفير المعطى", "A crc32 hash could not be evaluated for the given file" => "لا يمكن معرفة قيمة تشفير crc32 للملف", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_ExcludeExtension "File '%value%' has a false extension" => "امتداد الملف '%value%' خاطئ", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_ExcludeMimeType "File '%value%' has a false mimetype of '%type%'" => "الملف '%value%' له نوع خاطئ وهو '%type%'", "The mimetype of file '%value%' could not be detected" => "لم يتم التعرف على نوع الملف '%value%'", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_Exists "File '%value%' does not exist" => "الملف '%value%' غير موجود", // Zend_Validate_File_Extension "File '%value%' has a false extension" => "صيغة الملف '%value%' خاطئة", "File '%value%' is not readable or does not exist" => "'%value%' لا يمكن قراءة محتوى الملف أو أنه غير موجود", // Zend_Validate_File_FilesSize "All files in sum should have a maximum size of '%max%' but '%size%' were detected" => "'%size%' هو حجم أكبر من الحد الأقصى المسموح به للملفات وهو '%max%'", "All files in sum should have a minimum size of '%min%' but '%size%' were detected" => "'%size%' هو حجم أصغر من الحد الأدنى المسموح به للملفات وهو '%min%'", "One or more files can not be read" => "لا يمكن قراءة محتوى ملف أو أكثر", // Zend_Validate_File_Hash "File '%value%' does not match the given hashes" => "لم يطابق تشفير الملف '%value%' التشفير المعطى", "A hash could not be evaluated for the given file" => "لا يمكن معرفة قيمة التشفير للملف", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_ImageSize "Maximum allowed width for image '%value%' should be '%maxwidth%' but '%width%' detected" => "أكبر عرض مسموح به للصورة '%value%' هو '%maxwidth%' ولكن العرض الحالي هو '%width%'", "Minimum expected width for image '%value%' should be '%minwidth%' but '%width%' detected" => "أقل عرض مسموح به للصورة '%value%' هو '%minwidth%' ولكن العرض الحالي هو '%width%'", "Maximum allowed height for image '%value%' should be '%maxheight%' but '%height%' detected" => "أكبر ارتفاع مسموح به للصورة '%value%' هو '%maxheight%' ولكن الطول الحالي هو '%height%'", "Minimum expected height for image '%value%' should be '%minheight%' but '%height%' detected" => "أقل ارتفاع مسموح به للصورة '%value%' should be '%minheight%' ولكن الطول الحالي هو '%height%'", "The size of image '%value%' could not be detected" => "لا يمكن أبعاد الصورة '%value%'", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_IsCompressed "File '%value%' is not compressed, '%type%' detected" => "الملف '%value%' ليس ملف مضغوط، بل هو ملف '%type%'", "The mimetype of file '%value%' could not be detected" => "لم يتم التعرف على نوع الملف '%value%'", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_IsImage "File '%value%' is no image, '%type%' detected" => "الملف '%value%' ليس صورة، بل هو ملف '%type%'", "The mimetype of file '%value%' could not be detected" => "لم يتم التعرف على نوع الملف '%value%'", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_Md5 "File '%value%' does not match the given md5 hashes" => "لم يطابق تشفير md5 للملف '%value%' التشفير المعطى", "A md5 hash could not be evaluated for the given file" => "لا يمكن معرفة قيمة تشفير md5 للملف", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_MimeType "File '%value%' has a false mimetype of '%type%'" => "الملف '%value%' له نوع خاطئ وهو '%type%'", "The mimetype of file '%value%' could not be detected" => "لم يتم التعرف على نوع الملف '%value%'", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_NotExists "File '%value%' exists" => "الملف '%value%' موجود", // Zend_Validate_File_Sha1 "File '%value%' does not match the given sha1 hashes" => "لم يطابق تشفير sha1 للملف '%value%' التشفير المعطى", "A sha1 hash could not be evaluated for the given file" => "لا يمكن معرفة قيمة تشفير sha1 للملف", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_Size "Maximum allowed size for file '%value%' is '%max%' but '%size%' detected" => "حجم الملف '%value%' هو '%size%' وهذا الحجم أكبر من الحد الأقصى المسموح به وهو '%max%'", "Minimum expected size for file '%value%' is '%min%' but '%size%' detected" => "حجم الملف '%value%' هو '%size%' وهذا الحجم أقل من الحد الأدنى المسموح به وهو '%min%'", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_File_Upload "File '%value%' exceeds the defined ini size" => "الملف '%value%' تعدى الحجم المسموح به حسب التعريف في ini", "File '%value%' exceeds the defined form size" => "الملف '%value%' تعدى الحجم المسموح به حسب التعريف في النموذج", "File '%value%' was only partially uploaded" => "الملف '%value%' تم تحميل جزء منه", "File '%value%' was not uploaded" => "الملف '%value%' لم يتم تحميله", "No temporary directory was found for file '%value%'" => "لم يتم العثور على مكان مؤقت للملف '%value%'", "File '%value%' can't be written" => "الملف '%value%' لا يمكن كتابته وتخزينه", "A PHP extension returned an error while uploading the file '%value%'" => "لقد حصل خطأ من إضافة PHP في عملية تحميل الملف '%value%'", "File '%value%' was illegally uploaded. This could be a possible attack" => "لقد تم تحميل الملف '%value%' بطريقة غير مشروعة. وهذا يمكن أن يكون محاولة هجوم", "File '%value%' was not found" => "لم يتم العثور على الملف '%value%'", "Unknown error while uploading file '%value%'" => "حصل خطأ غير معروف في عملية تحميل الملف '%value%'", // Zend_Validate_File_WordCount "Too much words, maximum '%max%' are allowed but '%count%' were counted" => "'%count%' كلمات أكثر من العدد الأقصى المسموح به وهو '%max%' كلمات", "Too few words, minimum '%min%' are expected but '%count%' were counted" => "'%count%' كلمات أقل من العدد الأدنى المسموح وهو '%min%' كلمات", "File '%value%' is not readable or does not exist" => "الملف '%value%' لا يمكن قراءته أو أنه غير موجود", // Zend_Validate_Float "Invalid type given. String, integer or float expected" => "خطأ في المدخلة. يجب ادخال أرقام أو حروف فقط", "'%value%' does not appear to be a float" => "'%value%' ليس رقم", // Zend_Validate_GreaterThan "'%value%' is not greater than '%min%'" => "'%value%' ليس أكبر من '%min%'", // Zend_Validate_Hex "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", "'%value%' has not only hexadecimal digit characters" => "'%value%' يحتوي على حروف أو رموز ليست من النظام الست عشري (hexadecimal)", // Zend_Validate_Hostname "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", "'%value%' appears to be an IP address, but IP addresses are not allowed" => "قيمة '%value%' تبدو أنها عنوان بروتوكول انترنت (IP) وهذا غير مسموح به", "'%value%' appears to be a DNS hostname but cannot match TLD against known list" => "'%value%' هو اسم نظام أسماء المجالات (DNS)، ولكن اسم المجال ذو المستوى العال (TLD) غير معروف", "'%value%' appears to be a DNS hostname but contains a dash in an invalid position" => "'%value%' هو اسم نظام أسماء المجالات (DNS)، ولكنه يحتوي على (-) في مكان خاطئ", "'%value%' appears to be a DNS hostname but cannot match against hostname schema for TLD '%tld%'" => "'%value%' هو اسم نظام أسماء المجالات (DNS)، ولكن لا يمكن مطابقته مع اسم مخطط لاسم المجال ذو المستوى العال (TLD) '%tld%'", "'%value%' appears to be a DNS hostname but cannot extract TLD part" => "'%value%' هو اسم نظام أسماء المجالات (DNS)، ولكن لا يمكن معرفة جزء اسم مجال ذو مستوى عال (TLD) منه", "'%value%' does not match the expected structure for a DNS hostname" => "'%value%' لا يطابق شكل نظام أسماء المجالات (DNS)", "'%value%' does not appear to be a valid local network name" => "'%value%' ليس اسم صحيح لشبكة محلية", "'%value%' appears to be a local network name but local network names are not allowed" => "'%value%' هو اسم لشبكة محلية، والشبكة المحلية غير مسموح بها", "'%value%' appears to be a DNS hostname but the given punycode notation cannot be decoded" => "'%value%' هو اسم نظام أسماء المجالات (DNS)، ولكن الرموز في الاسم لا يمكن تفكيكها وتحويلها لصيغة أبسط", "'%value%' does not appear to be a valid URI hostname" => "'%value%' ليس عنوان اسم صحيح لمضيف", // Zend_Validate_Iban "Unknown country within the IBAN '%value%'" => "لم يتم التعرف على الدولة في الرقم الدولي للحساب البنكي (IBAN) '%value%'", "'%value%' has a false IBAN format" => "'%value%' ليس صيفة صحيحة لالرقم الدولي للحساب البنكي (IBAN)", "'%value%' has failed the IBAN check" => "'%value%' لم يجتز فحص الرقم الدولي للحساب البنكي (IBAN)", // Zend_Validate_Identical "The two given tokens do not match" => "الرمزان غير متطابقان", "No token was provided to match against" => "لا يوجد رمز للمقارنة به", // Zend_Validate_InArray "'%value%' was not found in the haystack" => "لم يتم العثور على '%value%' في المتسلسلة", // Zend_Validate_Int "Invalid type given. String or integer expected" => "خطأ في المدخلة. يجب ادخال أرقام", "'%value%' does not appear to be an integer" => "'%value%' ليس رقم", // Zend_Validate_Ip "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", "'%value%' does not appear to be a valid IP address" => "'%value%' ليس عنوان بروتوكول انترنت (IP) صحيح", // Zend_Validate_Isbn "Invalid type given. String or integer expected" => "خطأ في المدخلة. يجب ادخال أرقام أو حروف", "'%value%' is not a valid ISBN number" => "'%value%' ليس قيمة صحيحة لالرقم الدولي الموحد للكتاب (ISBN)", // Zend_Validate_LessThan "'%value%' is not less than '%max%'" => "'%value%' ليس أقل من '%max%'", // Zend_Validate_NotEmpty "Invalid type given. String, integer, float, boolean or array expected" => "خطأ في المدخلة. يجب ادخال أرقام، حروف، صح أو خطأ، أو متسلسلة", "Value is required and can't be empty" => "لا يمكن ترك هذا الحقل فارغ", // Zend_Validate_PostCode "Invalid type given. String or integer expected" => "خطأ في المدخلة. يجب ادخال أرقام أو حروف", "'%value%' does not appear to be a postal code" => "'%value%' ليس رمز بريدي صحيح", // Zend_Validate_Regex "Invalid type given. String, integer or float expected" => "خطأ في المدخلة. يجب ادخال أرقام أو حروف فقط", "'%value%' does not match against pattern '%pattern%'" => "'%value%' لا يطابق النمط '%pattern%'", "There was an internal error while using the pattern '%pattern%'" => "حصل خطأ داخلي أثناء استخدام النمط '%pattern%'", // Zend_Validate_Sitemap_Changefreq "'%value%' is not a valid sitemap changefreq" => "'%value%' ليست قيمة صحيحة لوتيرة التغيير لخريطة الموقع", "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", // Zend_Validate_Sitemap_Lastmod "'%value%' is not a valid sitemap lastmod" => "'%value%' ليست قيمة صحيحة لتاريخ آخر تعديل لخريطة الموقع", "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", // Zend_Validate_Sitemap_Loc "'%value%' is not a valid sitemap location" => "'%value%' ليس عنوان صحيح لخريطة الموقع", "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", // Zend_Validate_Sitemap_Priority "'%value%' is not a valid sitemap priority" => "'%value%' ليست أولوية صحيحة لعنوان خريطة الموقع", "Invalid type given. Numeric string, integer or float expected" => "خطأ في المدخلة. يجب ادخال أرقام أو حروف فقط", // Zend_Validate_StringLength "Invalid type given. String expected" => "خطأ في المدخلة. يجب ادخال نص", "'%value%' is less than %min% characters long" => "طول '%value%' يجب أن يكون %min% حرف على الأقل", "'%value%' is more than %max% characters long" => "طول '%value%' يجب أن يكون %max% كحد أقصى", );
bsd-3-clause
wuxianghou/phantomjs
src/qt/qtwebkit/Source/JavaScriptCore/bytecode/ExecutionCounter.cpp
6093
/* * Copyright (C) 2012 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ExecutionCounter.h" #include "CodeBlock.h" #include "ExecutableAllocator.h" #include <wtf/StringExtras.h> namespace JSC { ExecutionCounter::ExecutionCounter() { reset(); } bool ExecutionCounter::checkIfThresholdCrossedAndSet(CodeBlock* codeBlock) { if (hasCrossedThreshold(codeBlock)) return true; if (setThreshold(codeBlock)) return true; return false; } void ExecutionCounter::setNewThreshold(int32_t threshold, CodeBlock* codeBlock) { reset(); m_activeThreshold = threshold; setThreshold(codeBlock); } void ExecutionCounter::deferIndefinitely() { m_totalCount = 0; m_activeThreshold = std::numeric_limits<int32_t>::max(); m_counter = std::numeric_limits<int32_t>::min(); } double ExecutionCounter::applyMemoryUsageHeuristics(int32_t value, CodeBlock* codeBlock) { #if ENABLE(JIT) double multiplier = ExecutableAllocator::memoryPressureMultiplier( codeBlock->predictedMachineCodeSize()); #else // This code path will probably not be taken, but if it is, we fake it. double multiplier = 1.0; UNUSED_PARAM(codeBlock); #endif ASSERT(multiplier >= 1.0); return multiplier * value; } int32_t ExecutionCounter::applyMemoryUsageHeuristicsAndConvertToInt( int32_t value, CodeBlock* codeBlock) { double doubleResult = applyMemoryUsageHeuristics(value, codeBlock); ASSERT(doubleResult >= 0); if (doubleResult > std::numeric_limits<int32_t>::max()) return std::numeric_limits<int32_t>::max(); return static_cast<int32_t>(doubleResult); } bool ExecutionCounter::hasCrossedThreshold(CodeBlock* codeBlock) const { // This checks if the current count rounded up to the threshold we were targeting. // For example, if we are using half of available executable memory and have // m_activeThreshold = 1000, applyMemoryUsageHeuristics(m_activeThreshold) will be // 2000, but we will pretend as if the threshold was crossed if we reach 2000 - // 1000 / 2, or 1500. The reasoning here is that we want to avoid thrashing. If // this method returns false, then the JIT's threshold for when it will again call // into the slow path (which will call this method a second time) will be set // according to the difference between the current count and the target count // according to *current* memory usage. But by the time we call into this again, we // may have JIT'ed more code, and so the target count will increase slightly. This // may lead to a repeating pattern where the target count is slightly incremented, // the JIT immediately matches that increase, calls into the slow path again, and // again the target count is slightly incremented. Instead of having this vicious // cycle, we declare victory a bit early if the difference between the current // total and our target according to memory heuristics is small. Our definition of // small is arbitrarily picked to be half of the original threshold (i.e. // m_activeThreshold). double modifiedThreshold = applyMemoryUsageHeuristics(m_activeThreshold, codeBlock); return static_cast<double>(m_totalCount) + m_counter >= modifiedThreshold - static_cast<double>( std::min(m_activeThreshold, Options::maximumExecutionCountsBetweenCheckpoints())) / 2; } bool ExecutionCounter::setThreshold(CodeBlock* codeBlock) { if (m_activeThreshold == std::numeric_limits<int32_t>::max()) { deferIndefinitely(); return false; } ASSERT(!hasCrossedThreshold(codeBlock)); // Compute the true total count. double trueTotalCount = count(); // Correct the threshold for current memory usage. double threshold = applyMemoryUsageHeuristics(m_activeThreshold, codeBlock); // Threshold must be non-negative and not NaN. ASSERT(threshold >= 0); // Adjust the threshold according to the number of executions we have already // seen. This shouldn't go negative, but it might, because of round-off errors. threshold -= trueTotalCount; if (threshold <= 0) { m_counter = 0; m_totalCount = trueTotalCount; return true; } threshold = clippedThreshold(codeBlock->globalObject(), threshold); m_counter = static_cast<int32_t>(-threshold); m_totalCount = trueTotalCount + threshold; return false; } void ExecutionCounter::reset() { m_counter = 0; m_totalCount = 0; m_activeThreshold = 0; } void ExecutionCounter::dump(PrintStream& out) const { out.printf("%lf/%lf, %d", count(), static_cast<double>(m_activeThreshold), m_counter); } } // namespace JSC
bsd-3-clause
medikid/mccee
sites/all/libraries/Zend/Session/Validator/Abstract.php
2209
<?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 license@zend.com so we can send you a copy immediately. * * @category Zend * @package Zend_Session * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License * @version $Id: Abstract.php 24593 2012-01-05 20:35:02Z matthew $ * @since Preview Release 0.2 */ /** * @see Zend_Session_Validator_Interface */ require_once 'Zend/Session/Validator/Interface.php'; /** * Zend_Session_Validator_Abstract * * @category Zend * @package Zend_Session * @subpackage Validator * @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ abstract class Zend_Session_Validator_Abstract implements Zend_Session_Validator_Interface { /** * SetValidData() - This method should be used to store the environment variables that * will be needed in order to validate the session later in the validate() method. * These values are stored in the session in the __ZF namespace, in an array named VALID * * @param mixed $data * @return void */ protected function setValidData($data) { $validatorName = get_class($this); $_SESSION['__ZF']['VALID'][$validatorName] = $data; } /** * GetValidData() - This method should be used to retrieve the environment variables that * will be needed to 'validate' a session. * * @return mixed */ protected function getValidData() { $validatorName = get_class($this); if (isset($_SESSION['__ZF']['VALID'][$validatorName])) { return $_SESSION['__ZF']['VALID'][$validatorName]; } return null; } }
gpl-2.0
torstenzander/myinvoiz
vendor/gedmo-doctrine-extensions/tests/Gedmo/Tree/Fixture/Transport/Bus.php
129
<?php namespace Tree\Fixture\Transport; use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity */ class Bus extends Vehicle { }
mit
vancarney/apihero-module-socket.io
node_modules/docco/node_modules/highlight.js/lib/languages/stylus.js
8327
module.exports = function(hljs) { var VARIABLE = { className: 'variable', begin: '\\$' + hljs.IDENT_RE }; var HEX_COLOR = { className: 'hexcolor', begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})', relevance: 10 }; var AT_KEYWORDS = [ 'charset', 'css', 'debug', 'extend', 'font-face', 'for', 'import', 'include', 'media', 'mixin', 'page', 'warn', 'while' ]; var PSEUDO_SELECTORS = [ 'after', 'before', 'first-letter', 'first-line', 'active', 'first-child', 'focus', 'hover', 'lang', 'link', 'visited' ]; var TAGS = [ 'a', 'abbr', 'address', 'article', 'aside', 'audio', 'b', 'blockquote', 'body', 'button', 'canvas', 'caption', 'cite', 'code', 'dd', 'del', 'details', 'dfn', 'div', 'dl', 'dt', 'em', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'mark', 'menu', 'nav', 'object', 'ol', 'p', 'q', 'quote', 'samp', 'section', 'span', 'strong', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'ul', 'var', 'video' ]; var TAG_END = '[\\.\\s\\n\\[\\:,]'; var ATTRIBUTES = [ 'align-content', 'align-items', 'align-self', 'animation', 'animation-delay', 'animation-direction', 'animation-duration', 'animation-fill-mode', 'animation-iteration-count', 'animation-name', 'animation-play-state', 'animation-timing-function', 'auto', 'backface-visibility', 'background', 'background-attachment', 'background-clip', 'background-color', 'background-image', 'background-origin', 'background-position', 'background-repeat', 'background-size', 'border', 'border-bottom', 'border-bottom-color', 'border-bottom-left-radius', 'border-bottom-right-radius', 'border-bottom-style', 'border-bottom-width', 'border-collapse', 'border-color', 'border-image', 'border-image-outset', 'border-image-repeat', 'border-image-slice', 'border-image-source', 'border-image-width', 'border-left', 'border-left-color', 'border-left-style', 'border-left-width', 'border-radius', 'border-right', 'border-right-color', 'border-right-style', 'border-right-width', 'border-spacing', 'border-style', 'border-top', 'border-top-color', 'border-top-left-radius', 'border-top-right-radius', 'border-top-style', 'border-top-width', 'border-width', 'bottom', 'box-decoration-break', 'box-shadow', 'box-sizing', 'break-after', 'break-before', 'break-inside', 'caption-side', 'clear', 'clip', 'clip-path', 'color', 'column-count', 'column-fill', 'column-gap', 'column-rule', 'column-rule-color', 'column-rule-style', 'column-rule-width', 'column-span', 'column-width', 'columns', 'content', 'counter-increment', 'counter-reset', 'cursor', 'direction', 'display', 'empty-cells', 'filter', 'flex', 'flex-basis', 'flex-direction', 'flex-flow', 'flex-grow', 'flex-shrink', 'flex-wrap', 'float', 'font', 'font-family', 'font-feature-settings', 'font-kerning', 'font-language-override', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-variant-ligatures', 'font-weight', 'height', 'hyphens', 'icon', 'image-orientation', 'image-rendering', 'image-resolution', 'ime-mode', 'inherit', 'initial', 'justify-content', 'left', 'letter-spacing', 'line-height', 'list-style', 'list-style-image', 'list-style-position', 'list-style-type', 'margin', 'margin-bottom', 'margin-left', 'margin-right', 'margin-top', 'marks', 'mask', 'max-height', 'max-width', 'min-height', 'min-width', 'nav-down', 'nav-index', 'nav-left', 'nav-right', 'nav-up', 'none', 'normal', 'object-fit', 'object-position', 'opacity', 'order', 'orphans', 'outline', 'outline-color', 'outline-offset', 'outline-style', 'outline-width', 'overflow', 'overflow-wrap', 'overflow-x', 'overflow-y', 'padding', 'padding-bottom', 'padding-left', 'padding-right', 'padding-top', 'page-break-after', 'page-break-before', 'page-break-inside', 'perspective', 'perspective-origin', 'pointer-events', 'position', 'quotes', 'resize', 'right', 'tab-size', 'table-layout', 'text-align', 'text-align-last', 'text-decoration', 'text-decoration-color', 'text-decoration-line', 'text-decoration-style', 'text-indent', 'text-overflow', 'text-rendering', 'text-shadow', 'text-transform', 'text-underline-position', 'top', 'transform', 'transform-origin', 'transform-style', 'transition', 'transition-delay', 'transition-duration', 'transition-property', 'transition-timing-function', 'unicode-bidi', 'vertical-align', 'visibility', 'white-space', 'widows', 'width', 'word-break', 'word-spacing', 'word-wrap', 'z-index' ]; // illegals var ILLEGAL = [ '\\{', '\\}', '\\?', '(\\bReturn\\b)', // monkey '(\\bEnd\\b)', // monkey '(\\bend\\b)', // vbscript ';', // sql '#\\s', // markdown '\\*\\s', // markdown '===\\s', // markdown '\\|', '%', // prolog ]; return { aliases: ['styl'], case_insensitive: false, illegal: '(' + ILLEGAL.join('|') + ')', keywords: 'if else for in', contains: [ // strings hljs.QUOTE_STRING_MODE, hljs.APOS_STRING_MODE, // comments hljs.C_LINE_COMMENT_MODE, hljs.C_BLOCK_COMMENT_MODE, // hex colors HEX_COLOR, // class tag { begin: '\\.[a-zA-Z][a-zA-Z0-9_-]*' + TAG_END, returnBegin: true, contains: [ {className: 'class', begin: '\\.[a-zA-Z][a-zA-Z0-9_-]*'} ] }, // id tag { begin: '\\#[a-zA-Z][a-zA-Z0-9_-]*' + TAG_END, returnBegin: true, contains: [ {className: 'id', begin: '\\#[a-zA-Z][a-zA-Z0-9_-]*'} ] }, // tags { begin: '\\b(' + TAGS.join('|') + ')' + TAG_END, returnBegin: true, contains: [ {className: 'tag', begin: '\\b[a-zA-Z][a-zA-Z0-9_-]*'} ] }, // psuedo selectors { className: 'pseudo', begin: '&?:?:\\b(' + PSEUDO_SELECTORS.join('|') + ')' + TAG_END }, // @ keywords { className: 'at_rule', begin: '\@(' + AT_KEYWORDS.join('|') + ')\\b' }, // variables VARIABLE, // dimension hljs.CSS_NUMBER_MODE, // number hljs.NUMBER_MODE, // functions // - only from beginning of line + whitespace { className: 'function', begin: '\\b[a-zA-Z][a-zA-Z0-9_\-]*\\(.*\\)', illegal: '[\\n]', returnBegin: true, contains: [ {className: 'title', begin: '\\b[a-zA-Z][a-zA-Z0-9_\-]*'}, { className: 'params', begin: /\(/, end: /\)/, contains: [ HEX_COLOR, VARIABLE, hljs.APOS_STRING_MODE, hljs.CSS_NUMBER_MODE, hljs.NUMBER_MODE, hljs.QUOTE_STRING_MODE ] } ] }, // attributes // - only from beginning of line + whitespace // - must have whitespace after it { className: 'attribute', begin: '\\b(' + ATTRIBUTES.reverse().join('|') + ')\\b' } ] }; };
mit
diegopacheco/scala-playground
caliban-graphql-fun/src/main/resources/gateway/node_modules/core-js/internals/uid.js
177
var id = 0; var postfix = Math.random(); module.exports = function (key) { return 'Symbol(' + String(key === undefined ? '' : key) + ')_' + (++id + postfix).toString(36); };
unlicense
tmckayus/oshinko-cli
vendor/github.com/openshift/origin/cmd/service-catalog/go/src/github.com/kubernetes-incubator/service-catalog/vendor/github.com/pkg/errors/example_test.go
3886
package errors_test import ( "fmt" "github.com/pkg/errors" ) func ExampleNew() { err := errors.New("whoops") fmt.Println(err) // Output: whoops } func ExampleNew_printf() { err := errors.New("whoops") fmt.Printf("%+v", err) // Example output: // whoops // github.com/pkg/errors_test.ExampleNew_printf // /home/dfc/src/github.com/pkg/errors/example_test.go:17 // testing.runExample // /home/dfc/go/src/testing/example.go:114 // testing.RunExamples // /home/dfc/go/src/testing/example.go:38 // testing.(*M).Run // /home/dfc/go/src/testing/testing.go:744 // main.main // /github.com/pkg/errors/_test/_testmain.go:106 // runtime.main // /home/dfc/go/src/runtime/proc.go:183 // runtime.goexit // /home/dfc/go/src/runtime/asm_amd64.s:2059 } func ExampleWrap() { cause := errors.New("whoops") err := errors.Wrap(cause, "oh noes") fmt.Println(err) // Output: oh noes: whoops } func fn() error { e1 := errors.New("error") e2 := errors.Wrap(e1, "inner") e3 := errors.Wrap(e2, "middle") return errors.Wrap(e3, "outer") } func ExampleCause() { err := fn() fmt.Println(err) fmt.Println(errors.Cause(err)) // Output: outer: middle: inner: error // error } func ExampleWrap_extended() { err := fn() fmt.Printf("%+v\n", err) // Example output: // error // github.com/pkg/errors_test.fn // /home/dfc/src/github.com/pkg/errors/example_test.go:47 // github.com/pkg/errors_test.ExampleCause_printf // /home/dfc/src/github.com/pkg/errors/example_test.go:63 // testing.runExample // /home/dfc/go/src/testing/example.go:114 // testing.RunExamples // /home/dfc/go/src/testing/example.go:38 // testing.(*M).Run // /home/dfc/go/src/testing/testing.go:744 // main.main // /github.com/pkg/errors/_test/_testmain.go:104 // runtime.main // /home/dfc/go/src/runtime/proc.go:183 // runtime.goexit // /home/dfc/go/src/runtime/asm_amd64.s:2059 // github.com/pkg/errors_test.fn // /home/dfc/src/github.com/pkg/errors/example_test.go:48: inner // github.com/pkg/errors_test.fn // /home/dfc/src/github.com/pkg/errors/example_test.go:49: middle // github.com/pkg/errors_test.fn // /home/dfc/src/github.com/pkg/errors/example_test.go:50: outer } func ExampleWrapf() { cause := errors.New("whoops") err := errors.Wrapf(cause, "oh noes #%d", 2) fmt.Println(err) // Output: oh noes #2: whoops } func ExampleErrorf_extended() { err := errors.Errorf("whoops: %s", "foo") fmt.Printf("%+v", err) // Example output: // whoops: foo // github.com/pkg/errors_test.ExampleErrorf // /home/dfc/src/github.com/pkg/errors/example_test.go:101 // testing.runExample // /home/dfc/go/src/testing/example.go:114 // testing.RunExamples // /home/dfc/go/src/testing/example.go:38 // testing.(*M).Run // /home/dfc/go/src/testing/testing.go:744 // main.main // /github.com/pkg/errors/_test/_testmain.go:102 // runtime.main // /home/dfc/go/src/runtime/proc.go:183 // runtime.goexit // /home/dfc/go/src/runtime/asm_amd64.s:2059 } func Example_stackTrace() { type stackTracer interface { StackTrace() errors.StackTrace } err, ok := errors.Cause(fn()).(stackTracer) if !ok { panic("oops, err does not implement stackTracer") } st := err.StackTrace() fmt.Printf("%+v", st[0:2]) // top two frames // Example output: // github.com/pkg/errors_test.fn // /home/dfc/src/github.com/pkg/errors/example_test.go:47 // github.com/pkg/errors_test.Example_stackTrace // /home/dfc/src/github.com/pkg/errors/example_test.go:127 } func ExampleCause_printf() { err := errors.Wrap(func() error { return func() error { return errors.Errorf("hello %s", fmt.Sprintf("world")) }() }(), "failed") fmt.Printf("%v", err) // Output: failed: hello world }
apache-2.0
pplatek/camel
components/camel-spring/src/test/java/org/apache/camel/spring/interceptor/SpringTransactionalClientDataSourceUsingTransactedTest.java
1468
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.spring.interceptor; import org.springframework.context.support.AbstractXmlApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Easier transaction configuration as we do not have to setup a transaction error handler */ public class SpringTransactionalClientDataSourceUsingTransactedTest extends SpringTransactionalClientDataSourceTransactedTest { protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext( "/org/apache/camel/spring/interceptor/springTransactionalClientDataSourceUsingTransacted.xml"); } }
apache-2.0
gitromand/phantomjs
src/qt/qtwebkit/Source/WebCore/Modules/mediastream/NavigatorMediaStream.cpp
2339
/* * Copyright (C) 2000 Harri Porten (porten@kde.org) * Copyright (c) 2000 Daniel Molkentin (molkentin@kde.org) * Copyright (c) 2000 Stefan Schimanski (schimmi@kde.org) * Copyright (C) 2003, 2004, 2005, 2006 Apple Computer, Inc. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "config.h" #include "NavigatorMediaStream.h" #if ENABLE(MEDIA_STREAM) #include "Dictionary.h" #include "Document.h" #include "ExceptionCode.h" #include "Frame.h" #include "Navigator.h" #include "NavigatorUserMediaErrorCallback.h" #include "NavigatorUserMediaSuccessCallback.h" #include "Page.h" #include "UserMediaController.h" #include "UserMediaRequest.h" namespace WebCore { NavigatorMediaStream::NavigatorMediaStream() { } NavigatorMediaStream::~NavigatorMediaStream() { } void NavigatorMediaStream::webkitGetUserMedia(Navigator* navigator, const Dictionary& options, PassRefPtr<NavigatorUserMediaSuccessCallback> successCallback, PassRefPtr<NavigatorUserMediaErrorCallback> errorCallback, ExceptionCode& ec) { if (!successCallback) return; UserMediaController* userMedia = UserMediaController::from(navigator->frame() ? navigator->frame()->page() : 0); if (!userMedia) { ec = NOT_SUPPORTED_ERR; return; } RefPtr<UserMediaRequest> request = UserMediaRequest::create(navigator->frame()->document(), userMedia, options, successCallback, errorCallback, ec); if (!request) { ec = NOT_SUPPORTED_ERR; return; } request->start(); } } // namespace WebCore #endif // ENABLE(MEDIA_STREAM)
bsd-3-clause
dhoehna/corefx
src/System.IO.Ports/tests/SerialPort/CDHolding.cs
2697
// 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. using System.Diagnostics; using System.IO.PortsTests; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class CDHolding_Property : PortsTest { #region Test Cases [Fact] public void CDHolding_Default() { using (SerialPort com1 = new SerialPort()) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default CDHolding before Open"); serPortProp.SetAllPropertiesToDefaults(); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void CDHolding_Default_AfterOpen() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default CDHolding after Open"); serPortProp.SetAllPropertiesToOpenDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); com2.Open(); serPortProp.VerifyPropertiesAndPrint(com1); } } [ConditionalFact(nameof(HasNullModem))] public void CDHolding_Default_AfterClose() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { SerialPortProperties serPortProp = new SerialPortProperties(); Debug.WriteLine("Verifying default CDHolding after Close"); serPortProp.SetAllPropertiesToDefaults(); serPortProp.SetProperty("PortName", TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); com1.Open(); com2.Open(); if (com1.IsOpen) com1.Close(); if (com2.IsOpen) com2.Close(); serPortProp.VerifyPropertiesAndPrint(com1); } } #endregion #region Verification for Test Cases #endregion } }
mit
LeChuck42/or1k-gcc
gcc/testsuite/g++.dg/warn/deprecated-8.C
394
// PR c++/58305 class ToBeDeprecated { } __attribute__ ((deprecated ("deprecated!"))); typedef ToBeDeprecated NotToBeDeprecated; // { dg-warning "'ToBeDeprecated' is deprecated" } int main() { ToBeDeprecated(); // { dg-warning "'ToBeDeprecated' is deprecated" } ToBeDeprecated x; // { dg-warning "'ToBeDeprecated' is deprecated" } NotToBeDeprecated(); NotToBeDeprecated y; }
gpl-2.0
thomaslevesque/roslyn
src/Compilers/Core/Portable/SymbolDisplay/SymbolDisplayParameterOptions.cs
1961
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis { /// <summary> /// Specifies how parameters are displayed in the description of a (member, property/indexer, or delegate) symbol. /// </summary> [Flags] public enum SymbolDisplayParameterOptions { /// <summary> /// Omits parameters from symbol descriptions. /// </summary> /// <remarks> /// If this option is combined with <see cref="SymbolDisplayMemberOptions.IncludeParameters"/>, then only /// the parentheses will be shown (e.g. M()). /// </remarks> None = 0, /// <summary> /// Includes the <c>this</c> keyword before the first parameter of an extension method in C#. /// </summary> /// <remarks> /// This option has no effect in Visual Basic. /// </remarks> IncludeExtensionThis = 1 << 0, /// <summary> /// Includes the <c>params</c>, <c>ref</c>, <c>out</c>, <c>ByRef</c>, <c>ByVal</c> keywords before parameters. /// </summary> IncludeParamsRefOut = 1 << 1, /// <summary> /// Includes parameter types in symbol descriptions. /// </summary> IncludeType = 1 << 2, /// <summary> /// Includes parameter names in symbol descriptions. /// </summary> IncludeName = 1 << 3, /// <summary> /// Includes parameter default values in symbol descriptions. /// </summary> /// <remarks>Ignored if <see cref="IncludeName"/> is not set.</remarks> IncludeDefaultValue = 1 << 4, /// <summary> /// Includes square brackets around optional parameters. /// </summary> IncludeOptionalBrackets = 1 << 5, } }
apache-2.0