text
stringlengths
2
6.14k
version https://git-lfs.github.com/spec/v1 oid sha256:d15be6c4d52831d7f4c20b8f2b461332215072284affcf3ca299ddc2bb812ab0 size 2095
// GENERATED CODE -- DO NOT EDIT! // Original file comments: // Copyright 2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // 'use strict'; var grpc = require('grpc'); var helloworld_pb = require('./helloworld_pb.js'); function serialize_HelloReply(arg) { if (!(arg instanceof helloworld_pb.HelloReply)) { throw new Error('Expected argument of type HelloReply'); } return new Buffer(arg.serializeBinary()); } function deserialize_HelloReply(buffer_arg) { return helloworld_pb.HelloReply.deserializeBinary(new Uint8Array(buffer_arg)); } function serialize_HelloRequest(arg) { if (!(arg instanceof helloworld_pb.HelloRequest)) { throw new Error('Expected argument of type HelloRequest'); } return new Buffer(arg.serializeBinary()); } function deserialize_HelloRequest(buffer_arg) { return helloworld_pb.HelloRequest.deserializeBinary(new Uint8Array(buffer_arg)); } // The greeting service definition. var GreeterService = exports.GreeterService = { // Sends a greeting sayHello: { path: '/helloworld.Greeter/SayHello', requestStream: false, responseStream: false, requestType: helloworld_pb.HelloRequest, responseType: helloworld_pb.HelloReply, requestSerialize: serialize_HelloRequest, requestDeserialize: deserialize_HelloRequest, responseSerialize: serialize_HelloReply, responseDeserialize: deserialize_HelloReply, }, }; exports.GreeterClient = grpc.makeGenericClientConstructor(GreeterService);
(function ($) { $.fn.countTo = function (options) { options = options || {}; return $(this).each(function () { // set options for current element var settings = $.extend({}, $.fn.countTo.defaults, { from: $(this).data('from'), to: $(this).data('to'), speed: $(this).data('speed'), refreshInterval: $(this).data('refresh-interval'), decimals: $(this).data('decimals') }, options); // how many times to update the value, and how much to increment the value on each update var loops = Math.ceil(settings.speed / settings.refreshInterval), increment = (settings.to - settings.from) / loops; // references & variables that will change with each update var self = this, $self = $(this), loopCount = 0, value = settings.from, data = $self.data('countTo') || {}; $self.data('countTo', data); // if an existing interval can be found, clear it first if (data.interval) { clearInterval(data.interval); } data.interval = setInterval(updateTimer, settings.refreshInterval); // initialize the element with the starting value render(value); function updateTimer() { value += increment; loopCount++; render(value); if (typeof(settings.onUpdate) == 'function') { settings.onUpdate.call(self, value); } if (loopCount >= loops) { // remove the interval $self.removeData('countTo'); clearInterval(data.interval); value = settings.to; if (typeof(settings.onComplete) == 'function') { settings.onComplete.call(self, value); } } } function render(value) { var formattedValue = settings.formatter.call(self, value, settings); $self.html(formattedValue); } }); }; $.fn.countTo.defaults = { from: 0, // the number the element should start at to: 0, // the number the element should end at speed: 1000, // how long it should take to count between the target numbers refreshInterval: 100, // how often the element should be updated decimals: 0, // the number of decimal places to show formatter: formatter, // handler for formatting the value before rendering onUpdate: null, // callback method for every time the element is updated onComplete: null // callback method for when the element finishes updating }; function formatter(value, settings) { return value.toFixed(settings.decimals); } }(jQuery));
/** * @fileoverview Rule to flag references to undeclared variables. * @author Mark Macdonald */ "use strict"; //------------------------------------------------------------------------------ // Helpers //------------------------------------------------------------------------------ /** * Checks if the given node is the argument of a typeof operator. * @param {ASTNode} node The AST node being checked. * @returns {boolean} Whether or not the node is the argument of a typeof operator. */ function hasTypeOfOperator(node) { const parent = node.parent; return parent.type === "UnaryExpression" && parent.operator === "typeof"; } //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = { meta: { docs: { description: "disallow the use of undeclared variables unless mentioned in `/*global */` comments", category: "Variables", recommended: true }, schema: [ { type: "object", properties: { typeof: { type: "boolean" } }, additionalProperties: false } ] }, create(context) { const options = context.options[0]; const considerTypeOf = options && options.typeof === true || false; return { "Program:exit"(/* node */) { const globalScope = context.getScope(); globalScope.through.forEach(function(ref) { const identifier = ref.identifier; if (!considerTypeOf && hasTypeOfOperator(identifier)) { return; } context.report({ node: identifier, message: "'{{name}}' is not defined.", data: identifier }); }); } }; } };
/** * JavaScript routines for Krumo * * @version $Id: krumo.js,v 1.1.2.2 2008/06/03 20:36:03 weitzman Exp $ * @link http://sourceforge.net/projects/krumo */ ///////////////////////////////////////////////////////////////////////////// /** * Krumo JS Class */ function krumo() { } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Add a CSS class to an HTML element * * @param HtmlElement el * @param string className * @return void */ krumo.reclass = function(el, className) { if (el.className.indexOf(className) < 0) { el.className += (' ' + className); } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Remove a CSS class to an HTML element * * @param HtmlElement el * @param string className * @return void */ krumo.unclass = function(el, className) { if (el.className.indexOf(className) > -1) { el.className = el.className.replace(className, ''); } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Toggle the nodes connected to an HTML element * * @param HtmlElement el * @return void */ krumo.toggle = function(el) { var ul = el.parentNode.getElementsByTagName('ul'); for (var i=0; i<ul.length; i++) { if (ul[i].parentNode.parentNode == el.parentNode) { ul[i].parentNode.style.display = (ul[i].parentNode.style.display == 'none') ? 'block' : 'none'; } } // toggle class // if (ul[0].parentNode.style.display == 'block') { krumo.reclass(el, 'krumo-opened'); } else { krumo.unclass(el, 'krumo-opened'); } } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Hover over an HTML element * * @param HtmlElement el * @return void */ krumo.over = function(el) { krumo.reclass(el, 'krumo-hover'); } // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- /** * Hover out an HTML element * * @param HtmlElement el * @return void */ krumo.out = function(el) { krumo.unclass(el, 'krumo-hover'); } /////////////////////////////////////////////////////////////////////////////
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory() : typeof define === 'function' && define.amd ? define(factory) : (factory()); }(this, (function () { 'use strict'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ Zone.__load_patch('RTCPeerConnection', function (global, Zone, api) { var RTCPeerConnection = global['RTCPeerConnection']; if (!RTCPeerConnection) { return; } var addSymbol = api.symbol('addEventListener'); var removeSymbol = api.symbol('removeEventListener'); RTCPeerConnection.prototype.addEventListener = RTCPeerConnection.prototype[addSymbol]; RTCPeerConnection.prototype.removeEventListener = RTCPeerConnection.prototype[removeSymbol]; // RTCPeerConnection extends EventTarget, so we must clear the symbol // to allow pathc RTCPeerConnection.prototype.addEventListener again RTCPeerConnection.prototype[addSymbol] = null; RTCPeerConnection.prototype[removeSymbol] = null; api.patchEventTarget(global, [RTCPeerConnection.prototype], { useGlobalCallback: false }); }); })));
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ gTestsubsuite = 'Exceptions';
//// [tsxElementResolution.tsx] declare namespace JSX { interface IntrinsicElements { foundFirst: { x: string }; 'string_named'; 'var'; } } class foundFirst { } class Other {} module Dotted { export class Name { } } // Should find the intrinsic element, not the class element var a = <foundFirst x="hello" />; var b = <string_named />; // TODO: This should not be a parse error (should // parse a property name here, not identifier) // var c = <var />; var d = <Other />; var e = <Dotted.Name />; //// [tsxElementResolution.jsx] var foundFirst = (function () { function foundFirst() { } return foundFirst; })(); var Other = (function () { function Other() { } return Other; })(); var Dotted; (function (Dotted) { var Name = (function () { function Name() { } return Name; })(); Dotted.Name = Name; })(Dotted || (Dotted = {})); // Should find the intrinsic element, not the class element var a = <foundFirst x="hello"/>; var b = <string_named />; // TODO: This should not be a parse error (should // parse a property name here, not identifier) // var c = <var />; var d = <Other />; var e = <Dotted.Name />;
/** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import StyleSheet from '../StyleSheet'; import View from '../View'; import React, { createContext } from 'react'; var RootTagContext = createContext(null); export default function AppContainer(props) { var children = props.children, WrapperComponent = props.WrapperComponent; var innerView = React.createElement(View, { children: children, key: 1, pointerEvents: "box-none", style: styles.appContainer }); if (WrapperComponent) { innerView = React.createElement(WrapperComponent, null, innerView); } return React.createElement(RootTagContext.Provider, { value: props.rootTag }, React.createElement(View, { pointerEvents: "box-none", style: styles.appContainer }, innerView)); } var styles = StyleSheet.create({ appContainer: { flex: 1 } });
var assert = require('assert'); module.exports = function() {}; module.exports.prototype = { configure: function(requireLineFeedAtFileEnd) { assert( typeof requireLineFeedAtFileEnd === 'boolean', 'requireLineFeedAtFileEnd option requires boolean value' ); assert( requireLineFeedAtFileEnd === true, 'requireLineFeedAtFileEnd option requires true value or should be removed' ); }, getOptionName: function() { return 'requireLineFeedAtFileEnd'; }, check: function(file, errors) { var lines = file.getLines(); if (lines[lines.length - 1] !== '') { errors.add('Missing line feed at file end', lines.length, 0); } } };
'use strict'; /** * Class representing an event. * * @private */ class Event { /** * Create a new `Event`. * * @param {String} type The name of the event * @param {Object} target A reference to the target to which the event was dispatched */ constructor(type, target) { this.target = target; this.type = type; } } /** * Class representing a message event. * * @extends Event * @private */ class MessageEvent extends Event { /** * Create a new `MessageEvent`. * * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(data, target) { super('message', target); this.data = data; } } /** * Class representing a close event. * * @extends Event * @private */ class CloseEvent extends Event { /** * Create a new `CloseEvent`. * * @param {Number} code The status code explaining why the connection is being closed * @param {String} reason A human-readable string explaining why the connection is closing * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(code, reason, target) { super('close', target); this.wasClean = target._closeFrameReceived && target._closeFrameSent; this.reason = reason; this.code = code; } } /** * Class representing an open event. * * @extends Event * @private */ class OpenEvent extends Event { /** * Create a new `OpenEvent`. * * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(target) { super('open', target); } } /** * Class representing an error event. * * @extends Event * @private */ class ErrorEvent extends Event { /** * Create a new `ErrorEvent`. * * @param {Object} error The error that generated this event * @param {WebSocket} target A reference to the target to which the event was dispatched */ constructor(error, target) { super('error', target); this.message = error.message; this.error = error; } } /** * This provides methods for emulating the `EventTarget` interface. It's not * meant to be used directly. * * @mixin */ const EventTarget = { /** * Register an event listener. * * @param {String} method A string representing the event type to listen for * @param {Function} listener The listener to add * @public */ addEventListener(method, listener) { if (typeof listener !== 'function') return; function onMessage(data) { listener.call(this, new MessageEvent(data, this)); } function onClose(code, message) { listener.call(this, new CloseEvent(code, message, this)); } function onError(error) { listener.call(this, new ErrorEvent(error, this)); } function onOpen() { listener.call(this, new OpenEvent(this)); } if (method === 'message') { onMessage._listener = listener; this.on(method, onMessage); } else if (method === 'close') { onClose._listener = listener; this.on(method, onClose); } else if (method === 'error') { onError._listener = listener; this.on(method, onError); } else if (method === 'open') { onOpen._listener = listener; this.on(method, onOpen); } else { this.on(method, listener); } }, /** * Remove an event listener. * * @param {String} method A string representing the event type to remove * @param {Function} listener The listener to remove * @public */ removeEventListener(method, listener) { const listeners = this.listeners(method); for (var i = 0; i < listeners.length; i++) { if (listeners[i] === listener || listeners[i]._listener === listener) { this.removeListener(method, listeners[i]); } } } }; module.exports = EventTarget;
/* Flot plugin for automatically redrawing plots as the placeholder resizes. Copyright (c) 2007-2013 IOLA and Ole Laursen. Licensed under the MIT license. It works by listening for changes on the placeholder div (through the jQuery resize event plugin) - if the size changes, it will redraw the plot. There are no options. If you need to disable the plugin for some plots, you can just fix the size of their placeholders. */ /* Inline dependency: * jQuery resize event - v1.1 - 3/14/2010 * http://benalman.com/projects/jquery-resize-plugin/ * * Copyright (c) 2010 "Cowboy" Ben Alman * Dual licensed under the MIT and GPL licenses. * http://benalman.com/about/license/ */(function($,h,c){var a=$([]),e=$.resize=$.extend($.resize,{}),i,k="setTimeout",j="resize",d=j+"-special-event",b="delay",f="throttleWindow";e[b]=250;e[f]=true;$.event.special[j]={setup:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.add(l);$.data(this,d,{w:l.width(),h:l.height()});if(a.length===1){g()}},teardown:function(){if(!e[f]&&this[k]){return false}var l=$(this);a=a.not(l);l.removeData(d);if(!a.length){clearTimeout(i)}},add:function(l){if(!e[f]&&this[k]){return false}var n;function m(s,o,p){var q=$(this),r=$.data(this,d);r.w=o!==c?o:q.width();r.h=p!==c?p:q.height();n.apply(this,arguments)}if($.isFunction(l)){n=l;return m}else{n=l.handler;l.handler=m}}};function g(){i=h[k](function(){a.each(function(){var n=$(this),m=n.width(),l=n.height(),o=$.data(this,d);if(m!==o.w||l!==o.h){n.trigger(j,[o.w=m,o.h=l])}});g()},e[b])}})(jQuery,this); (function(e){function n(e){function t(){var t=e.getPlaceholder();if(t.width()==0||t.height()==0)return;e.resize(),e.setupGrid(),e.draw()}function n(e,n){e.getPlaceholder().resize(t)}function r(e,n){e.getPlaceholder().unbind("resize",t)}e.hooks.bindEvents.push(n),e.hooks.shutdown.push(r)}var t={};e.plot.plugins.push({init:n,options:t,name:"resize",version:"1.0"})})(jQuery);
'use strict'; module.exports = { set: function (v) { this.setProperty('counter-increment', v); }, get: function () { return this.getPropertyValue('counter-increment'); }, enumerable: true };
(function ($) { if(typeof $.metadata == "undefined") throw "jsTree metadata: jQuery metadata plugin not included."; $.extend($.tree.plugins, { "metadata" : { defaults : { attribute : "data" }, callbacks : { check : function(rule, obj, value, tree) { var opts = $.extend(true, {}, $.tree.plugins.metadata.defaults, this.settings.plugins.metadata); if(typeof $(obj).metadata({ type : "attr", name : opts.attribute })[rule] != "undefined") return $(obj).metadata()[rule]; } } } }); })(jQuery);
//console:messageId:refHandle var CONSOLE_ID_MATCHER = /^console:(\d+):(\d+)$/; function ConsoleClient(config, debuggerClient, frontendClient) { this._debuggerClient = debuggerClient; this._frontendClient = frontendClient; } ConsoleClient.prototype.isConsoleId = function(objectId) { return CONSOLE_ID_MATCHER.test(objectId); }; ConsoleClient.prototype.lookupConsoleId = function(objectId, done) { var matchedId = CONSOLE_ID_MATCHER.exec(objectId); var messageId = matchedId[1]; this._debuggerClient.request( 'Console._lookupConsoleId', { messageId: messageId, objectId: matchedId[2] }, function(error, lookupBody, lookupRefs) { if (error) return done(error); Object.keys(lookupRefs).forEach(function(key) { this.convertHandleToConsoleHandle(lookupRefs[key], messageId); }, this); done(null, lookupBody, lookupRefs); }.bind(this) ); }; ConsoleClient.prototype.convertHandleToConsoleHandle = function(ref, messageId) { if (ref.handle !== undefined) { ref.handle = 'console:' + messageId + ':' + ref.handle; } }; exports.ConsoleClient = ConsoleClient;
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "AM", "PM" ], "DAY": [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], "MONTH": [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], "SHORTDAY": [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], "SHORTMONTH": [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], "fullDate": "EEEE, MMMM d, y", "longDate": "MMMM d, y", "medium": "MMM d, y h:mm:ss a", "mediumDate": "MMM d, y", "mediumTime": "h:mm:ss a", "short": "M/d/yy h:mm a", "shortDate": "M/d/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "$", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "\u00a4-", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "en-vg", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;} }); }]);
function warning(){ throw new Error('You must require a mode before requiring anything else.'); } exports.Surface = warning; exports.Path = warning; exports.Shape = warning; exports.Group = warning; exports.ClippingRectangle = warning; exports.Text = warning; exports.setCurrent = function(mode){ for (var key in mode){ exports[key] = mode[key]; } };
/* YUI 3.13.0 (build 508226d) Copyright 2013 Yahoo! Inc. All rights reserved. Licensed under the BSD License. http://yuilibrary.com/license/ */ YUI.add('datasource-arrayschema', function (Y, NAME) { /** * Extends DataSource with schema-parsing on array data. * * @module datasource * @submodule datasource-arrayschema */ /** * Adds schema-parsing to the DataSource Utility. * @class DataSourceArraySchema * @extends Plugin.Base */ var DataSourceArraySchema = function() { DataSourceArraySchema.superclass.constructor.apply(this, arguments); }; Y.mix(DataSourceArraySchema, { /** * The namespace for the plugin. This will be the property on the host which * references the plugin instance. * * @property NS * @type String * @static * @final * @value "schema" */ NS: "schema", /** * Class name. * * @property NAME * @type String * @static * @final * @value "dataSourceArraySchema" */ NAME: "dataSourceArraySchema", ///////////////////////////////////////////////////////////////////////////// // // DataSourceArraySchema Attributes // ///////////////////////////////////////////////////////////////////////////// ATTRS: { schema: { //value: {} } } }); Y.extend(DataSourceArraySchema, Y.Plugin.Base, { /** * Internal init() handler. * * @method initializer * @param config {Object} Config object. * @private */ initializer: function(config) { this.doBefore("_defDataFn", this._beforeDefDataFn); }, /** * Parses raw data into a normalized response. * * @method _beforeDefDataFn * @param tId {Number} Unique transaction ID. * @param request {Object} The request. * @param callback {Object} The callback object with the following properties: * <dl> * <dt>success (Function)</dt> <dd>Success handler.</dd> * <dt>failure (Function)</dt> <dd>Failure handler.</dd> * </dl> * @param data {Object} Raw data. * @protected */ _beforeDefDataFn: function(e) { var data = (Y.DataSource.IO && (this.get("host") instanceof Y.DataSource.IO) && Y.Lang.isString(e.data.responseText)) ? e.data.responseText : e.data, response = Y.DataSchema.Array.apply.call(this, this.get("schema"), data), payload = e.details[0]; // Default if (!response) { response = { meta: {}, results: data }; } payload.response = response; this.get("host").fire("response", payload); return new Y.Do.Halt("DataSourceArraySchema plugin halted _defDataFn"); } }); Y.namespace('Plugin').DataSourceArraySchema = DataSourceArraySchema; }, '3.13.0', {"requires": ["datasource-local", "plugin", "dataschema-array"]});
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * The global object. * @type {!Object} */ const global = this; // TODO(estade): This should be removed and calls replaced with cr.isMac const IS_MAC = /^Mac/.test(navigator.platform); /** * Alias for document.getElementById. * @param {string} id The ID of the element to find. * @return {HTMLElement} The found element or null if not found. */ function $(id) { return document.getElementById(id); } /** * Calls chrome.send with a callback and restores the original afterwards. * @param {string} name The name of the message to send. * @param {!Array} params The parameters to send. * @param {string} callbackName The name of the function that the backend calls. * @param {!Function} The function to call. */ function chromeSend(name, params, callbackName, callback) { var old = global[callbackName]; global[callbackName] = function() { // restore global[callbackName] = old; var args = Array.prototype.slice.call(arguments); return callback.apply(global, args); }; chrome.send(name, params); } /** * Generates a CSS url string. * @param {string} s The URL to generate the CSS url for. * @return {string} The CSS url string. */ function url(s) { // http://www.w3.org/TR/css3-values/#uris // Parentheses, commas, whitespace characters, single quotes (') and double // quotes (") appearing in a URI must be escaped with a backslash var s2 = s.replace(/(\(|\)|\,|\s|\'|\"|\\)/g, '\\$1'); // WebKit has a bug when it comes to URLs that end with \ // https://bugs.webkit.org/show_bug.cgi?id=28885 if (/\\\\$/.test(s2)) { // Add a space to work around the WebKit bug. s2 += ' '; } return 'url("' + s2 + '")'; } /** * Parses query parameters from Location. * @param {string} s The URL to generate the CSS url for. * @return {object} Dictionary containing name value pairs for URL */ function parseQueryParams(location) { var params = {}; var query = unescape(location.search.substring(1)); var vars = query.split("&"); for (var i=0; i < vars.length; i++) { var pair = vars[i].split("="); params[pair[0]] = pair[1]; } return params; } function findAncestorByClass(el, className) { return findAncestor(el, function(el) { if (el.classList) return el.classList.contains(className); return null; }); } /** * Return the first ancestor for which the {@code predicate} returns true. * @param {Node} node The node to check. * @param {function(Node) : boolean} predicate The function that tests the * nodes. * @return {Node} The found ancestor or null if not found. */ function findAncestor(node, predicate) { var last = false; while (node != null && !(last = predicate(node))) { node = node.parentNode; } return last ? node : null; } function swapDomNodes(a, b) { var afterA = a.nextSibling; if (afterA == b) { swapDomNodes(b, a); return; } var aParent = a.parentNode; b.parentNode.replaceChild(a, b); aParent.insertBefore(b, afterA); } // Handle click on a link. If the link points to a chrome: or file: url, then // call into the browser to do the navigation. document.addEventListener('click', function(e) { // Allow preventDefault to work. if (!e.returnValue) return; var el = e.target; if (el.nodeType == Node.ELEMENT_NODE && el.webkitMatchesSelector('A, A *')) { while (el.tagName != 'A') { el = el.parentElement; } if ((el.protocol == 'file:' || el.protocol == 'about:') && (e.button == 0 || e.button == 1)) { chrome.send('navigateToUrl', [ el.href, el.target, e.button, e.altKey, e.ctrlKey, e.metaKey, e.shiftKey ]); e.preventDefault(); } } });
/*! * jQuery QueryBuilder 2.3.0 * Locale: Norwegian (no) * Author: Jna Borup Coyle, github@coyle.dk * Licensed under MIT (http://opensource.org/licenses/MIT) */ (function(root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery', 'query-builder'], factory); } else { factory(root.jQuery); } }(this, function($) { "use strict"; var QueryBuilder = $.fn.queryBuilder; QueryBuilder.regional['no'] = { "__locale": "Norwegian (no)", "__author": "Jna Borup Coyle, github@coyle.dk", "add_rule": "Legg til regel", "add_group": "Legg til gruppe", "delete_rule": "Slett regel", "delete_group": "Slett gruppe", "conditions": { "AND": "OG", "OR": "ELLER" }, "operators": { "equal": "er lik", "not_equal": "er ikke lik", "in": "finnes i", "not_in": "finnes ikke i", "less": "er mindre enn", "less_or_equal": "er mindre eller lik", "greater": "er større enn", "greater_or_equal": "er større eller lik", "begins_with": "begynner med", "not_begins_with": "begynner ikke med", "contains": "inneholder", "not_contains": "inneholder ikke", "ends_with": "slutter med", "not_ends_with": "slutter ikke med", "is_empty": "er tom", "is_not_empty": "er ikke tom", "is_null": "er null", "is_not_null": "er ikke null" } }; QueryBuilder.defaults({ lang_code: 'no' }); }));
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. if (!process.addAsyncListener) require('../index.js'); if (!global.setImmediate) global.setImmediate = setTimeout; var assert = require('assert'); function onAsync0() {} var set = 0; var asyncNoHandleError = { before : function () { set++; }, after : function () { set++; } }; var key = process.addAsyncListener(onAsync0, asyncNoHandleError); setImmediate(function () { return 1; }); process.removeAsyncListener(key); process.on('exit', function () { // calling removeAsyncListener *after* a callback is scheduled // should not affect the handler from responding to the callback assert.equal(set, 2); console.log('ok'); });
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Position */ 'use strict'; var PooledClass = require('react/lib/PooledClass'); var twoArgumentPooler = PooledClass.twoArgumentPooler; /** * Position does not expose methods for construction via an `HTMLDOMElement`, * because it isn't meaningful to construct such a thing without first defining * a frame of reference. * * @param {number} windowStartKey Key that window starts at. * @param {number} windowEndKey Key that window ends at. */ function Position(left, top) { this.left = left; this.top = top; } Position.prototype.destructor = function() { this.left = null; this.top = null; }; PooledClass.addPoolingTo(Position, twoArgumentPooler); module.exports = Position;
//! moment.js locale configuration //! locale : Irish english (en-ie) //! author : Chris Cartlidge : https://github.com/chriscartlidge ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var en_ie = moment.defineLocale('en-ie', { months : 'January_February_March_April_May_June_July_August_September_October_November_December'.split('_'), monthsShort : 'Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec'.split('_'), weekdays : 'Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday'.split('_'), weekdaysShort : 'Sun_Mon_Tue_Wed_Thu_Fri_Sat'.split('_'), weekdaysMin : 'Su_Mo_Tu_We_Th_Fr_Sa'.split('_'), longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD-MM-YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : 'in %s', past : '%s ago', s : 'a few seconds', m : 'a minute', mm : '%d minutes', h : 'an hour', hh : '%d hours', d : 'a day', dd : '%d days', M : 'a month', MM : '%d months', y : 'a year', yy : '%d years' }, ordinalParse: /\d{1,2}(st|nd|rd|th)/, ordinal : function (number) { var b = number % 10, output = (~~(number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return en_ie; }));
;(function ($, window, document, undefined) { var pluginName = 'gray', defaults = {}; function Plugin (element, options) { this.element = element; this.settings = $.extend({}, defaults, options); this._defaults = defaults; this._name = pluginName; this.init(); } Plugin.prototype = { init: function () { // TODO: better feature detection if (this.isIE10() || this.isIE11()) { this.switchImage(); } }, isIE10: function() { return Function('/*@cc_on return document.documentMode===10.0@*/')(); }, isIE11: function() { return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./); }, elementType: function(element) { var type; if (element.prop('tagName') === 'IMG') { type = 'Img'; } else { type = 'Bg'; } return type; }, getComputedStyle: function(element) { var computedStyle = {}, styles = {}; computedStyle = window.getComputedStyle(element, null); for(var i = 0, length = computedStyle.length; i < length; i++) { var prop = computedStyle[i]; var val = computedStyle.getPropertyValue(prop); styles[prop] = val; } return styles; }, extractUrl: function(backgroundImage) { var url, regex; startRegex = /^url\(["']?/; endRegex = /["']?\)$/; url = backgroundImage.replace(startRegex, '') .replace(endRegex, ''); return url; }, positionToNegativeMargin: function(backgroundPosition) { var x, y, margin; x = backgroundPosition.match(/^(-?\d+\S+)/)[0] y = backgroundPosition.match(/\s(-?\d+\S+)$/)[0] margin = 'margin:' + y + ' 0 0 ' + x; return margin; }, getBgSize: function(url, backgroundSize) { var img, ratio, defaultW, w, defaultH, h, size; img = new Image(); img.src = url; // TODO: Break this up or simplify if (backgroundSize !== 'auto' && backgroundSize !== 'cover' && backgroundSize !== 'contain' && backgroundSize !== 'inherit') { var $element = $(this.element); ratio = img.width / img.height; w = parseInt((backgroundSize.match(/^(\d+)px/) || [0,0])[1]); h = parseInt((backgroundSize.match(/\s(\d+)px$/) || [0,0])[1]); defaultW = $element.height() * ratio; defaultH = $element.width() / ratio; w = w || defaultW; h = h || defaultH; } if (w || h) { size = { width: w, height: h } } else { size = { width : img.width, height: img.height }; } return size; }, getParams: function(element) { var type = this.elementType(element); return this['get' + type + 'Params'](element); }, getImgParams: function(element) { var params = {}; params.styles = this.getComputedStyle(element[0]); params.svg = { url : element[0].src, width : params.styles.width.replace('px', ''), height: params.styles.height.replace('px', ''), offset: '' }; return params; }, getBgParams: function(element) { var params = {}, url, position; url = this.extractUrl(element.css('background-image')); bgSize = this.getBgSize(url, element.css('background-size')) offset = this.positionToNegativeMargin(element.css('background-position')); params.styles = this.getComputedStyle(element[0]); params.svg = $.extend( { url : url }, bgSize, { offset: offset } ); return params; }, switchImage: function () { var template, element = $(this.element); params = this.getParams(element); // TODO: use templating or DOM elements here template = $( '<div>' + '<svg xmlns="http://www.w3.org/2000/svg" id="svgroot" viewBox="0 0 '+params.svg.width+' '+params.svg.height+'" width="'+params.svg.width+'" height="'+params.svg.height+'" style="'+params.svg.offset+'">' + '<defs>' + '<filter id="gray">' + '<feComposite in="SourceGraphic" in2="SourceGraphic" operator="arithmetic" k1="0" k2="1" k3="0" k4="0" />' + '<feColorMatrix type="saturate" values="0" />' + '</filter>' + '</defs>' + '<image filter="url(&quot;#gray&quot;)" x="0" y="0" width="'+params.svg.width+'" height="'+params.svg.height+'" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="'+params.svg.url+'" />' + '</svg>' + '</div>'); params.styles['display'] = 'inline-block'; params.styles['overflow'] = params.styles['overflow-x'] = params.styles['overflow-y'] = 'hidden'; // TODO: Should this really set all params or should we set only unique ones by comparing to a control element? template.css(params.styles); element.replaceWith(template); } }; $.fn[pluginName] = function (options) { this.each(function() { if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, 'plugin_' + pluginName, new Plugin(this, options)); } }); return this; }; $(window).on('load', function() { $('.grayscale')[pluginName](); }); })(jQuery, window, document);
CKEDITOR.plugins.setLang("selectall","et",{toolbar:"Kõige valimine"});
(function ($) { /** * Toggle the visibility of a fieldset using smooth animations. */ Drupal.toggleFieldset = function (fieldset) { var $toggle = $($(fieldset).find('[data-toggle=collapse]').data('target')); if ($toggle.length) { $toggle.collapse('toggle'); } }; /** * Scroll a given fieldset into view as much as possible. */ Drupal.collapseScrollIntoView = function (node) { var h = document.documentElement.clientHeight || document.body.clientHeight || 0; var offset = document.documentElement.scrollTop || document.body.scrollTop || 0; var posY = $(node).offset().top; var fudge = 55; if (posY + node.offsetHeight + fudge > h + offset) { if (node.offsetHeight > h) { window.scrollTo(0, posY); } else { window.scrollTo(0, posY + node.offsetHeight - h + fudge); } } }; Drupal.behaviors.collapse = { attach: function (context, settings) { $('fieldset.collapsible', context).once('collapse', function () { var $fieldset = $(this); // Expand fieldset if there are errors inside, or if it contains an // element that is targeted by the URI fragment identifier. var anchor = location.hash && location.hash != '#' ? ', ' + location.hash : ''; if ($fieldset.find('.error' + anchor).length) { $fieldset.removeClass('collapsed'); } var summary = $('<span class="summary"></span>'); $fieldset. bind('summaryUpdated', function () { var text = $.trim($fieldset.drupalGetSummary()); summary.html(text ? ' (' + text + ')' : ''); }) .trigger('summaryUpdated'); // Turn the legend into a clickable link, but retain span.fieldset-legend // for CSS positioning. var $legend = $('> legend .fieldset-legend', this); $('<span class="fieldset-legend-prefix element-invisible"></span>') .append($fieldset.hasClass('collapsed') ? Drupal.t('Show') : Drupal.t('Hide')) .prependTo($legend); $fieldset.find('[data-toggle=collapse]').on('click', function (e) { e.preventDefault(); }); // Bind Bootstrap events with Drupal core events. $fieldset .append(summary) .on('show.bs.collapse', function () { $fieldset .removeClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Hide')); }) .on('shown.bs.collapse', function () { $fieldset.trigger({ type: 'collapsed', value: false }); Drupal.collapseScrollIntoView($fieldset.get(0)); }) .on('hide.bs.collapse', function () { $fieldset .addClass('collapsed') .find('> legend span.fieldset-legend-prefix').html(Drupal.t('Show')); }) .on('hidden.bs.collapse', function () { $fieldset.trigger({ type: 'collapsed', value: true }); }); }); } }; })(jQuery);
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import invariant from 'fbjs/lib/invariant'; var ensurePositiveDelayProps = function ensurePositiveDelayProps(props) { invariant(!(props.delayPressIn < 0 || props.delayPressOut < 0 || props.delayLongPress < 0), 'Touchable components cannot have negative delay properties'); }; export default ensurePositiveDelayProps;
'use strict'; var pify = module.exports = function (fn, P, opts) { if (typeof P !== 'function') { opts = P; P = Promise; } opts = opts || {}; if (typeof fn !== 'function') { return P.reject(new TypeError('Expected a function')); } return function () { var that = this; var args = [].slice.call(arguments); return new P(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else if (opts.multiArgs) { resolve([].slice.call(arguments, 1)); } else { resolve(result); } }); fn.apply(that, args); }); }; }; pify.all = function (obj, P, opts) { if (typeof P !== 'function') { opts = P; P = Promise; } opts = opts || {}; var filter = function (key) { if (opts.include) { return opts.include.indexOf(key) !== -1; } if (opts.exclude) { return opts.exclude.indexOf(key) === -1; } return true; }; var ret = (typeof obj === 'function') ? function () { if (opts.excludeMain) { return obj.apply(this, arguments); } return pify(obj, P, opts).apply(this, arguments); } : {}; return Object.keys(obj).reduce(function (ret, key) { var x = obj[key]; ret[key] = (typeof x === 'function') && filter(key) ? pify(x, P, opts) : x; return ret; }, ret); };
/* eslint-disable */ // adapted based on rackt/history (MIT) // Node 0.10+ var execSync = require('child_process').execSync; var fs = require('fs'); // Node 0.10 check if (!execSync) { execSync = require('sync-exec'); } function exec(command) { execSync(command, { stdio: [0, 1, 2] }); } fs.stat('dist', function(error, stat) { // Skip building on Travis if (process.env.TRAVIS) { return; } if (error || !stat.isDirectory()) { // Create a directory to avoid getting stuck // in postinstall loop fs.mkdirSync('dist'); exec('npm install --only=dev'); exec('npm run build'); } });
/* Copyright (c) 2012, Yahoo! Inc. All rights reserved. Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms. */ var fileset = require('fileset'), path = require('path'), seq = 0; function filesFor(options, callback) { if (!callback && typeof options === 'function') { callback = options; options = null; } options = options || {}; var root = options.root, includes = options.includes, excludes = options.excludes, relative = options.relative, opts; root = root || process.cwd(); includes = includes && Array.isArray(includes) ? includes : [ '**/*.js' ]; excludes = excludes && Array.isArray(excludes) ? excludes : [ '**/node_modules/**' ]; opts = { cwd: root }; seq += 1; opts['x' + seq + new Date().getTime()] = true; //cache buster for minimatch cache bug fileset(includes.join(' '), excludes.join(' '), opts, function (err, files) { if (err) { return callback(err); } if (!relative) { files = files.map(function (file) { return path.resolve(root, file); }); } callback(err, files); }); } function matcherFor(options, callback) { if (!callback && typeof options === 'function') { callback = options; options = null; } options = options || {}; options.relative = false; //force absolute paths filesFor(options, function (err, files) { var fileMap = {}, matchFn; if (err) { return callback(err); } files.forEach(function (file) { fileMap[file] = true; }); matchFn = function (file) { return fileMap[file]; }; matchFn.files = Object.keys(fileMap); return callback(null, matchFn); }); } module.exports = { filesFor: filesFor, matcherFor: matcherFor };
var argscheck = require('cordova/argscheck'), utils = require('cordova/utils'), exec = require('cordova/exec'), channel = require('cordova/channel'); var Keyboard = function() { }; Keyboard.hideKeyboardAccessoryBar = function(hide) { exec(null, null, "Keyboard", "hideKeyboardAccessoryBar", [hide]); }; Keyboard.close = function() { exec(null, null, "Keyboard", "close", []); }; Keyboard.show = function() { exec(null, null, "Keyboard", "show", []); }; Keyboard.disableScroll = function(disable) { exec(null, null, "Keyboard", "disableScroll", [disable]); }; /* Keyboard.styleDark = function(dark) { exec(null, null, "Keyboard", "styleDark", [dark]); }; */ Keyboard.isVisible = false; channel.onCordovaReady.subscribe(function() { exec(success, null, 'Keyboard', 'init', []); function success(msg) { var action = msg.charAt(0); if ( action === 'S' ) { var keyboardHeight = msg.substr(1); cordova.plugins.Keyboard.isVisible = true; cordova.fireWindowEvent('native.keyboardshow', { 'keyboardHeight': + keyboardHeight }); //deprecated cordova.fireWindowEvent('native.showkeyboard', { 'keyboardHeight': + keyboardHeight }); } else if ( action === 'H' ) { cordova.plugins.Keyboard.isVisible = false; cordova.fireWindowEvent('native.keyboardhide'); //deprecated cordova.fireWindowEvent('native.hidekeyboard'); } } }); module.exports = Keyboard;
var m1_a1 = 10; var m1_c1 = (function () { function m1_c1() { } return m1_c1; })(); var m1_instance1 = new m1_c1(); function m1_f1() { return m1_instance1; } //# sourceMappingURL=m1.js.map
import * as t from "babel-types"; import * as util from "./util"; // this function converts a shorthand object generator method into a normal // (non-shorthand) object property which is a generator function expression. for // example, this: // // var foo = { // *bar(baz) { return 5; } // } // // should be replaced with: // // var foo = { // bar: function*(baz) { return 5; } // } // // to do this, it clones the parameter array and the body of the object generator // method into a new FunctionExpression. // // this method can be passed any Function AST node path, and it will return // either: // a) the path that was passed in (iff the path did not need to be replaced) or // b) the path of the new FunctionExpression that was created as a replacement // (iff the path did need to be replaced) // // In either case, though, the caller can count on the fact that the return value // is a Function AST node path. // // If this function is called with an AST node path that is not a Function (or with an // argument that isn't an AST node path), it will throw an error. export default function replaceShorthandObjectMethod(path) { if (!path.node || !t.isFunction(path.node)) { throw new Error("replaceShorthandObjectMethod can only be called on Function AST node paths."); } // this function only replaces shorthand object methods (called ObjectMethod // in Babel-speak). if (!t.isObjectMethod(path.node)) { return path; } // this function only replaces generators. if (!path.node.generator) { return path; } const parameters = path.node.params.map(function (param) { return t.cloneDeep(param); }) const functionExpression = t.functionExpression( null, // id parameters, // params t.cloneDeep(path.node.body), // body path.node.generator, path.node.async ); util.replaceWithOrRemove(path, t.objectProperty( t.cloneDeep(path.node.key), // key functionExpression, //value path.node.computed, // computed false // shorthand ) ); // path now refers to the ObjectProperty AST node path, but we want to return a // Function AST node path for the function expression we created. we know that // the FunctionExpression we just created is the value of the ObjectProperty, // so return the "value" path off of this path. return path.get("value"); }
define(function (require) { var a = require('a'); return { name: 'c', aName: a.name }; });
ace.define('ace/snippets/ada', ['require', 'exports', 'module' ], function(require, exports, module) { exports.snippetText = ""; exports.scope = "ada"; });
define([ "../Data" ], function( Data ) { return new Data(); });
//>>built define("dojox/lang/functional/curry",["dijit","dojo","dojox","dojo/require!dojox/lang/functional/lambda"],function(_1,_2,_3){ _2.provide("dojox.lang.functional.curry"); _2.require("dojox.lang.functional.lambda"); (function(){ var df=_3.lang.functional,ap=Array.prototype; var _4=function(_5){ return function(){ var _6=_5.args.concat(ap.slice.call(arguments,0)); if(arguments.length+_5.args.length<_5.arity){ return _4({func:_5.func,arity:_5.arity,args:_6}); } return _5.func.apply(this,_6); }; }; _2.mixin(df,{curry:function(f,_7){ f=df.lambda(f); _7=typeof _7=="number"?_7:f.length; return _4({func:f,arity:_7,args:[]}); },arg:{},partial:function(f){ var a=arguments,l=a.length,_8=new Array(l-1),p=[],i=1,t; f=df.lambda(f); for(;i<l;++i){ t=a[i]; _8[i-1]=t; if(t===df.arg){ p.push(i-1); } } return function(){ var t=ap.slice.call(_8,0),i=0,l=p.length; for(;i<l;++i){ t[p[i]]=arguments[i]; } return f.apply(this,t); }; },mixer:function(f,_9){ f=df.lambda(f); return function(){ var t=new Array(_9.length),i=0,l=_9.length; for(;i<l;++i){ t[i]=arguments[_9[i]]; } return f.apply(this,t); }; },flip:function(f){ f=df.lambda(f); return function(){ var a=arguments,l=a.length-1,t=new Array(l+1),i=0; for(;i<=l;++i){ t[l-i]=a[i]; } return f.apply(this,t); }; }}); })(); });
/** * Test the side menu directive. For more test coverage of the side menu, * see the core Ionic sideMenu controller tests. */ describe('Ionic Angular Slide Box', function() { var el, compile, rootScope, timeout; beforeEach(module('ionic')); beforeEach(inject(function($compile, $rootScope, $timeout) { timeout = $timeout; rootScope = $rootScope; compile = $compile; el = $compile('<ion-slide-box>' + '<ion-slide>' + '<div class="box blue">' + '<h1>BLUE {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box yellow">' + '<h1>YELLOW {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box pink"><h1>PINK {{slideBox.slideIndex}}</h1></div>' + '</ion-slide>' + '</ion-slide-box>')($rootScope); })); it('should register with $ionicSlideBoxDelegate', inject(function($compile, $rootScope, $ionicSlideBoxDelegate) { var deregisterSpy = jasmine.createSpy('deregister'); spyOn($ionicSlideBoxDelegate, '_registerInstance').andCallFake(function() { return deregisterSpy; }); var el = $compile('<ion-slide-box delegate-handle="superHandle">')($rootScope.$new()); $rootScope.$apply(); expect($ionicSlideBoxDelegate._registerInstance) .toHaveBeenCalledWith(el.controller('ionSlideBox').__slider, 'superHandle', jasmine.any(Function)); expect(deregisterSpy).not.toHaveBeenCalled(); el.scope().$destroy(); expect(deregisterSpy).toHaveBeenCalled(); })); }); describe('ionSlideBox with active slide', function() { beforeEach(module('ionic')); it('Should set initial active slide', inject(function($ionicSlideBoxDelegate, $rootScope, $compile) { el = $compile('<ion-slide-box active-slide="2">' + '<ion-slide>' + '<div class="box blue">' + '<h1>BLUE {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box yellow">' + '<h1>YELLOW {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box pink"><h1>PINK {{slideBox.slideIndex}}</h1></div>' + '</ion-slide>' + '</ion-slide-box>')($rootScope.$new()); var scope = el.scope(); scope.$apply(); expect($ionicSlideBoxDelegate.currentIndex()).toBe(2); })); it('Should create and show pager unless told not to', inject(function($rootScope, $compile, $timeout) { el = $compile('<ion-slide-box>' + '<ion-slide>' + '<div class="box blue">' + '<h1>BLUE {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box yellow">' + '<h1>YELLOW {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '</ion-slide-box>')($rootScope.$new()); var scope = el.scope(); scope.$apply(); expect(el.find('.slider-pager').length).toBe(1); expect(el.find('.slider-pager.hide').length).toBe(0); })); it('Should create and show pager unless told not to', inject(function($rootScope, $compile, $timeout) { el = $compile('<ion-slide-box show-pager="false">' + '<ion-slide>' + '<div class="box blue">' + '<h1>BLUE {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '<ion-slide>' + '<div class="box yellow">' + '<h1>YELLOW {{slideBox.slideIndex}}</h1>' + '</div>' + '</ion-slide>' + '</ion-slide-box>')($rootScope.$new()); var scope = el.scope(); scope.$apply(); expect(el.find('.slider-pager.hide').length).toBe(1); })); });
// moment.js locale configuration // locale : uzbek (uz) // author : Sardor Muminov : https://github.com/muminoff (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.defineLocale('uz', { months : "январь_февраль_март_апрель_май_июнь_июль_август_сентябрь_октябрь_ноябрь_декабрь".split("_"), monthsShort : "янв_фев_мар_апр_май_июн_июл_авг_сен_окт_ноя_дек".split("_"), weekdays : "Якшанба_Душанба_Сешанба_Чоршанба_Пайшанба_Жума_Шанба".split("_"), weekdaysShort : "Якш_Душ_Сеш_Чор_Пай_Жум_Шан".split("_"), weekdaysMin : "Як_Ду_Се_Чо_Па_Жу_Ша".split("_"), longDateFormat : { LT : "HH:mm", L : "DD/MM/YYYY", LL : "D MMMM YYYY", LLL : "D MMMM YYYY LT", LLLL : "D MMMM YYYY, dddd LT" }, calendar : { sameDay : '[Бугун соат] LT [да]', nextDay : '[Эртага] LT [да]', nextWeek : 'dddd [куни соат] LT [да]', lastDay : '[Кеча соат] LT [да]', lastWeek : '[Утган] dddd [куни соат] LT [да]', sameElse : 'L' }, relativeTime : { future : "Якин %s ичида", past : "Бир неча %s олдин", s : "фурсат", m : "бир дакика", mm : "%d дакика", h : "бир соат", hh : "%d соат", d : "бир кун", dd : "%d кун", M : "бир ой", MM : "%d ой", y : "бир йил", yy : "%d йил" }, week : { dow : 1, // Monday is the first day of the week. doy : 7 // The week that contains Jan 4th is the first week of the year. } }); }));
"use strict"; var _classCallCheck = require("babel-runtime/helpers/class-call-check")["default"]; var _interopRequireDefault = require("babel-runtime/helpers/interop-require-default")["default"]; var _interopRequireWildcard = require("babel-runtime/helpers/interop-require-wildcard")["default"]; exports.__esModule = true; var _binding = require("../binding"); var _binding2 = _interopRequireDefault(_binding); var _babelTypes = require("babel-types"); var t = _interopRequireWildcard(_babelTypes); var renameVisitor = { ReferencedIdentifier: function ReferencedIdentifier(_ref, state) { var node = _ref.node; if (node.name === state.oldName) { node.name = state.newName; } }, Scope: function Scope(path, state) { if (!path.scope.bindingIdentifierEquals(state.oldName, state.binding.identifier)) { path.skip(); } }, "AssignmentExpression|Declaration": function AssignmentExpressionDeclaration(path, state) { var ids = path.getOuterBindingIdentifiers(); for (var _name in ids) { if (_name === state.oldName) ids[_name].name = state.newName; } } }; var Renamer = (function () { function Renamer(binding, oldName, newName) { _classCallCheck(this, Renamer); this.newName = newName; this.oldName = oldName; this.binding = binding; } Renamer.prototype.maybeConvertFromExportDeclaration = function maybeConvertFromExportDeclaration(parentDeclar) { var exportDeclar = parentDeclar.parentPath.isExportDeclaration() && parentDeclar.parentPath; if (!exportDeclar) return; // build specifiers that point back to this export declaration var isDefault = exportDeclar.isExportDefaultDeclaration(); if (isDefault && (parentDeclar.isFunctionDeclaration() || parentDeclar.isClassDeclaration()) && !parentDeclar.node.id) { // Ensure that default class and function exports have a name so they have a identifier to // reference from the export specifier list. parentDeclar.node.id = parentDeclar.scope.generateUidIdentifier("default"); } var bindingIdentifiers = parentDeclar.getOuterBindingIdentifiers(); var specifiers = []; for (var _name2 in bindingIdentifiers) { var localName = _name2 === this.oldName ? this.newName : _name2; var exportedName = isDefault ? "default" : _name2; specifiers.push(t.exportSpecifier(t.identifier(localName), t.identifier(exportedName))); } var aliasDeclar = t.exportNamedDeclaration(null, specifiers); // hoist to the top if it's a function if (parentDeclar.isFunctionDeclaration()) { aliasDeclar._blockHoist = 3; } exportDeclar.insertAfter(aliasDeclar); exportDeclar.replaceWith(parentDeclar.node); }; Renamer.prototype.maybeConvertFromClassFunctionDeclaration = function maybeConvertFromClassFunctionDeclaration(path) { return; // TODO // retain the `name` of a class/function declaration if (!path.isFunctionDeclaration() && !path.isClassDeclaration()) return; if (this.binding.kind !== "hoisted") return; path.node.id = t.identifier(this.oldName); path.node._blockHoist = 3; path.replaceWith(t.variableDeclaration("let", [t.variableDeclarator(t.identifier(this.newName), t.toExpression(path.node))])); }; Renamer.prototype.maybeConvertFromClassFunctionExpression = function maybeConvertFromClassFunctionExpression(path) { return; // TODO // retain the `name` of a class/function expression if (!path.isFunctionExpression() && !path.isClassExpression()) return; if (this.binding.kind !== "local") return; path.node.id = t.identifier(this.oldName); this.binding.scope.parent.push({ id: t.identifier(this.newName) }); path.replaceWith(t.assignmentExpression("=", t.identifier(this.newName), path.node)); }; Renamer.prototype.rename = function rename(block) { var binding = this.binding; var oldName = this.oldName; var newName = this.newName; var scope = binding.scope; var path = binding.path; var parentDeclar = path.find(function (path) { return path.isDeclaration() || path.isFunctionExpression(); }); if (parentDeclar) { this.maybeConvertFromExportDeclaration(parentDeclar); } scope.traverse(block || scope.block, renameVisitor, this); if (!block) { scope.removeOwnBinding(oldName); scope.bindings[newName] = binding; this.binding.identifier.name = newName; } if (binding.type === "hoisted") { // https://github.com/babel/babel/issues/2435 // todo: hoist and convert function to a let } if (parentDeclar) { this.maybeConvertFromClassFunctionDeclaration(parentDeclar); this.maybeConvertFromClassFunctionExpression(parentDeclar); } }; return Renamer; })(); exports["default"] = Renamer; module.exports = exports["default"];
/** * ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v4.1.1 * @link http://www.ag-grid.com/ * @license MIT */
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ "use strict"; var ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin"); class ExternalsPlugin { constructor(type, externals) { this.type = type; this.externals = externals; } apply(compiler) { compiler.plugin("compile", (params) => { params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals)); }); } } module.exports = ExternalsPlugin;
// Validation errors messages for Parsley // Load this after Parsley Parsley.addMessages('sv', { dateiso: "Ange ett giltigt datum (ÅÅÅÅ-MM-DD)." });
/** * Tag-closer extension for CodeMirror. * * This extension adds an "autoCloseTags" option that can be set to * either true to get the default behavior, or an object to further * configure its behavior. * * These are supported options: * * `whenClosing` (default true) * Whether to autoclose when the '/' of a closing tag is typed. * `whenOpening` (default true) * Whether to autoclose the tag when the final '>' of an opening * tag is typed. * `dontCloseTags` (default is empty tags for HTML, none for XML) * An array of tag names that should not be autoclosed. * `indentTags` (default is block tags for HTML, none for XML) * An array of tag names that should, when opened, cause a * blank line to be added inside the tag, and the blank line and * closing line to be indented. * * See demos/closetag.html for a usage example. */ (function() { CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) { if (val && (old == CodeMirror.Init || !old)) { var map = {name: "autoCloseTags"}; if (typeof val != "object" || val.whenClosing) map["'/'"] = function(cm) { autoCloseTag(cm, '/'); }; if (typeof val != "object" || val.whenOpening) map["'>'"] = function(cm) { autoCloseTag(cm, '>'); }; cm.addKeyMap(map); } else if (!val && (old != CodeMirror.Init && old)) { cm.removeKeyMap("autoCloseTags"); } }); var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]; var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4", "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"]; function autoCloseTag(cm, ch) { var pos = cm.getCursor(), tok = cm.getTokenAt(pos); var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state; if (inner.mode.name != "xml") throw CodeMirror.Pass; var opt = cm.getOption("autoCloseTags"), html = inner.mode.configuration == "html"; var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose); var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent); if (ch == ">" && state.tagName) { var tagName = state.tagName; if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch); var lowerTagName = tagName.toLowerCase(); // Don't process the '>' at the end of an end-tag or self-closing tag if (tok.type == "tag" && state.type == "closeTag" || /\/\s*$/.test(tok.string) || dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1) throw CodeMirror.Pass; var doIndent = indentTags && indexOf(indentTags, lowerTagName) > -1; cm.replaceSelection(">" + (doIndent ? "\n\n" : "") + "</" + tagName + ">", doIndent ? {line: pos.line + 1, ch: 0} : {line: pos.line, ch: pos.ch + 1}); if (doIndent) { cm.indentLine(pos.line + 1); cm.indentLine(pos.line + 2); } return; } else if (ch == "/" && tok.type == "tag" && tok.string == "<") { var tagName = state.context && state.context.tagName; if (tagName) cm.replaceSelection("/" + tagName + ">", "end"); return; } throw CodeMirror.Pass; } function indexOf(collection, elt) { if (collection.indexOf) return collection.indexOf(elt); for (var i = 0, e = collection.length; i < e; ++i) if (collection[i] == elt) return i; return -1; } })();
/*! * classie - class helper functions * from bonzo https://github.com/ded/bonzo * * classie.has( elem, 'my-class' ) -> true/false * classie.add( elem, 'my-new-class' ) * classie.remove( elem, 'my-unwanted-class' ) */ /*jshint browser: true, strict: true, undef: true */ ( function( window ) { 'use strict'; // class helper functions from bonzo https://github.com/ded/bonzo function classReg( className ) { return new RegExp("(^|\\s+)" + className + "(\\s+|$)"); } // classList support for class management // altho to be fair, the api sucks because it won't accept multiple classes at once var hasClass, addClass, removeClass; if ( 'classList' in document.documentElement ) { hasClass = function( elem, c ) { return elem.classList.contains( c ); }; addClass = function( elem, c ) { elem.classList.add( c ); }; removeClass = function( elem, c ) { elem.classList.remove( c ); }; } else { hasClass = function( elem, c ) { return classReg( c ).test( elem.className ); }; addClass = function( elem, c ) { if ( !hasClass( elem, c ) ) { elem.className = elem.className + ' ' + c; } }; removeClass = function( elem, c ) { elem.className = elem.className.replace( classReg( c ), ' ' ); }; } window.classie = { // full names hasClass: hasClass, addClass: addClass, removeClass: removeClass, // short names has: hasClass, add: addClass, remove: removeClass }; })( window );
var castSlice = require('./_castSlice'), charsEndIndex = require('./_charsEndIndex'), charsStartIndex = require('./_charsStartIndex'), stringToArray = require('./_stringToArray'), toString = require('./toString'); /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** * Removes leading and trailing whitespace or specified characters from `string`. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to trim. * @param {string} [chars=whitespace] The characters to trim. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {string} Returns the trimmed string. * @example * * _.trim(' abc '); * // => 'abc' * * _.trim('-_-abc-_-', '_-'); * // => 'abc' * * _.map([' foo ', ' bar '], _.trim); * // => ['foo', 'bar'] */ function trim(string, chars, guard) { string = toString(string); if (!string) { return string; } if (guard || chars === undefined) { return string.replace(reTrim, ''); } if (!(chars += '')) { return string; } var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; return castSlice(strSymbols, start, end).join(''); } module.exports = trim;
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 Error(sequenceContainsNoElements)); } else { o.onNext(value); o.onCompleted(); } }); }, source); }
define({ name: 'prototype' });
/** * @license AngularJS v1.3.0-beta.11 * (c) 2010-2014 Google, Inc. http://angularjs.org * License: MIT */ (function(window, angular, undefined) {'use strict'; /** * @ngdoc module * @name ngCookies * @description * * # ngCookies * * The `ngCookies` module provides a convenient wrapper for reading and writing browser cookies. * * * <div doc-module-components="ngCookies"></div> * * See {@link ngCookies.$cookies `$cookies`} and * {@link ngCookies.$cookieStore `$cookieStore`} for usage. */ angular.module('ngCookies', ['ng']). /** * @ngdoc service * @name $cookies * * @description * Provides read/write access to browser's cookies. * * Only a simple Object is exposed and by adding or removing properties to/from this object, new * cookies are created/deleted at the end of current $eval. * The object's properties can only be strings. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * function ExampleController($cookies) { * // Retrieving a cookie * var favoriteCookie = $cookies.myFavorite; * // Setting a cookie * $cookies.myFavorite = 'oatmeal'; * } * ``` */ factory('$cookies', ['$rootScope', '$browser', function ($rootScope, $browser) { var cookies = {}, lastCookies = {}, lastBrowserCookies, runEval = false, copy = angular.copy, isUndefined = angular.isUndefined; //creates a poller fn that copies all cookies from the $browser to service & inits the service $browser.addPollFn(function() { var currentCookies = $browser.cookies(); if (lastBrowserCookies != currentCookies) { //relies on browser.cookies() impl lastBrowserCookies = currentCookies; copy(currentCookies, lastCookies); copy(currentCookies, cookies); if (runEval) $rootScope.$apply(); } })(); runEval = true; //at the end of each eval, push cookies //TODO: this should happen before the "delayed" watches fire, because if some cookies are not // strings or browser refuses to store some cookies, we update the model in the push fn. $rootScope.$watch(push); return cookies; /** * Pushes all the cookies from the service to the browser and verifies if all cookies were * stored. */ function push() { var name, value, browserCookies, updated; //delete any cookies deleted in $cookies for (name in lastCookies) { if (isUndefined(cookies[name])) { $browser.cookies(name, undefined); } } //update all cookies updated in $cookies for(name in cookies) { value = cookies[name]; if (!angular.isString(value)) { value = '' + value; cookies[name] = value; } if (value !== lastCookies[name]) { $browser.cookies(name, value); updated = true; } } //verify what was actually stored if (updated){ updated = false; browserCookies = $browser.cookies(); for (name in cookies) { if (cookies[name] !== browserCookies[name]) { //delete or reset all cookies that the browser dropped from $cookies if (isUndefined(browserCookies[name])) { delete cookies[name]; } else { cookies[name] = browserCookies[name]; } updated = true; } } } } }]). /** * @ngdoc service * @name $cookieStore * @requires $cookies * * @description * Provides a key-value (string-object) storage, that is backed by session cookies. * Objects put or retrieved from this storage are automatically serialized or * deserialized by angular's toJson/fromJson. * * Requires the {@link ngCookies `ngCookies`} module to be installed. * * @example * * ```js * function ExampleController($cookieStore) { * // Put cookie * $cookieStore.put('myFavorite','oatmeal'); * // Get cookie * var favoriteCookie = $cookieStore.get('myFavorite'); * // Removing a cookie * $cookieStore.remove('myFavorite'); * } * ``` */ factory('$cookieStore', ['$cookies', function($cookies) { return { /** * @ngdoc method * @name $cookieStore#get * * @description * Returns the value of given cookie key * * @param {string} key Id to use for lookup. * @returns {Object} Deserialized cookie value. */ get: function(key) { var value = $cookies[key]; return value ? angular.fromJson(value) : value; }, /** * @ngdoc method * @name $cookieStore#put * * @description * Sets a value for given cookie key * * @param {string} key Id for the `value`. * @param {Object} value Value to be stored. */ put: function(key, value) { $cookies[key] = angular.toJson(value); }, /** * @ngdoc method * @name $cookieStore#remove * * @description * Remove given cookie * * @param {string} key Id of the key-value pair to delete. */ remove: function(key) { delete $cookies[key]; } }; }]); })(window, window.angular);
"use strict"; import assert from "assert"; import sinon from "sinon"; import testPlease from "../helpers/testPlease"; import { genericDouble } from "../helpers/doubles"; import * as JobsActionCreators from "../../../src/js/actions/JobsActionCreators"; import * as JobItemsActionCreators from "../../../src/js/actions/JobItemsActionCreators"; import * as ProductActionCreators from "../../../src/js/actions/ProductActionCreators"; import * as SharedActionCreators from "../../../src/js/actions/SharedActionCreators"; import * as JobsAPI from "../../../src/js/api/JobsAPI"; const toTest = [ { fn: "startLoading", type: "IS_LOADING", give: [], desc: "no data" }, { fn: "changeItem", type: "CHANGE_SINGLE_JOB_ITEM", give: [{item: "newItem"}], want: {item: "newItem"}, desc: "a new job item" }, { fn: "changeDetails", type: "CHANGE_SINGLE_JOB_DETAILS", give: [{details: "newDetails"}], want: {details: "newDetails"}, desc: "a new job details" }, { fn: "sortBy", type: "SORT_ONE", give: ["doctor"], want: "doctor", desc: "a sort string" }, { fn: "setCurrentY", type: "SET_CURRENT_Y", give: [158], want: 158, desc: "a new y position" }, { fn: "setTableHeight", type: "SET_TABLE_HEIGHT", give: [450], want: 450, desc: "a new table height" } ]; describe("SharedActionCreators", () => { describe(".externalSortBy", () => { let result, sortStub, jSpy, jiSpy, pSpy; before(() => { sortStub = sinon.stub(JobsAPI, "getSortedThings", (r, f, d) => { result = [r, f, d]; }); jSpy = sinon.spy(JobsActionCreators, "sortBy"); jiSpy = sinon.spy(JobItemsActionCreators, "sortBy"); pSpy = sinon.spy(ProductActionCreators, "sortBy"); }); after(() => { [sortStub, jSpy, jiSpy, pSpy].forEach(e => e.restore()); }); it("#calls the relevant sortBy action creator", () => { SharedActionCreators.externalSortBy("jobs", "dawg", false); assert(jSpy.called); assert.deepEqual(jSpy.firstCall.args, ["dawg"]); SharedActionCreators.externalSortBy("items", "caht", true); assert(jSpy.called); assert.deepEqual(jiSpy.firstCall.args, ["caht"]); SharedActionCreators.externalSortBy("products", "forks", false); assert(pSpy.called); assert.deepEqual(pSpy.firstCall.args, ["forks"]); }); it("#calls JobsAPI.getSortedThings with the endpoint," + " sort field and sort direction, defaulting to false", () => { const args1 = ["items", "chickens", false]; const args2 = ["jobs", "frogs", true]; SharedActionCreators.externalSortBy(args1[0], args1[1], args1[2]); assert.deepEqual(result, [args1[0], args1[1], !args1[2]]); SharedActionCreators.externalSortBy(args2[0], args2[1], args2[2]); assert.deepEqual(result, [args2[0], args2[1], !args2[2]]); }); }); describe("API callers", () => { let dubbel; let result = {}; before(() => { dubbel = genericDouble(JobsAPI, result); }); after(() => dubbel()); it(".getSelections calls JobsAPI.getSelections", () => { SharedActionCreators.getSelections(); assert.equal(result.getSelections, "calledWithNoArgs"); }); it(".getAllProducts calls JobsAPI.getAllProducts", () => { SharedActionCreators.getAllProducts(); assert.equal(result.getAllProducts, "calledWithNoArgs"); }); it(".getUserProfile calls JobsAPI.getUserProfile", () => { SharedActionCreators.getUserProfile(); assert.equal(result.getUserProfile, "calledWithNoArgs"); }); it(".saveDetails calls JobsAPI.saveDetails with an id and details", () => { SharedActionCreators.saveDetails(123, "hello hi"); assert.deepEqual(result.saveDetails, [123, "hello hi"]); }); it(".saveItem calls JobsAPI.saveItem with an id and item", () => { SharedActionCreators.saveItem(123, "hello hi"); assert.deepEqual(result.saveItem, [123, "hello hi"]); }); it(".createItem calls JobsAPI.createItem with an id and blueprint", () => { SharedActionCreators.createItem(123, {name: "hello hi"}); assert.deepEqual(result.createSingleJobItem, [123, {name: "hello hi"}]); }); it(".deleteItem calls JobsAPI.deleteItem with any arg and an immutable object", () => { SharedActionCreators.deleteItem(null, { get(thing) { return thing; } }); assert.deepEqual(result.deleteSingleItem, "item_id"); }); }); testPlease(toTest, SharedActionCreators); });
import { t } from '../../core/localizer'; import { uiPane } from '../pane'; import { uiSectionPrivacy } from '../sections/privacy'; export function uiPanePreferences(context) { let preferencesPane = uiPane('preferences', context) .key(t('preferences.key')) .label(t.html('preferences.title')) .description(t.html('preferences.description')) .iconName('fas-user-cog') .sections([ uiSectionPrivacy(context) ]); return preferencesPane; }
import SpvChoicePage from "components/views/GetStartedPage/SpvChoicePage"; import { render } from "test-utils.js"; import { screen } from "@testing-library/react"; import user from "@testing-library/user-event"; import * as sel from "selectors"; import * as da from "actions/DaemonActions"; let mockIsTestNet; let mockToggleSpv; const selectors = sel; const daemonActions = da; beforeEach(() => { mockIsTestNet = selectors.isTestNet = jest.fn(() => false); mockToggleSpv = daemonActions.toggleSpv = jest.fn(() => () => {}); selectors.stakeTransactions = jest.fn(() => []); }); test("render SPV choice page", () => { render(<SpvChoicePage />); expect(screen.getByTestId("getstarted-pagebody").className).not.toMatch( /testnetBody/ ); const spvLabel = screen.getByText(/simple payment verification \(spv\)/i); expect(spvLabel).toBeInTheDocument(); expect(spvLabel.nextSibling.textContent).toMatchInlineSnapshot( '"Select how Decrediton should connect to the Decred network. You can change this in the application settings later. For more in-depth information about SPV and how it works, you can go here"' ); const enableSpvLabel = screen.getByText(/enable spv/i); expect(enableSpvLabel).toBeInTheDocument(); expect(enableSpvLabel.nextSibling.textContent).toMatchInlineSnapshot( "\"SPV will allow your wallets to be restored and used much more quickly. This speed comes at cost, with blocks not being fully verified. It's 'less secure' but very unlikely that there will be any problems.\"" ); user.click(enableSpvLabel); expect(mockToggleSpv).toHaveBeenCalledWith(true); mockToggleSpv.mockClear(); const disableSpvLabel = screen.getByText(/disable spv/i); expect(disableSpvLabel).toBeInTheDocument(); expect(disableSpvLabel.nextSibling.textContent).toMatchInlineSnapshot( '"This will use the regular Decred daemon and fully verify blocks. This will take longer but is fully secure. Any block or mined transaction can be fully trusted."' ); user.click(disableSpvLabel); expect(mockToggleSpv).toHaveBeenCalledWith(false); }); test("render SPV choice page in testnet mode", () => { mockIsTestNet = selectors.isTestNet = jest.fn(() => true); render(<SpvChoicePage />); expect(mockIsTestNet).toHaveBeenCalled(); expect(screen.getByTestId("getstarted-pagebody").className).toMatch( /testnetBody/ ); });
const webpack = require('webpack'); const path = require('path'); const {debugMode, pkg} = require('./env'); const cwd = process.cwd(); const srcPath = path.join(cwd, pkg.src.js); const distPath = path.join(cwd, pkg.dist.js); // Babel loaders const babelLoaders = (function () { const presets = ['react', 'es2015', 'stage-0']; const plugins = ['react-html-attrs', 'transform-decorators-legacy', 'transform-class-properties']; const presetsQuery = presets.map(p => `presets[]=${p}`).join(','); const pluginsQuery = plugins.map(p => `plugins[]=${p}`).join(','); const query = [presetsQuery, pluginsQuery].join(','); return [`babel?${query}`]; }()); if (debugMode) { // Only hot load on debug mode babelLoaders.push('webpack-module-hot-accept'); babelLoaders.unshift('react-hot'); } const plugins = (function () { const dedup = new webpack.optimize.DedupePlugin(); const occurenceOrder = new webpack.optimize.OccurenceOrderPlugin(); const noErrors = new webpack.NoErrorsPlugin(); const hotModuleReplacement = new webpack.HotModuleReplacementPlugin(); const uglifyJS = new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, output: { comments: false }, mangle: false, sourcemap: false, }); const define = new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify(debugMode ? 'debug' : 'production'), }, '__PRODUCTION_MODE': JSON.stringify(!debugMode), '__DEBUG_MODE': JSON.stringify(debugMode), '__APP_NAME': JSON.stringify(pkg.name), '__APP_VERSION': JSON.stringify(pkg.version), }); if (debugMode) { return [occurenceOrder, hotModuleReplacement, noErrors]; } return [dedup, occurenceOrder, uglifyJS, define]; }()); const webpackSettings = { debug: debugMode, plugins, entry: { app: [ path.join(srcPath, './app.jsx'), ], }, output: { path: distPath, publicPath: '/js/', filename: '[name].js', }, resolve: { extensions: ['', '.js', '.jsx'], }, module: { loaders: [{ test: /\.jsx$/, exclude: /(?:node_modules|bower_components)/, include: [srcPath], loaders: babelLoaders, }], }, }; // debug mode settings if (debugMode) { webpackSettings.devtool = 'inline-sourcemap'; for (const key in webpackSettings.entry) { if (webpackSettings.entry.hasOwnProperty(key)) { webpackSettings.entry[key].unshift('webpack-hot-middleware/client'); webpackSettings.entry[key].unshift('webpack/hot/dev-server'); } } } module.exports = webpackSettings;
/* global PropertyFactory, extendPrototype, RenderableElement, BaseElement, FrameElement */ function AudioElement(data, globalData, comp) { this.initFrame(); this.initRenderable(); this.assetData = globalData.getAssetData(data.refId); this.initBaseData(data, globalData, comp); this._isPlaying = false; this._canPlay = false; var assetPath = this.globalData.getAssetsPath(this.assetData); this.audio = this.globalData.audioController.createAudio(assetPath); this._currentTime = 0; this.globalData.audioController.addAudio(this); this.tm = data.tm ? PropertyFactory.getProp(this, data.tm, 0, globalData.frameRate, this) : { _placeholder: true }; } AudioElement.prototype.prepareFrame = function (num) { this.prepareRenderableFrame(num, true); this.prepareProperties(num, true); if (!this.tm._placeholder) { var timeRemapped = this.tm.v; this._currentTime = timeRemapped; } else { this._currentTime = num / this.data.sr; } }; extendPrototype([RenderableElement, BaseElement, FrameElement], AudioElement); AudioElement.prototype.renderFrame = function () { if (this.isInRange && this._canPlay) { if (!this._isPlaying) { this.audio.play(); this.audio.seek(this._currentTime / this.globalData.frameRate); this._isPlaying = true; } else if (!this.audio.playing() || Math.abs(this._currentTime / this.globalData.frameRate - this.audio.seek()) > 0.1 ) { this.audio.seek(this._currentTime / this.globalData.frameRate); } } }; AudioElement.prototype.show = function () { // this.audio.play() }; AudioElement.prototype.hide = function () { this.audio.pause(); this._isPlaying = false; }; AudioElement.prototype.pause = function () { this.audio.pause(); this._isPlaying = false; this._canPlay = false; }; AudioElement.prototype.resume = function () { this._canPlay = true; }; AudioElement.prototype.setRate = function (rateValue) { this.audio.rate(rateValue); }; AudioElement.prototype.volume = function (volumeValue) { this.audio.volume(volumeValue); }; AudioElement.prototype.getBaseElement = function () { return null; }; AudioElement.prototype.destroy = function () { }; AudioElement.prototype.sourceRectAtTime = function () { }; AudioElement.prototype.initExpressions = function () { };
/* Module handles message posting. */ 'use strict'; const AWS = require('aws-sdk'), Joi = require('joi'), config = require('../environments/config'), dynamodb = new AWS.DynamoDB({ region: 'us-east-1' }); /* Joi validation object */ const postMessageValidate = Joi.object().keys({ UserName: Joi .string() .not('') .default('Anonymous') .description('Name of user who posts the message.'), MessageBody: Joi .string() .not('') .description('The message content.'), Extra: Joi .string() .default('') .description('Any additional info about the message.') }).requiredKeys( 'UserName', 'MessageBody' ); /* params for postMessage */ const postMessageParams = (query) => { let curTime = (new Date()).getTime(); let item = { 'UserName': { S: query.UserName }, 'TimeStamp': { S: curTime.toString() }, 'MessageBody': { S: query.MessageBody } }; if(query.Extra && query.Extra !== ''){ item['Extra'] = { S: query.Extra }; } return { TableName: config.dynamodb, Item: item }; }; /* Handler for postMessage */ const postMessage = (req, resp) => { let query = req.query, params = postMessageParams(query); dynamodb.putItem(params, (err, data) => { if(err){ console.log('ERR: ' + err); resp({Error: err}).code(400); } else { resp({mete: {status: "Success"}, data: data}).code(200); } }); }; module.exports = { postMessageParams, config: { handler: postMessage, description: 'Allow user to post a message.', tags: ['api'], validate: { query: postMessageValidate } } };
define(["config"], function(Config) { "use strict"; var width = 100, height = 27, padding = 6; function drawScore(ctx, score, screenWidth) { ctx.beginPath(); ctx.strokeStyle = "#fff"; ctx.lineWidth = 1; ctx.moveTo(screenWidth - 100, 0); ctx.lineTo(screenWidth - 100, height); ctx.lineTo(screenWidth, height); ctx.stroke(); ctx.closePath(); ctx.beginPath(); ctx.fillStyle = Config.text.score.color; ctx.textBaseline = "top"; ctx.font = Config.text.score.font; ctx.fillText("Score: " + score, screenWidth - width + padding, padding); ctx.closePath(); } return drawScore; });
import { connect } from 'react-redux'; import get from 'lodash.get'; import { QuestionView } from '../../components/Questions'; import { openEditQuestionForm, deleteQuestion } from '../../actions'; const mapStateToProps = (state, ownProps) => { const { isAdmin, groups } = state.profile; return { question: get(state.questions.questions, ownProps.id, {}), groups, isAdmin, }; }; const Question = connect(mapStateToProps, { editQuestion: openEditQuestionForm, deleteQuestion, })(QuestionView); export { Question };
'use strict'; const chalk = require('chalk'); function log(type) { if (arguments.length < 2) { return; } const msgs = Array.from(arguments).slice(1); let log = ['[rise]']; switch(type) { case 'error': log.push(chalk.red('ERRO')); break; case 'warn': log.push(chalk.yellow('WARN')); break; case 'info': log.push(chalk.blue('INFO')); break; case 'debug': log.push(chalk.gray('DEBU')); break; } log = log.concat(msgs.map(function(m) { if (m instanceof Error) { return m.stack; } return m; })); log.push("\n"); const msg = log.join(' '); if (process.env.NODE_ENV === 'test') { // Don't log in tests. return; } if (type === 'error') { process.stderr.write(msg); } else { process.stdout.write(msg); } } module.exports = { error(/* msg */) { log.apply(this, ['error'].concat(Array.from(arguments))); }, warn(/* msg */) { log.apply(this, ['warn'].concat(Array.from(arguments))); }, info(/* msg */) { log.apply(this, ['info'].concat(Array.from(arguments))); }, debug(/* msg */) { log.apply(this, ['debug'].concat(Array.from(arguments))); } };
// I used to use `util.format()` which was massive, then I switched to // format-util, although when using rollup I discovered that the index.js // just exported `require('util').format`, and then had the below contents // in another file. at any rate all I want is this function: function format(fmt) { fmt = String(fmt); // this is closer to util.format() behavior var re = /(%?)(%([jds]))/g , args = Array.prototype.slice.call(arguments, 1); if(args.length) { if(Array.isArray(args[0])) args = args[0]; fmt = fmt.replace(re, function(match, escaped, ptn, flag) { var arg = args.shift(); switch(flag) { case 's': arg = '' + arg; break; case 'd': arg = Number(arg); break; case 'j': arg = JSON.stringify(arg); break; } if(!escaped) { return arg; } args.unshift(arg); return match; }) } // arguments remain after formatting if(args.length) { fmt += ' ' + args.join(' '); } // update escaped %% values fmt = fmt.replace(/%{2,2}/g, '%'); return '' + fmt; } export default format;
var plates = [{img:"centralamerica-inset.gif", start: 1900, end: 2020, left: -10, top: 500}, {img:"mexicanrevolution1910.png", start: 1910, end: 1920, top: 190, left: -30}, {img:"zapatista1994.png", start: 1994, end: 1994, top: 190, left: -30}, {img:"fococuba1959.gif", start: 1959, end: 1965, top: 105, left: 650} ];
'use strict'; var lab = require('lab'), describe = lab.describe, it = lab.it, demand = require('must'), bole = require('bole'), fs = require('fs'), LogOutput = require('../lib/output-logfile'), mkdirp = require('mkdirp'), path = require('path'), rimraf = require('rimraf') ; var tmpdir = './tmp'; describe('logfile output', function() { var output; var mockopts = { path: path.join(tmpdir, 'foo.log'), name: 'test-1' }; lab.before(function(done) { mkdirp(tmpdir, done); }); it('demands an options object', function(done) { function shouldThrow() { return new LogOutput(); } shouldThrow.must.throw(/options/); done(); }); it('demands a name object', function(done) { function shouldThrow() { return new LogOutput({ path: '../tmp'}); } shouldThrow.must.throw(/name/); done(); }); it('can be constructed', function(done) { output = new LogOutput(mockopts); output.must.be.an.object(); output.must.be.instanceof(LogOutput); done(); }); it('creates a logger client', function(done) { output.must.have.property('client'); output.client.must.be.truthy(); output.client.must.have.property('info'); output.client.info.must.be.a.function(); done(); }); it('emits to its logfile', function(done) { output.write({ test: 'yes'}, function() { fs.readFile(mockopts.path, function(err, data) { data = data.toString('utf8'); var first = data.split('\n')[0]; var written = JSON.parse(first); written.must.be.an.object(); written.level.must.equal('info'); written.name.must.equal('test-1'); written.test.must.equal('yes'); done(); }); }); }); it('the path option is optional', function(done) { var consoleOut = new LogOutput({ name: 'test-2' }); output.write({ test: 'yes'}, function() { done(); }); }); it('has a useful toString() implementation', function(done) { var str = output.toString(); str.must.equal('[ logfile @ tmp/foo.log ]'); done(); }); lab.after(function(done) { rimraf(tmpdir, done); }); });
import {normalize} from '../lib/themeUtils' const unused = new Set() const freeze = Object.freeze const createAccessors = (object, path = '') => { for (const key of Object.keys(object)) { const value = object[key] const keyPath = path ? `${path}.${key}` : key if (value && typeof value === 'object') { createAccessors(value, keyPath) } else if (typeof value === 'string') { unused.add(keyPath) Object.defineProperty(object, key, { get () { unused.delete(keyPath) return `%${keyPath}${value ? '#' + value : ''}%` } }) } } freeze.call(Object, object) } const theme = {} // normalize() caches the result, so this is just a cache key Object.freeze = obj => obj // Stub out so accessors can be created const normalized = normalize({theme}) createAccessors(normalized) Object.freeze = freeze export default theme export {normalized as normalizedTheme} export function checkThemeUsage (t) { t.deepEqual(unused, new Set(), 'All theme properties should be accessed at least once') }
/** * Icon based on ion-ios-paper-outline */ import React, { Component } from 'react'; class Many extends Component { render() { return ( <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="512px" height="512px" viewBox="0 0 512 512" enable-background="new 0 0 512 512"> <g> <path d="M112,64v16v320h16V80h304v337.143c0,8.205-6.652,14.857-14.857,14.857H94.857C86.652,432,80,425.348,80,417.143V128h16v-16 H64v305.143C64,434.157,77.843,448,94.857,448h322.285C434.157,448,448,434.157,448,417.143V64H112z"/> <rect x="160" y="112" width="128" height="16"/> <rect x="160" y="192" width="240" height="16"/> <rect x="160" y="272" width="192" height="16"/> <rect x="160" y="352" width="240" height="16"/> </g> </svg> ) } } export default Many;
describe('getting elements by class name', function () { var chai = require('chai'), assert = chai.assert; var DomParser = require('../index.js'), parser = new DomParser(); context('Dom', function(){ it('spaces and case', function(){ var html = '<div class="examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="exAmple "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as">' + ' </div>\n' + '</div>'; var dom = parser.parseFromString(html), elements = dom.getElementsByClassName('example'); assert.equal(elements.length, 5, 'html contains 5 elements with className "example"'); }); it('nested elements', function(){ var html = '<div class="examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="example "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as nasted">' + ' <div class="examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="example "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as nasted">' + ' </div>\n' + ' </div>' + ' </div>\n' + '</div>'; var dom = parser.parseFromString(html), elements = dom.getElementsByClassName('example'); assert.equal(elements.length, 12, 'html contains 12 elements with className "example"'); }); }); context('Node', function(){ it('root: spaces and case', function(){ var html = '<div class="examples root">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="exAmple "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as">' + ' </div>\n' + '</div>'; var dom = parser.parseFromString(html), root = dom.getElementsByClassName('root')[0], elements = root.getElementsByClassName('example'); assert.equal(elements.length, 5, 'root element contains 5 elements with className "example"'); }); it('nested elements', function(){ var html = '<div class=" root examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="example "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as nasted">' + ' <div class="examples">\n' + ' <span>text</span>\n' + ' <div class="example"></div>\n' + ' <span>text</span>\n' + ' <div class=" example"></div>\n' + ' <div class=" example"></div>\n' + ' <span>text</span>\n' + ' <div class="example "></div>\n' + ' <span>text</span>\n' + ' <div class=" asd example ss"></div>\n' + ' <div class=" sd examples"></div>\n' + ' <span>text</span>\n' + ' <div class=" example as nasted">' + ' </div>\n' + ' </div>' + ' </div>\n' + '</div>'; var dom = parser.parseFromString(html), root = dom.getElementsByClassName('root')[0], elements = root.getElementsByClassName('example'); assert.equal(elements.length, 12, 'root element contains 12 elements with className "example"'); }); }); });
// A database of labels define(['util', 'label'], function(Util, Label) { var Labels = function() { this.getURL = '/annotate.database.getlabels'; this.addURL = '/annotate.database.addlabel'; this.saveLabelURL = '/annotate.database.savelabel'; this.removeLabelURL = '/annotate.database.removelabel'; this.database = []; this.databaseByColor = {}; this.databaseByName = {}; this.databaseById = {}; this.labelsLoadedCallback = []; this.labelAddedCallbacks = []; }; Labels.prototype.getById = function(i) { return this.databaseById[i]; } Labels.prototype.getByColor = function(color) { return this.databaseByColor[color]; } Labels.prototype.getByName = function(name) { return this.databaseByName[name]; } Labels.prototype.registerLabelsLoadedCallback = function(callback) { this.labelsLoadedCallback.push( callback ); } Labels.prototype.registerLabelAddedCallback = function(callback) { this.labelAddedCallbacks.push( callback ); } Labels.prototype.load = function() { Util.load_data(this.getURL, this.onLoaded.bind(this) ); } Labels.prototype.onLoaded = function(res) { var compressed = new Uint8Array(res.response); var inflate = new Zlib.Inflate(compressed); var binary = inflate.decompress(); var binaryconverter = new TextDecoder('utf-8'); var decompressed = binaryconverter.decode(binary); var data = JSON.parse( window.atob(decompressed) ); // decode the string this.database = data; var colorKey = ''; var label = null; for(var i=0; i<this.database.length; i++) { label = this.database[i]; colorKey = label.r + '' + label.b + '' + label.g; this.databaseByColor[colorKey] = label; this.databaseById[label.index] = label; this.databaseByName[label.name] = label; } this.trigerLoadedCallback(); } Labels.prototype.add = function(name, r, g, b, imageId) { //Util.load_data(this.getURL, this.onLoaded.bind(this) ); var label = new Label(name, r, g, b); label.index = this.getavailableindex(); var colorKey = label.r + '' + label.b + '' + label.g; this.database.push( label ); this.databaseById[label.index] = label; this.databaseByName[label.name] = label; this.databaseByColor[colorKey] = label; console.log(this.database); //this.triggerLabelAdded(name); this.saveLabel(label); return label; } Labels.prototype.trigerLoadedCallback = function() { for(var i=0; i<this.labelsLoadedCallback.length; i++) { this.labelsLoadedCallback[i](); } } Labels.prototype.triggerLabelAdded = function(name) { for(var i=0; i<this.labelAddedCallbacks.length; i++) { //this.labelAddedCallbacks[i](name); } } Labels.prototype.update = function(name, newname, r, g, b, imageId) { console.log('Labels.prototype.update'); var label = this.databaseByName[name]; if (label == null) { return; } delete this.databaseByName[name]; label.name = newname; label.r = r; label.g = g; label.b = b; console.log(this); this.databaseByName[newname] = label; this.triggerLabelAdded(); //Util.load_data(this.getURL, this.onLoaded.bind(this) ); this.saveLabel(label, imageId); console.log(label); console.log(this); } Labels.prototype.remove = function(name) { console.log('labels.Labels.prototype.remove'); var label = this.databaseByName[name]; if (label == null) { return false; } console.log('ref: ' + label.references); console.log(label); if (label.references != null && label.references.length > 0) return false; var colorKey = label.r + '' + label.b + '' + label.g; delete this.databaseByName[label.name]; delete this.databaseByColor[colorKey]; delete this.databaseById[label.index]; //this.triggerLabelAdded(); this.removeLabel(label.index); this.load(); return true; } Labels.prototype.saveLabel = function(label, imageId) { console.log('labels.Labels.prototype.saveLabel'); console.log(label); input = JSON.stringify(label); Util.send_data(this.saveLabelURL, 'id=' + this.id + ';label='+input); } Labels.prototype.removeLabel = function(labelId) { console.log('labels.Labels.prototype.removeLabel labelId: ' + labelId); Util.send_data(this.removeLabelURL, 'id=' + labelId); } Labels.prototype.getavailableindex = function() { var index = 0; for(var i=0; i<this.database.length; i++) { if (this.database[i].index == index) index++; } console.log(this.database[0]); console.log('available index: ' + index); return index; } return Labels; });
(function(){ var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x){ window.requestAnimation = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimtionFrame = window[vendors[x] + 'CancelAnimationFrame'] || window[vendors[x] + 'CancelRequestAnimtionFrame']; } if(!window.requestAnimationFrame) window.requestAnimationFrame = function(callback, element){ var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function(){ callback(currTime + timeToCall) ;},timeToCall); lastTime = currTime + timeToCall; return id; }; if(!window.cancelAnimationFrame) window.cancelAnimationFrame = function(id){ clearTimeout(id); } })();
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _glob = require('glob'); var _glob2 = _interopRequireDefault(_glob); var _lodash = require('lodash'); var _lodash2 = _interopRequireDefault(_lodash); var _path = require('path'); var _path2 = _interopRequireDefault(_path); var _fs = require('fs'); var _fs2 = _interopRequireDefault(_fs); 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"); } } var FlowRequireManager = function () { function FlowRequireManager(settings) { _classCallCheck(this, FlowRequireManager); this.settings = settings || {}; this.items = {}; } _createClass(FlowRequireManager, [{ key: 'log', value: function log(level, message) { if (this.settings.logger) { this.settings.logger.log(level, message); } } }, { key: 'getAbsolutePath', value: function getAbsolutePath(relative) { return _path2.default.normalize(_path2.default.join(process.cwd(), relative)); } }, { key: 'addItem', value: function addItem(item) { this.log('info', 'Adding item ' + item.name); this.items[item.name] = item; } }, { key: 'removeItem', value: function removeItem(name) { this.log('info', 'Removing item ' + name); delete this.items[name]; } }, { key: 'getItem', value: function getItem(name) { return this.items[name]; } }, { key: 'addFolder', value: function addFolder(folder, cb) { (0, _glob2.default)(folder + '/' + this.settings.pattern, {}, function (err, files) { if (err) { return cb(err); } for (var i = 0; i < files.length; i++) { var extension = _path2.default.extname(files[i]); var content = void 0; var absolutePath = this.getAbsolutePath(files[i]); if (extension === '.json' || extension === '.js') { content = require(absolutePath); } else { content = _fs2.default.readFileSync(absolutePath, 'utf8'); } if (content) { if (!_lodash2.default.isArray(content)) { var name = content.name; if (_lodash2.default.isFunction(content)) { content = { method: content }; } else if (_lodash2.default.isString(content)) { content = { text: content }; } if (!name) { name = _path2.default.basename(files[i], extension).toLowerCase(); } content.name = name; content = [content]; } for (var j = 0; j < content.length; j++) { this.addItem(content[j]); } } else { this.log('warning', 'Content not found for file ' + files[i]); } } return cb(); }.bind(this)); } }]); return FlowRequireManager; }(); exports.default = FlowRequireManager;
module.exports = function() { 'use strict'; this.title = element(by.model('movie.title')); this.releaseYear = element(by.model('movie.releaseYear')); this.description = element(by.css('div[contenteditable=true]')); this.save = element(by.css('.btn-primary')); this.open = function() { browser.get('/movies/new'); }; this.addMovie = function(title, description, releaseYear) { this.open(); this.title.clear(); this.title.sendKeys(title); if (releaseYear !== undefined) { this.releaseYear.clear(); this.releaseYear.sendKeys(releaseYear); } this.description.clear(); this.description.sendKeys(description); this.save.click(); }; };
/* global process */ /** * Dependencies */ // Third party libraries var debug = require('debug')('wakizashi'); var merge = require('merge-descriptors'); var fs = require('fs'); // Wakizashi libraries var domoweb = require('./domoweb'); var auth = require('./auth'); var dataset = require('./dataset'); var dataflow = require('./dataflow'); /** * Expose `createInstance()` */ exports = module.exports = createInstance; /** * Create a new instance of Wakizashi. Pass in a Domo Developer API Token * * @paran token * @return {Function} * @api public */ function createInstance(instance, token) { // Look for a credentials file if (instance == null || token == null) { try { var credFile = fs.readFileSync(".creds", 'utf8'); var creds = JSON.parse(credFile); token = creds.token; instance = creds.instance; } catch(error) { console.log("Not configured! Create a .creds file in the root folder."); } } // Store globally-accessible settings this.settings = { // Authentication details _authtoken: token, _instance: instance, // The DataSource Type to upload as // This can be overridden per create _type: "Wakizashi" }; // Create empty container function var app = function(){}; // Add in library functions merge(app, domoweb, false); merge(app, auth, false); merge(app, dataset, false); merge(app, dataflow, false); // And away we go! return app; }
var casper = require('casper').create(), x = require('casper').selectXPath, config = require('config.json'), fs = require('fs'), moment = require('moment'); casper.start("http://caravantomidnight.com/show-archive/"); var currentMonthUrl = "http://caravantomidnight.com/show-archive-" + moment(casper.cli.get(0)).format("MMMM-YYYY/").toLowerCase(); var basePath = casper.cli.get(1); var episodes = []; var mp3Folder = basePath + 'mp3/'; function downloadEpisode(url, file) { var mp3Filepath = mp3Folder + file; if(!fs.exists(mp3Filepath)) { casper.download(url, mp3Filepath); } } casper.then(function () { casper.fillSelectors('#wma_login_form', { '#user_login': config.username, '#user_pass': config.password }); casper.click('#wp-submit'); }); casper.thenOpen(currentMonthUrl); casper.then(function () { var blocks = casper.getElementsInfo('div.content-column'); var episodeBlocks = casper.getElementsInfo(x('//div[contains(@class,"content-column")]/p[last()]')); if(blocks.length !== episodeBlocks.length) { casper.exit("Oh noes."); } for(var i=0; i < blocks.length; i++) { var episodeDescription = blocks[i].html.split('<p>')[0]; var episodeNumber = /Ep. (\d+) /.exec(episodeDescription)[1]; var mp3RegexMatches = /(http.+\.mp3)\".+>(.+) \(Full MP3\)/.exec(episodeBlocks[i].html); var mp3FileUrl = mp3RegexMatches[1]; episodes.push({ number: episodeNumber, description: episodeDescription, file: 'episode_' + episodeNumber + '.mp3', date: new Date(mp3RegexMatches[2]) }); downloadEpisode(mp3FileUrl, 'episode_' + episodeNumber + '.mp3'); } casper.echo(JSON.stringify(episodes)); }); casper.run();
/** * Module dependencies. */ var passport = require('passport'); module.exports.loginForm = function(req, res) { res.render('login'); }; module.exports.login = passport.authenticate('local', { successReturnToOrRedirect: '/login/status/success', failureRedirect: '/login/status/failure' }); module.exports.logout = function(req, res) { req.logout(); res.status(200).json('logout success'); } module.exports.loginStatus = function(req, res) { const { status } = req.params; if (status === 'current') { if (req.session.passport) { res.status(230).json('logining'); } else { res.status(403).json('no login'); } } else if (status === 'success'){ res.status(200).json('login success'); } else { res.status(403).json('login failure'); } }
// Generated by CoffeeScript 1.9.0 exports.MSGBYPAGE = 30; exports.LIMIT_DESTROY = 200; exports.LIMIT_UPDATE = 30; exports.CONCURRENT_DESTROY = 1; exports.FETCH_AT_ONCE = 1000;
/** * Copyright (C) 2013 Emay Komarudin * 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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * @author Emay Komarudin * **/ Ext.define('App.store.PO.ssupplier', { extend: 'Ext.data.Store', fields: [ 'id', 'address', "email", "fax", "phone", "name" ], proxy: { type: 'rest', url: getApiUrl() + '/suppliers', reader: { type: 'json', root: 'results', totalProperty: 'total' } } });
import nodeResolve from '@rollup/plugin-node-resolve'; import commonjs from '@rollup/plugin-commonjs'; import nodePolyfills from 'rollup-plugin-node-polyfills'; export default [ { input: 'support/demo_template/demo.js', output: { file: 'demo/demo.js', format: 'iife', name: 'demo' }, plugins: [ nodePolyfills(), nodeResolve(), commonjs() ] } ];
$('section').horizon(); $(".menu-list").find("li").each(function(){ var menuIndex = $(this).index()+1; $(this).click(function(){ $(document).stop().horizon('scrollTo', menuIndex); }) })
export { default } from './RubymineOriginal'
define(['./module'], function (controllers) { 'use strict'; controllers.controller('msg_ctrl', [function ($scope) {}]); });
import buble from 'rollup-plugin-buble'; import resolve from 'rollup-plugin-node-resolve'; import vue from 'rollup-plugin-vue'; export default { entry: 'index.js', dest: 'dist/v-tags.js', format: 'umd', sourceMap: true, useStrict: true, moduleName: 'VTags', plugins: [ vue({ compileTemplate: false }), buble({ objectAssign: 'Vue.util.extend' }), resolve({ jsnext: true, main: true, browser: true }), ] };
/** * App * * Root application file. * Load main controllers here. */ define([ "jquery", "modules/connected-devices/index" ], function( $, ConnectedDevices ) { "use strict"; var retriveData = function(callback) { var connected_devices_request = $.getJSON("data/connected-devices.json", { cache: + new Date() }); $.when(connected_devices_request) .then(function(connected_devices_data) { callback(null, connected_devices_data); }, function() { callback(new Error("An error has occurred requesting init data")); }); }, app = {}, connected_devices; /* * * */ app.init = function() { var $app_el = $(".js-app"); if ($app_el.length < 1) { throw new Error("Placeholder element is not available"); } retriveData(function(err, connected_devices_data) { if (err) { return window.console.error(err); } connected_devices = new ConnectedDevices({ el: $app_el.get(0), data: connected_devices_data }); connected_devices.render(); }); return true; }; /* * * */ app.destroy = function() { connected_devices.destroy(); }; /* * * */ app.update = function() { retriveData(function(err, connected_devices_data) { if (err) { return window.console.error(err); } connected_devices.update({ data: connected_devices_data }); }); }; return app; });
// The following will make sure the team_leader does not have access to certain menu items // All menu items have been tested at the administration level describe("Shakeout Menu", () => { // Before running tests - we have to make sure the admin user is logged in before(() => { cy.login('team_leader','Test1234$'); cy.getCookie("sessionid").should("exist"); cy.getCookie("csrftoken").should("exist"); }); //Making sure we still have the sessionid and csrftoken beforeEach(() => { Cypress.Cookies.preserveOnce("sessionid", "csrftoken"); }); //Make sure the administration menu does not exist it("Check no admin menu", () => { //Go to dashboard cy.visit('http://localhost:8000/'); //Make sure the administration drop down does not exist cy.get('#administrationDropdown') .should('not.exist'); }) })
import * as R from 'ramda'; import ascent from './ascent'; import descent from './descent'; import lineGap from './lineGap'; /** * Get run height * * @param {Object} run * @return {number} height */ const height = R.either( R.path(['attributes', 'lineHeight']), R.compose(R.sum, R.juxt([ascent, R.o(R.negate, descent), lineGap])), ); export default height;
'use strict' import assert from 'assert' import {remove} from '..' describe('remove', () => { it('throws a TypeError if the first argument is not an array', () => { const targets = [null, true, function() {}, {}] if (global.Map) targets.push(new Map()) targets.forEach(value => { assert.throws(() => { remove(value, 'foo') }, TypeError) }) }) it('remove the value (once) if target is an array', () => { const target = ['bar', 'bar'] remove(target, 'bar') assert.strictEqual(target.length, 1) }) if (global.Set) { it('removes the value if target is a set', () => { const target = new Set() target.add('foo') remove(target, 'foo') assert(!target.has('foo')) assert.strictEqual(target.size, 0) }) } })
var gulp = require('gulp'); var Path = require('path'); var compass = require('gulp-compass'); var minifyCss = require('gulp-minify-css'); var del = require('del'); var browserify = require('browserify'); var source = require('vinyl-source-stream'); var browserSync = require('browser-sync'); var reload = browserSync.reload; var plumber = require('gulp-plumber'); var replace = require('gulp-replace'); var karma = require('gulp-karma'); var shell = require('gulp-shell'); var zip = require('gulp-zip'); gulp.task('sass', sassCompile); gulp.task('assets', assetCopy); gulp.task('scripts', scriptCompile); gulp.task('flash', flashCompile); gulp.task('clean', clean); gulp.task('packageCopy', packageJsonCopy); gulp.task('devPackageCopy', devPackageCopy); gulp.task('reloader', ['build'], reload); gulp.task('reloadFlash', ['flash'], reload); gulp.task('dev', ['devPackageCopy', 'build', 'flash'], server); gulp.task('test', ['build', 'flash'], test); gulp.task('build', ['sass', 'assets', 'scripts']); gulp.task('nw', ['build', 'flash', 'packageCopy'], packageNodeWebkit); gulp.task('default', ['nw']); var outDir = 'out'; var packageDir = '.'; function sassCompile() { return gulp.src('src/main/scss/style.scss') .pipe(plumber({ errorHandler : function (error) { console.log(error.message); this.emit('end'); } })) .pipe(compass({ project : Path.join(__dirname), css : outDir + '/css', sass : 'src/main/scss', image : 'src/main/img' })) .pipe(minifyCss()) .pipe(gulp.dest(outDir + '/css')); } function scriptCompile() { return browserify('src/main/js/app.js') .bundle() .on('error', function (err) { console.log('error occured:', err); this.emit('end'); }) .pipe(source('app.js')) .pipe(gulp.dest(outDir + '/js')); } function flashCompile() { var flashCompileCommand; if (process.platform === 'darwin') { flashCompileCommand = 'osascript -e \'tell application "Adobe Flash CS6" to open posix file "' + __dirname + '/src/flash/compile.jsfl"\''; } else { flashCompileCommand = 'flash.exe "src\\flash\\compile.jsfl"'; } return gulp.src(['src/flash/compile.jsfl']) .pipe(plumber()) .pipe(shell('echo 1 > src/flash/compile.jsfl.deleteme')) .pipe(shell(flashCompileCommand)) } function assetCopy() { return gulp.src(['src/main/**', '!src/main/js/**', '!src/main/scss', '!src/main/scss/**']) .pipe(gulp.dest(outDir)); } function packageJsonCopy() { return gulp.src(['src/package.json']) .pipe(gulp.dest(outDir)); } function devPackageCopy() { return gulp.src(['src/package.json']) .pipe(replace(/(\s*)"main"(\s*:\s*)"([^"]*)"(\s*,\s*)/, '$1"main"$2"http://localhost:3000/$3"$4"node-remote"$2"http://localhost:3000"$4')) .pipe(gulp.dest(outDir)); } function test() { return gulp.src('src/test/**/*Spec.js') .pipe(karma({ configFile : 'karma.conf.js', action : 'run' })) .on('error', function (err) { throw err; }); } function server() { browserSync({ server : { baseDir : outDir }, open: false }); gulp.watch(['src/main/**', 'src/main/js/**', 'src/main/scss/**/*.scss'], {}, ['reloader']); gulp.watch(['src/flash/**'], {}, ['reloadFlash']); gulp.src('src/test/**/*Spec.js').pipe(karma({ configFile : 'karma.conf.js', action : 'watch' })); } function packageNodeWebkit() { return gulp.src(outDir + '/**') .pipe(zip('xlc_shop.nw')) .pipe(gulp.dest(packageDir)) } function clean(cb) { del([outDir], cb); }
munit( 'Rule Compression.Hex to Safe Color', function( assert ) { assert.exists( "Table", CSSCompressor.tables[ 'Hex to Safe Color' ] ); testRule( assert, 'Hex to Safe Color', [ { name: 'Basic', actual: '#000080', expected: 'navy' }, { name: 'Basic Uppercase', actual: '#c0c0c0', expected: 'silver' }, { name: 'Unsafe Color', actual: '#f0ffff', expected: undefined }, { name: 'No Conversion', actual: '#f02de5', expected: undefined } ]); });
var searchData= [ ['cache',['Cache',['../classCache.html',1,'']]], ['conversation',['Conversation',['../classConversation.html',1,'']]] ];
'use strict'; function curry (fn) { var args = Array.prototype.slice.call(arguments, 1); return function () { var nextArgs = Array.prototype.slice.call(arguments), allArgs = args.concat(nextArgs); return fn.apply(this, allArgs); }; } function compose () { var args = Array.prototype.slice.call(arguments).reverse(); return function (obj) { return args.reduce(function (result, F) { return F(result); }, obj); }; } module.exports = { identity: function (i) { return i; }, constant: function (k) { return function () { return k; }; }, noop: function () {}, compose: compose, curry: curry };
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. * * @flow */ /** * Get a hash for the provider object. Hashes are unique per-hasher, so if you have two different * hashers, there is no guarantee that they will give the same hash for the same object. * * One use case for this is with lists of React elements. Just create a hasher and use the hash as * a key: * * class MyComponent extends React.Component { * constructor(props) { * super(props); * this._hasher = new Hasher(); * } * render() { * return this.props.items.map(item => ( * <ItemView key={this._hasher.getHash(item)} model={item} /> * )); * } * } */ export default class Hasher<K> { _hashes: WeakMap<K, string>; _objectCount: number; constructor() { this._hashes = new WeakMap(); this._objectCount = 0; } getHash(item: K): string | number { if (item === null) { return 'null'; } const type = typeof item; switch (typeof item) { case 'object': { let hash = this._hashes.get(item); if (hash == null) { hash = `${type}:${this._objectCount}`; this._hashes.set(item, hash); this._objectCount = this._objectCount + 1 === Number.MAX_SAFE_INTEGER ? Number.MIN_SAFE_INTEGER : this._objectCount + 1; } return hash; } case 'undefined': return 'undefined'; case 'string': case 'boolean': return `${type}:${item.toString()}`; case 'number': return item; default: throw new Error('Unhashable object'); } } }
//Categories service used to communicate Categories REST endpoints (function () { 'use strict'; angular .module('categories') .factory('CategoriesService', CategoriesService); CategoriesService.$inject = ['$resource']; function CategoriesService($resource) { return $resource('api/categories/:categoryId', { categoryId: '@_id' }, { update: { method: 'PUT' } }); } })();
'use strict'; var Transform = require('readable-stream').Transform; var inherits = require('inherits'); var deepMatch = require('./lib/deepMatch'); var wrap = require('./lib/wrapMessage'); var jschan = require('jschan'); function noop() {} function Graft() { if (!(this instanceof Graft)) { return new Graft(); } Transform.call(this, { objectMode: true, highWaterMark: 16 }); var that = this; function readFirst() { /*jshint validthis:true */ this.removeListener('readable', readFirst); that._transform(wrap(this.read(), this), null, noop); } this._session = jschan.memorySession(); this._session.on('channel', function(channel) { channel.on('readable', readFirst); }); this._nextChannel = this._session.WriteChannel(); this.on('pipe', function(source) { source.on('ready', that.emit.bind(that, 'ready')); this.on('end', function() { source.end(); }); }); this._patterns = []; } inherits(Graft, Transform); Graft.prototype._transform = function flowing(obj, enc, done) { if (!obj._session && !obj._channel) { // it quacks like a duck, so it's a duck - s/duck/request/g var channel = this._nextChannel; this._nextChannel = this._session.WriteChannel(); channel.write(obj); return done(); } var i; for (i = 0; i < this._patterns.length; i++) { if (this._patterns[i].pattern(obj)) { this._patterns[i].stream.write(obj, done); return; } } this.push(obj); done(); }; Graft.prototype.branch = function(pattern, stream) { if (!pattern) { throw new Error('missing pattern'); } if (!stream) { throw new Error('missing destination'); } this._patterns.push({ pattern: pattern, stream: stream }); return this; }; Graft.prototype.where = function(pattern, stream) { return this.branch(function(req) { return deepMatch(pattern, req); }, stream); }; Graft.prototype.close = function(cb) { function complete() { /*jshint validthis:true */ this._session.close(function(err) { if (err) { return cb(err); } return cb(); }); } if (this._readableState.endEmitted) { complete.call(this); } else { this.on('end', complete); } if (!this._readableState.flowing) { this.resume(); } this.end(); }; Graft.prototype.ReadChannel = function() { return this._nextChannel.ReadChannel(); }; Graft.prototype.WriteChannel = function() { return this._nextChannel.WriteChannel(); }; module.exports = Graft;
'use strict'; // Declare app level module which depends on views, and components var accountModule = angular.module('accountModule', []); var partnerModule = angular.module('partnerModule', []); var dodoModule = angular.module('dodoModule', []); angular.module('myApp', [ 'ngMaterial', 'ngRoute', 'myApp.version', 'accountModule', 'partnerModule', 'dodoModule' ]). config(['$routeProvider', function ($routeProvider) { $routeProvider.otherwise({redirectTo: '/view1'}); }]).factory('storageService', ['$log', '$rootScope', function ($log, $rootScope) { var localStorageMaxCount = 10; var storageService = { save: function (storageName, data) { localStorage[storageName] = JSON.stringify(data); if (localStorage.length > localStorageMaxCount) { $log.warn('local storage count (length) is over 10, this may be a bug, please check it out - Message from StorageService'); } $rootScope.$broadcast(storageName, data); return data; }, load: function (storageName) { var storedData = localStorage[storageName]; if (typeof storedData !== "undefined") { return JSON.parse(storedData); } else { return undefined; } }, clear: function (storageName) { delete localStorage[storageName]; $rootScope.$broadcast(storageName); return undefined; }, swipeAll: function () { localStorage.clear(); return 'localStorage is cleared!'; }, status: function () { $log.info('Current status -> localstorage: ', localStorage); } }; return storageService; }]).config(['$sceProvider', function ($sceProvider) { // Completely disable SCE. For demonstration purposes only! // Do not use in new projects. $sceProvider.enabled(false); }]).run(['storageService', '$location', '$http', function (storageService, $location, $http) { var currentUser = storageService.load('currentUser'); if (typeof currentUser == "undefined") { $location.path('/account/login'); } else { $http.defaults.headers.common["X-Parse-Session-Token"] = currentUser.sessionToken; } }]) .config(function ($mdThemingProvider) { $mdThemingProvider.theme('default') .primaryPalette('pink') .accentPalette('orange'); });
"use strict"; const root = require('./helpers.js').root const ip = require('ip'); exports.HOST = ip.address(); exports.DEV_PORT = 3000; exports.E2E_PORT = 4201; exports.PROD_PORT = 8088; exports.UNIVERSAL_PORT = process.env.PORT || 8000; exports.SHOW_WEBPACK_BUNDLE_ANALYZER = false; /** * These constants set whether or not you will use proxy for Webpack DevServer * For advanced configuration details, go to: * https://webpack.github.io/docs/webpack-dev-server.html#proxy */ exports.USE_DEV_SERVER_PROXY = false; exports.DEV_SERVER_PROXY_CONFIG = { '**': 'http://localhost:8089' } /** * These constants set the source maps that will be used on build. * For info on source map options, go to: * https://webpack.github.io/docs/configuration.html#devtool */ exports.DEV_SOURCE_MAPS = 'eval'; exports.PROD_SOURCE_MAPS = 'source-map'; /** * Set watch options for Dev Server. For better HMR performance, you can * try setting poll to 1000 or as low as 300 and set aggregateTimeout to as low as 0. * These settings will effect CPU usage, so optimal setting will depend on your dev environment. * https://github.com/webpack/docs/wiki/webpack-dev-middleware#watchoptionsaggregatetimeout */ exports.DEV_SERVER_WATCH_OPTIONS = { poll: undefined, aggregateTimeout: 300, ignored: /node_modules/ } /** * specifies which @ngrx dev tools will be available when you build and load * your app in dev mode. Options are: monitor | logger | both | none */ exports.STORE_DEV_TOOLS = 'monitor' exports.EXCLUDE_SOURCE_MAPS = [ // these packages have problems with their sourcemaps root('node_modules/@angular'), root('node_modules/@nguniversal'), root('node_modules/rxjs') ] exports.MY_COPY_FOLDERS = [ // use this for folders you want to be copied in to Client dist // src/assets and index.html are already copied by default. // format is { from: 'folder_name', to: 'folder_name' } ] exports.MY_POLYFILL_DLLS = [ // list polyfills that you want to be included in your dlls files // this will speed up initial dev server build and incremental builds. // Be sure to run `npm run build:dll` if you make changes to this array. ] exports.MY_VENDOR_DLLS = [ // list vendors that you want to be included in your dlls files // this will speed up initial dev server build and incremental builds. // Be sure to run `npm run build:dll` if you make changes to this array. ] exports.MY_CLIENT_PLUGINS = [ // use this to import your own webpack config Client plugins. ] exports.MY_CLIENT_PRODUCTION_PLUGINS = [ // use this to import your own webpack config plugins for production use. ] exports.MY_CLIENT_RULES = [ // use this to import your own rules for Client webpack config. ] exports.MY_TEST_RULES = [ // use this to import your own rules for Test webpack config. ] exports.MY_TEST_PLUGINS = [ // use this to import your own Test webpack config plugins. ]
function report(str) { console.log(str); } function vec3(x,y,z) { return new THREE.Vector3(x,y,z); } SCENE = {}; SCENE.getCard = function(boxW, boxH, rotZ) { boxD = 0.1; if (!rotZ) rotZ = 0; //report("getImageCard "+imageUrl); var material = new THREE.MeshLambertMaterial( { color: 0xdddddd, //map: THREE.ImageUtils.loadTexture(imageUrl) //transparent: true }); material.side = THREE.DoubleSide; material.transparency = 0.5; var geometry = new THREE.PlaneGeometry( boxW, boxH ); var obj = new THREE.Mesh( geometry, material ); var card = new THREE.Object3D(); card.add(obj); obj.rotation.z = rotZ; obj.position.y += 0.5*boxH + boxD; obj.position.x += 0.0*boxW; obj.position.z += 0.0*boxD; card.obj = obj; card.material = material; return card; } var scene; SCENE.scene = scene; if ( ! Detector.webgl ) Detector.addGetWebGLMessage(); var container, stats; var camera, renderer; var object, arrow; var useFog = true; var useGround = true; function start() { init(); animate(); } function init() { P = {}; P.v0 = 0.04; P.theta0 = 0; P.xbias = 0; P.lastTrackedTime = 0; P.pauseTime = 5; container = document.createElement( 'div' ); document.body.appendChild( container ); // scene scene = new THREE.Scene(); clearColor = 0xcce0ff; if (useFog) //scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 ); //NOFOG scene.fog = new THREE.Fog( clearColor, 500, 10000 ); //NOFOG //scene.fog = new THREE.Fog( 0xcce0ff, 500, 50000 ); //NOFOG // camera //camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 10000 ); camera = new THREE.PerspectiveCamera( 30, window.innerWidth / window.innerHeight, 1, 30000 ); camera.position.y = 50; camera.position.z = 1500; scene.add( camera ); P.camera = camera; // lights var light, materials; scene.add( new THREE.AmbientLight( 0x666666 ) ); var group = new THREE.Scene(); scene.add(group); light = new THREE.DirectionalLight( 0xdfebff, 1.75 ); light.position.set( 50, 200, 100 ); light.position.multiplyScalar( 1.3 ); light.castShadow = true; //light.shadowCameraVisible = true; light.shadowMapWidth = 1024; light.shadowMapHeight = 1024; //var d = 300; var d = 1200; light.shadowCameraLeft = -d; light.shadowCameraRight = d; light.shadowCameraTop = d; light.shadowCameraBottom = -d; light.shadowCameraFar = 1000; light.shadowDarkness = 0.5; scene.add( light ); // ground if (useGround) { var texLoader = new THREE.TextureLoader(); //var groundTexture = texLoader.load( "textures/terrain/grasslight-big.jpg" ); //groundTexture.repeat.set( 25, 25 ); //var groundTexture = texLoader.load( "textures/terrain/dark_grass.png" ); //groundTexture.repeat.set( 15, 15 ); var groundTexture = texLoader.load( "textures/terrain/red_earth.png" ); groundTexture.repeat.set( 15, 15 ); //var groundTexture = texLoader.load( "textures/terrain/BrownLeaves.jpg" ); groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping; //groundTexture.repeat.set( 5, 5 ); groundTexture.anisotropy = 16; var groundMaterial = new THREE.MeshPhongMaterial( { color: 0x664444, specular: 0x111111, map: groundTexture } ); var mesh = new THREE.Mesh( new THREE.PlaneBufferGeometry( 20000, 20000 ), groundMaterial ); mesh.position.y = -250; mesh.rotation.x = - Math.PI / 2; mesh.receiveShadow = true; scene.add( mesh ); } // renderer = new THREE.WebGLRenderer( { antialias: true } ); renderer.setPixelRatio( window.devicePixelRatio ); renderer.setSize( window.innerWidth, window.innerHeight ); renderer.setClearColor( clearColor ); //NOFOG container.appendChild( renderer.domElement ); renderer.gammaInput = true; renderer.gammaOutput = true; //renderer.shadowMapEnabled = true; renderer.shadowMap.enabled = true; // stats = new Stats(); container.appendChild( stats.domElement ); // window.addEventListener( 'resize', onWindowResize, false ); trackball = 1; if (trackball) { //controls = new THREE.TrackballControls( camera, container ); //controls = new THREE.EditorControls( camera, container ); //controls = new THREE.OrthographicTrackballControls( camera, container ); //controls = new THREE.OrbitControls( camera, container ); controls = new THREE.PVControls( camera, container, scene ); controls.rotateSpeed = 2.0; controls.zoomSpeed = 1.2; controls.panSpeed = 0.8; controls.noZoom = false; controls.noPan = false; controls.staticMoving = true; controls.dynamicDampingFactor = 0.3; controls.keys = [ 65, 83, 68 ]; //controls.addEventListener( 'change', render ); } } function onWindowResize() { camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize( window.innerWidth, window.innerHeight ); } // function animate() { requestAnimationFrame( animate ); render(); var time = Date.now(); //arrow.setLength( windMag ); //arrow.setDirection( SKIRT.windForce ); var ct = new Date().getTime() / 1000; // Adjust renderer.render( scene, camera ); stats.update(); } function render() { var timer = Date.now() * 0.0002; //sphere.position.copy( ballPosition ); //camera.lookAt( scene.position ); }
#!/usr/bin/env node var mkdirp = require('yeoman-generator/node_modules/mkdirp') var path = require('path') var fs = require('fs') var win32 = process.platform === 'win32' var homeDir = process.env[ win32? 'USERPROFILE' : 'HOME'] var libPath = path.join(homeDir, '.generator-lego', 'node_modules') var configPath = path.join(homeDir, '.generator-lego', 'config.json') // USERPROFILE 文件夹创建 mkdirp.sync(libPath) fs.writeFileSync(configPath, JSON.stringify({}, null, 4), { encoding: 'utf8' })
exports.platform = function () { switch(process.platform){ case 'win32': dep='win'; break; case 'linux': case 'mac': dep=process.platform; } return 'node-' + dep; };
var add = require('./add'); QUnit.test('add example', function () { // add function returns sum of numbers QUnit.equal(add(2, 3), 5); // it also concatenates strings QUnit.equal(add('foo', 'bar'), 'foobar') });
/* * Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. * See LICENSE in the project root for license information. */ /** * This sample shows how to: * - Get the current user's metadata * - Get the current user's profile photo * - Attach the photo as a file attachment to an email message * - Upload the photo to the user's root drive * - Get a sharing link for the file and add it to the message * - Send the email */ const express = require('express'); const router = express.Router(); const graphHelper = require('../utils/graphHelper.js'); const emailer = require('../utils/emailer.js'); const passport = require('passport'); // ////const fs = require('fs'); // ////const path = require('path'); // Get the home page. router.get('/', (req, res) => { // check if user is authenticated if (!req.isAuthenticated()) { res.render('login'); } else { renderSendMail(req, res); } }); // Authentication request. router.get('/login', passport.authenticate('azuread-openidconnect', { failureRedirect: '/' }), (req, res) => { res.redirect('/'); }); // Authentication callback. // After we have an access token, get user data and load the sendMail page. router.get('/token', passport.authenticate('azuread-openidconnect', { failureRedirect: '/' }), (req, res) => { graphHelper.getUserData(req.user.accessToken, (err, user) => { if (!err) { req.user.profile.displayName = user.body.displayName; req.user.profile.emails = [{ address: user.body.mail || user.body.userPrincipalName }]; renderSendMail(req, res); } else { renderError(err, res); } }); }); // Load the sendMail page. function renderSendMail(req, res) { res.render('sendMail', { display_name: req.user.profile.displayName, email_address: req.user.profile.emails[0].address }); } // Do prep before building the email message. // The message contains a file attachment and embeds a sharing link to the file in the message body. function prepForEmailMessage(req, callback) { const accessToken = req.user.accessToken; const displayName = req.user.profile.displayName; const destinationEmailAddress = req.body.default_email; // Get the current user's profile photo. graphHelper.getProfilePhoto(accessToken, (errPhoto, profilePhoto) => { // //// TODO: MSA flow with local file (using fs and path?) if (!errPhoto) { // Upload profile photo as file to OneDrive. graphHelper.uploadFile(accessToken, profilePhoto, (errFile, file) => { // Get sharingLink for file. graphHelper.getSharingLink(accessToken, file.id, (errLink, link) => { const mailBody = emailer.generateMailBody( displayName, destinationEmailAddress, link.webUrl, profilePhoto ); callback(null, mailBody); }); }); } else { var fs = require('fs'); var readableStream = fs.createReadStream('public/img/test.jpg'); var picFile; var chunk; readableStream.on('readable', function() { while ((chunk=readableStream.read()) != null) { picFile = chunk; } }); readableStream.on('end', function() { graphHelper.uploadFile(accessToken, picFile, (errFile, file) => { // Get sharingLink for file. graphHelper.getSharingLink(accessToken, file.id, (errLink, link) => { const mailBody = emailer.generateMailBody( displayName, destinationEmailAddress, link.webUrl, picFile ); callback(null, mailBody); }); }); }); } }); } // Send an email. router.post('/sendMail', (req, res) => { const response = res; const templateData = { display_name: req.user.profile.displayName, email_address: req.user.profile.emails[0].address, actual_recipient: req.body.default_email }; prepForEmailMessage(req, (errMailBody, mailBody) => { if (errMailBody) renderError(errMailBody); graphHelper.postSendMail(req.user.accessToken, JSON.stringify(mailBody), (errSendMail) => { if (!errSendMail) { response.render('sendMail', templateData); } else { if (hasAccessTokenExpired(errSendMail)) { errSendMail.message += ' Expired token. Please sign out and sign in again.'; } renderError(errSendMail, response); } }); }); }); router.get('/disconnect', (req, res) => { req.session.destroy(() => { req.logOut(); res.clearCookie('graphNodeCookie'); res.status(200); res.redirect('/'); }); }); // helpers function hasAccessTokenExpired(e) { let expired; if (!e.innerError) { expired = false; } else { expired = e.forbidden && e.message === 'InvalidAuthenticationToken' && e.response.error.message === 'Access token has expired.'; } return expired; } /** * * @param {*} e * @param {*} res */ function renderError(e, res) { e.innerError = (e.response) ? e.response.text : ''; res.render('error', { error: e }); } module.exports = router;
(function($,window){ })(Zepto,window);
module.exports = require('./src/angularjs-dependencies-wrapper');
describe('async methods', () => { it('commits multiple valid inserts to the database', done => { const methodUnderTest = async (unitOfWork) => { const insert = { method: 'insert' }; await new unitOfWork.Users(getUserWithEmail('1')).save(null, insert); await new unitOfWork.Users(getUserWithEmail('2')).save(null, insert); await new unitOfWork.Users(getUserWithEmail('3')).save(null, insert); }; new SomeService(methodUnderTest) .runMethodUnderTest() .then(() => bookshelf.Users.count()) .then(count => expect(count).to.equal('3')) .then(() => done(), done); }) });
'use strict'; var CurrentCourseStore = require('../../../js/stores/CurrentCourseStore'); var CourseActions = require('../../../js/actions/CourseActions'); require('../../../utils/createAuthenticatedSuite')('Store: CurrentCourse', function() { it('should be empty on init', function(done) { (CurrentCourseStore.course === null).should.be.true; // jshint ignore:line done(); }); it('should set course on action', function(done) { var course = { id: 1 }; CourseActions.setCourse(course, function(err) { (err === null).should.be.true; // jshint ignore:line CurrentCourseStore.course.should.be.instanceOf(Object); CurrentCourseStore.course.id.should.equal(1); done(); }); }); it('should load a course on action', function(done) { CourseActions.openCourse(1, function(err) { (err === null).should.be.true; // jshint ignore:line CurrentCourseStore.course.should.be.instanceOf(Object); CurrentCourseStore.course.id.should.equal(1); CurrentCourseStore.course.should.have.property('title'); CurrentCourseStore.course.should.have.property('slug'); CurrentCourseStore.course.should.have.property('description'); done(); }); }); it('should create a new lesson on action', function(done) { var lesson = { title: 'lesson to test creation', description: 'test description', bodyElements: [] }; // Make sure `this.course` is set in store before attempting to access `this.course.id` CourseActions.setCourse({ id: 1 }, function() { CourseActions.createLesson(lesson, function(err, lesson) { console.log('error creating lesson:', err); (err === null).should.be.true; // jshint ignore:line lesson.should.be.instanceOf(Object); lesson.should.have.property('title'); lesson.should.have.property('description'); lesson.should.have.property('bodyElements'); done(); }); }); }); });