code
stringlengths
2
1.05M
/** * RuleController * * @description :: Server-side logic for managing rules * @help :: See http://links.sailsjs.org/docs/controllers */ module.exports = { };
/* * Copyright (c) 2012-2016 André Bargull * Alle Rechte vorbehalten / All Rights Reserved. Use is subject to license terms. * * <https://github.com/anba/es6draft> */ const { assertSame } = Assert; // 15.1.2.1: Lexical declarations should always get into a new declarative environment // https://bugs.ecmascript.org/show_bug.cgi?id=1788 { let x = 0; { /* block scope */ eval("let x = 1"); assertSame(0, x); } assertSame(0, x); } function testBlock() { let x = 0; { /* block scope */ eval("let x = 1"); assertSame(0, x); } assertSame(0, x); } testBlock(); function testBlockInner() { { /* block scope */ let x = 0; { /* block scope */ eval("let x = 1"); assertSame(0, x); } assertSame(0, x); } assertSame("undefined", typeof x); } testBlockInner(); { let o = {}; with(o) eval("let x = 1"); assertSame(void 0, o.x); assertSame("undefined", typeof x); } function testWith() { let o = {}; with(o) eval("let x = 1"); assertSame(void 0, o.x); assertSame("undefined", typeof x); } testWith();
'use strict'; module.exports = function concat(grunt) { // Load task grunt.loadNpmTasks('grunt-contrib-concat'); return { options: { banner: '<%= banner %>\n<%= jqueryCheck %>', stripBanners: false }, dist: { src: [ 'js/offcanvas.js' ], dest: 'dist/js/<%= pkg.name %>.js' } }; }
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 _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var __decorate = this && this.__decorate || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);else for (var i = decorators.length - 1; i >= 0; i--) { if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; }return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = this && this.__metadata || function (k, v) { if ((typeof Reflect === "undefined" ? "undefined" : _typeof(Reflect)) === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; import { Component, ComponentResolver, HostListener, ViewChild, ViewContainerRef } from '@angular/core'; import { addSelector } from '../../config/bootstrap'; import { Animation } from '../../animations/animation'; import { NavParams } from '../nav/nav-params'; import { isPresent, pascalCaseToDashCase } from '../../util/util'; import { Key } from '../../util/key'; import { Transition } from '../../transitions/transition'; import { ViewController } from '../nav/view-controller'; import { windowDimensions } from '../../util/dom'; /** * @name Modal * @description * A Modal is a content pane that goes over the user's current page. * Usually it is used for making a choice or editing an item. A modal uses the * `NavController` to * {@link /docs/v2/api/components/nav/NavController/#present present} * itself in the root nav stack. It is added to the stack similar to how * {@link /docs/v2/api/components/nav/NavController/#push NavController.push} * works. * * When a modal (or any other overlay such as an alert or actionsheet) is * "presented" to a nav controller, the overlay is added to the app's root nav. * After the modal has been presented, from within the component instance The * modal can later be closed or "dismissed" by using the ViewController's * `dismiss` method. Additionally, you can dismiss any overlay by using `pop` * on the root nav controller. * * Data can be passed to a new modal through `Modal.create()` as the second * argument. The data can then be accessed from the opened page by injecting * `NavParams`. Note that the page, which opened as a modal, has no special * "modal" logic within it, but uses `NavParams` no differently than a * standard page. * * @usage * ```ts * import {Page, Modal, NavController, NavParams} from 'ionic-angular'; * * @Component(...) * class HomePage { * * constructor(nav: NavController) { * this.nav = nav; * } * * presentProfileModal() { * let profileModal = Modal.create(Profile, { userId: 8675309 }); * this.nav.present(profileModal); * } * * } * * @Component(...) * class Profile { * * constructor(params: NavParams) { * console.log('UserId', params.get('userId')); * } * * } * ``` * * A modal can also emit data, which is useful when it is used to add or edit * data. For example, a profile page could slide up in a modal, and on submit, * the submit button could pass the updated profile data, then dismiss the * modal. * * ```ts * import {Component} from '@angular/core'; * import {Modal, NavController, ViewController} from 'ionic-angular'; * * @Component(...) * class HomePage { * * constructor(nav: NavController) { * this.nav = nav; * } * * presentContactModal() { * let contactModal = Modal.create(ContactUs); * this.nav.present(contactModal); * } * * presentProfileModal() { * let profileModal = Modal.create(Profile, { userId: 8675309 }); * profileModal.onDismiss(data => { * console.log(data); * }); * this.nav.present(profileModal); * } * * } * * @Component(...) * class Profile { * * constructor(viewCtrl: ViewController) { * this.viewCtrl = viewCtrl; * } * * dismiss() { * let data = { 'foo': 'bar' }; * this.viewCtrl.dismiss(data); * } * * } * ``` * @demo /docs/v2/demos/modal/ * @see {@link /docs/v2/components#modals Modal Component Docs} */ export var Modal = function (_ViewController) { _inherits(Modal, _ViewController); function Modal(componentType) { var data = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; _classCallCheck(this, Modal); data.componentType = componentType; opts.showBackdrop = isPresent(opts.showBackdrop) ? !!opts.showBackdrop : true; opts.enableBackdropDismiss = isPresent(opts.enableBackdropDismiss) ? !!opts.enableBackdropDismiss : true; data.opts = opts; var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(Modal).call(this, ModalCmp, data)); _this.modalViewType = componentType.name; _this.viewType = 'modal'; _this.isOverlay = true; _this.usePortal = true; return _this; } /** * @private */ _createClass(Modal, [{ key: "getTransitionName", value: function getTransitionName(direction) { var key = direction === 'back' ? 'modalLeave' : 'modalEnter'; return this._nav && this._nav.config.get(key); } /** * Create a modal with the following options * * | Option | Type | Description | * |-----------------------|------------|------------------------------------------------------------------------------------------------------------------| * | showBackdrop |`boolean` | Whether to show the backdrop. Default true. | * | enableBackdropDismiss |`boolean` | Whether the popover should be dismissed by tapping the backdrop. Default true. | * * * @param {object} componentType The Modal view * @param {object} data Any data to pass to the Modal view * @param {object} opts Modal options */ }, { key: "loaded", // Override the load method and load our child component value: function loaded(done) { var _this2 = this; // grab the instance, and proxy the ngAfterViewInit method var originalNgAfterViewInit = this.instance.ngAfterViewInit; this.instance.ngAfterViewInit = function () { if (originalNgAfterViewInit) { originalNgAfterViewInit(); } _this2.instance.loadComponent(done); }; } }], [{ key: "create", value: function create(componentType) { var data = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var opts = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; return new Modal(componentType, data, opts); } }]); return Modal; }(ViewController); export var ModalCmp = function () { function ModalCmp(_compiler, _navParams, _viewCtrl) { _classCallCheck(this, ModalCmp); this._compiler = _compiler; this._navParams = _navParams; this._viewCtrl = _viewCtrl; this.d = _navParams.data.opts; } _createClass(ModalCmp, [{ key: "loadComponent", value: function loadComponent(done) { var _this3 = this; addSelector(this._navParams.data.componentType, 'ion-modal-inner'); this._compiler.resolveComponent(this._navParams.data.componentType).then(function (componentFactory) { var componentRef = _this3.viewport.createComponent(componentFactory, _this3.viewport.length, _this3.viewport.parentInjector); _this3._viewCtrl.setInstance(componentRef.instance); _this3.enabled = true; done(); }); } }, { key: "ngAfterViewInit", value: function ngAfterViewInit() { // intentionally kept empty } }, { key: "dismiss", value: function dismiss(role) { return this._viewCtrl.dismiss(null, role); } }, { key: "bdClick", value: function bdClick() { if (this.enabled && this.d.enableBackdropDismiss) { this.dismiss('backdrop'); } } }, { key: "_keyUp", value: function _keyUp(ev) { if (this.enabled && this._viewCtrl.isLast() && ev.keyCode === Key.ESCAPE) { this.bdClick(); } } }]); return ModalCmp; }(); __decorate([ViewChild('viewport', { read: ViewContainerRef }), __metadata('design:type', typeof (_a = typeof ViewContainerRef !== 'undefined' && ViewContainerRef) === 'function' && _a || Object)], ModalCmp.prototype, "viewport", void 0); __decorate([HostListener('body:keyup', ['$event']), __metadata('design:type', Function), __metadata('design:paramtypes', [Object]), __metadata('design:returntype', void 0)], ModalCmp.prototype, "_keyUp", null); ModalCmp = __decorate([Component({ selector: 'ion-modal', template: '<ion-backdrop disableScroll="false" (click)="bdClick($event)"></ion-backdrop>' + '<div class="modal-wrapper">' + '<div #viewport></div>' + '</div>' }), __metadata('design:paramtypes', [typeof (_b = typeof ComponentResolver !== 'undefined' && ComponentResolver) === 'function' && _b || Object, typeof (_c = typeof NavParams !== 'undefined' && NavParams) === 'function' && _c || Object, typeof (_d = typeof ViewController !== 'undefined' && ViewController) === 'function' && _d || Object])], ModalCmp); /** * Animations for modals */ var ModalSlideIn = function (_Transition) { _inherits(ModalSlideIn, _Transition); function ModalSlideIn(enteringView, leavingView, opts) { _classCallCheck(this, ModalSlideIn); var _this4 = _possibleConstructorReturn(this, Object.getPrototypeOf(ModalSlideIn).call(this, opts)); var ele = enteringView.pageRef().nativeElement; var backdropEle = ele.querySelector('ion-backdrop'); var backdrop = new Animation(backdropEle); var wrapper = new Animation(ele.querySelector('.modal-wrapper')); var page = ele.querySelector('ion-page'); var pageAnimation = new Animation(page); // auto-add page css className created from component JS class name var cssClassName = pascalCaseToDashCase(enteringView.modalViewType); pageAnimation.before.addClass(cssClassName); pageAnimation.before.addClass('show-page'); backdrop.fromTo('opacity', 0.01, 0.4); wrapper.fromTo('translateY', '100%', '0%'); _this4.element(enteringView.pageRef()).easing('cubic-bezier(0.36,0.66,0.04,1)').duration(400).add(backdrop).add(wrapper).add(pageAnimation); if (enteringView.hasNavbar()) { // entering page has a navbar var enteringNavBar = new Animation(enteringView.navbarRef()); enteringNavBar.before.addClass('show-navbar'); _this4.add(enteringNavBar); } return _this4; } return ModalSlideIn; }(Transition); Transition.register('modal-slide-in', ModalSlideIn); var ModalSlideOut = function (_Transition2) { _inherits(ModalSlideOut, _Transition2); function ModalSlideOut(enteringView, leavingView, opts) { _classCallCheck(this, ModalSlideOut); var _this5 = _possibleConstructorReturn(this, Object.getPrototypeOf(ModalSlideOut).call(this, opts)); var ele = leavingView.pageRef().nativeElement; var backdrop = new Animation(ele.querySelector('ion-backdrop')); var wrapperEle = ele.querySelector('.modal-wrapper'); var wrapperEleRect = wrapperEle.getBoundingClientRect(); var wrapper = new Animation(wrapperEle); // height of the screen - top of the container tells us how much to scoot it down // so it's off-screen var screenDimensions = windowDimensions(); wrapper.fromTo('translateY', '0px', screenDimensions.height - wrapperEleRect.top + "px"); backdrop.fromTo('opacity', 0.4, 0.0); _this5.element(leavingView.pageRef()).easing('ease-out').duration(250).add(backdrop).add(wrapper); return _this5; } return ModalSlideOut; }(Transition); Transition.register('modal-slide-out', ModalSlideOut); var ModalMDSlideIn = function (_Transition3) { _inherits(ModalMDSlideIn, _Transition3); function ModalMDSlideIn(enteringView, leavingView, opts) { _classCallCheck(this, ModalMDSlideIn); var _this6 = _possibleConstructorReturn(this, Object.getPrototypeOf(ModalMDSlideIn).call(this, opts)); var ele = enteringView.pageRef().nativeElement; var backdrop = new Animation(ele.querySelector('ion-backdrop')); var wrapper = new Animation(ele.querySelector('.modal-wrapper')); var page = ele.querySelector('ion-page'); var pageAnimation = new Animation(page); // auto-add page css className created from component JS class name var cssClassName = pascalCaseToDashCase(enteringView.modalViewType); pageAnimation.before.addClass(cssClassName); pageAnimation.before.addClass('show-page'); backdrop.fromTo('opacity', 0.01, 0.4); wrapper.fromTo('translateY', '40px', '0px'); wrapper.fromTo('opacity', '0.01', '1.0'); var DURATION = 280; var EASING = 'cubic-bezier(0.36,0.66,0.04,1)'; _this6.element(enteringView.pageRef()).easing(EASING).duration(DURATION).add(backdrop).add(wrapper).add(pageAnimation); if (enteringView.hasNavbar()) { // entering page has a navbar var enteringNavBar = new Animation(enteringView.navbarRef()); enteringNavBar.before.addClass('show-navbar'); _this6.add(enteringNavBar); } return _this6; } return ModalMDSlideIn; }(Transition); Transition.register('modal-md-slide-in', ModalMDSlideIn); var ModalMDSlideOut = function (_Transition4) { _inherits(ModalMDSlideOut, _Transition4); function ModalMDSlideOut(enteringView, leavingView, opts) { _classCallCheck(this, ModalMDSlideOut); var _this7 = _possibleConstructorReturn(this, Object.getPrototypeOf(ModalMDSlideOut).call(this, opts)); var ele = leavingView.pageRef().nativeElement; var backdrop = new Animation(ele.querySelector('ion-backdrop')); var wrapper = new Animation(ele.querySelector('.modal-wrapper')); backdrop.fromTo('opacity', 0.4, 0.0); wrapper.fromTo('translateY', '0px', '40px'); wrapper.fromTo('opacity', '1.0', '0.00'); _this7.element(leavingView.pageRef()).duration(200).easing('cubic-bezier(0.47,0,0.745,0.715)').add(wrapper).add(backdrop); return _this7; } return ModalMDSlideOut; }(Transition); Transition.register('modal-md-slide-out', ModalMDSlideOut); var _a, _b, _c, _d;
require('source-map-support').install(); var assert = require('chai').assert; var sinon = require('sinon'); var AuctionSniper = require('../src/AuctionSniper'); var SNIPER_ID = 'sniper'; const ITEM_ID = 'item-5347'; describe('auction sniper', () => { let mockListener; let mockAuction; let sniper; let priceSource; beforeEach('init mock listener', ()=>{ mockAuction = { itemId: ITEM_ID, bid : sinon.spy() }; mockListener = { sniperLost : sinon.spy(), sniperBidding : sinon.spy(), sniperWon : sinon.spy(), sniperWinning : sinon.spy() }; priceSource = { FROM_OTHER_BIDDER: 'someone else', FROM_SNIPER: 'sniper' }; sniper = new AuctionSniper(mockAuction, mockListener); }); it('reports lost when auction closes immediately', () => { sniper.auctionClosed(); assert(mockListener.sniperLost.calledOnce, 'listener.sniperLost not called once'); }); it('reports lost if auction closes when bidding', () => { let price = 1001; let increment = 25; sniper.currentPrice(price, increment, priceSource.FROM_OTHER_BIDDER); sniper.auctionClosed(); assert(mockListener.sniperBidding.calledOnce, 'listener.sniperBidding not called once'); assert(mockListener.sniperLost.calledOnce, 'listener.sniperLost not called once'); assert(mockListener.sniperBidding.calledBefore(mockListener.sniperLost), 'listener.sniperBidding not called before listener.sniperLost'); }); it('bids higher and reports bidding when new price arrives', () => { let price = 1001; let increment = 25; sniper.currentPrice(price, increment, priceSource.FROM_OTHER_BIDDER); assert(mockAuction.bid.calledOnce, 'auction.bid not called once'); assert(mockAuction.bid.calledWithExactly(SNIPER_ID, price + increment), 'auction.bid not called with right arguments'); assert(mockListener.sniperBidding.calledOnce, 'listener.sniperBidding not called once'); assert(mockListener.sniperBidding.calledWithExactly(ITEM_ID, price, price + increment), 'listener.sniperBidding not called with right arguments'); }); it('reports is winning when current price comes from sniper', function () { let price = 123; let increment = 45; sniper.currentPrice(price, increment, priceSource.FROM_SNIPER); assert(mockListener.sniperWinning.calledOnce, 'listener.sniperWinning not called once'); }); it('reports won if auction closes when winning', function () { let price = 123; let increment = 45; sniper.currentPrice(price, increment, priceSource.FROM_SNIPER); sniper.auctionClosed(); assert(mockListener.sniperWinning.calledOnce, 'listener.sniperWinning not called once'); assert(mockListener.sniperWon.calledOnce, 'listener.sniperWon not called once'); assert(mockListener.sniperWinning.calledBefore(mockListener.sniperWon), 'listener.sniperWinning not called before listener.sniperWon'); }); });
/*global describe, it*/ "use strict"; var fs = require("fs"), should = require("should"); require("mocha"); delete require.cache[require.resolve("../")]; var gutil = require("gulp-util"), includer = require("../"); describe("gulp-includer", function () { var expectedFile = new gutil.File({ path: "test/expected/entry.js", cwd: "test/", base: "test/expected", contents: fs.readFileSync("test/expected/entry.js") }); it("should produce expected file via buffer", function (done) { var srcFile = new gutil.File({ path: "test/fixtures/entry.js", cwd: "test/", base: "test/fixtures", contents: fs.readFileSync("test/fixtures/entry.js") }); var stream = includer(); stream.on("error", function (err) { should.exist(err); done(err); }); stream.on("data", function (newFile) { process.nextTick(function () { should.exist(newFile); should.exist(newFile.contents); String(newFile.contents).should.equal(String(expectedFile.contents)); done(); }); }); stream.write(srcFile); stream.end(); }); });
module.exports = [[1, 2, 3, 4, 5, 6, 7]];
module.exports = Cmds.addCommand({ cmds: [";channels"], requires: { guild: true, loud: false }, desc: "Get all guild channels", args: "", example: "", /////////////////////////////////////////////////////////////////////////////////////////// func: (cmd, args, msgObj, speaker, channel, guild) => { var outStr = []; outStr.push("**Guild text channels:**\n```"); Util.getTextChannels(guild).forEach(function(value, index, self) { outStr.push("Channel: " + value.name + " (" + value.id + ") | Topic: " + value.topic + " | Position: " + value.position + " | Created: " + value.createdAt); }); outStr.push("```"); outStr.push("**Guild voice channels:**\n```"); Util.getVoiceChannels(guild).forEach(function(value, index, self) { outStr.push("Channel: " + value.name + " (" + value.id + ") | Topic: " + value.topic + " | Position: " + value.position + " | Created: " + value.createdAt + " | Bitrate: " + value.bitrate); }); Util.print(channel, outStr.join("\n")); } });
export { default } from './GithubLink';
(function ($, window, document) { 'use strict'; var cssTransitionSupport = function () { var s = document.body || document.documentElement; s = s.style; if (s.WebkitTransition === '') { return '-webkit-'; } if (s.MozTransition === '') { return '-moz-'; } if (s.OTransition === '') { return '-o-'; } if (s.transition === '') { return ''; } return false; }; var isCssTransitionSupport = cssTransitionSupport() !== false; var cssTransitionTranslateX = function (element, positionX, speed) { var options = {}, prefix = cssTransitionSupport(); options[prefix + 'transform'] = 'translateX(' + positionX + ')'; options[prefix + 'transition'] = prefix + 'transform ' + speed + 's linear'; element.css(options); }; var CONST_HASTOUCH = ('ontouchstart' in window); var CONST_HASPOINTERS = window.navigator.pointerEnabled || window.navigator.msPointerEnabled; var wasTouched = function (event) { if (CONST_HASTOUCH) { return true; } if (!CONST_HASPOINTERS || typeof event === 'undefined' || typeof event.pointerType === 'undefined') { return false; } if (typeof event.MSPOINTER_TYPE_MOUSE !== 'undefined') { if (event.MSPOINTER_TYPE_MOUSE !== event.pointerType) { return true; } } else if (event.pointerType !== 'mouse') { return true; } return false; }; $.fn.imageLightbox = function (opts) { // private data members var options = $.extend({ selector: 'id="imagelightbox"', animationSpeed: 250, preloadNext: true, enableKeyboard: true, quitOnEnd: false, quitOnImgClick: false, quitOnDocClick: true, quitOnEscKey: true, // quit when Esc key is pressed // custom callbacks onStart: undefined, // fired when lightbox opens onLoadStart: undefined, // fired a new image starts to load (after onStart) onLoadEnd: undefined, // fired after a new image has loaded onEnd: undefined, // fired when lightbox closes previousTarget: function () { var targetIndex = ILBState.targetsArray.index(ILBState.target) - 1; if (targetIndex < 0) { if (options.quitOnEnd) { quitLightbox(); return false; } targetIndex = ILBState.targetsArray.length - 1; } ILBState.target = ILBState.targetsArray.eq(targetIndex); }, nextTarget: function () { var targetIndex = ILBState.targetsArray.index(ILBState.target) + 1; if (targetIndex >= ILBState.targetsArray.length) { if (options.quitOnEnd) { quitLightbox(); return false; } targetIndex = 0; } ILBState.target = ILBState.targetsArray.eq(targetIndex); }, }, opts); var ILBState = { targetsArray: $([]), target: $(), img: $(), imageWidth: 0, imageHeight: 0, swipeDiff: 0, currentlyLoadingAnImage: false, }; // private methods var setImage = function () { if (!ILBState.img.length) { return true; } var screenWidth = $(window).width() * 0.8; var screenHeight = $(window).height() * 0.9; var tmpImage = new Image(); tmpImage.src = ILBState.img.attr('src'); tmpImage.onload = function () { ILBState.imageWidth = tmpImage.width; ILBState.imageHeight = tmpImage.height; if (ILBState.imageWidth > screenWidth || ILBState.imageHeight > screenHeight) { var ratio = ILBState.imageWidth / ILBState.imageHeight > screenWidth / screenHeight ? ILBState.imageWidth / screenWidth: ILBState.imageHeight / screenHeight; ILBState.imageWidth /= ratio; ILBState.imageHeight /= ratio; } ILBState.img.css({ 'width': ILBState.imageWidth + 'px', 'height': ILBState.imageHeight + 'px', 'top': ($(window).height() - ILBState.imageHeight) / 2 + 'px', 'left': ($(window).width() - ILBState.imageWidth) / 2 + 'px', }); }; }; var loadImage = function (direction) { if (ILBState.currentlyLoadingAnImage) { return false; } direction = typeof direction === 'undefined' ? false: direction === 'left' ? 1: -1; if (ILBState.img.length) { var params = { 'opacity': 0, }; if (isCssTransitionSupport) { cssTransitionTranslateX(ILBState.img, (100 * direction) - ILBState.swipeDiff + 'px', options.animationSpeed / 1000); } else { params.left = parseInt(ILBState.img.css('left')) + 100 * direction + 'px'; } ILBState.img.animate(params, options.animationSpeed, function () { removeImage(); }); ILBState.swipeDiff = 0; } ILBState.currentlyLoadingAnImage = true; if (typeof options.onLoadStart === 'function') { options.onLoadStart(); } setTimeout(function () { var imgPath = ILBState.target.attr('href'); if (imgPath === undefined) { imgPath = ILBState.target.attr('data-lightbox'); } ILBState.img = $('<img ' + options.selector + ' />') .attr('src', imgPath) .load(function () { ILBState.img.appendTo('body'); setImage(); var params = { 'opacity': 1, }; ILBState.img.css('opacity', 0); if (isCssTransitionSupport) { cssTransitionTranslateX(ILBState.img, -100 * direction + 'px', 0); setTimeout(function () { cssTransitionTranslateX(ILBState.img, 0 + 'px', options.animationSpeed / 1000); }, 50); } else { var imagePosLeft = parseInt(ILBState.img.css('left')); params.left = imagePosLeft + 'px'; ILBState.img.css('left', imagePosLeft - 100 * direction + 'px'); } ILBState.img.animate(params, options.animationSpeed, function () { ILBState.currentlyLoadingAnImage = false; if (typeof options.onLoadEnd === 'function') { options.onLoadEnd(); } }); if (options.preloadNext) { var nextTarget = ILBState.targetsArray.eq(ILBState.targetsArray.index(ILBState.target) + 1); if (!nextTarget.length) { nextTarget = ILBState.targetsArray.eq(0); } $('<img />').attr('src', nextTarget.attr('href')).load(); } }) .error(function () { if (typeof options.onLoadEnd === 'function') { options.onLoadEnd(); } }); var swipeStart = 0; var swipeEnd = 0; var imagePosLeft = 0; ILBState.img.on(CONST_HASPOINTERS ? 'pointerup MSPointerUp': 'click', function (e) { e.preventDefault(); if (options.quitOnImgClick) { quitLightbox(); return false; } if (wasTouched(e.originalEvent)) { return true; } var posX = (e.pageX || e.originalEvent.pageX) - e.target.offsetLeft; if (ILBState.imageWidth / 2 > posX) { loadPreviousImage(); } else { loadNextImage(); } }) .on('touchstart pointerdown MSPointerDown', function (e) { if (!wasTouched(e.originalEvent) || options.quitOnImgClick) { return true; } if (isCssTransitionSupport) { imagePosLeft = parseInt(ILBState.img.css('left')); } swipeStart = e.originalEvent.pageX || e.originalEvent.touches[0].pageX; }) .on('touchmove pointermove MSPointerMove', function (e) { if (!wasTouched(e.originalEvent) || options.quitOnImgClick) { return true; } e.preventDefault(); swipeEnd = e.originalEvent.pageX || e.originalEvent.touches[0].pageX; ILBState.swipeDiff = swipeStart - swipeEnd; if (isCssTransitionSupport) { cssTransitionTranslateX(ILBState.img, -ILBState.swipeDiff + 'px', 0); } else { ILBState.img.css('left', imagePosLeft - ILBState.swipeDiff + 'px'); } }) .on('touchend touchcancel pointerup pointercancel MSPointerUp MSPointerCancel', function (e) { if (!wasTouched(e.originalEvent) || options.quitOnImgClick) { return true; } if (Math.abs(ILBState.swipeDiff) > 50) { if (ILBState.swipeDiff < 0) { loadPreviousImage(); } else { loadNextImage(); } } else { if (isCssTransitionSupport) { cssTransitionTranslateX(ILBState.img, 0 + 'px', options.animationSpeed / 1000); } else { ILBState.img.animate({ 'left': imagePosLeft + 'px' }, options.animationSpeed / 2); } } }); }, options.animationSpeed + 100); }; var loadPreviousImage = function () { if (options.previousTarget() !== false) { loadImage('left'); } }; var loadNextImage = function () { if (options.nextTarget() !== false) { loadImage('right'); } }; var removeImage = function () { if (!ILBState.img.length) { return false; } ILBState.img.remove(); ILBState.img = $(); }; var quitLightbox = function () { if (!ILBState.img.length) { return false; } ILBState.img.animate({ 'opacity': 0 }, options.animationSpeed, function () { removeImage(); ILBState.currentlyLoadingAnImage = false; if (typeof options.onEnd === 'function') { options.onEnd(); } }); }; // public methods this.startImageLightbox = function (e) { if (e !== undefined) { e.preventDefault(); } if (ILBState.currentlyLoadingAnImage) { return false; } if (typeof options.onStart === 'function') { options.onStart(); } ILBState.target = $(this); loadImage(); }; this.switchImageLightbox = function (index) { var tmpTarget = ILBState.targetsArray.eq(index); if (tmpTarget.length) { var currentIndex = ILBState.targetsArray.index(ILBState.target); ILBState.target = tmpTarget; loadImage(index < currentIndex ? 'left': 'right'); } return this; }; this.loadPreviousImage = function () { loadPreviousImage(); }; this.loadNextImage = function () { loadNextImage(); }; this.quitImageLightbox = function () { quitLightbox(); return this; }; // events $(document).off('click', this.selector); $(document).on('click', this.selector, this.startImageLightbox); $(window).on('resize', setImage); // "constructor" if (options.quitOnDocClick) { $(document).on(CONST_HASTOUCH ? 'touchend': 'click', function (e) { if (ILBState.img.length && !$(e.target).is(ILBState.img)) { quitLightbox(); } }); } if (options.enableKeyboard) { $(document).on('keyup', function (e) { if (!ILBState.img.length) { return true; } e.preventDefault(); if (e.keyCode === 27 && options.quitOnEscKey) { quitLightbox(); } if (e.keyCode === 37) { loadPreviousImage(); } else if (e.keyCode === 39) { loadNextImage(); } }); } this.each(function () { ILBState.targetsArray = ILBState.targetsArray.add($(this)); }); return this; }; })(jQuery, window, document);
import angular from 'angular'; import 'angular-route'; import '../style/app.css'; global.jQuery = require('jquery'); require('bootstrap-loader'); var jsonUrl = "/json/" var jsonName = "esp-" var app = angular.module("JsonRecordApp", ["ngRoute"]); app.config(function($routeProvider, $locationProvider){ $routeProvider .when('/add',{ templateUrl: 'add.html', controller: 'addCtrl' }) .when('/get',{ templateUrl: 'get.html', controller: 'getCtrl' }) .when('/modify',{ templateUrl: 'modify.html', controller: 'modifyCtrl' }) .otherwise({ redirectTo: '/get' }); });
var filterGitSha = require('./filterGitSha.js'); var expect = require('chai').expect; describe('filterGitSha', function () { var actual; var expected; describe('smoke tests', function () { it('should exist', function () { // Expected an assignment or function call and instead saw an expression. /* jshint -W030 */ expect(filterGitSha).to.exist; }); it('should be a function', function () { expect(filterGitSha).to.be.a('function'); }); it('test 1', function () { expect(filterGitSha(['foo', 'bar'])).to.eql(['foo', 'bar']); }); it('test 2', function () { expect(filterGitSha([23, 42])).to.eql([23, 42]); }); }); describe('tests', function () { it('test 3', function () { actual = filterGitSha([ '06f58df', 'this', '08b3763', '09284e3', 'should', '0c6d074', '0dbb6b0', 'be', '1401dde', '1bbffe3', '25cd792', '272330e', 'left', '4996a04' ]); expected = [ 'this', 'should', 'be', 'left' ]; expect(actual).to.eql(expected); }); it('test 4', function () { actual = filterGitSha([ '5db945g', '636ac81' ]); expected = [ '5db945g' ]; expect(actual).to.eql(expected); }); it('test 5', function () { actual = filterGitSha([ '5db945aa', '636ac81' ]); expected = [ '5db945aa' ]; expect(actual).to.eql(expected); }); it('should not filter words that are all letters', function () { expect(filterGitSha(['deedeed', '06f58df'])).to.eql(['deedeed']); }); it('should not filter words that are all numbers', function () { expect(filterGitSha(['0123456', '06f58df'])).to.eql(['0123456']); }); }); describe('40 character', function () { it('test 6', function () { actual = filterGitSha([ '606b8f77af3456639a3bfa9e73c9171771fc9482', '3452b0c4c051161b39291793be2ad36c4a26d120', '8e3e17ecf0e2bfa682eeaa078eda661708f3706e', 'leave this', 'cd55551224dbbef683653d19793a219bc1fd6558', 'b8553adbdb283f9dc73c4e0d6d6cd307db3d1117', '42dc77f365a2fb59499c1523075bfe9bcf6ddaca', '20fadb666950abb481f8c7fab6e5dad05e027ef7' ]); expected = [ 'leave this' ]; expect(actual).to.eql(expected); }); }); });
var FIREBASE_URL = 'https://sketch-gallery-test.firebaseio.com'; var Stream = require('stream').Transform; module.exports = function(method, path, data, auth, callback) { var http = require(FIREBASE_URL.split('://')[0]); var options = { host: FIREBASE_URL.split('://')[1], method: method, path: path + '.json' + (auth ? '?auth=' + auth : ''), } var request = http.request(options, function(response) { var data = new Stream(); response.on('data', function(chunk) { data.push(chunk); }); response.on('end', function() { callback && callback(data.read().toString()); }); }); if (data) { request.write(data); } request.end(); };
/** * Object.keys polyfill * https://gist.github.com/atk/1034464 */ Object.keys=Object.keys||function(o,k,r){r=[];for(k in o)r.hasOwnProperty.call(o,k)&&r.push(k);return r} /** * Array.prototype.find polyfill * https://github.com/paulmillr/Array.prototype.find */ Array.prototype.find||function(){var a=function(a){var b=Object(this),c=b.length<0?0:b.length>>>0;if(0===c)return void 0;if('function'!==typeof a||'[object Function]'!==Object.prototype.toString.call(a))throw new TypeError('Array#find: predicate must be a function');for(var f,d=arguments[1],e=0;c>e;e++)if(f=b[e],a.call(d,f,e,b))return f;return void 0};if(Object.defineProperty)try{Object.defineProperty(Array.prototype,'find',{value:a,configurable:!0,enumerable:!1,writable:!0})}catch(b){}Array.prototype.find=Array.prototype.find||a}(); /** * Element.prototype.matchesSelector polyfill * https://gist.github.com/jonathantneal/3062955 */ (function(E){E.matchesSelector=E.matchesSelector||E.mozMatchesSelector||E.msMatchesSelector||E.oMatchesSelector||E.webkitMatchesSelector||function(s){var n=this,ns=(n.parentNode||n.document).querySelectorAll(s),i=-1;while(ns[++i]&&ns[i]!==n);return !!ns[i];}})(Element.prototype); /** * @ngdoc module * @name pouch-model * @description * * # pouch-model * * The `pouch-model` module provides PouchDB-based model "classes" * for Angular via the `$pouchModel` service. * * See {@link pouch-model.$pouchModel `$pouchModel`} for usage. */ angular.module('pouch-model', []); var $pouchModelMinErr = angular.$$minErr('$pouchModel');
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'bundle.js' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }, { test: /\.(png|jpg|gif|svg)$/, loader: 'url-loader', } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false } }), new webpack.LoaderOptionsPlugin({ minimize: true }) ]) }
/** * Created by albertin on 07/06/14. */ var canadianDollar = 0.91; function roundTwoDecimals(amount){ return Math.round(amount * 100) / 100; } exports.canadianToUS = function(canadian){ return roundTwoDecimals(canadian * canadianDollar); }; exports.USToCanadian = function(us){ return roundTwoDecimals(us / canadianDollar); };
if (typeof exports != "undefined") { var driver = require("./driver.js"); var test = driver.test, testFail = driver.testFail, testAssert = driver.testAssert, misMatch = driver.misMatch; var acorn = require(".."); } //----------------------------------------------------------------------------- // Async Function Declarations // async == false test("function foo() { }", { "type": "Program", "start": 0, "end": 18, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 18, "id": { "type": "Identifier", "start": 9, "end": 12, "name": "foo" }, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 15, "end": 18, "body": [] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // async == true test("async function foo() { }", { "type": "Program", "start": 0, "end": 24, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 24, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 21, "end": 24, "body": [] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // a reference and a normal function declaration if there is a linebreak between 'async' and 'function'. test("async\nfunction foo() { }", { "type": "Program", "start": 0, "end": 24, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 5, "expression": { "type": "Identifier", "start": 0, "end": 5, "name": "async" } }, { "type": "FunctionDeclaration", "start": 6, "end": 24, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 21, "end": 24, "body": [] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // export test("export async function foo() { }", { "type": "Program", "start": 0, "end": 31, "body": [ { "type": "ExportNamedDeclaration", "start": 0, "end": 31, "declaration": { "type": "FunctionDeclaration", "start": 7, "end": 31, "id": { "type": "Identifier", "start": 22, "end": 25, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 28, "end": 31, "body": [] } }, "specifiers": [], "source": null } ], "sourceType": "module" }, {ecmaVersion: 8, sourceType: "module"}) // export default test("export default async function() { }", { "type": "Program", "start": 0, "end": 35, "body": [ { "type": "ExportDefaultDeclaration", "start": 0, "end": 35, "declaration": { "type": "FunctionDeclaration", "start": 15, "end": 35, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 32, "end": 35, "body": [] } } } ], "sourceType": "module" }, {ecmaVersion: 8, sourceType: "module"}) // cannot combine with generators testFail("async function* foo() { }", "Unexpected token (1:14)", {ecmaVersion: 8}) // 'await' is valid as function names. test("async function await() { }", { "type": "Program", "start": 0, "end": 26, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 26, "id": { "type": "Identifier", "start": 15, "end": 20, "name": "await" }, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 23, "end": 26, "body": [] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // cannot use 'await' inside async functions. testFail("async function wrap() {\nasync function await() { }\n}", "Can not use 'await' as identifier inside an async function (2:15)", {ecmaVersion: 8}) testFail("async function foo(await) { }", "Can not use 'await' as identifier inside an async function (1:19)", {ecmaVersion: 8}) testFail("async function foo() { return {await} }", "Can not use 'await' as identifier inside an async function (1:31)", {ecmaVersion: 8}) //----------------------------------------------------------------------------- // Async Function Expressions // async == false test("(function foo() { })", { "type": "Program", "start": 0, "end": 20, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 20, "expression": { "type": "FunctionExpression", "start": 1, "end": 19, "id": { "type": "Identifier", "start": 10, "end": 13, "name": "foo" }, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 16, "end": 19, "body": [] } } } ], "sourceType": "script" }, {ecmaVersion: 8}) // async == true test("(async function foo() { })", { "type": "Program", "start": 0, "end": 26, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 26, "expression": { "type": "FunctionExpression", "start": 1, "end": 25, "id": { "type": "Identifier", "start": 16, "end": 19, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 22, "end": 25, "body": [] } } } ], "sourceType": "script" }, {ecmaVersion: 8}) // cannot insert a linebreak to between 'async' and 'function'. testFail("(async\nfunction foo() { })", "Unexpected token (2:0)", {ecmaVersion: 8}) // cannot combine with generators. testFail("(async function* foo() { })", "Unexpected token (1:15)", {ecmaVersion: 8}) // export default test("export default (async function() { })", { "type": "Program", "start": 0, "end": 37, "body": [ { "type": "ExportDefaultDeclaration", "start": 0, "end": 37, "declaration": { "type": "FunctionExpression", "start": 16, "end": 36, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 33, "end": 36, "body": [] } } } ], "sourceType": "module" }, {ecmaVersion: 8, sourceType: "module"}) // cannot use 'await' inside async functions. testFail("(async function await() { })", "Can not use 'await' as identifier inside an async function (1:16)", {ecmaVersion: 8}) testFail("(async function foo(await) { })", "Can not use 'await' as identifier inside an async function (1:20)", {ecmaVersion: 8}) testFail("(async function foo() { return {await} })", "Can not use 'await' as identifier inside an async function (1:32)", {ecmaVersion: 8}) //----------------------------------------------------------------------------- // Async Arrow Function Expressions // async == false test("a => a", { "type": "Program", "start": 0, "end": 6, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 6, "expression": { "type": "ArrowFunctionExpression", "start": 0, "end": 6, "id": null, "generator": false, "expression": true, "async": false, "params": [ { "type": "Identifier", "start": 0, "end": 1, "name": "a" } ], "body": { "type": "Identifier", "start": 5, "end": 6, "name": "a" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("(a) => a", { "type": "Program", "start": 0, "end": 8, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 8, "expression": { "type": "ArrowFunctionExpression", "start": 0, "end": 8, "id": null, "generator": false, "expression": true, "async": false, "params": [ { "type": "Identifier", "start": 1, "end": 2, "name": "a" } ], "body": { "type": "Identifier", "start": 7, "end": 8, "name": "a" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) // async == true test("async a => a", { "type": "Program", "start": 0, "end": 12, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 12, "expression": { "type": "ArrowFunctionExpression", "start": 0, "end": 12, "id": null, "generator": false, "expression": true, "async": true, "params": [ { "type": "Identifier", "start": 6, "end": 7, "name": "a" } ], "body": { "type": "Identifier", "start": 11, "end": 12, "name": "a" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("async () => a", { "type": "Program", "start": 0, "end": 13, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 13, "expression": { "type": "ArrowFunctionExpression", "start": 0, "end": 13, "id": null, "generator": false, "expression": true, "async": true, "params": [], "body": { "type": "Identifier", "start": 12, "end": 13, "name": "a" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("async (a, b) => a", { "type": "Program", "start": 0, "end": 17, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 17, "expression": { "type": "ArrowFunctionExpression", "start": 0, "end": 17, "id": null, "generator": false, "expression": true, "async": true, "params": [ { "type": "Identifier", "start": 7, "end": 8, "name": "a" }, { "type": "Identifier", "start": 10, "end": 11, "name": "b" } ], "body": { "type": "Identifier", "start": 16, "end": 17, "name": "a" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) // OK even if it's an invalid syntax in the case `=>` didn't exist. test("async ({a = b}) => a", { "type": "Program", "start": 0, "end": 20, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 20, "expression": { "type": "ArrowFunctionExpression", "start": 0, "end": 20, "id": null, "generator": false, "expression": true, "async": true, "params": [ { "type": "ObjectPattern", "start": 7, "end": 14, "properties": [ { "type": "Property", "start": 8, "end": 13, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 8, "end": 9, "name": "a" }, "kind": "init", "value": { "type": "AssignmentPattern", "start": 8, "end": 13, "left": { "type": "Identifier", "start": 8, "end": 9, "name": "a" }, "right": { "type": "Identifier", "start": 12, "end": 13, "name": "b" } } } ] } ], "body": { "type": "Identifier", "start": 19, "end": 20, "name": "a" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) // syntax error if `=>` didn't exist. testFail("async ({a = b})", "Shorthand property assignments are valid only in destructuring patterns (1:10)", {ecmaVersion: 8}) // AssignmentPattern/AssignmentExpression test("async ({a: b = c}) => a", { "type": "Program", "start": 0, "end": 23, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 23, "expression": { "type": "ArrowFunctionExpression", "start": 0, "end": 23, "id": null, "generator": false, "expression": true, "async": true, "params": [ { "type": "ObjectPattern", "start": 7, "end": 17, "properties": [ { "type": "Property", "start": 8, "end": 16, "method": false, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 8, "end": 9, "name": "a" }, "value": { "type": "AssignmentPattern", "start": 11, "end": 16, "left": { "type": "Identifier", "start": 11, "end": 12, "name": "b" }, "right": { "type": "Identifier", "start": 15, "end": 16, "name": "c" } }, "kind": "init" } ] } ], "body": { "type": "Identifier", "start": 22, "end": 23, "name": "a" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("async ({a: b = c})", { "type": "Program", "start": 0, "end": 18, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 18, "expression": { "type": "CallExpression", "start": 0, "end": 18, "callee": { "type": "Identifier", "start": 0, "end": 5, "name": "async" }, "arguments": [ { "type": "ObjectExpression", "start": 7, "end": 17, "properties": [ { "type": "Property", "start": 8, "end": 16, "method": false, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 8, "end": 9, "name": "a" }, "value": { "type": "AssignmentExpression", "start": 11, "end": 16, "operator": "=", "left": { "type": "Identifier", "start": 11, "end": 12, "name": "b" }, "right": { "type": "Identifier", "start": 15, "end": 16, "name": "c" } }, "kind": "init" } ] } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // a reference and a normal arrow function if there is a linebreak between 'async' and the 1st parameter. test("async\na => a", { "type": "Program", "start": 0, "end": 12, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 5, "expression": { "type": "Identifier", "start": 0, "end": 5, "name": "async" } }, { "type": "ExpressionStatement", "start": 6, "end": 12, "expression": { "type": "ArrowFunctionExpression", "start": 6, "end": 12, "id": null, "generator": false, "expression": true, "async": false, "params": [ { "type": "Identifier", "start": 6, "end": 7, "name": "a" } ], "body": { "type": "Identifier", "start": 11, "end": 12, "name": "a" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) // 'async()' call expression and invalid '=>' token. testFail("async\n() => a", "Unexpected token (2:3)", {ecmaVersion: 8}) // cannot insert a linebreak before '=>'. testFail("async a\n=> a", "Unexpected token (2:0)", {ecmaVersion: 8}) testFail("async ()\n=> a", "Unexpected token (2:0)", {ecmaVersion: 8}) // a call expression with 'await' reference. test("async (await)", { "type": "Program", "start": 0, "end": 13, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 13, "expression": { "type": "CallExpression", "start": 0, "end": 13, "callee": { "type": "Identifier", "start": 0, "end": 5, "name": "async" }, "arguments": [ { "type": "Identifier", "start": 7, "end": 12, "name": "await" } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // cannot use 'await' inside async functions. testFail("async await => 1", "Can not use 'await' as identifier inside an async function (1:6)", {ecmaVersion: 8}) testFail("async (await) => 1", "Can not use 'await' as identifier inside an async function (1:7)", {ecmaVersion: 8}) testFail("async ({await}) => 1", "Can not use 'await' as identifier inside an async function (1:8)", {ecmaVersion: 8}) testFail("async ({a: await}) => 1", "Can not use 'await' as identifier inside an async function (1:11)", {ecmaVersion: 8}) testFail("async ([await]) => 1", "Can not use 'await' as identifier inside an async function (1:8)", {ecmaVersion: 8}) // can use 'yield' identifier outside generators. test("async yield => 1", { "type": "Program", "start": 0, "end": 16, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 16, "expression": { "type": "ArrowFunctionExpression", "start": 0, "end": 16, "id": null, "generator": false, "expression": true, "async": true, "params": [ { "type": "Identifier", "start": 6, "end": 11, "name": "yield" } ], "body": { "type": "Literal", "start": 15, "end": 16, "value": 1, "raw": "1" } } } ], "sourceType": "script" }, {ecmaVersion: 8}) //----------------------------------------------------------------------------- // Async Methods (object) // async == false test("({foo() { }})", { "type": "Program", "start": 0, "end": 13, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 13, "expression": { "type": "ObjectExpression", "start": 1, "end": 12, "properties": [ { "type": "Property", "start": 2, "end": 11, "method": true, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 2, "end": 5, "name": "foo" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 5, "end": 11, "id": null, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 8, "end": 11, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // async == true test("({async foo() { }})", { "type": "Program", "start": 0, "end": 19, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 19, "expression": { "type": "ObjectExpression", "start": 1, "end": 18, "properties": [ { "type": "Property", "start": 2, "end": 17, "method": true, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 8, "end": 11, "name": "foo" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 11, "end": 17, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 14, "end": 17, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // OK with 'async' as a method name test("({async() { }})", { "type": "Program", "start": 0, "end": 15, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 15, "expression": { "type": "ObjectExpression", "start": 1, "end": 14, "properties": [ { "type": "Property", "start": 2, "end": 13, "method": true, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 2, "end": 7, "name": "async" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 7, "end": 13, "id": null, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 10, "end": 13, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // invalid syntax if there is a linebreak after 'async'. testFail("({async\nfoo() { }})", "Unexpected token (2:0)", {ecmaVersion: 8}) // cannot combine with getters/setters/generators. testFail("({async get foo() { }})", "Unexpected token (1:12)", {ecmaVersion: 8}) testFail("({async set foo(value) { }})", "Unexpected token (1:12)", {ecmaVersion: 8}) testFail("({async* foo() { }})", "Unexpected token (1:7)", {ecmaVersion: 8}) // 'await' is valid as function names. test("({async await() { }})", { "type": "Program", "start": 0, "end": 21, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 21, "expression": { "type": "ObjectExpression", "start": 1, "end": 20, "properties": [ { "type": "Property", "start": 2, "end": 19, "method": true, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 8, "end": 13, "name": "await" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 13, "end": 19, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 16, "end": 19, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // cannot use 'await' inside async functions. test("async function wrap() {\n({async await() { }})\n}", {}, {ecmaVersion: 8}) testFail("({async foo() { var await }})", "Can not use 'await' as identifier inside an async function (1:20)", {ecmaVersion: 8}) testFail("({async foo(await) { }})", "Can not use 'await' as identifier inside an async function (1:12)", {ecmaVersion: 8}) testFail("({async foo() { return {await} }})", "Can not use 'await' as identifier inside an async function (1:24)", {ecmaVersion: 8}) // invalid syntax 'async foo: 1' testFail("({async foo: 1})", "Unexpected token (1:11)", {ecmaVersion: 8}) //----------------------------------------------------------------------------- // Async Methods (class) // async == false test("class A {foo() { }}", { "type": "Program", "start": 0, "end": 19, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 19, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 19, "body": [ { "type": "MethodDefinition", "start": 9, "end": 18, "computed": false, "key": { "type": "Identifier", "start": 9, "end": 12, "name": "foo" }, "static": false, "kind": "method", "value": { "type": "FunctionExpression", "start": 12, "end": 18, "id": null, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 15, "end": 18, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // async == true test("class A {async foo() { }}", { "type": "Program", "start": 0, "end": 25, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 25, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 25, "body": [ { "type": "MethodDefinition", "start": 9, "end": 24, "computed": false, "key": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "static": false, "kind": "method", "value": { "type": "FunctionExpression", "start": 18, "end": 24, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 21, "end": 24, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("class A {static async foo() { }}", { "type": "Program", "start": 0, "end": 32, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 32, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 32, "body": [ { "type": "MethodDefinition", "start": 9, "end": 31, "computed": false, "key": { "type": "Identifier", "start": 22, "end": 25, "name": "foo" }, "static": true, "kind": "method", "value": { "type": "FunctionExpression", "start": 25, "end": 31, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 28, "end": 31, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // OK 'async' as a method name. test("class A {async() { }}", { "type": "Program", "start": 0, "end": 21, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 21, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 21, "body": [ { "type": "MethodDefinition", "start": 9, "end": 20, "computed": false, "key": { "type": "Identifier", "start": 9, "end": 14, "name": "async" }, "static": false, "kind": "method", "value": { "type": "FunctionExpression", "start": 14, "end": 20, "id": null, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 17, "end": 20, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("class A {static async() { }}", { "type": "Program", "start": 0, "end": 28, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 28, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 28, "body": [ { "type": "MethodDefinition", "start": 9, "end": 27, "computed": false, "key": { "type": "Identifier", "start": 16, "end": 21, "name": "async" }, "static": true, "kind": "method", "value": { "type": "FunctionExpression", "start": 21, "end": 27, "id": null, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 24, "end": 27, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("class A {*async() { }}", { "type": "Program", "start": 0, "end": 22, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 22, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 22, "body": [ { "type": "MethodDefinition", "start": 9, "end": 21, "computed": false, "key": { "type": "Identifier", "start": 10, "end": 15, "name": "async" }, "static": false, "kind": "method", "value": { "type": "FunctionExpression", "start": 15, "end": 21, "id": null, "generator": true, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 18, "end": 21, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("class A {static* async() { }}", { "type": "Program", "start": 0, "end": 29, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 29, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 29, "body": [ { "type": "MethodDefinition", "start": 9, "end": 28, "computed": false, "key": { "type": "Identifier", "start": 17, "end": 22, "name": "async" }, "static": true, "kind": "method", "value": { "type": "FunctionExpression", "start": 22, "end": 28, "id": null, "generator": true, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 25, "end": 28, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // invalid syntax if there is a linebreak after 'async'. conflicts with property named async // testFail("class A {async\nfoo() { }}", "Unexpected token (2:0)", {ecmaVersion: 8}) // testFail("class A {static async\nfoo() { }}", "Unexpected token (2:0)", {ecmaVersion: 8}) // cannot combine with constructors/getters/setters/generators. testFail("class A {async constructor() { }}", "Constructor can't be an async method (1:15)", {ecmaVersion: 8}) testFail("class A {async get foo() { }}", "Unexpected token (1:19)", {ecmaVersion: 8}) testFail("class A {async set foo(value) { }}", "Unexpected token (1:19)", {ecmaVersion: 8}) testFail("class A {async* foo() { }}", "Unexpected token (1:14)", {ecmaVersion: 8}) testFail("class A {static async get foo() { }}", "Unexpected token (1:26)", {ecmaVersion: 8}) testFail("class A {static async set foo(value) { }}", "Unexpected token (1:26)", {ecmaVersion: 8}) testFail("class A {static async* foo() { }}", "Unexpected token (1:21)", {ecmaVersion: 8}) // 'await' is valid as function names. test("class A {async await() { }}", { "type": "Program", "start": 0, "end": 27, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 27, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 27, "body": [ { "type": "MethodDefinition", "start": 9, "end": 26, "computed": false, "key": { "type": "Identifier", "start": 15, "end": 20, "name": "await" }, "static": false, "kind": "method", "value": { "type": "FunctionExpression", "start": 20, "end": 26, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 23, "end": 26, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("class A {static async await() { }}", { "type": "Program", "start": 0, "end": 34, "body": [ { "type": "ClassDeclaration", "start": 0, "end": 34, "id": { "type": "Identifier", "start": 6, "end": 7, "name": "A" }, "superClass": null, "body": { "type": "ClassBody", "start": 8, "end": 34, "body": [ { "type": "MethodDefinition", "start": 9, "end": 33, "computed": false, "key": { "type": "Identifier", "start": 22, "end": 27, "name": "await" }, "static": true, "kind": "method", "value": { "type": "FunctionExpression", "start": 27, "end": 33, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 30, "end": 33, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // cannot use 'await' inside async functions. test("async function wrap() {\nclass A {async await() { }}\n}", {}, {ecmaVersion: 8}) testFail("class A {async foo() { var await }}", "Can not use 'await' as identifier inside an async function (1:27)", {ecmaVersion: 8}) testFail("class A {async foo(await) { }}", "Can not use 'await' as identifier inside an async function (1:19)", {ecmaVersion: 8}) testFail("class A {async foo() { return {await} }}", "Can not use 'await' as identifier inside an async function (1:31)", {ecmaVersion: 8}) //----------------------------------------------------------------------------- // Await Expressions // 'await' is an identifier in scripts. test("await", { "type": "Program", "start": 0, "end": 5, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 5, "expression": { "type": "Identifier", "start": 0, "end": 5, "name": "await" } } ], "sourceType": "script" }, {ecmaVersion: 8}) // 'await' is a keyword in modules. testFail("await", "The keyword 'await' is reserved (1:0)", {ecmaVersion: 8, sourceType: "module"}) // Await expressions is invalid outside of async functions. testFail("await a", "Unexpected token (1:6)", {ecmaVersion: 8}) testFail("await a", "The keyword 'await' is reserved (1:0)", {ecmaVersion: 8, sourceType: "module"}) // Await expressions in async functions. test("async function foo(a, b) { await a }", { "type": "Program", "start": 0, "end": 36, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 36, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [ { "type": "Identifier", "start": 19, "end": 20, "name": "a" }, { "type": "Identifier", "start": 22, "end": 23, "name": "b" } ], "body": { "type": "BlockStatement", "start": 25, "end": 36, "body": [ { "type": "ExpressionStatement", "start": 27, "end": 34, "expression": { "type": "AwaitExpression", "start": 27, "end": 34, "argument": { "type": "Identifier", "start": 33, "end": 34, "name": "a" } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("(async function foo(a) { await a })", { "type": "Program", "start": 0, "end": 35, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 35, "expression": { "type": "FunctionExpression", "start": 1, "end": 34, "id": { "type": "Identifier", "start": 16, "end": 19, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [ { "type": "Identifier", "start": 20, "end": 21, "name": "a" } ], "body": { "type": "BlockStatement", "start": 23, "end": 34, "body": [ { "type": "ExpressionStatement", "start": 25, "end": 32, "expression": { "type": "AwaitExpression", "start": 25, "end": 32, "argument": { "type": "Identifier", "start": 31, "end": 32, "name": "a" } } } ] } } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("(async (a) => await a)", { "type": "Program", "start": 0, "end": 22, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 22, "expression": { "type": "ArrowFunctionExpression", "start": 1, "end": 21, "id": null, "generator": false, "expression": true, "async": true, "params": [ { "type": "Identifier", "start": 8, "end": 9, "name": "a" } ], "body": { "type": "AwaitExpression", "start": 14, "end": 21, "argument": { "type": "Identifier", "start": 20, "end": 21, "name": "a" } } } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("({async foo(a) { await a }})", { "type": "Program", "start": 0, "end": 28, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 28, "expression": { "type": "ObjectExpression", "start": 1, "end": 27, "properties": [ { "type": "Property", "start": 2, "end": 26, "method": true, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 8, "end": 11, "name": "foo" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 11, "end": 26, "id": null, "generator": false, "expression": false, "async": true, "params": [ { "type": "Identifier", "start": 12, "end": 13, "name": "a" } ], "body": { "type": "BlockStatement", "start": 15, "end": 26, "body": [ { "type": "ExpressionStatement", "start": 17, "end": 24, "expression": { "type": "AwaitExpression", "start": 17, "end": 24, "argument": { "type": "Identifier", "start": 23, "end": 24, "name": "a" } } } ] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("(class {async foo(a) { await a }})", { "type": "Program", "start": 0, "end": 34, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 34, "expression": { "type": "ClassExpression", "start": 1, "end": 33, "id": null, "superClass": null, "body": { "type": "ClassBody", "start": 7, "end": 33, "body": [ { "type": "MethodDefinition", "start": 8, "end": 32, "computed": false, "key": { "type": "Identifier", "start": 14, "end": 17, "name": "foo" }, "static": false, "kind": "method", "value": { "type": "FunctionExpression", "start": 17, "end": 32, "id": null, "generator": false, "expression": false, "async": true, "params": [ { "type": "Identifier", "start": 18, "end": 19, "name": "a" } ], "body": { "type": "BlockStatement", "start": 21, "end": 32, "body": [ { "type": "ExpressionStatement", "start": 23, "end": 30, "expression": { "type": "AwaitExpression", "start": 23, "end": 30, "argument": { "type": "Identifier", "start": 29, "end": 30, "name": "a" } } } ] } } } ] } } } ], "sourceType": "script" }, {ecmaVersion: 8}) // Await expressions are an unary expression. test("async function foo(a, b) { await a + await b }", { "type": "Program", "start": 0, "end": 46, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 46, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [ { "type": "Identifier", "start": 19, "end": 20, "name": "a" }, { "type": "Identifier", "start": 22, "end": 23, "name": "b" } ], "body": { "type": "BlockStatement", "start": 25, "end": 46, "body": [ { "type": "ExpressionStatement", "start": 27, "end": 44, "expression": { "type": "BinaryExpression", "start": 27, "end": 44, "left": { "type": "AwaitExpression", "start": 27, "end": 34, "argument": { "type": "Identifier", "start": 33, "end": 34, "name": "a" } }, "operator": "+", "right": { "type": "AwaitExpression", "start": 37, "end": 44, "argument": { "type": "Identifier", "start": 43, "end": 44, "name": "b" } } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // 'await + 1' is a binary expression outside of async functions. test("function foo() { await + 1 }", { "type": "Program", "start": 0, "end": 28, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 28, "id": { "type": "Identifier", "start": 9, "end": 12, "name": "foo" }, "generator": false, "expression": false, "async": false, "params": [], "body": { "type": "BlockStatement", "start": 15, "end": 28, "body": [ { "type": "ExpressionStatement", "start": 17, "end": 26, "expression": { "type": "BinaryExpression", "start": 17, "end": 26, "left": { "type": "Identifier", "start": 17, "end": 22, "name": "await" }, "operator": "+", "right": { "type": "Literal", "start": 25, "end": 26, "value": 1, "raw": "1" } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // 'await + 1' is an await expression in async functions. test("async function foo() { await + 1 }", { "type": "Program", "start": 0, "end": 34, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 34, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 21, "end": 34, "body": [ { "type": "ExpressionStatement", "start": 23, "end": 32, "expression": { "type": "AwaitExpression", "start": 23, "end": 32, "argument": { "type": "UnaryExpression", "start": 29, "end": 32, "operator": "+", "prefix": true, "argument": { "type": "Literal", "start": 31, "end": 32, "value": 1, "raw": "1" } } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // Await expressions need one argument. testFail("async function foo() { await }", "Unexpected token (1:29)", {ecmaVersion: 8}) testFail("(async function foo() { await })", "Unexpected token (1:30)", {ecmaVersion: 8}) testFail("async () => await", "Unexpected token (1:17)", {ecmaVersion: 8}) testFail("({async foo() { await }})", "Unexpected token (1:22)", {ecmaVersion: 8}) testFail("(class {async foo() { await }})", "Unexpected token (1:28)", {ecmaVersion: 8}) // Forbid await expressions in default parameters: testFail("async function foo(a = await b) {}", "Await expression cannot be a default value (1:23)", {ecmaVersion: 8}) testFail("(async function foo(a = await b) {})", "Await expression cannot be a default value (1:24)", {ecmaVersion: 8}) testFail("async (a = await b) => {}", "Unexpected token (1:17)", {ecmaVersion: 8}) testFail("async function wrapper() {\nasync (a = await b) => {}\n}", "Await expression cannot be a default value (2:11)", {ecmaVersion: 8}) testFail("({async foo(a = await b) {}})", "Await expression cannot be a default value (1:16)", {ecmaVersion: 8}) testFail("(class {async foo(a = await b) {}})", "Await expression cannot be a default value (1:22)", {ecmaVersion: 8}) testFail("async function foo(a = class extends (await b) {}) {}", "Await expression cannot be a default value (1:38)", {ecmaVersion: 8}) // Allow await expressions inside functions in default parameters: test("async function foo(a = async function foo() { await b }) {}", { "type": "Program", "start": 0, "end": 59, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 59, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [ { "type": "AssignmentPattern", "start": 19, "end": 55, "left": { "type": "Identifier", "start": 19, "end": 20, "name": "a" }, "right": { "type": "FunctionExpression", "start": 23, "end": 55, "id": { "type": "Identifier", "start": 38, "end": 41, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 44, "end": 55, "body": [ { "type": "ExpressionStatement", "start": 46, "end": 53, "expression": { "type": "AwaitExpression", "start": 46, "end": 53, "argument": { "type": "Identifier", "start": 52, "end": 53, "name": "b" } } } ] } } } ], "body": { "type": "BlockStatement", "start": 57, "end": 59, "body": [] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("async function foo(a = async () => await b) {}", { "type": "Program", "start": 0, "end": 46, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 46, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [ { "type": "AssignmentPattern", "start": 19, "end": 42, "left": { "type": "Identifier", "start": 19, "end": 20, "name": "a" }, "right": { "type": "ArrowFunctionExpression", "start": 23, "end": 42, "id": null, "generator": false, "expression": true, "async": true, "params": [], "body": { "type": "AwaitExpression", "start": 35, "end": 42, "argument": { "type": "Identifier", "start": 41, "end": 42, "name": "b" } } } } ], "body": { "type": "BlockStatement", "start": 44, "end": 46, "body": [] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("async function foo(a = {async bar() { await b }}) {}", { "type": "Program", "start": 0, "end": 52, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 52, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [ { "type": "AssignmentPattern", "start": 19, "end": 48, "left": { "type": "Identifier", "start": 19, "end": 20, "name": "a" }, "right": { "type": "ObjectExpression", "start": 23, "end": 48, "properties": [ { "type": "Property", "start": 24, "end": 47, "method": true, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 30, "end": 33, "name": "bar" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 33, "end": 47, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 36, "end": 47, "body": [ { "type": "ExpressionStatement", "start": 38, "end": 45, "expression": { "type": "AwaitExpression", "start": 38, "end": 45, "argument": { "type": "Identifier", "start": 44, "end": 45, "name": "b" } } } ] } } } ] } } ], "body": { "type": "BlockStatement", "start": 50, "end": 52, "body": [] } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("async function foo(a = class {async bar() { await b }}) {}", { "type": "Program", "start": 0, "end": 58, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 58, "id": { "type": "Identifier", "start": 15, "end": 18, "name": "foo" }, "generator": false, "expression": false, "async": true, "params": [ { "type": "AssignmentPattern", "start": 19, "end": 54, "left": { "type": "Identifier", "start": 19, "end": 20, "name": "a" }, "right": { "type": "ClassExpression", "start": 23, "end": 54, "id": null, "superClass": null, "body": { "type": "ClassBody", "start": 29, "end": 54, "body": [ { "type": "MethodDefinition", "start": 30, "end": 53, "computed": false, "key": { "type": "Identifier", "start": 36, "end": 39, "name": "bar" }, "static": false, "kind": "method", "value": { "type": "FunctionExpression", "start": 39, "end": 53, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 42, "end": 53, "body": [ { "type": "ExpressionStatement", "start": 44, "end": 51, "expression": { "type": "AwaitExpression", "start": 44, "end": 51, "argument": { "type": "Identifier", "start": 50, "end": 51, "name": "b" } } } ] } } } ] } } } ], "body": { "type": "BlockStatement", "start": 56, "end": 58, "body": [] } } ], "sourceType": "script" }, {ecmaVersion: 8}) // Distinguish ParenthesizedExpression or ArrowFunctionExpression test("async function wrap() {\n(a = await b)\n}", { "type": "Program", "start": 0, "end": 39, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 39, "id": { "type": "Identifier", "start": 15, "end": 19, "name": "wrap" }, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 22, "end": 39, "body": [ { "type": "ExpressionStatement", "start": 24, "end": 37, "expression": { "type": "AssignmentExpression", "start": 25, "end": 36, "operator": "=", "left": { "type": "Identifier", "start": 25, "end": 26, "name": "a" }, "right": { "type": "AwaitExpression", "start": 29, "end": 36, "argument": { "type": "Identifier", "start": 35, "end": 36, "name": "b" } } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) testFail("async function wrap() {\n(a = await b) => a\n}", "Await expression cannot be a default value (2:5)", {ecmaVersion: 8}) test("async function wrap() {\n({a = await b} = obj)\n}", { "type": "Program", "start": 0, "end": 47, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 47, "id": { "type": "Identifier", "start": 15, "end": 19, "name": "wrap" }, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 22, "end": 47, "body": [ { "type": "ExpressionStatement", "start": 24, "end": 45, "expression": { "type": "AssignmentExpression", "start": 25, "end": 44, "operator": "=", "left": { "type": "ObjectPattern", "start": 25, "end": 38, "properties": [ { "type": "Property", "start": 26, "end": 37, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 26, "end": 27, "name": "a" }, "kind": "init", "value": { "type": "AssignmentPattern", "start": 26, "end": 37, "left": { "type": "Identifier", "start": 26, "end": 27, "name": "a" }, "right": { "type": "AwaitExpression", "start": 30, "end": 37, "argument": { "type": "Identifier", "start": 36, "end": 37, "name": "b" } } } } ] }, "right": { "type": "Identifier", "start": 41, "end": 44, "name": "obj" } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) testFail("async function wrap() {\n({a = await b} = obj) => a\n}", "Await expression cannot be a default value (2:6)", {ecmaVersion: 8}) test("function* wrap() {\nasync(a = yield b)\n}", { "type": "Program", "start": 0, "end": 39, "body": [ { "type": "FunctionDeclaration", "start": 0, "end": 39, "id": { "type": "Identifier", "start": 10, "end": 14, "name": "wrap" }, "params": [], "generator": true, "expression": false, "async": false, "body": { "type": "BlockStatement", "start": 17, "end": 39, "body": [ { "type": "ExpressionStatement", "start": 19, "end": 37, "expression": { "type": "CallExpression", "start": 19, "end": 37, "callee": { "type": "Identifier", "start": 19, "end": 24, "name": "async" }, "arguments": [ { "type": "AssignmentExpression", "start": 25, "end": 36, "operator": "=", "left": { "type": "Identifier", "start": 25, "end": 26, "name": "a" }, "right": { "type": "YieldExpression", "start": 29, "end": 36, "delegate": false, "argument": { "type": "Identifier", "start": 35, "end": 36, "name": "b" } } } ] } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8}) testFail("function* wrap() {\nasync(a = yield b) => a\n}", "Yield expression cannot be a default value (2:10)", {ecmaVersion: 8}) // https://github.com/ternjs/acorn/issues/464 test("f = ({ w = counter(), x = counter(), y = counter(), z = counter() } = { w: null, x: 0, y: false, z: '' }) => {}", { "type": "Program", "start": 0, "end": 111, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 111, "expression": { "type": "AssignmentExpression", "start": 0, "end": 111, "operator": "=", "left": { "type": "Identifier", "start": 0, "end": 1, "name": "f" }, "right": { "type": "ArrowFunctionExpression", "start": 4, "end": 111, "id": null, "params": [ { "type": "AssignmentPattern", "start": 5, "end": 104, "left": { "type": "ObjectPattern", "start": 5, "end": 67, "properties": [ { "type": "Property", "start": 7, "end": 20, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 7, "end": 8, "name": "w" }, "kind": "init", "value": { "type": "AssignmentPattern", "start": 7, "end": 20, "left": { "type": "Identifier", "start": 7, "end": 8, "name": "w" }, "right": { "type": "CallExpression", "start": 11, "end": 20, "callee": { "type": "Identifier", "start": 11, "end": 18, "name": "counter" }, "arguments": [] } } }, { "type": "Property", "start": 22, "end": 35, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 22, "end": 23, "name": "x" }, "kind": "init", "value": { "type": "AssignmentPattern", "start": 22, "end": 35, "left": { "type": "Identifier", "start": 22, "end": 23, "name": "x" }, "right": { "type": "CallExpression", "start": 26, "end": 35, "callee": { "type": "Identifier", "start": 26, "end": 33, "name": "counter" }, "arguments": [] } } }, { "type": "Property", "start": 37, "end": 50, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 37, "end": 38, "name": "y" }, "kind": "init", "value": { "type": "AssignmentPattern", "start": 37, "end": 50, "left": { "type": "Identifier", "start": 37, "end": 38, "name": "y" }, "right": { "type": "CallExpression", "start": 41, "end": 50, "callee": { "type": "Identifier", "start": 41, "end": 48, "name": "counter" }, "arguments": [] } } }, { "type": "Property", "start": 52, "end": 65, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 52, "end": 53, "name": "z" }, "kind": "init", "value": { "type": "AssignmentPattern", "start": 52, "end": 65, "left": { "type": "Identifier", "start": 52, "end": 53, "name": "z" }, "right": { "type": "CallExpression", "start": 56, "end": 65, "callee": { "type": "Identifier", "start": 56, "end": 63, "name": "counter" }, "arguments": [] } } } ] }, "right": { "type": "ObjectExpression", "start": 70, "end": 104, "properties": [ { "type": "Property", "start": 72, "end": 79, "method": false, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 72, "end": 73, "name": "w" }, "kind": "init", "value": { "type": "Literal", "start": 75, "end": 79, "value": null, "raw": "null" } }, { "type": "Property", "start": 81, "end": 85, "method": false, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 81, "end": 82, "name": "x" }, "kind": "init", "value": { "type": "Literal", "start": 84, "end": 85, "value": 0, "raw": "0" } }, { "type": "Property", "start": 87, "end": 95, "method": false, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 87, "end": 88, "name": "y" }, "kind": "init", "value": { "type": "Literal", "start": 90, "end": 95, "value": false, "raw": "false" } }, { "type": "Property", "start": 97, "end": 102, "method": false, "shorthand": false, "computed": false, "key": { "type": "Identifier", "start": 97, "end": 98, "name": "z" }, "kind": "init", "value": { "type": "Literal", "start": 100, "end": 102, "value": "", "raw": "''" } } ] } } ], "generator": false, "expression": false, "async": false, "body": { "type": "BlockStatement", "start": 109, "end": 111, "body": [] } } } } ], "sourceType": "script" }, {ecmaVersion: 8}) test("({ async: true })", { type: "Program", body: [{ type: "ExpressionStatement", expression: { type: "ObjectExpression", properties: [{ type: "Property", key: { type: "Identifier", name: "async" }, value: { type: "Literal", value: true }, kind: "init" }] } }] }, {ecmaVersion: 8}); // Tests for B.3.4 FunctionDeclarations in IfStatement Statement Clauses test( "if (x) async function f() {}", { type: "Program", body: [{ type: "IfStatement", consequent: { type: "FunctionDeclaration", async: true }, alternate: null }] }, {ecmaVersion: 8} ) testFail("(async)(a) => 12", "Unexpected token (1:11)", {ecmaVersion: 8}) testFail("f = async ((x)) => x", "Parenthesized pattern (1:11)", {ecmaVersion: 8}) // allow 'async' as a shorthand property in script. test( "({async})", { "type": "Program", "start": 0, "end": 9, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 9, "expression": { "type": "ObjectExpression", "start": 1, "end": 8, "properties": [ { "type": "Property", "start": 2, "end": 7, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 2, "end": 7, "name": "async" }, "kind": "init", "value": { "type": "Identifier", "start": 2, "end": 7, "name": "async" } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8} ) test( "({async, foo})", { "type": "Program", "start": 0, "end": 14, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 14, "expression": { "type": "ObjectExpression", "start": 1, "end": 13, "properties": [ { "type": "Property", "start": 2, "end": 7, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 2, "end": 7, "name": "async" }, "kind": "init", "value": { "type": "Identifier", "start": 2, "end": 7, "name": "async" } }, { "type": "Property", "start": 9, "end": 12, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 9, "end": 12, "name": "foo" }, "kind": "init", "value": { "type": "Identifier", "start": 9, "end": 12, "name": "foo" } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8} ) test( "({async = 0} = {})", { "type": "Program", "start": 0, "end": 18, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 18, "expression": { "type": "AssignmentExpression", "start": 1, "end": 17, "operator": "=", "left": { "type": "ObjectPattern", "start": 1, "end": 12, "properties": [ { "type": "Property", "start": 2, "end": 11, "method": false, "shorthand": true, "computed": false, "key": { "type": "Identifier", "start": 2, "end": 7, "name": "async" }, "kind": "init", "value": { "type": "AssignmentPattern", "start": 2, "end": 11, "left": { "type": "Identifier", "start": 2, "end": 7, "name": "async" }, "right": { "type": "Literal", "start": 10, "end": 11, "value": 0, "raw": "0" } } } ] }, "right": { "type": "ObjectExpression", "start": 15, "end": 17, "properties": [] } } } ], "sourceType": "script" }, {ecmaVersion: 8} ) // async functions with vary names. test( "({async \"foo\"(){}})", { "type": "Program", "start": 0, "end": 19, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 19, "expression": { "type": "ObjectExpression", "start": 1, "end": 18, "properties": [ { "type": "Property", "start": 2, "end": 17, "method": true, "shorthand": false, "computed": false, "key": { "type": "Literal", "start": 8, "end": 13, "value": "foo", "raw": "\"foo\"" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 13, "end": 17, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 15, "end": 17, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8} ) test( "({async 'foo'(){}})", { "type": "Program", "start": 0, "end": 19, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 19, "expression": { "type": "ObjectExpression", "start": 1, "end": 18, "properties": [ { "type": "Property", "start": 2, "end": 17, "method": true, "shorthand": false, "computed": false, "key": { "type": "Literal", "start": 8, "end": 13, "value": "foo", "raw": "'foo'" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 13, "end": 17, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 15, "end": 17, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8} ) test( "({async 100(){}})", { "type": "Program", "start": 0, "end": 17, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 17, "expression": { "type": "ObjectExpression", "start": 1, "end": 16, "properties": [ { "type": "Property", "start": 2, "end": 15, "method": true, "shorthand": false, "computed": false, "key": { "type": "Literal", "start": 8, "end": 11, "value": 100, "raw": "100" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 11, "end": 15, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 13, "end": 15, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8} ) test( "({async [foo](){}})", { "type": "Program", "start": 0, "end": 19, "body": [ { "type": "ExpressionStatement", "start": 0, "end": 19, "expression": { "type": "ObjectExpression", "start": 1, "end": 18, "properties": [ { "type": "Property", "start": 2, "end": 17, "method": true, "shorthand": false, "computed": true, "key": { "type": "Identifier", "start": 9, "end": 12, "name": "foo" }, "kind": "init", "value": { "type": "FunctionExpression", "start": 13, "end": 17, "id": null, "generator": false, "expression": false, "async": true, "params": [], "body": { "type": "BlockStatement", "start": 15, "end": 17, "body": [] } } } ] } } ], "sourceType": "script" }, {ecmaVersion: 8} ) test("({ async delete() {} })", {}, {ecmaVersion: 8})
// Use λ for the placeholder window.λ = function delta() { this.version = "1"; }; λ.rebind_caf = function() { $('.caf').each(function() { if (typeof $._data($(this)[0], "events") === "undefined") { $(this).on('click', function(e) { e.preventDefault(); λ[$(this).attr('data-func')](this); }); } }); }; λ.rebind_magnific = function() { if (typeof $.fn.magnificPopup !== "undefined") { $('.popup-vimeo').magnificPopup({ type:'iframe' }); } }; λ.rebind_responsive_background_images = function() { $( '[data-bgimg]' ).each(function() { /* make the data usable */ var source_set = atob($( this ).attr( 'data-bgimg' )), source_set = replace_all( source_set,'\'', '"' ), initial_element = this; var items = JSON.parse( source_set ); λ.reasses_background_images(items, initial_element); $(window).off('resize.reasses_background_images'); $(window).on('resize.reasses_background_images', function() { λ.reasses_background_images(items, initial_element); }); }); }; λ.reasses_background_images = function(items, initial_element) { var bg_img = items['default']; /*** * This each will go test the first entry all the way to the last entry for matches, with each match * overriding the bg_img variable. **/ $.each( items, function(media_query, image_uri) { /* feel free to clone this if you'd like to add new hardcoded names, this one checks for "mobile" */ media_query = ( media_query === "mobile" ) ? '(max-width: 640px)' : media_query; if (Modernizr.mq(media_query)) { bg_img = image_uri; } }); /* TODO: Cache these images so we don't request them on resize. */ $(initial_element).css('background-image', 'url("' + bg_img + '")'); }; λ.check_for_progressive_images = function() { $('.progressive_image.js-not_loaded').each(function() { if ($(this).offset().top <= $(window).scrollTop() + ( $(window).innerHeight() * 1.25 ) ) { try { $(window).off('scroll.load_progressive_images'); $(this).removeClass('js-not_loaded'); var the_whole_element = this; var has_zoom = ($(this).hasClass('has_zoom')) ? 'data-action="zoom"' : ''; var picture_array = JSON.parse(atob($('.js-swap-for-picture', this).attr('data-image_info'))); var largest_image, source = ''; $.each(picture_array, function(key, val) { source += '<source srcset="' + val + '" media="' + key + '" />'; largest_image = val; }); var picture_tag = '<picture src="' + largest_image + '">'; picture_tag += source; picture_tag += '<img srcset="' + largest_image + '" alt="…" ' + has_zoom + ' />'; picture_tag += '</picture>'; $('.js-swap-for-picture', this).replaceWith(picture_tag); $('picture img', this).bind('load', function() { $(the_whole_element).addClass('totally-loaded'); }); λ.rebind_progressive_images(); } catch(error) { λ.rebind_progressive_images(); } } }); }; λ.rebind_progressive_images = function() { λ.check_for_progressive_images(); $(window).on('scroll.load_progressive_images', function() { λ.check_for_progressive_images(); }); }; λ.hide_scroll_params = { 'did_scroll' : null, 'last_scroll_top' : null, 'delta' : null, 'navbar_height' : null, 'interval': null }; λ.rebind_hide_navigation_on_scroll = function() { $('header').removeClass('nav-up nav-down'); clearInterval(λ.hide_scroll_params.interval); λ.hide_scroll_params = { 'did_scroll' : null, 'last_scroll_top' : null, 'delta' : null, 'navbar_height' : null, 'interval': null }; if ($('body').hasClass('single-blog')) { // Hide Header on on scroll down λ.hide_scroll_params.did_scroll; λ.hide_scroll_params.last_scroll_top = 0; λ.hide_scroll_params.delta = 5; λ.hide_scroll_params.navbar_height = $('header').outerHeight(); $(window).scroll(function(event){ λ.hide_scroll_params.did_scroll = true; }); λ.hide_scroll_params.interval = setInterval(function() { if (λ.hide_scroll_params.did_scroll) { hasScrolled(); λ.hide_scroll_params.did_scroll = false; } }, 100); function hasScrolled() { var st = $(this).scrollTop(); // Make sure they scroll more than delta if(Math.abs(λ.hide_scroll_params.last_scroll_top - st) <= λ.hide_scroll_params.delta) return; // If they scrolled down and are past the navbar, add class .nav-up. // This is necessary so you never see what is "behind" the navbar. if (st > λ.hide_scroll_params.last_scroll_top && st > λ.hide_scroll_params.navbar_height){ // Scroll Down $('header').removeClass('nav-down').addClass('nav-up'); } else { // Scroll Up if(st + $(window).height() < $(document).height()) { $('header').removeClass('nav-up').addClass('nav-down'); } } λ.hide_scroll_params.last_scroll_top = st; } } else { $('header').removeClass('nav-up nav-down'); clearInterval(λ.hide_scroll_params.interval); λ.hide_scroll_params = { 'did_scroll' : null, 'last_scroll_top' : null, 'delta' : null, 'navbar_height' : null, 'interval': null }; } }; function scrollTo(e,d) { var page = $("html, body"); page.on("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove", function() { page.stop(); }); page.animate({ scrollTop: e }, d, function() { page.off("scroll mousedown wheel DOMMouseScroll mousewheel keyup touchmove"); }); return false; } function escape_reg_exp(string) { return string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"); } function replace_all(string, find, replace) { return string.replace(new RegExp(escape_reg_exp(find), 'g'), replace); }
'use strict'; require('babel/register')({ ignore: false, only: new RegExp('^' + __dirname.replace(/[\[\]\/{}()*+?.\\^$|-]/g, "\\$&")) }); module.exports = require('./one.js');
/** * First Common Ancestor * * Design an algorithm and write code to find the first common ancestor of two nodes in a binary search tree. * Avoid storing additional nodes in a data structure. * * NOTE: This is not necessarily a binary search tree * */ const Graph = require('../../../collections/Graph'); // Approach: Traverse the tree and bubble up the sub trees that contain one of the values // The first node that has a value on either sub-tree is the First Common Ancestor // // Run time: O(n) // function getFirstCommonAncestor(tree, val1, val2) { let valuesFound = []; const result = getFirstCommonAncestorWorker(tree, 0, val1, val2, valuesFound); return valuesFound.length === 2 ? result : undefined; } function getFirstCommonAncestorWorker(tree, v, val1, val2, valuesFound) { let foundEdges = []; for (let i in tree.vertices[v].edges) { const e = tree.vertices[v].edges[i]; let result = getFirstCommonAncestorWorker(tree, e, val1, val2, valuesFound); if (result) { foundEdges.push(result); } } if (v === val1 && v === val2) { valuesFound.push(val1); valuesFound.push(val2); return v; } else if (v === val1) { valuesFound.push(val1); return v; } else if (v === val2) { valuesFound.push(val2); return v; } else if (foundEdges.length === 0) { return undefined; } else if (foundEdges.length === 1) { return foundEdges[0]; } else { //(foundEdges.length === 2) { return v; } } const should = require('should'); const binaryTree = new Graph(20, {mode: Graph.OPTIONS.DIRECTED}) .addEdge(0, 10) .addEdge(0, 6) .addEdge(10, 15) .addEdge(10, 18) .addEdge(18, 14) .addEdge(18, 11) .addEdge(15, 2) .addEdge(15, 8) .addEdge(8, 4) .addEdge(6, 3) .addEdge(6, 7) .addEdge(3, 1) .addEdge(3, 19) .addEdge(7, 17) .addEdge(7, 13) .addEdge(13, 5) .addEdge(13, 16) .addEdge(5, 9) .addEdge(5, 12); const tests = [ [1, 5], // on either side of the subtree [4, 10], // along the same subtree [0, 12], // at the root [15, 15],// same node [9, 20] // not found ]; const expected = [ 6, 10, 0, 15, undefined ]; for (let i in tests) { should(getFirstCommonAncestor(binaryTree, tests[i][0], tests[i][1])).eql(expected[i]); console.log(`getFirstCommonAncestor (${tests[i][0]}, ${tests[i][1]}): [${expected[i]}]`); } console.log('Success!\n'); module.exports = getFirstCommonAncestor;
angular.module('myList',[]) .controller('ListController',function($http){ var list = this; list.data = []; list.getData = function(){ $http({ method: 'GET', url: 'http://api-nivesh2.c9users.io/api/v1/fetch' }).then(function successCallback(response){ list.data = response.data.data; }, function errorCallback(response){ console.log(response); }); }; list.addData = function() { console.log('add function called'); if(list.key!==undefined){ var _data = JSON.stringify({"key":list.key, "value":list.value}); console.log(_data); // Simple GET request example: $http({ method: 'POST', url: 'http://api-nivesh2.c9users.io/api/v1/insert', data: _data }).then(function successCallback(response) { console.log(response); var _index=-1; list.data.forEach(function(item,index,array){ if(item.key === list.key){ item.value = list.value; _index = 0; } }); if(_index===-1){ list.data.push({'key':list.key,'value':list.value}); } list.key=''; list.value=''; }, function errorCallback(response) { console.log(response); }); } }; list.delete = function(key){ console.log('deleting '+key); $http({ method: 'GET', url: "http://api-nivesh2.c9users.io/api/v1/delete?key="+key }).then(function successCallback(response){ console.log(response); }, function errorCallback(response){ console.log(response); }); setTimeout(()=>{ list.data = list.data.filter((item)=>{ return item.key !== key; }); },0); }; });
! function(window, angular, undefined) { var defaultMapSettings = { center: { lat: 12.94206, lng: 77.62229 }, zoom: 8 }, setMarkerFunc = undefined; function setMarkerCurryFunc(placesMap) { if (placesMap) { var map = placesMap; } return function(marker) { if (!map) { throw "Please pass a map reference before setting marker"; } if (Object.prototype.toString.call(marker) == "[object Object]" && marker.position !== undefined) { marker.map = map; var newMarker = new google.maps.Marker(marker); newMarker.setMap(map); return newMarker; } } } angular.module('ds.map', []). factory('dsMapFactory', ['$http', function($http) { var obj = { getDefaultMapSettings: getDefaultMapSettingsFunc, setDefaultMapSettings: setDefaultMapSettingsFunc, setDirectionsToLocation: function() {} }; function getDefaultMapSettingsFunc() { return defaultMapSettings; } function setDefaultMapSettingsFunc(settingsObj) { defaultMapSettings = settingsObj; } return obj; }]). directive('dsMap', ['$q', '$timeout', 'dsMapFactory', function($q, $timeout, dsMapFactory) { var deferred = $q.defer(), obj = { scope: { mapSettings: "=" }, restrict: "E", link: function(scope) { }, controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) { var _deferred = $q.defer(), placesDeferred = $q.defer(), dsMapElements = 0, deferredArray = [], that = this, mapSettings = that.mapSettings = $scope.mapSettings || dsMapFactory.getDefaultMapSettings(), map = new google.maps.Map(document.createElement('div'), mapSettings); function getLocationFunc() { return that.dsPlacesLocation; } function setLocationFunc(center) { that.dsPlacesLocation = center || that.getMap().getCenter(); } function getMapFunc() { return that.map; } function setMapFunc(map) { dsMapFactory.map = that.map = map; that.setLocation(that.map.getCenter()); } function iterateAllMarkersFunc(callback) { for (var groups in that.placesGroupHash) { var eachGroupRef = that.placesGroupHash[groups]; for (var _count = 0, len = eachGroupRef.length; _count < len; _count++) { var allIteratedMarkers = eachGroupRef[_count]; callback.call(allIteratedMarkers); } } } function iterateMarkersMatchingBooleanFunc(bool, callback) { that.iterateAllMarkers(function() { var eachPreviousMarker = this; if (eachPreviousMarker.visible === bool) { callback.call(eachPreviousMarker); eachPreviousMarker.setMap(eachPreviousMarker.getMap()); } }); } function setGroupMarkerVisibilityFunc(group, bool, setVisibleMarkerBounds) { var currentGroupRef = that.placesGroupHash[group], previousGroup = undefined; if (previousGroup != group) { that.bounds = new google.maps.LatLngBounds(); for (var currentGroupCount = 0, len = currentGroupRef.length; currentGroupCount < len; currentGroupCount++) { var eachCurrentMarker = currentGroupRef[currentGroupCount]; if (eachCurrentMarker.visible !== bool) { eachCurrentMarker.visible = bool; eachCurrentMarker.setMap(eachCurrentMarker.getMap()); if (setVisibleMarkerBounds && eachCurrentMarker.visible) { that.bounds.extend(eachCurrentMarker.position); } } } if (setVisibleMarkerBounds) { that.changeMapBounds(); } } previousGroup = group; } function hideAllVisibleMarkersFunc() { that.iterateMarkersMatchingBoolean(true, function() { var visibleMarker = this; visibleMarker.visible = false; }); } function changeMapBoundsFunc() { that.getMap().fitBounds(that.bounds); that.getMap().setCenter(that.getLocation()); that.getMap().setZoom(that.getMap().getZoom() - 1); } that.mapDeferred = deferred; that.mapRendered = deferred.promise; that.placesDeferred = placesDeferred; that.placesRendered = placesDeferred.promise; that.placesGroupHash = {}; that.placesCount = 0; that.getLocation = getLocationFunc; that.setLocation = setLocationFunc; that.getMap = getMapFunc; that.setMap = setMapFunc; that.iterateAllMarkers = iterateAllMarkersFunc; that.iterateMarkersMatchingBoolean = iterateMarkersMatchingBooleanFunc; that.setGroupMarkerVisibility = setGroupMarkerVisibilityFunc; that.hideAllVisibleMarkers = hideAllVisibleMarkersFunc; that.changeMapBounds = changeMapBoundsFunc; that.setMap(map); that.placesRendered.then(function() { that.changeMapBounds(); }); (function(dfrd, _dfrd) { that.mapRendered.then(function() { dsMapFactory.setMarker = setMarkerFunc = setMarkerCurryFunc(that.getMap()); }); })(deferred, _deferred); that.nextDefer = deferred = _deferred; }] }; return obj; }]). directive('dsMapView', function() { var obj = { scope: { mapSettings: "=", originOptions: "=", destinationOptions: "=" }, restrict: "E", replace: true, template: "<div></div>", require: "^?dsMap", link: function(scope, element, attrs, dsMapController) { var map = new google.maps.Map(element[0], scope.mapSettings || dsMapController.mapSettings), clonedOriginMarkerObject = angular.copy(scope.originOptions || {}); dsMapController.setMap(map); dsMapController.isViewSet = true; dsMapController.destinationOptions = angular.copy(scope.destinationOptions || {}); dsMapController.mapRendered.then(function() { clonedOriginMarkerObject.position = dsMapController.getLocation(); setMarkerFunc(clonedOriginMarkerObject); }); }, controller: ['$scope', function($scope) { var that = this; that.originOptions = $scope.originOptions; that.destinationOptions = angular.copy($scope.destinationOptions); }] }; return obj; }).directive('dsMapPlaces', ['$q', 'dsMapFactory', function($q, dsMapFactory) { var initialdsMapView = true, deferred = $q.defer(), obj = { scope: { options: "=" }, restrict: "E", replace: true, require: "^?dsMap", link: function(scope, element, attrs, dsMapController) { var rankByDistance = google.maps.places.RankBy.DISTANCE; if (initialdsMapView) { dsMapController.mapDeferred.resolve(); initialdsMapView = false; } dsMapController.mapRendered.then(function() { dsMapController.placesService = new google.maps.places.PlacesService(dsMapController.getMap()); dsMapController.directionsService = new google.maps.DirectionsService(); scope.options.map = dsMapController.getMap(); dsMapController.directionsDisplay = new google.maps.DirectionsRenderer(scope.options); dsMapController.bounds = new google.maps.LatLngBounds(); deferred.resolve(dsMapController.placesService); }); }, controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) { var that = this; function dsMapPlacesDeferredFunc() { var _deferred = $q.defer(); return function() { return _deferred; }; } function dsMapPlacesLoadedFunc(callback) { that.dsMapPlacesDeferred().promise.then(callback); } that.placesServiceSet = deferred.promise; that.dsMapPlacesDeferred = dsMapPlacesDeferredFunc(); dsMapFactory.dsMapPlacesLoaded = that.dsMapPlacesLoaded = dsMapPlacesLoadedFunc; }] }; return obj; }]) .directive('dsGroup', ['dsMapFactory', function(dsMapFactory) { var obj = { scope: true, restrict: "E", require: ["^?dsMap", "^?dsMapPlaces"], link: function(scope, element, attrs, dsMapControllers) { previousGroup = undefined; dsMapController = dsMapControllers[0]; dsMapPlacesController = dsMapControllers[1]; (function(previousGroup, dsMapController, dsMapPlacesController) { var isMapPlacesLoaded = false; function onToggleClickFunc(group) { dsMapController.directionsDisplay.setMap(null); if (previousGroup !== undefined) { if (previousGroup == group) { return; } dsMapController.setGroupMarkerVisibility(previousGroup, false, true); } else { dsMapController.hideAllVisibleMarkers(); } dsMapController.setGroupMarkerVisibility(group, true, true); previousGroup = group; } function toggleGroupVisibilityFunc(group) { dsMapPlacesController.dsMapPlacesLoaded(function() { isMapPlacesLoaded = true; }); if (isMapPlacesLoaded) { onToggleClickFunc(group); } } function setDirectionsToLocationFunc(location, mode) { var request = { origin: dsMapController.getLocation(), destination: location, travelMode: google.maps.TravelMode[mode] }; dsMapController.destinationOptions.position = location; dsMapPlacesController.dsMapPlacesLoaded(function() { dsMapController.hideAllVisibleMarkers(); dsMapController.directionsDisplay.setMap(dsMapController.getMap()); dsMapController.directionsService.route(request, function(response, status) { if (status == "OK") { var destinationMarker = setMarkerFunc(dsMapController.destinationOptions); dsMapController.directionsDisplay.setDirections(response); dsMapController.bounds = new google.maps.LatLngBounds(); dsMapController.bounds.extend(dsMapController.getLocation()); dsMapController.bounds.extend(location); dsMapController.placesGroupHash['searchedLocation'] = [destinationMarker]; dsMapController.changeMapBounds(); } }); }); } scope.toggleGroupVisibility = toggleGroupVisibilityFunc; if (dsMapController.isViewSet) { dsMapFactory.setDirectionsToLocation = setDirectionsToLocationFunc; } })(previousGroup, dsMapController, dsMapPlacesController); }, controller: ['$scope', function($scope) { var that = undefined; that = this; that.isGroupSet = true; }] }; return obj; }]) .directive('dsPlacesType', ['$q', '$timeout', function($q, $timeout) { var deferred = $q.defer(), placesServiceCount = 0, obj = { scope: { group: "@", types: "=", options: "=", sortOption: "@", radius: "=" }, templateUrl: "dsMapPlaces.html", restrict: "E", replace: true, require: ["^?dsMap", "^?dsMapPlaces", "^?dsGroup"], link: function(scope, element, attrs, dsMapControllers) { var dsMapController = dsMapControllers[0], dsMapPlacesController = dsMapControllers[1], dsGroupController = dsMapControllers[2], obj = { location: dsMapController.getMap().getCenter(), types: [] }, showDirectionTimeoutId = undefined; function callPlacesServiceFunc(dfrd, _dfrd, type) { dsMapController.placesCount++; dsMapController.mapRendered.then(function() { dfrd.promise.then(function() { dsMapPlacesController.placesServiceSet.then(function(placesService) { if (type) { obj.types = [type]; } placesService.nearbySearch(obj, function(results, status) { if (status == "OK" && Object.prototype.toString.call(results) == "[object Array]") { scope.Places = scope.Places.concat(type === undefined ? results : results.slice(0, scope.types[type])); } $timeout(function() { if ((--dsMapController.placesCount) === 0) { dsMapController.nextDefer.resolve(); dsMapController.nextDefer.promise.then(function() { _dfrd.resolve(); dsMapPlacesController.dsMapPlacesDeferred().resolve(); }); dsMapController.placesDeferred.resolve(); } else { _dfrd.resolve(); } }, 300); }); }); }); }); } function showDirectionFunc() { var that = this; $timeout.cancel(showDirectionTimeoutId); showDirectionTimeoutId = $timeout(function() { var request = { origin: dsMapController.getLocation(), destination: that.place.geometry.location, travelMode: google.maps.TravelMode["DRIVING"] }; if (dsGroupController && dsMapController.placesGroupHash[scope.group][0].visible === false) { dsMapController.setGroupMarkerVisibility(scope.group, true, true); } dsMapController.directionsDisplay.setMap(dsMapController.getMap()); try { if (that.isDirectionResponseCallMade) { if (that.directionResponse) { dsMapController.directionsDisplay.setDirections(that.directionResponse); } return; } that.isDirectionResponseCallMade = true; dsMapController.directionsService.route(request, function(response, status) { if (status == "OK") { dsMapController.directionsDisplay.setDirections(that.directionResponse = response); } }); } catch (err) {} }, 300) } if (scope.group !== undefined) { dsMapController.placesGroupHash[scope.group] = []; } if (scope.sortOption && scope.sortOption == "radius") { obj.radius = scope.radius || 5000; } else { obj.rankBy = google.maps.places.RankBy.DISTANCE; } if (Object.prototype.toString.call(scope.types) == "[object Array]") { var _deferred = $q.defer(); obj.types = scope.types; callPlacesServiceFunc(deferred, _deferred); deferred = _deferred; } else if (Object.prototype.toString.call(scope.types) == "[object Object]") { for (var _types in scope.types) { (function(_deferred) { _deferred = $q.defer(); callPlacesServiceFunc(deferred, _deferred, _types); deferred = _deferred; })(_deferred); } } else { throw "'types' attribute must be an array or object" } if (dsMapController.isViewSet) { dsMapPlacesController.dsMapPlacesLoaded(function() { scope.showDirection = showDirectionFunc; }); } }, controller: ['$scope', '$element', '$attrs', function($scope, $element, $attr) { $scope.Places = []; }] }; deferred.resolve(); return obj; }]).directive('dsEachPlace', [function() { var obj = { require: ["^?dsMap", "^?dsMapPlaces", "^?dsPlacesType"], link: function(scope, element, attrs, dsMapControllers) { var dsMapController = dsMapControllers[0], dsMapPlacesController = dsMapControllers[1], dsPlacesTypeController = dsMapControllers[2]; if (scope.place) { var placeLocation = scope.place.geometry.location, clonedOptions = angular.copy(scope.options), distanceThis = parseFloat(google.maps.geometry.spherical.computeDistanceBetween(dsMapController.getLocation(), placeLocation) / 1000).toFixed(1), durationThis = parseInt(distanceThis * 42 / 3.5, 10); if (clonedOptions === undefined) { clonedOptions = { position: placeLocation, visible: true }; } else if (Object.prototype.toString.call(clonedOptions) == "[object Object]") { clonedOptions.position = placeLocation; clonedOptions.visible = clonedOptions.visible === undefined ? true : clonedOptions.visible; } if (clonedOptions.visible) { dsMapController.bounds.extend(placeLocation); } scope.place.distance = distanceThis; scope.place.duration = durationThis; dsMapController.mapRendered.then(function() { var marker = setMarkerFunc(clonedOptions); try { dsMapController.placesGroupHash[scope.group].push(marker); } catch (err) { console.warn(err); } }); } } }; return obj; }]); }(window, window.angular);
// All code points in the `Cf` category as per Unicode v3.2.0: [ 0x6DD, 0x70F, 0x180E, 0x200C, 0x200D, 0x200E, 0x200F, 0x202A, 0x202B, 0x202C, 0x202D, 0x202E, 0x2060, 0x2061, 0x2062, 0x2063, 0x206A, 0x206B, 0x206C, 0x206D, 0x206E, 0x206F, 0xFEFF, 0xFFF9, 0xFFFA, 0xFFFB, 0x1D173, 0x1D174, 0x1D175, 0x1D176, 0x1D177, 0x1D178, 0x1D179, 0x1D17A, 0xE0001, 0xE0020, 0xE0021, 0xE0022, 0xE0023, 0xE0024, 0xE0025, 0xE0026, 0xE0027, 0xE0028, 0xE0029, 0xE002A, 0xE002B, 0xE002C, 0xE002D, 0xE002E, 0xE002F, 0xE0030, 0xE0031, 0xE0032, 0xE0033, 0xE0034, 0xE0035, 0xE0036, 0xE0037, 0xE0038, 0xE0039, 0xE003A, 0xE003B, 0xE003C, 0xE003D, 0xE003E, 0xE003F, 0xE0040, 0xE0041, 0xE0042, 0xE0043, 0xE0044, 0xE0045, 0xE0046, 0xE0047, 0xE0048, 0xE0049, 0xE004A, 0xE004B, 0xE004C, 0xE004D, 0xE004E, 0xE004F, 0xE0050, 0xE0051, 0xE0052, 0xE0053, 0xE0054, 0xE0055, 0xE0056, 0xE0057, 0xE0058, 0xE0059, 0xE005A, 0xE005B, 0xE005C, 0xE005D, 0xE005E, 0xE005F, 0xE0060, 0xE0061, 0xE0062, 0xE0063, 0xE0064, 0xE0065, 0xE0066, 0xE0067, 0xE0068, 0xE0069, 0xE006A, 0xE006B, 0xE006C, 0xE006D, 0xE006E, 0xE006F, 0xE0070, 0xE0071, 0xE0072, 0xE0073, 0xE0074, 0xE0075, 0xE0076, 0xE0077, 0xE0078, 0xE0079, 0xE007A, 0xE007B, 0xE007C, 0xE007D, 0xE007E, 0xE007F ];
'use strict'; /* eslint-disable prefer-const */ /*! * Collection * https://github.com/kobezzza/Collection * * Released under the MIT license * https://github.com/kobezzza/Collection/blob/master/LICENSE */ import $C from '../core'; import { GLOBAL } from './env'; Object.assign($C, { ready: false, cache: { str: {}, cycle: {} } }); export const LOCAL_CACHE = GLOBAL['COLLECTION_LOCAL_CACHE'] !== false; export const compiledCycles = $C.cache.cycle, localCacheAttrs = GLOBAL['COLLECTION_LOCAL_CACHE_ATTRS'] || {};
/* eslint-disable es/no-bigint -- safe */ if (typeof BigInt == 'function') QUnit.test('BigInt.range', assert => { const { range } = BigInt; const { from } = Array; assert.isFunction(range); assert.name(range, 'range'); assert.arity(range, 3); assert.looksNative(range); assert.nonEnumerable(BigInt, 'range'); let iterator = range(BigInt(1), BigInt(2)); assert.isIterator(iterator); assert.isIterable(iterator); assert.deepEqual(iterator.next(), { value: BigInt(1), done: false, }); assert.deepEqual(iterator.next(), { value: undefined, done: true, }); assert.deepEqual(from(range(BigInt(-1), BigInt(5))), [BigInt(-1), BigInt(0), BigInt(1), BigInt(2), BigInt(3), BigInt(4)]); assert.deepEqual(from(range(BigInt(-5), BigInt(1))), [BigInt(-5), BigInt(-4), BigInt(-3), BigInt(-2), BigInt(-1), BigInt(0)]); assert.deepEqual( from(range(BigInt('9007199254740991'), BigInt('9007199254740992'), { inclusive: true })), [BigInt('9007199254740991'), BigInt('9007199254740992')], ); assert.deepEqual(from(range(BigInt(0), BigInt(0))), []); assert.deepEqual(from(range(BigInt(0), BigInt(-5), BigInt(1))), []); iterator = range(BigInt(1), BigInt(3)); assert.deepEqual(iterator.start, BigInt(1)); assert.deepEqual(iterator.end, BigInt(3)); assert.deepEqual(iterator.step, BigInt(1)); assert.false(iterator.inclusive); iterator = range(BigInt(-1), BigInt(-3), { inclusive: true }); assert.deepEqual(iterator.start, BigInt(-1)); assert.deepEqual(iterator.end, BigInt(-3)); assert.same(iterator.step, BigInt(-1)); assert.true(iterator.inclusive); iterator = range(BigInt(-1), BigInt(-3), { step: BigInt(4), inclusive() { /* empty */ } }); assert.same(iterator.start, BigInt(-1)); assert.same(iterator.end, BigInt(-3)); assert.same(iterator.step, BigInt(4)); assert.true(iterator.inclusive); iterator = range(BigInt(0), BigInt(5)); assert.throws(() => Object.getOwnPropertyDescriptor(iterator, 'start').call({}), TypeError); assert.throws(() => range(Infinity, BigInt(10), BigInt(0)), TypeError); assert.throws(() => range(-Infinity, BigInt(10), BigInt(0)), TypeError); assert.throws(() => range(BigInt(0), BigInt(10), Infinity), TypeError); assert.throws(() => range(BigInt(0), BigInt(10), { step: Infinity }), TypeError); assert.throws(() => range({}, BigInt(1)), TypeError); assert.throws(() => range(BigInt(1), {}), TypeError); });
import { createClient } from 'restify'; import { contains } from 'ramda'; import { log } from './logger'; import sharp from 'sharp'; /** @ignore */ const IMAGE_MIMES = [ 'image/gif', 'image/jpeg', 'image/png', 'image/svg+xml', ]; /** * Formats an image buffer as instructed by options param * * _If the options height and width are not equal, then we have to * consult the crop option. If crop is enabled, we will crop the * longer dimension. If crop is disabled, we will only scale to fit * the dimension that is largest between height and width._ * * @param {Uint8Array} imageBuffer supplied image buffer to action * @param {Object} options options object * @param {Boolean} options.crop will determine if image is cropped * @param {Number} options.height desired height in pixels * @param {Number} options.width desired width in pixels * * @return {Promise<Uint8Array, Error>} formatted image buffer promise */ export const formatImage = (imageBuffer, options) => sharp(imageBuffer) .resize(options.height, options.width) .toBuffer(); /** * Retreives an image buffer from supplied host/option combination * * @param {String} host host to be used by client * @param {Object} options Restify client options * * @return {Promise<Uint8Array, Error>} image buffer promise */ export const getImage = (host, options) => { // TODO - remove hardcoded https:// const client = createClient(`https://${host}`); return new Promise((resolve, reject) => { client.get(options, (err, req) => { if (err) reject(err); req.on('result', (err, res) => { if (err || !contains(res.contentType(), IMAGE_MIMES)) reject(err); // Setting up image buffer let bufferPosition = 0; const imageBuffer = new Buffer.alloc(parseInt(res.header('Content-Length'))); res.setEncoding('binary'); res.on('data', (chunk) => { imageBuffer.write(chunk, bufferPosition, 'binary'); bufferPosition += chunk.length; }); res.on('end', () => { log.info('Image buffer resolved'); resolve(imageBuffer); }); res.on('error', (err) => { reject(err); }); }); }); }); };
/** # perambulate #### Simple parameter validation * Author: Baz O'Mahony <the.ewok#gmail.com> * Date: 08/20/2014 * License: MIT **/ var isArray = require('util').isArray; module.exports = function perambulate(for_validation) { var current_parameter = {}; var is_valid = false; //It had better validate it's own params! if(typeof for_validation !== "object") { throw new TypeError("paramvalidate was not passed an object"); } is_valid = for_validation.every(function(item){ var type = Object.keys(item)[0]; current_parameter = item; //Arrays are speshul. if(type === "array") { return isArray(item[type]); } //null iz teh speshulz two. if(type === "null") { return item[type] === null; } //We're not even going to talk about NaN... return typeof item[type] === type; }); current_parameter = is_valid ? {}:current_parameter; return {failed_parameter:current_parameter,is_valid:is_valid}; };
var protoclass = require("protoclass"); /** */ function Fragment(children) { this.children = children; } /** */ module.exports = protoclass(Fragment, { /** */ initialize: function(template) { if (this.children.length === 1) return this.children[0].initialize(template); var frag = template.document.createDocumentFragment(); this.children.forEach(function(child) { frag.appendChild(child.initialize(template)); }); return frag; } }); /** */ module.exports.create = function(children) { return new Fragment(children); };
window.$('#responseOnce').append('Script loaded<br>');
const PlotCard = require('../../plotcard.js'); class FavorsFromTheCrown extends PlotCard { setupCardAbilities() { this.reaction({ when: { //Don't see any advantage in bestow-boosting your opponent's cards, so limiting this to own controlled cards onCardEntersPlay: event => event.card.getType() !== 'plot' && event.card.isBestow() && event.card.controller === this.controller }, handler: context => { let numToAdd = context.event.card.tokens['gold'] >= 3 ? 2 : 1; context.event.card.addToken('gold', numToAdd); this.game.addMessage('{0} uses {1} to place {2} gold from the treasury on {3}', this.controller, this, numToAdd, context.event.card); } }); } } FavorsFromTheCrown.code = '06120'; module.exports = FavorsFromTheCrown;
import {defineValidator} from './../definition'; import {InvalidTypeError} from './../errors'; import extractName from './../../classes/extract-name'; export default defineValidator( (value) => { if (typeof value !== 'function') { throw new InvalidTypeError(`value ${extractName(value)} must be instance of Function`); } }, {register: 'function'} );
'use strict'; define([ 'angular', 'modules/utils/Utils', 'modules/promotion/services/PromotionService', 'modules/promotion/services/PromotionProductService', 'modules/promotion/services/PromotionDrawService', 'modules/promotion/services/PromotionRulesService', 'modules/promotion/controllers/PromotionListController', 'modules/promotion/controllers/PromotionCreateController', 'modules/promotion/controllers/PromotionDetailsController', 'modules/promotion/controllers/PromotionProductController', 'modules/promotion/controllers/PromotionDrawController', 'modules/promotion/controllers/PromotionRulesController', // Vendors 'angular-routes', 'angular-sanitize', 'angular-ngprogress', 'angular-bootstrap', 'angular-carousel', 'ckeditor', 'angular-ckeditor' ], function (angular, Utils, PromotionService, PromotionProductService, PromotionDrawService, PromotionRulesService, PromotionListController, PromotionCreateController, PromotionDetailsController, PromotionProductController, PromotionDrawController, PromotionRulesController) { var moduleName = "promotion"; angular .module(moduleName, ['ngRoute', 'ngSanitize', 'ngProgress', 'ui.bootstrap.modal', 'angular-carousel', 'ckeditor', Utils]) .service('PromotionService', PromotionService) .service('PromotionProductService', PromotionProductService) .service('PromotionDrawService', PromotionDrawService) .service('PromotionRulesService', PromotionRulesService) .controller('PromotionListController', PromotionListController) .controller('PromotionCreateController', PromotionCreateController) .controller('PromotionDetailsController', PromotionDetailsController) .controller('PromotionProductController', PromotionProductController) .controller('PromotionDrawController', PromotionDrawController) .controller('PromotionRulesController', PromotionRulesController); return moduleName; });
/** * Created by Josh on 12/3/15. */ //file for implementing frequencies across distances in texts //such as around a specific position, what is the most common word? function getMaxOfArray(numArray) { return Math.max.apply(null, numArray); } function getMinofArray(numArray) { return Math.min.apply(null, numArray); } //gets first index of word function first_index(text, word) { var words = text.split(" "); for(i=0;i<words.length;i++) if(words[i]==word) return i; } //find distance of first word from the end function dist_end(text, word) { var words = text.split(" "); for(i=words.length-1;i>=0;i-=1) if(words[i]==word) return words.length - i; } function all_indexes(text, word) { var words = text.split(" "); var indexes = []; for(var num in words) if(words[num]==word) indexes.push(num); return indexes; } //gets the max separation between two words in text function max_distance(text, word1, word2) { return Math.abs(getMaxOfArray(all_indexes(text, word1)) - getMinofArray(all_indexes(text, word2))); } //creates dictionary of word indexes in a text. var index_dict = function(text) { var words = text.split(" "); for(var num in words) this[words[num]] = all_indexes(text, words[num]); };
/** * 评论详情 * @author jackieLin <dashi_lin@163.com> */ 'use strict'; import React, { Component, PropTypes} from 'react'; import { StyleSheet, Image, Text, View } from 'react-native'; import v2exStyle from '../styles/v2ex'; import TimeAgo from './timeAgo'; const articleListStyles = StyleSheet.create(v2exStyle.articleList); class CommentList extends Component { constructor() { super(); } render() { const {comments} = this.props; return ( <View> {comments.map((comment, ix) => { return ( <View key={ix}> <View style={[articleListStyles.userMessage, {marginTop: 0}]}> <View style={[articleListStyles.favicon, {flex: 8}]}> <Image source={{uri: 'https:' + comment.member.avatar_normal}} style={articleListStyles.faviconImage} resizeMode={'stretch'} /> </View> <View style={articleListStyles.reply}> <Text style={articleListStyles.userName}>{comment.member.username}</Text> <TimeAgo style={articleListStyles.time} time={comment.last_modified}></TimeAgo> </View> </View> <Text style={[articleListStyles.text, {fontSize: 14, lineHeight: 20}]}>{comment.content}</Text> </View> ) })} </View> ); } }; CommentList.propTypes = { comments: PropTypes.array.isRequired } export default CommentList;
// my-custom-environment const http = require('http') const getPort = require('get-port') const seleniumServer = require('selenium-standalone') const NodeEnvironment = require('jest-environment-node') const { BROWSER_NAME: browserName = 'chrome', SKIP_LOCAL_SELENIUM_SERVER, } = process.env const newTabPg = ` <!DOCTYPE html> <html> <head> <title>new tab</title> </head> <body> <a href="about:blank" target="_blank" id="new">Click me</a> </body> </html> ` class CustomEnvironment extends NodeEnvironment { async setup() { await super.setup() // Since ie11 doesn't like dataURIs we have to spin up a // server to handle the new tab page this.server = http.createServer((req, res) => { res.statusCode = 200 res.end(newTabPg) }) const newTabPort = await getPort() await new Promise((resolve, reject) => { this.server.listen(newTabPort, (err) => { if (err) return reject(err) resolve() }) }) let seleniumServerPort if (browserName !== 'chrome' && SKIP_LOCAL_SELENIUM_SERVER !== 'true') { console.log('Installing selenium server') await new Promise((resolve, reject) => { seleniumServer.install((err) => { if (err) return reject(err) resolve() }) }) console.log('Starting selenium server') await new Promise((resolve, reject) => { seleniumServer.start((err, child) => { if (err) return reject(err) this.seleniumServer = child resolve() }) }) console.log('Started selenium server') seleniumServerPort = 4444 } this.global.wd = null this.global._newTabPort = newTabPort this.global.browserName = browserName this.global.seleniumServerPort = seleniumServerPort this.global.browserStackLocalId = global.browserStackLocalId } async teardown() { await super.teardown() if (this.server) { this.server.close() } if (this.global.wd) { try { await this.global.wd.quit() } catch (err) { console.log(`Failed to quit webdriver instance`, err) } } // must come after wd.quit() if (this.seleniumServer) { this.seleniumServer.kill() } } } module.exports = CustomEnvironment
import { List, Repeat } from 'immutable'; /** * Template for semantic Relations, defining the roles (i.e. semantic function and weights) in the default order. */ export default class RelationTemplate { /** * @constructor * @param {AssociateRole} leadingAssociate - first associate's role/weight * @param {?AssociateRole} repetitiveAssociate - recurring associate's role/weight (if there are more than two associates) * @param {AssociateRole} trailingAssociate - last associate's role/weight * @param {string} [description = null] - description of the represented relation type */ constructor(leadingAssociate, repetitiveAssociate, trailingAssociate, description = null) { this.leadingAssociate = leadingAssociate; this.repetitiveAssociate = repetitiveAssociate; this.trailingAssociate = trailingAssociate; this.description = description; Object.freeze(this); } /** * @returns {boolean} whether this template supports relations with more than two associates */ get canHaveMoreThanTwoAssociates() { return this.repetitiveAssociate !== null; } /** * @param {integer} associateCount - number of associates in the targeted relation * @returns {List<AssociateRole>} matching number of associate roles/weights */ getAssociateRoles(associateCount) { if (associateCount < 2 || associateCount > 2 && !this.canHaveMoreThanTwoAssociates) { throw new Error('invalid number of associates for relation: ' + associateCount); } return List.of( this.leadingAssociate, ...Repeat(this.repetitiveAssociate, associateCount - 2), this.trailingAssociate); } }
/** * Created by timfulmer on 7/26/15. */ var passport = require('passport'), BasicStrategy = require('passport-http').BasicStrategy, BearerStrategy = require('passport-http-bearer').Strategy, Promise=require('bluebird'); function initialize(options){ options=options || {}; function initializePromise(resolve){ passport.serializeUser(function(user,done) { return done(null,user.username); }); passport.deserializeUser(function(id,done) { options.collections.user.findOne({username: id}) .then(function (user){ return done(null, user); }) .catch(function(err){ return done(err); }); }); passport.use("clientBasic",new BasicStrategy( function (clientId,clientSecret,done) { options.collections.client.findOne({clientId:clientId}) .then(function(client){ if(!client) return done(null, false); return done(null, client); }) .catch(function(err){ return done(err); }); } )); passport.use("userBasic",new BasicStrategy( function (username,password,done) { options.collections.user.findOne({username:username}) .then(function(user) { if(!user) return done(null, false); if(user.password!==password){ return done(null,false); } return done(null,user); }) .catch(function(err){ return done(err); }); } )); passport.use("accessToken", new BearerStrategy( function (accessToken, done) { options.collections.accesstoken.findOne({token: accessToken}) .then(function(token) { if(!token) return done(null, false); if(new Date() > token.expirationDate) { options.collections.accesstoken.destroy({token: accessToken}) .then(function(){ return done(null) }) .catch(function(err){ return done(err); }); } else { var findUserPromise=options.collections.user.findOne({username:token.userId}) .then(function(user){ return {user:user}; }); var findClientPromise=options.collections.client.findOne({clientId:token.clientId}) .then(function(client){ return {client:client}; }); Promise .reduce([findUserPromise,findClientPromise],function(results,result){ if(result.user){ results.user=result.user; } if(result.client){ results.client=result.client; } return results; },{}) .then(function(results){ if (!results.user || !results.client) return done(null, false); // Put client redirect URI in scope for authorization later, // located in `req.authInfo`. var info={scope:results.client.redirectURI}; return done(null,results.user,info); }) .catch(function(err){ return done(err); }); } }) .catch(function(err){ return done(err); }); } )); options.passport=passport; return resolve(options); } return new Promise(initializePromise); } module.exports={ initialize:initialize };
var configUnitsForFaculty = function () { var facultyID = $("#faculty-id").val(); var facultyItem = $('option[value=' + facultyID + ']'); var left = facultyItem.attr('data-left'); var right = facultyItem.attr('data-right'); var unitSelected = false; $(".unit-option-item").each(function (index, element) { if ($(this).attr("data-left") >= left && $(this).attr("data-right") <= right) { $(this).show(); if (unitSelected == false) { $(this).attr("selected", true); unitSelected = true; } } else { $(this).hide(); $(this).attr("selected", false); } }); }; $(document).ready(function () { // config course and program for add-new-student modal configUnitsForFaculty(); $("#faculty-id").change(function () { configUnitsForFaculty(); }); // set data for fields drop down var fields = JSON.parse($("#current-field-ids").text()); var fieldIDs = []; fields.forEach(function (field) { fieldIDs.push(field.id); }); $("#field-ids").val(fieldIDs); $('.selectpicker').selectpicker('refresh'); console.log($("#current-facultyID").text()); // set faculty and unit data $("#faculty-id").val($("#current-faculty-id").text()); $("#unit-id").val($("#current-unit-id").text()); // on form submit $("#info-form").submit(function (e) { e.preventDefault(); e.stopPropagation(); data = { full_name: $("#full-name").val(), rank: $("#rank").val(), unit_id: $("#unit-id").val(), fields: JSON.stringify($("#field-ids").val()), email: $("#email").val() }; NProgress.start(); $.ajax({ type: "POST", url: "/profile/api/update-profile", data: data, success: function (response) { NProgress.done(); if (response.status == true) { swal( 'Success!', 'Your profile has been updated.', 'success' ) } else { showError(response.message); } }, error: errorHandler }) }); $("#btn-add-topic").click(function (e) { $('#add-topic-modal').modal('show'); }); $("#topic-form").submit(function (e) { $('#add-topic-modal').modal('toggle'); e.preventDefault(); e.stopPropagation(); data = { topic_title: $("#topic-title").val(), topic_description: $("#topic-description").val(), fields: JSON.stringify($("#topic-field-ids").val()), }; NProgress.start(); $.ajax({ type: "POST", url: "/profile/api/add-topic", data: data, success: function (response) { NProgress.done(); if (response.status == true) { NProgress.done(); var fieldsHTML = ""; $("#topic-field-ids").val().forEach(function (id, index) { fieldsHTML = fieldsHTML.concat($("option[value=" + id + "]").text()); if (index != ($("#topic-field-ids").val().length - 1)) { fieldsHTML = fieldsHTML.concat(', '); } }); $("#topics").prepend('<div class="panel panel-default">' + '<div class="panel-heading">' + '<h5>' + data.topic_title + '</h5>' + '</div>' + '<div class="panel-body">' + '<p>' + data.topic_description + '</p>' + '</div>' + '<div class="panel-footer">' + fieldsHTML + '</div>' + '</div>') } else { showError(response.message); } }, error: errorHandler }) }); });
'use strict'; //Sidemenus service used to communicate Sidemenus REST endpoints angular.module('sidemenus').factory('Sidemenus', ['$http', function($http){ /* Private functions */ //Here the proviates functions /* Public functions */ return function(model){ if(model){ for(var keys in model){ this[keys] = model[keys]; } this.selected = false; }else{ this.title = ''; this.icon = 'modules/sidemenus/svg/default.JSON'; this.selected = false; } //CRUD FUNCTIONS this.save = function(callback){ $http.post('api/sidemenus', this) .success(function(newSidemenu){ if(callback){callback(newSidemenu);} }) .error(function(err) { if (callback) {callback(err);} }); }; this.update = function(callback){ $http.put('api/sidemenus', this) .success(function(newSidemenu){ if(callback){callback(newSidemenu);} }) .error(function(err) { if (callback) {callback(err);} }); }; //GET //QUERY //DELETE }; } ]); angular.module('sidemenus').factory('Sidebar', ['$http', function($http){ return { getSidebarByUser : function(callback){ $http.get('api/getSidebarByUser') .success(function(sidebar){ if(callback){callback(sidebar);} else{return sidebar;} }) .error(function(err){ if(callback){callback(err);} }); }, addNotification : function(userId, sidemenuId, callback){ $http.put('api/sidebar/notification', {userId : userId, sidemenuId: sidemenuId}) .success(function() { if (callback) {callback();} }) .error(function(err){ if(callback){callback(err);} else{console.log(err);} }); } }; } ]);
/* global document */ function toArray(xs) { return Array.prototype.slice.call(xs); } function filterToc() { var f = filterElement.bind(null, nameFilter.value, ''); funcs.forEach(f); } function filterElement(nameFilter, categoryFilter, elem) { var name = elem.getAttribute('data-name'); var category = elem.getAttribute('data-category'); var matches = strIn(nameFilter, name) || category === categoryFilter; elem.style.display = matches ? '' : 'none'; } function strIn(a, b) { a = a.toLowerCase(); b = b.toLowerCase(); return b.indexOf(a) >= 0; } function scrollToTop() { var main = document.querySelector('main'); main.scrollTop = 0; } function tryToggleCollapse(elem) { var sel = elem && elem.getAttribute('data-collapser'); if (!sel) { return; } elem .classList .toggle('open'); document .querySelector(sel) .classList .toggle('in'); } function isTopLink(elem) { return elem.getAttribute('href') === '#'; } function dispatchEvent(event) { var target = event.target; var parent = target.parentNode; if (isTopLink(target)) { scrollToTop(target); } else { tryToggleCollapse(target); tryToggleCollapse(parent); } } var nameFilter = document.getElementById('name-filter'); var funcs = toArray(document.querySelectorAll('.toc .func')); filterToc(); document.body.addEventListener('click', dispatchEvent, false); nameFilter.addEventListener('input', filterToc, false);
var rf = require("fs"), readline = require("readline"), rs = rf.ReadStream("datatt.json"); rl = readline.createInterface({'input':rs,'output':{}}); var i = 0; rl.on('line',function(line){ console.log("********::"); //console.log(i++ + ': '+ line.trim()); var arr = line.split("|"); console.log(i++ + ': '+ arr[0]+' '+arr[1]); }); rl.resume(); console.log("READ FILE ASYNC END");
/** * Created by ms on 1/25/2017. */
// // NOTES: // // - The service initialization is asynchronous, so there's a race condition. // RPC.Calculator may not be ready when CalcCntl.add/subtract are called // - This can be solved a few ways, but I didn't want to complicate the example // with that, as it depends on how your app is actually setup. See: // http://stackoverflow.com/questions/16286605/initialize-angularjs-service-with-asynchronous-data // - The "endpoints" array to RPC object mapping assumes that your set of interface names // is unique across all endpoints. If that doesn't hold for your system, then you'll // need to add an endpoint id to the names to make them unique. // var app = angular.module("calcApp", []); app.service("RPC", function($http) { var i, RPC = {}, // update this list with all Barrister endpoints and interfaces you want // to expose endpoints = [{ url: "/api/calc", interfaces: ["Calculator"] }], clientOpts = { // automatically convert JS types to conform to IDL types // if it can be done w/o data loss (e.g. "1" -> 1, "true" -> true) coerce: true }; function initClient(endpoint) { var transport = function(req, callback) { $http.post(endpoint.url, Barrister.JSON_stringify(req)) .success(function(data, status, headers, config) { callback(Barrister.parseResponse(req, null, data)); }) .error(function(data, status, headers, config) { callback(Barrister.parseResponse(req, status + " data: " + data, null)); }); }, client = new Barrister.Client(transport, clientOpts); client.loadContract(function(err) { var i, name; if (err) { alert("Unable to load contract: " + Barrister.JSON_stringify(err)); } else { for (i = 0; i < endpoint.interfaces.length; i++) { name = endpoint.interfaces[i]; RPC[name] = client.proxy(name); } } }); } for (i = 0; i < endpoints.length; i++) { initClient(endpoints[i]); } return RPC; }); app.controller("CalcCntl", ["$scope", "RPC", function($scope, RPC) { var showResult = function(err, result) { if (err) { $scope.result = "ERR: " + Barrister.JSON_stringify(err); } else { $scope.result = result; } }; $scope.add = function() { $scope.result = RPC.Calculator.add($scope.x, $scope.y, showResult); }; $scope.subtract = function() { $scope.result = RPC.Calculator.subtract($scope.x, $scope.y, showResult); }; } ]);
import infoAddon from "@storybook/addon-info"; import { setAddon, storiesOf } from "@storybook/react"; import { action } from "@storybook/addon-actions"; import { withInfo } from "@storybook/addon-info"; import React from "react"; import styled, { ThemeProvider } from "styled-components"; import Switch from "binary-ui-components/mobile/Switch"; import { THEME_MAIN } from "binary-ui-styles"; setAddon(infoAddon); class Demo extends React.Component { constructor(props) { super(props); this.state = { isChecked: false }; this.onChange = this.onChange.bind(this); } onChange(isChecked) { this.setState(() => ({ isChecked })); } render() { const { isChecked } = this.state; return ( <Switch isChecked={isChecked} label="Demo" onChange={this.onChange} /> ); } } storiesOf("binary-ui-components/mobile", module).add( "Switch", withInfo("Switch component")(() => ( <ThemeProvider theme={THEME_MAIN}> <div> <Switch isChecked label="Switch label" onChange={action()} /> <Switch isChecked isDisabled label="Switch disabled" onChange={action()} /> <Switch isChecked={false} onChange={action()} /> <Demo /> </div> </ThemeProvider> )) );
/****** * * EditArea * Developped by Christophe Dolivet * Released under LGPL, Apache and BSD licenses (use the one you want) * ******/ function EditArea(){ var t=this; t.error= false; // to know if load is interrrupt t.inlinePopup= [{popup_id: "area_search_replace", icon_id: "search"}, {popup_id: "edit_area_help", icon_id: "help"}]; t.plugins= {}; t.line_number=0; parent.editAreaLoader.set_browser_infos(t); // navigator identification // fix IE8 detection as we run in IE7 emulate mode through X-UA <meta> tag if( t.isIE >= 8 ) t.isIE = 7; t.last_selection={}; t.last_text_to_highlight=""; t.last_hightlighted_text= ""; t.syntax_list= []; t.allready_used_syntax= {}; t.check_line_selection_timer= 50; // the timer delay for modification and/or selection change detection t.textareaFocused= false; t.highlight_selection_line= null; t.previous= []; t.next= []; t.last_undo=""; t.files= {}; t.filesIdAssoc= {}; t.curr_file= ''; //t.loaded= false; t.assocBracket={}; t.revertAssocBracket= {}; // bracket selection init t.assocBracket["("]=")"; t.assocBracket["{"]="}"; t.assocBracket["["]="]"; for(var index in t.assocBracket){ t.revertAssocBracket[t.assocBracket[index]]=index; } t.is_editable= true; /*t.textarea=""; t.state="declare"; t.code = []; // store highlight syntax for languagues*/ // font datas t.lineHeight= 16; /*t.default_font_family= "monospace"; t.default_font_size= 10;*/ t.tab_nb_char= 8; //nb of white spaces corresponding to a tabulation if(t.isOpera) t.tab_nb_char= 6; t.is_tabbing= false; t.fullscreen= {'isFull': false}; t.isResizing=false; // resize var // init with settings and ID (area_id is a global var defined by editAreaLoader on iframe creation t.id= area_id; t.settings= editAreas[t.id]["settings"]; if((""+t.settings['replace_tab_by_spaces']).match(/^[0-9]+$/)) { t.tab_nb_char= t.settings['replace_tab_by_spaces']; t.tabulation=""; for(var i=0; i<t.tab_nb_char; i++) t.tabulation+=" "; }else{ t.tabulation="\t"; } // retrieve the init parameter for syntax if(t.settings["syntax_selection_allow"] && t.settings["syntax_selection_allow"].length>0) t.syntax_list= t.settings["syntax_selection_allow"].replace(/ /g,"").split(","); if(t.settings['syntax']) t.allready_used_syntax[t.settings['syntax']]=true; }; EditArea.prototype.init= function(){ var t=this, a, s=t.settings; t.textarea = _$("textarea"); t.container = _$("container"); t.result = _$("result"); t.content_highlight = _$("content_highlight"); t.selection_field = _$("selection_field"); t.selection_field_text= _$("selection_field_text"); t.processing_screen = _$("processing"); t.editor_area = _$("editor"); t.tab_browsing_area = _$("tab_browsing_area"); t.test_font_size = _$("test_font_size"); a = t.textarea; if(!s['is_editable']) t.set_editable(false); t.set_show_line_colors( s['show_line_colors'] ); if(syntax_selec= _$("syntax_selection")) { // set up syntax selection lsit in the toolbar for(var i=0; i<t.syntax_list.length; i++) { var syntax= t.syntax_list[i]; var option= document.createElement("option"); option.value= syntax; if(syntax==s['syntax']) option.selected= "selected"; dispSyntax = parent.editAreaLoader.syntax_display_name[ syntax ]; option.innerHTML= typeof( dispSyntax ) == 'undefined' ? syntax.substring( 0, 1 ).toUpperCase() + syntax.substring( 1 ) : dispSyntax;//t.get_translation("syntax_" + syntax, "word"); syntax_selec.appendChild(option); } } // add plugins buttons in the toolbar spans= parent.getChildren(_$("toolbar_1"), "span", "", "", "all", -1); for(var i=0; i<spans.length; i++){ id=spans[i].id.replace(/tmp_tool_(.*)/, "$1"); if(id!= spans[i].id){ for(var j in t.plugins){ if(typeof(t.plugins[j].get_control_html)=="function" ){ html=t.plugins[j].get_control_html(id); if(html!=false){ html= t.get_translation(html, "template"); var new_span= document.createElement("span"); new_span.innerHTML= html; var father= spans[i].parentNode; spans[i].parentNode.replaceChild(new_span, spans[i]); break; // exit the for loop } } } } } // init datas //a.value = 'a';//editAreas[t.id]["textarea"].value; if(s["debug"]) { t.debug=parent.document.getElementById("edit_area_debug_"+t.id); } // init size //this.update_size(); if(_$("redo") != null) t.switchClassSticky(_$("redo"), 'editAreaButtonDisabled', true); // insert css rules for highlight mode if(typeof(parent.editAreaLoader.syntax[s["syntax"]])!="undefined"){ for(var i in parent.editAreaLoader.syntax){ if (typeof(parent.editAreaLoader.syntax[i]["styles"]) != "undefined"){ t.add_style(parent.editAreaLoader.syntax[i]["styles"]); } } } // init key events if(t.isOpera) _$("editor").onkeypress = keyDown; else _$("editor").onkeydown = keyDown; for(var i=0; i<t.inlinePopup.length; i++){ if(t.isOpera) _$(t.inlinePopup[i]["popup_id"]).onkeypress = keyDown; else _$(t.inlinePopup[i]["popup_id"]).onkeydown = keyDown; } if(s["allow_resize"]=="both" || s["allow_resize"]=="x" || s["allow_resize"]=="y") t.allow_resize(true); parent.editAreaLoader.toggle(t.id, "on"); //a.focus(); // line selection init t.change_smooth_selection_mode(editArea.smooth_selection); // highlight t.execCommand("change_highlight", s["start_highlight"]); // get font size datas t.set_font(editArea.settings["font_family"], editArea.settings["font_size"]); // set unselectable text children= parent.getChildren(document.body, "", "selec", "none", "all", -1); for(var i=0; i<children.length; i++){ if(t.isIE) children[i].unselectable = true; // IE else children[i].onmousedown= function(){return false}; /* children[i].style.MozUserSelect = "none"; // Moz children[i].style.KhtmlUserSelect = "none"; // Konqueror/Safari*/ } a.spellcheck= s["gecko_spellcheck"]; /** Browser specific style fixes **/ // fix rendering bug for highlighted lines beginning with no tabs if( t.isFirefox >= '3' ) { t.content_highlight.style.paddingLeft= "1px"; t.selection_field.style.paddingLeft= "1px"; t.selection_field_text.style.paddingLeft= "1px"; } if(t.isIE && t.isIE < 8 ){ a.style.marginTop= "-1px"; } /* if(t.isOpera){ t.editor_area.style.position= "absolute"; }*/ if( t.isSafari ){ t.editor_area.style.position = "absolute"; // a.style.marginLeft ="-3px"; if( t.isSafari < 3.2 ) // Safari 3.0 (3.1?) a.style.marginTop ="1px"; } // si le textarea n'est pas grand, un click sous le textarea doit provoquer un focus sur le textarea parent.editAreaLoader.add_event(t.result, "click", function(e){ if((e.target || e.srcElement)==editArea.result) { editArea.area_select(editArea.textarea.value.length, 0);} }); if(s['is_multi_files']!=false) t.open_file({'id': t.curr_file, 'text': ''}); t.set_word_wrap( s['word_wrap'] ); setTimeout("editArea.focus();editArea.manage_size();editArea.execCommand('EA_load');", 10); //start checkup routine t.check_undo(); t.check_line_selection(true); t.scroll_to_view(); for(var i in t.plugins){ if(typeof(t.plugins[i].onload)=="function") t.plugins[i].onload(); } if(s['fullscreen']==true) t.toggle_full_screen(true); parent.editAreaLoader.add_event(window, "resize", editArea.update_size); parent.editAreaLoader.add_event(parent.window, "resize", editArea.update_size); parent.editAreaLoader.add_event(top.window, "resize", editArea.update_size); parent.editAreaLoader.add_event(window, "unload", function(){ // in case where editAreaLoader have been already cleaned if( parent.editAreaLoader ) { parent.editAreaLoader.remove_event(parent.window, "resize", editArea.update_size); parent.editAreaLoader.remove_event(top.window, "resize", editArea.update_size); } if(editAreas[editArea.id] && editAreas[editArea.id]["displayed"]){ editArea.execCommand("EA_unload"); } }); /*date= new Date(); alert(date.getTime()- parent.editAreaLoader.start_time);*/ }; //called by the toggle_on EditArea.prototype.update_size= function(){ var d=document,pd=parent.document,height,width,popup,maxLeft,maxTop; if( typeof editAreas != 'undefined' && editAreas[editArea.id] && editAreas[editArea.id]["displayed"]==true){ if(editArea.fullscreen['isFull']){ pd.getElementById("frame_"+editArea.id).style.width = pd.getElementsByTagName("html")[0].clientWidth + "px"; pd.getElementById("frame_"+editArea.id).style.height = pd.getElementsByTagName("html")[0].clientHeight + "px"; } if(editArea.tab_browsing_area.style.display=='block' && ( !editArea.isIE || editArea.isIE >= 8 ) ) { editArea.tab_browsing_area.style.height = "0px"; editArea.tab_browsing_area.style.height = (editArea.result.offsetTop - editArea.tab_browsing_area.offsetTop -1)+"px"; } height = d.body.offsetHeight - editArea.get_all_toolbar_height() - 4; editArea.result.style.height = height +"px"; width = d.body.offsetWidth -2; editArea.result.style.width = width+"px"; //alert("result h: "+ height+" w: "+width+"\ntoolbar h: "+this.get_all_toolbar_height()+"\nbody_h: "+document.body.offsetHeight); // check that the popups don't get out of the screen for( i=0; i < editArea.inlinePopup.length; i++ ) { popup = _$(editArea.inlinePopup[i]["popup_id"]); maxLeft = d.body.offsetWidth - popup.offsetWidth; maxTop = d.body.offsetHeight - popup.offsetHeight; if( popup.offsetTop > maxTop ) popup.style.top = maxTop+"px"; if( popup.offsetLeft > maxLeft ) popup.style.left = maxLeft+"px"; } editArea.manage_size( true ); editArea.fixLinesHeight( editArea.textarea.value, 0,-1); } }; EditArea.prototype.manage_size= function(onlyOneTime){ if(!editAreas[this.id]) return false; if(editAreas[this.id]["displayed"]==true && this.textareaFocused) { var area_height,resized= false; //1) Manage display width //1.1) Calc the new width to use for display if( !this.settings['word_wrap'] ) { var area_width= this.textarea.scrollWidth; area_height= this.textarea.scrollHeight; // bug on old opera versions if(this.isOpera && this.isOpera < 9.6 ){ area_width=10000; } //1.2) the width is not the same, we must resize elements if(this.textarea.previous_scrollWidth!=area_width) { this.container.style.width= area_width+"px"; this.textarea.style.width= area_width+"px"; this.content_highlight.style.width= area_width+"px"; this.textarea.previous_scrollWidth=area_width; resized=true; } } // manage wrap width if( this.settings['word_wrap'] ) { newW=this.textarea.offsetWidth; if( this.isFirefox || this.isIE ) newW-=2; if( this.isSafari ) newW-=6; this.content_highlight.style.width=this.selection_field_text.style.width=this.selection_field.style.width=this.test_font_size.style.width=newW+"px"; } //2) Manage display height //2.1) Calc the new height to use for display if( this.isOpera || this.isFirefox || this.isSafari ) { area_height= this.getLinePosTop( this.last_selection["nb_line"] + 1 ); } else { area_height = this.textarea.scrollHeight; } //2.2) the width is not the same, we must resize elements if(this.textarea.previous_scrollHeight!=area_height) { this.container.style.height= (area_height+2)+"px"; this.textarea.style.height= area_height+"px"; this.content_highlight.style.height= area_height+"px"; this.textarea.previous_scrollHeight= area_height; resized=true; } //3) if there is new lines, we add new line numbers in the line numeration area if(this.last_selection["nb_line"] >= this.line_number) { var newLines= '', destDiv=_$("line_number"), start=this.line_number, end=this.last_selection["nb_line"]+100; for( i = start+1; i < end; i++ ) { newLines+='<div id="line_'+ i +'">'+i+"</div>"; this.line_number++; } destDiv.innerHTML= destDiv.innerHTML + newLines; if(this.settings['word_wrap']){ this.fixLinesHeight( this.textarea.value, start, -1 ); } } //4) be sure the text is well displayed this.textarea.scrollTop="0px"; this.textarea.scrollLeft="0px"; if(resized==true){ this.scroll_to_view(); } } if(!onlyOneTime) setTimeout("editArea.manage_size();", 100); }; EditArea.prototype.execCommand= function(cmd, param){ for(var i in this.plugins){ if(typeof(this.plugins[i].execCommand)=="function"){ if(!this.plugins[i].execCommand(cmd, param)) return; } } switch(cmd){ case "save": if(this.settings["save_callback"].length>0) eval("parent."+this.settings["save_callback"]+"('"+ this.id +"', editArea.textarea.value);"); break; case "load": if(this.settings["load_callback"].length>0) eval("parent."+this.settings["load_callback"]+"('"+ this.id +"');"); break; case "onchange": if(this.settings["change_callback"].length>0) eval("parent."+this.settings["change_callback"]+"('"+ this.id +"');"); break; case "EA_load": if(this.settings["EA_load_callback"].length>0) eval("parent."+this.settings["EA_load_callback"]+"('"+ this.id +"');"); break; case "EA_unload": if(this.settings["EA_unload_callback"].length>0) eval("parent."+this.settings["EA_unload_callback"]+"('"+ this.id +"');"); break; case "toggle_on": if(this.settings["EA_toggle_on_callback"].length>0) eval("parent."+this.settings["EA_toggle_on_callback"]+"('"+ this.id +"');"); break; case "toggle_off": if(this.settings["EA_toggle_off_callback"].length>0) eval("parent."+this.settings["EA_toggle_off_callback"]+"('"+ this.id +"');"); break; case "re_sync": if(!this.do_highlight) break; case "file_switch_on": if(this.settings["EA_file_switch_on_callback"].length>0) eval("parent."+this.settings["EA_file_switch_on_callback"]+"(param);"); break; case "file_switch_off": if(this.settings["EA_file_switch_off_callback"].length>0) eval("parent."+this.settings["EA_file_switch_off_callback"]+"(param);"); break; case "file_close": if(this.settings["EA_file_close_callback"].length>0) return eval("parent."+this.settings["EA_file_close_callback"]+"(param);"); break; default: if(typeof(eval("editArea."+cmd))=="function") { if(this.settings["debug"]) eval("editArea."+ cmd +"(param);"); else try{eval("editArea."+ cmd +"(param);");}catch(e){}; } } }; EditArea.prototype.get_translation= function(word, mode){ if(mode=="template") return parent.editAreaLoader.translate(word, this.settings["language"], mode); else return parent.editAreaLoader.get_word_translation(word, this.settings["language"]); }; EditArea.prototype.add_plugin= function(plug_name, plug_obj){ for(var i=0; i<this.settings["plugins"].length; i++){ if(this.settings["plugins"][i]==plug_name){ this.plugins[plug_name]=plug_obj; plug_obj.baseURL=parent.editAreaLoader.baseURL + "plugins/" + plug_name + "/"; if( typeof(plug_obj.init)=="function" ) plug_obj.init(); } } }; EditArea.prototype.load_css= function(url){ try{ link = document.createElement("link"); link.type = "text/css"; link.rel= "stylesheet"; link.media="all"; link.href = url; head = document.getElementsByTagName("head"); head[0].appendChild(link); }catch(e){ document.write("<link href='"+ url +"' rel='stylesheet' type='text/css' />"); } }; EditArea.prototype.load_script= function(url){ try{ script = document.createElement("script"); script.type = "text/javascript"; script.src = url; script.charset= "UTF-8"; head = document.getElementsByTagName("head"); head[0].appendChild(script); }catch(e){ document.write("<script type='text/javascript' src='" + url + "' charset=\"UTF-8\"><"+"/script>"); } }; // add plugin translation to language translation array EditArea.prototype.add_lang= function(language, values){ if(!parent.editAreaLoader.lang[language]) parent.editAreaLoader.lang[language]={}; for(var i in values) parent.editAreaLoader.lang[language][i]= values[i]; }; // short cut for document.getElementById() function _$(id){return document.getElementById( id );}; var editArea = new EditArea(); parent.editAreaLoader.add_event(window, "load", init); function init(){ setTimeout("editArea.init(); ", 10); };
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { Platform, StyleSheet, TextInput } from 'react-native'; import { connect } from 'react-redux'; import config from '../../config'; import { searchSongs } from '../../redux/songs'; import { navigatorPropTypes } from '../../helpers/PropTypes'; const styles = StyleSheet.create({ input: { height: 40, paddingVertical: 4, paddingHorizontal: 8, marginVertical: 16, borderWidth: Platform.OS === 'ios' ? 1 : 0, borderColor: config.colors.grayMid, color: config.colors.blackLight, fontSize: 18 } }); export class SearchTextInput extends Component { static propTypes = { searchSongs: PropTypes.func.isRequired, navigation: navigatorPropTypes() }; render() { return ( <TextInput style={styles.input} placeholder='Hae lauluja..' placeholderTextColor={config.colors.grayDark} autoCorrect={false} returnKeyType='search' onSubmitEditing={this.handleSubmit} /> ); } handleSubmit = ({nativeEvent}) => { this.props.searchSongs(nativeEvent.text); this.props.navigation.navigate('SongSearch', {searchString: nativeEvent.text}); }; } export default connect(null, { searchSongs })(SearchTextInput);
var d3_time = require('d3-time'), d3_timeF = require('d3-time-format'), d3_numberF = require('d3-format'), numberF = d3_numberF, // defaults to EN-US timeF = d3_timeF; // defaults to EN-US function numberLocale(l) { var f = d3_numberF.localeFormat(l); if (f == null) throw Error('Unrecognized locale: ' + l); numberF = f; } function timeLocale(l) { var f = d3_timeF.localeFormat(l); if (f == null) throw Error('Unrecognized locale: ' + l); timeF = f; } module.exports = { // Update number formatter to use provided locale configuration. // For more see https://github.com/d3/d3-format numberLocale: numberLocale, number: function(f) { return numberF.format(f); }, numberPrefix: function(f, v) { return numberF.formatPrefix(f, v); }, // Update time formatter to use provided locale configuration. // For more see https://github.com/d3/d3-time-format timeLocale: timeLocale, time: function(f) { return timeF.format(f); }, utc: function(f) { return timeF.utcFormat(f); }, // Set number and time locale simultaneously. locale: function(l) { numberLocale(l); timeLocale(l); }, // automatic formatting functions auto: { number: numberAutoFormat, time: function() { return timeAutoFormat(); }, utc: function() { return utcAutoFormat(); } } }; var e10 = Math.sqrt(50), e5 = Math.sqrt(10), e2 = Math.sqrt(2); function intervals(domain, count) { if (!domain.length) domain = [0]; if (count == null) count = 10; var start = domain[0], stop = domain[domain.length - 1]; if (stop < start) { error = stop; stop = start; start = error; } var span = (stop - start) || (count = 1, start || stop || 1), step = Math.pow(10, Math.floor(Math.log(span / count) / Math.LN10)), error = span / count / step; // Filter ticks to get closer to the desired count. if (error >= e10) step *= 10; else if (error >= e5) step *= 5; else if (error >= e2) step *= 2; // Round start and stop values to step interval. return [ Math.ceil(start / step) * step, Math.floor(stop / step) * step + step / 2, // inclusive step ]; } function significantDigits(domain) { return domain.map(function(x) { // determine significant digits based on exponential format var s = x.toExponential(), e = s.indexOf('e'), d = s.indexOf('.'); return d < 0 ? 1 : (e-d); }).reduce(function(max, p) { // return the maximum sig digit count return Math.max(max, p); }, 0); } function numberAutoFormat(domain, count, f) { var range = intervals(domain, count); if (f == null) { f = ',.' + d3_numberF.precisionFixed(range[2]) + 'f'; } else { switch (f = d3_numberF.formatSpecifier(f), f.type) { case 's': { if (f.precision == null) f.precision = significantDigits(domain); return numberF.format(f); } case '': case 'e': case 'g': case 'p': case 'r': { if (f.precision == null) f.precision = d3_numberF.precisionRound(range[2], Math.max(Math.abs(range[0]), Math.abs(range[1]))) - (f.type === 'e'); break; } case 'f': case '%': { if (f.precision == null) f.precision = d3_numberF.precisionFixed(range[2]) - (f.type === '%') * 2; break; } } } return numberF.format(f); } function timeAutoFormat() { var f = timeF.format, formatMillisecond = f('.%L'), formatSecond = f(':%S'), formatMinute = f('%I:%M'), formatHour = f('%I %p'), formatDay = f('%a %d'), formatWeek = f('%b %d'), formatMonth = f('%B'), formatYear = f('%Y'); return function(date) { var d = +date; return (d3_time.second(date) < d ? formatMillisecond : d3_time.minute(date) < d ? formatSecond : d3_time.hour(date) < d ? formatMinute : d3_time.day(date) < d ? formatHour : d3_time.month(date) < d ? (d3_time.week(date) < d ? formatDay : formatWeek) : d3_time.year(date) < d ? formatMonth : formatYear)(date); }; } function utcAutoFormat() { var f = timeF.utcFormat, formatMillisecond = f('.%L'), formatSecond = f(':%S'), formatMinute = f('%I:%M'), formatHour = f('%I %p'), formatDay = f('%a %d'), formatWeek = f('%b %d'), formatMonth = f('%B'), formatYear = f('%Y'); return function(date) { var d = +date; return (d3_time.utcSecond(date) < d ? formatMillisecond : d3_time.utcMinute(date) < d ? formatSecond : d3_time.utcHour(date) < d ? formatMinute : d3_time.utcDay(date) < d ? formatHour : d3_time.utcMonth(date) < d ? (d3_time.utcWeek(date) < d ? formatDay : formatWeek) : d3_time.utcYear(date) < d ? formatMonth : formatYear)(date); }; }
'use strict'; angular.module('hackshareApp') .config(function ($stateProvider) { $stateProvider .state('hack', { url: '/hacks/:hackId', templateUrl: 'app/hacks/hack/hack.html', controller: 'HackCtrl' }); });
//star rating export default function(cell, onRendered, success, cancel, editorParams){ var self = this, element = cell.getElement(), value = cell.getValue(), maxStars = element.getElementsByTagName("svg").length || 5, size = element.getElementsByTagName("svg")[0] ? element.getElementsByTagName("svg")[0].getAttribute("width") : 14, stars = [], starsHolder = document.createElement("div"), star = document.createElementNS('http://www.w3.org/2000/svg', "svg"); //change star type function starChange(val){ stars.forEach(function(star, i){ if(i < val){ if(self.table.browser == "ie"){ star.setAttribute("class", "tabulator-star-active"); }else{ star.classList.replace("tabulator-star-inactive", "tabulator-star-active"); } star.innerHTML = '<polygon fill="#488CE9" stroke="#014AAE" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/>'; }else{ if(self.table.browser == "ie"){ star.setAttribute("class", "tabulator-star-inactive"); }else{ star.classList.replace("tabulator-star-active", "tabulator-star-inactive"); } star.innerHTML = '<polygon fill="#010155" stroke="#686868" stroke-width="37.6152" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" points="259.216,29.942 330.27,173.919 489.16,197.007 374.185,309.08 401.33,467.31 259.216,392.612 117.104,467.31 144.25,309.08 29.274,197.007 188.165,173.919 "/>'; } }); } //build stars function buildStar(i){ var starHolder = document.createElement("span"); var nextStar = star.cloneNode(true); stars.push(nextStar); starHolder.addEventListener("mouseenter", function(e){ e.stopPropagation(); e.stopImmediatePropagation(); starChange(i); }); starHolder.addEventListener("mousemove", function(e){ e.stopPropagation(); e.stopImmediatePropagation(); }); starHolder.addEventListener("click", function(e){ e.stopPropagation(); e.stopImmediatePropagation(); success(i); element.blur(); }); starHolder.appendChild(nextStar); starsHolder.appendChild(starHolder); } //handle keyboard navigation value change function changeValue(val){ value = val; starChange(val); } //style cell element.style.whiteSpace = "nowrap"; element.style.overflow = "hidden"; element.style.textOverflow = "ellipsis"; //style holding element starsHolder.style.verticalAlign = "middle"; starsHolder.style.display = "inline-block"; starsHolder.style.padding = "4px"; //style star star.setAttribute("width", size); star.setAttribute("height", size); star.setAttribute("viewBox", "0 0 512 512"); star.setAttribute("xml:space", "preserve"); star.style.padding = "0 1px"; if(editorParams.elementAttributes && typeof editorParams.elementAttributes == "object"){ for (let key in editorParams.elementAttributes){ if(key.charAt(0) == "+"){ key = key.slice(1); starsHolder.setAttribute(key, starsHolder.getAttribute(key) + editorParams.elementAttributes["+" + key]); }else{ starsHolder.setAttribute(key, editorParams.elementAttributes[key]); } } } //create correct number of stars for(var i=1;i<= maxStars;i++){ buildStar(i); } //ensure value does not exceed number of stars value = Math.min(parseInt(value), maxStars); // set initial styling of stars starChange(value); starsHolder.addEventListener("mousemove", function(e){ starChange(0); }); starsHolder.addEventListener("click", function(e){ success(0); }); element.addEventListener("blur", function(e){ cancel(); }); //allow key based navigation element.addEventListener("keydown", function(e){ switch(e.keyCode){ case 39: //right arrow changeValue(value + 1); break; case 37: //left arrow changeValue(value - 1); break; case 13: //enter success(value); break; case 27: //escape cancel(); break; } }); return starsHolder; };
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import throttle from 'lodash.throttle'; import ReactMarkedEditor, { Replacer } from '../../src/'; export default class App extends Component { constructor(props) { super(props); this.handleMarkdownChange = this.handleMarkdownChange.bind(this); this.handleWindowResize = throttle(this.handleWindowResize.bind(this), 200); this.state = { winWidth: 1024, winHeight: 768 } this.markdown = md; } handleMarkdownChange (newValue) { this.markdown = newValue; } componentDidMount() { this.setState({ winWidth: window.innerWidth, winHeight: window.innerHeight }); window.addEventListener('resize', this.handleWindowResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleWindowResize); } handleWindowResize() { this.setState({ winWidth: window.innerWidth, winHeight: window.innerHeight }); } /** * @param codeMirror -> the codemirror doc instance * @param clickEvent -> the click event */ handleImageUploadClick(codeMirror, clickEvent) { alert('You clicked the custom button! And an image will be added to editor.'); const replacer = new Replacer(codeMirror) replacer.image('http://codemirror.net/doc/logo.png') } render() { const styles = { wrapper: { width: this.state.winWidth - 100, border: '1px solid #eee' } } //custom buttons defined here const btns = [ { title: 'custom button', icon: 'upload', onClick: this.handleImageUploadClick.bind(this) } ] return ( <div className="wrapper"> <ReactMarkedEditor style={styles.wrapper} editorHeight={this.state.winHeight - 140} initialMarkdown={md} toolbarCustomButtons={btns} onChange={this.handleMarkdownChange} /> <style jsx>{` .wrapper { margin: 50px 50px 0px 50px; } `}</style> <style jsx global>{` * { margin: 0px; padding: 0px; } `}</style> </div> ); } } const md = ` # React marked editor example 1. item1 2. item3 3. item3 -------- - item1 - item2 - item3 A text of \`markdown\`. \`\`\`js console.log('this is javascript code'); \`\`\` |this is table| A | B | |-------------|---|---| | hello | 1 | 2 | | world | 3 | 4 | #### EOF `;
// ========================================================================== // Project: Welcome Strings // Copyright: ©2010 Apple Inc. // ========================================================================== /*globals Welcome */ // Place strings you want to localize here. In your app, use the key and // localize it using "key string".loc(). HINT: For your key names, use the // english string with an underscore in front. This way you can still see // how your UI will look and you'll notice right away when something needs a // localized string added to this file! // SC.stringsFor('English', { // "_String Key": "Localized String" }) ;
import React, {Component} from 'react'; import { Form, Icon, Input, Button } from 'antd'; const FormItem = Form.Item; import Animate from './animate'; import './login.css'; import { Http } from '../utils/http'; import {connect} from "react-redux"; import { login, setTags } from '../actions/index'; class NormalLoginForm extends React.Component { handleSubmit = (e) => { e.preventDefault(); this.props.form.validateFields((err, values) => { if (!err) { const { login } = this.props; console.log('Received values of form: ', values); login(values); } }); } render() { const { getFieldDecorator } = this.props.form; return ( <Form onSubmit={this.handleSubmit} className="login-form"> <FormItem> {getFieldDecorator('userName', { rules: [ { required: true, message: 'Please input your username!' } ], })( <Input prefix={<Icon type="user" style={{ fontSize: 13 }}/>} placeholder="Username"/> )} </FormItem> <FormItem> {getFieldDecorator('password', { rules: [ { required: true, message: 'Please input your Password!' } ], })( <Input prefix={<Icon type="lock" style={{ fontSize: 13 }}/>} type="password" placeholder="Password"/> )} </FormItem> <FormItem> <Button type="primary" htmlType="submit" className="login-form-button"> Log in </Button> </FormItem> </Form> ); } } const WrappedNormalLoginForm = Form.create()(NormalLoginForm); class Login extends Component { constructor(props) { super(props); this.state = { image: require('../image/a.png'), pixSize: 20, pointSize: 10, isMode: false, show: false, }; } componentWillMount(){ this.get_set_tags(); } get_set_tags(){ Http.get(Http.url('article/gettags'), '', (res) => { if(res.status === 0){ this.props.dispatch(setTags(res.resp.tags)); } }) } render() { return ( <Animate child={this.child} image={this.state.image} pixSize={this.state.pixSize} pointSizeMin={this.state.pointSize} /> ) } child = () => { return ( <div className='loginBox'> <a href='/#/container' id='loginLink' style={{display: 'none'}}>aaaa</a> <WrappedNormalLoginForm login={(val) => this.handleLogin(val)}/> </div> ) }; handleLogin(value) { Http.post(Http.url('admin/login'), '', value, (res) => { console.log(res) if(res.status === 0){ this.props.dispatch(login(res.resp)); } // todo: 注释的方法只能实现url变化,无法跳转,用reload会导致短暂白屏。暂时用模拟点击实现跳转 //browserHistory.push('/#/articles'); //location.reload(); //context.router.push('/#/articles') let redirect = document.getElementById('loginLink'); redirect.click(); }) } } function select(store) { return { logged: store.admin.logged, token: store.admin.token } } export default connect(select)(Login);
'use strict'; /*! * V4Fire Client Core * https://github.com/V4Fire/Client * * Released under the MIT license * https://github.com/V4Fire/Client/blob/master/LICENSE */ require('config'); const {plainDesignSystem} = include('build/stylus/ds/test/scheme/plain'), {fullThemed} = include('build/stylus/ds/test/scheme/themes'), {createDesignSystem} = include('build/stylus/ds/helpers'); describe('build/stylus/ds', () => { it('should creates a plain design system', () => { const stylus = require('stylus'), {data: designSystem} = createDesignSystem(plainDesignSystem); expect(Object.isDictionary(designSystem.colors)).toBeTrue(); const {colors} = designSystem; Object.keys(colors).forEach((key) => { expect(Object.isArray(colors[key])).toBeTrue(); colors[key].forEach((c) => { expect(['expression', 'rgba']).toContain(stylus.functions.type(c)); }); }); const {text} = designSystem; expect(Object.isDictionary(text)).toBeTrue(); expect(Object.keys(text).length).toBe(Object.keys(plainDesignSystem.text).length); Object.keys(text).forEach((key) => { const style = text[key]; expect(Object.isDictionary(style)).toBeTrue(); Object.keys(style).forEach((t) => { expect(['string', 'unit']).toContain(stylus.functions.type(style[t])); }); }); const {rounding} = designSystem; expect(Object.isDictionary(rounding)).toBeTrue(); expect(Object.keys(rounding).length).toBe(Object.keys(plainDesignSystem.rounding).length); Object.keys(rounding).forEach((key) => { expect(stylus.functions.type(rounding[key])).toBe('unit'); }); }); it('should creates a themed design system', () => { const stylus = require('stylus'), {data: designSystem} = createDesignSystem(fullThemed); expect(Object.isDictionary(designSystem.colors)).toBeTrue(); const {colors: {theme}} = designSystem; Object.keys(theme).forEach((key) => { Object.keys(theme[key]).forEach((colorSet) => { theme[key][colorSet].forEach((c) => { expect(['expression', 'rgba']).toContain(stylus.functions.type(c)); }); }); }); const {text: {theme: themedTextObj}} = designSystem; Object.keys(themedTextObj).forEach((themeName) => { Object.keys(themedTextObj[themeName]).forEach((id) => { const style = themedTextObj[themeName][id]; expect(Object.isDictionary(style)).toBeTrue(); Object.keys(style).forEach((t) => { expect(['string', 'unit']).toContain(stylus.functions.type(style[t])); }); }); }); const {rounding: {theme: themedRoundingObj}} = designSystem; expect(Object.isDictionary(themedRoundingObj)).toBeTrue(); Object.keys(themedRoundingObj).forEach((themeName) => { Object.keys(themedRoundingObj[themeName]).forEach((id) => { expect(stylus.functions.type(themedRoundingObj[themeName][id])).toBe('unit'); }); }); }); });
require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({"./lang/nb_NO":[function(require,module,exports){ module.exports = { accepted: ':attribute må være akseptert.', alpha: ':attribute feltet kan kun inneholde alfabetiske tegn.', alpha_dash: ':attribute feltet kan kun inneholde alfanumeriske tegn, i tillegg til bindestreker og understreker.', alpha_num: ':attribute feltet må være alfanumerisk.', between: ':attribute feltet må være mellom :min og :max.', confirmed: ':attribute feltet stemmer ikke overens med bekreftelsen.', email: ':attribute formatet er ugyldig.', date: ':attribute er et ugyldig datoformat.', def: ':attribute attributtet har feil.', digits: ':attribute må være på :digits siffer.', digits_between: ':attribute må være mellom :min og :max siffer.', different: ':attribute og :different må være forskjellige.', in: 'Den oppgitte verdien for :attribute er ugyldig.', integer: ':attribute må være et heltall.', hex: 'The :attribute should have hexadecimal format', min: { numeric: ':attribute må minst være :min.', string: ':attribute må være på minst :min tegn.' }, max: { numeric: ':attribute kan ikke være større enn :max.', string: ':attribute kan maks ha :max tegn.' }, not_in: 'Den oppgitte verdien for :attribute er ugyldig.', numeric: ':attribute må være et tall.', present: 'The :attribute field must be present (but can be empty).', required: ':attribute feltet er påkrevd.', required_if: ':attribute er påkrevd når :other er :value.', same: ':attribute og :same må være like.', size: { numeric: ':attribute må ha størrelsen :size.', string: ':attribute må ha :size tegn.' }, string: ':attribute må være tekst.', url: ':attribute formatet er ugyldig.', regex: ':attribute formatet er ugyldig.', attributes: {} }; },{}]},{},[]);
const should = require("should"); const { assert } = require("node-opcua-assert"); const { Benchmarker } = require("node-opcua-benchmarker"); const { removeDecoration } = require("node-opcua-debug"); const { coerceNodeId, resolveNodeId, makeNodeId, NodeIdType, NodeId, sameNodeId } = require(".."); describe("testing NodeIds", function() { it("should create a NUMERIC nodeID", function() { const nodeId = new NodeId(NodeIdType.NUMERIC, 23, 2); nodeId.value.should.equal(23); nodeId.namespace.should.equal(2); nodeId.identifierType.should.eql(NodeIdType.NUMERIC); nodeId.toString().should.eql("ns=2;i=23"); }); it("should create a NUMERIC nodeID with the largest possible values", function() { const nodeId = new NodeId(NodeIdType.NUMERIC, 0xffffffff, 0xffff); nodeId.value.should.equal(0xffffffff); nodeId.namespace.should.equal(0xffff); nodeId.identifierType.should.eql(NodeIdType.NUMERIC); nodeId.toString().should.eql("ns=65535;i=4294967295"); }); it("should raise an error for NUMERIC nodeID with invalid values", function() { should(function() { const nodeId = new NodeId(NodeIdType.NUMERIC, -1, -1); }).throwError(); }); it("should create a STRING nodeID", function() { const nodeId = new NodeId(NodeIdType.STRING, "TemperatureSensor", 4); nodeId.value.should.equal("TemperatureSensor"); nodeId.namespace.should.equal(4); nodeId.identifierType.should.eql(NodeIdType.STRING); nodeId.toString().should.eql("ns=4;s=TemperatureSensor"); }); it("should create a OPAQUE nodeID", function() { const buffer = Buffer.alloc(4); buffer.writeUInt32BE(0xdeadbeef, 0); const nodeId = new NodeId(NodeIdType.BYTESTRING, buffer, 4); nodeId.value.toString("hex").should.equal("deadbeef"); nodeId.namespace.should.equal(4); nodeId.identifierType.should.eql(NodeIdType.BYTESTRING); nodeId.toString().should.eql("ns=4;b=3q2+7w=="); }); it("should create a OPAQUE nodeID with null buffer", function() { const nodeId = new NodeId(NodeIdType.BYTESTRING, null, 4); nodeId.toString().should.eql("ns=4;b=<null>"); }); it("NodeId#toString with addressSpace object (standard Nodes) 0", () => { const nodeId = new NodeId(NodeIdType.NUMERIC, 2254, 0); removeDecoration(nodeId.toString({ addressSpace: "Hello" })) .should.eql("ns=0;i=2254 Server_ServerArray" ); nodeId.displayText().should.eql("Server_ServerArray (ns=0;i=2254)"); }); it("NodeId#toString with addressSpace object (findNode) 2", () => { const addressSpace = { findNode() { return { browseName: "Hello" } } }; const nodeId = new NodeId(NodeIdType.STRING, "AAA", 3); nodeId.toString({ addressSpace }) .should.eql("ns=3;s=AAA Hello"); nodeId.displayText().should.eql("ns=3;s=AAA"); }); it("NodeId#toJSON", () => { const nodeId = new NodeId(NodeIdType.STRING, "AAA", 3); nodeId.toJSON().should.eql("ns=3;s=AAA"); }) }); describe("testing coerceNodeId", function() { it("should coerce a string of a form 'i=1234'", function() { coerceNodeId("i=1234").should.eql(makeNodeId(1234)); }); it("should coerce a string of a form 'ns=2;i=1234'", function() { coerceNodeId("ns=2;i=1234").should.eql(makeNodeId(1234, 2)); }); it("should coerce a string of a form 's=TemperatureSensor' ", function() { const ref_nodeId = new NodeId(NodeIdType.STRING, "TemperatureSensor", 0); coerceNodeId("s=TemperatureSensor").should.eql(ref_nodeId); }); it("should coerce a string of a form 'ns=2;s=TemperatureSensor' ", function() { const ref_nodeId = new NodeId(NodeIdType.STRING, "TemperatureSensor", 2); coerceNodeId("ns=2;s=TemperatureSensor").should.eql(ref_nodeId); }); it("should coerce a string of a form '1E14849E-3744-470d-8C7B-5F9110C2FA32' ", function() { const ref_nodeId = new NodeId(NodeIdType.GUID, "1E14849E-3744-470d-8C7B-5F9110C2FA32", 0); coerceNodeId("1E14849E-3744-470d-8C7B-5F9110C2FA32").should.eql(ref_nodeId); }); it("should coerce a NodeId from a NodeIdOptions", function() { const ref_nodeId = new NodeId(NodeIdType.STRING, "Hello", 3); coerceNodeId({ namespace: 3, identifierType: 2, value: "Hello" }).should.eql(ref_nodeId); }); it("should coerce a string of a form 'ns=4;s=Test32;datatype=Int32' (Mika)", function() { const ref_nodeId = new NodeId(NodeIdType.STRING, "Test32;datatype=Int32", 4); coerceNodeId("ns=4;s=Test32;datatype=Int32").should.eql(ref_nodeId); try { makeNodeId("ns=4;s=Test32;datatype=Int32").should.eql(ref_nodeId); } catch (err) { should.exist(err); } }); it("should coerce a string of a form 'ns=4;s=||)))AA(((||'", function() { const ref_nodeId = new NodeId(NodeIdType.STRING, "||)))AA(((||", 4); coerceNodeId("ns=4;s=||)))AA(((||").should.eql(ref_nodeId); try { makeNodeId("ns=4;s=||)))AA(((||").should.eql(ref_nodeId); } catch (err) { should.exist(err); } }); it("should coerce a string of a form `ns=2;s=45QAZE2323||XC86@5`", function() { const ref_nodeId = new NodeId(NodeIdType.STRING, "45QAZE2323||XC86@5", 2); coerceNodeId("ns=2;s=45QAZE2323||XC86@5").should.eql(ref_nodeId); try { makeNodeId("ns=2;s=45QAZE2323||XC86@5").should.eql(ref_nodeId); } catch (err) { should.exist(err); } }); it("should coerce a integer", function() { coerceNodeId(1234).should.eql(makeNodeId(1234)); }); it("makeNodeId('1E14849E-3744-470d-8C7B-5F9110C2FA32')", () => { const nodeId1 = coerceNodeId("g=1E14849E-3744-470d-8C7B-5F9110C2FA32"); const nodeId2 = makeNodeId('1E14849E-3744-470d-8C7B-5F9110C2FA32'); nodeId1.should.eql(nodeId2); }) it("makeNodeId(buffer)", () => { const nodeId2 = makeNodeId(Buffer.from([1, 2, 3])); nodeId2.toString().should.eql("ns=0;b=AQID"); }) it("resolveNodeId", () => { resolveNodeId("i=12"); resolveNodeId(Buffer.from([1, 2, 3])); }) it("should coerce a OPAQUE buffer as a BYTESTRING", function() { const buffer = Buffer.alloc(8); buffer.writeUInt32BE(0xb1dedada, 0); buffer.writeUInt32BE(0xb0b0abba, 4); const nodeId = coerceNodeId(buffer); nodeId.toString().should.eql("ns=0;b=sd7a2rCwq7o="); nodeId.value.toString("base64").should.eql("sd7a2rCwq7o="); }); it("should coerce a OPAQUE buffer in a string ( with namespace ) ", function() { const nodeId = coerceNodeId("ns=0;b=sd7a2rCwq7o="); nodeId.identifierType.should.eql(NodeIdType.BYTESTRING); nodeId.toString().should.eql("ns=0;b=sd7a2rCwq7o="); nodeId.value.toString("hex").should.eql("b1dedadab0b0abba"); }); it("should coerce a OPAQUE buffer in a string ( without namespace ) ", function() { const nodeId = coerceNodeId("b=sd7a2rCwq7o="); nodeId.identifierType.should.eql(NodeIdType.BYTESTRING); nodeId.toString().should.eql("ns=0;b=sd7a2rCwq7o="); nodeId.value.toString("hex").should.eql("b1dedadab0b0abba"); }); it("should coerce a GUID node id (without namespace)", function() { const nodeId = coerceNodeId("g=1E14849E-3744-470d-8C7B-5F9110C2FA32"); nodeId.identifierType.should.eql(NodeIdType.GUID); nodeId.toString().should.eql("ns=0;g=1E14849E-3744-470d-8C7B-5F9110C2FA32"); nodeId.value.should.eql("1E14849E-3744-470d-8C7B-5F9110C2FA32"); }); it("should coerce a GUID node id (with namespace)", function() { const nodeId = coerceNodeId("ns=0;g=1E14849E-3744-470d-8C7B-5F9110C2FA32"); nodeId.identifierType.should.eql(NodeIdType.GUID); nodeId.toString().should.eql("ns=0;g=1E14849E-3744-470d-8C7B-5F9110C2FA32"); nodeId.value.should.eql("1E14849E-3744-470d-8C7B-5F9110C2FA32"); }); it("should not coerce a malformed string to a nodeid", function() { let nodeId; (function() { nodeId = coerceNodeId("ThisIsNotANodeId"); }.should.throw()); (function() { nodeId = coerceNodeId("HierarchicalReferences"); }.should.throw()); (function() { nodeId = coerceNodeId("ns=0;s=HierarchicalReferences"); assert(nodeId !== null); }.should.not.throw()); }); it("should detect empty Numeric NodeIds", function() { const empty_nodeId = makeNodeId(0, 0); empty_nodeId.identifierType.should.eql(NodeIdType.NUMERIC); empty_nodeId.isEmpty().should.be.eql(true); const non_empty_nodeId = makeNodeId(1, 0); non_empty_nodeId.isEmpty().should.be.eql(false); }); it("should detect empty String NodeIds", function() { // empty string nodeId const empty_nodeId = coerceNodeId("ns=0;s="); empty_nodeId.identifierType.should.eql(NodeIdType.STRING); empty_nodeId.isEmpty().should.be.eql(true); const non_empty_nodeId = coerceNodeId("ns=0;s=A"); non_empty_nodeId.identifierType.should.eql(NodeIdType.STRING); non_empty_nodeId.isEmpty().should.be.eql(false); }); it("should detect empty Opaque NodeIds", function() { // empty opaque nodeId const empty_nodeId = coerceNodeId(Buffer.alloc(0)); empty_nodeId.identifierType.should.eql(NodeIdType.BYTESTRING); empty_nodeId.isEmpty().should.be.eql(true); const non_empty_nodeId = coerceNodeId(Buffer.alloc(1)); empty_nodeId.identifierType.should.eql(NodeIdType.BYTESTRING); non_empty_nodeId.isEmpty().should.be.eql(false); }); it("should detect empty GUID NodeIds", function() { // empty GUID nodeId const empty_nodeId = coerceNodeId("g=00000000-0000-0000-0000-000000000000"); empty_nodeId.identifierType.should.eql(NodeIdType.GUID); empty_nodeId.isEmpty().should.be.eql(true); const non_empty_nodeId = coerceNodeId("g=00000000-0000-0000-0000-000000000001"); empty_nodeId.identifierType.should.eql(NodeIdType.GUID); non_empty_nodeId.isEmpty().should.be.eql(false); }); it("should convert an empty NodeId to <empty nodeid> string", function() { const empty_nodeId = makeNodeId(0, 0); empty_nodeId.toString().should.eql("ns=0;i=0"); }); it("should coerce a string nodeid containing special characters", function() { // see issue# const nodeId = coerceNodeId("ns=3;s={360273AA-F2B9-4A7F-A5E3-37B7074E2529}.MechanicalDomain"); }); }); describe("#sameNodeId", function() { const nodeIds = [ makeNodeId(2, 3), makeNodeId(2, 4), makeNodeId(4, 3), makeNodeId(4, 300), new NodeId(NodeIdType.NUMERIC, 23, 2), new NodeId(NodeIdType.STRING, "TemperatureSensor", 4), new NodeId(NodeIdType.STRING, "A very long string very very long string", 4), new NodeId(NodeIdType.BYTESTRING, Buffer.from("AZERTY"), 4) ]; for (let i = 0; i < nodeIds.length; i++) { const nodeId1 = nodeIds[i]; for (let j = 0; j < nodeIds.length; j++) { const nodeId2 = nodeIds[j]; if (i === j) { it( "should be true : #sameNodeId('" + nodeId1.toString() + "','" + nodeId2.toString() + "');", function() { sameNodeId(nodeId1, nodeId2).should.eql(true); } ); } else { it( "should be false : #sameNodeId('" + nodeId1.toString() + "','" + nodeId2.toString() + "');", function() { sameNodeId(nodeId1, nodeId2).should.eql(false); } ); } } } function sameNodeIdOld(n1, n2) { return n1.toString() === n2.toString(); } it("should implement a efficient sameNodeId ", function(done) { const bench = new Benchmarker(); bench .add("sameNodeIdOld", function() { for (let i = 0; i < nodeIds.length; i++) { const nodeId1 = nodeIds[i]; for (let j = 0; j < nodeIds.length; j++) { const nodeId2 = nodeIds[j]; sameNodeIdOld(nodeId1, nodeId2).should.eql(i === j); } } }) .add("sameNodeId", function() { for (let i = 0; i < nodeIds.length; i++) { const nodeId1 = nodeIds[i]; for (let j = 0; j < nodeIds.length; j++) { const nodeId2 = nodeIds[j]; sameNodeId(nodeId1, nodeId2).should.eql(i === j); } } }) .on("cycle", function(message) { console.log(message); }) .on("complete", function() { console.log(" Fastest is " + this.fastest.name); // the following line is commented out as test may fail due to gc taking place randomly // this.fastest.name.should.eql("sameNodeId"); done(); }) .run({ max_time: 0.1 }); }); }); describe("testing resolveNodeId", function() { // some objects it("should resolve RootFolder to 'ns=0;i=84' ", function() { const ref_nodeId = new NodeId(NodeIdType.NUMERIC, 84, 0); resolveNodeId("RootFolder").should.eql(ref_nodeId); resolveNodeId("RootFolder") .toString() .should.equal("ns=0;i=84"); }); it("should resolve ObjectsFolder to 'ns=0;i=85' ", function() { const ref_nodeId = new NodeId(NodeIdType.NUMERIC, 85, 0); resolveNodeId("ObjectsFolder").should.eql(ref_nodeId); resolveNodeId("ObjectsFolder") .toString() .should.equal("ns=0;i=85"); }); // Variable it("should resolve ServerType_NamespaceArray to 'ns=0;i=2006' ", function() { resolveNodeId("ServerType_NamespaceArray") .toString() .should.equal("ns=0;i=2006"); }); // ObjectType it("should resolve FolderType to 'ns=0;i=61' ", function() { resolveNodeId("FolderType") .toString() .should.equal("ns=0;i=61"); }); // VariableType it("should resolve AnalogItemType to 'ns=0;i=2368' ", function() { resolveNodeId("AnalogItemType") .toString() .should.equal("ns=0;i=2368"); }); //ReferenceType it("should resolve HierarchicalReferences to 'ns=0;i=33' ", function() { resolveNodeId("HierarchicalReferences") .toString() .should.equal("ns=0;i=33"); }); }); describe("testing NodeId coercing bug ", function() { it("should handle strange string nodeId ", function() { coerceNodeId("ns=2;s=S7_Connection_1.db1.0,x0").should.eql(makeNodeId("S7_Connection_1.db1.0,x0", 2)); }); }); describe("testing NodeId.displayText", function() { it("should provide a richer display text when nodeid is known", function() { const ref_nodeId = new NodeId(NodeIdType.NUMERIC, 85, 0); ref_nodeId.displayText().should.equal("ObjectsFolder (ns=0;i=85)"); }); }); describe("issue#372 coercing & making nodeid string containing semi-column", function() { it("should coerce a nodeid string containing a semi-column", function() { const nodeId = coerceNodeId("ns=0;s=my;nodeid;with;semicolum"); nodeId.identifierType.should.eql(NodeIdType.STRING); nodeId.value.should.be.eql("my;nodeid;with;semicolum"); }); it("should make a nodeid as a string containing semi-column", function() { const nodeId = makeNodeId("my;nodeid;with;semicolum"); nodeId.identifierType.should.eql(NodeIdType.STRING); nodeId.value.should.be.eql("my;nodeid;with;semicolum"); }); }); describe("nullId constness", ()=>{ it("should throw an exception if one try to modify the NodeId.nullNodeId property: namespace", ()=>{ should.throws(()=>{ NodeId.nullNodeId.namespace = 1; }, "should not be able assign to read only property 'namespace' of object '#<NodeId>'"); NodeId.nullNodeId.namespace.should.eql(0) }) it("should throw an exception if one try to modify the NodeId.nullNodeId property: value", ()=>{ should.throws(()=>{ NodeId.nullNodeId.value = 1; }, "should not be able assign to read only property 'namespace' of object '#<NodeId>'"); NodeId.nullNodeId.value.should.eql(0) }) it("should throw an exception if one try to modify the NodeId.nullNodeId property: type", ()=>{ should.throws(()=>{ NodeId.nullNodeId.identifierType = NodeIdType.GUID; }, "should not be able assign to read only property 'namespace' of object '#<NodeId>'"); NodeId.nullNodeId.identifierType.should.eql(NodeIdType.NUMERIC) }) });
_gaq.push(['_trackPageview']); // If awaiting activation var waiting = true; // If trusted exit, for exit confirmation var trustedExit = false; // Used to fade out subtitles after calculated duration var subtitleVanishTimer = false; var subtitleVanishBaseMillis; var subtitleVanishExtraMillisPerChar; // Holder object for audio files to test mp3 duration var subtitleMp3; // If auto-focus on window to capture key events or not var autoFocus = 0; // Critical Animation var critAnim = false; // Idle time check /* variables explanation: longestIdleTime - high score of idle time idleTimer - timer ID for interval function of idleFunction idleTimeout - timer ID for unsafe idle time marker idleFunction - function that indicates the way of the idle counter */ localStorage.longestIdleTime = Math.max(localStorage.longestIdleTime || 0,1800000); var lastRequestMark = Date.now(), idleTimer, idleTimeout, idleFunction; // Show game screens function ActivateGame(){ waiting = false; $(".box-wrap").css("background", "#fff"); $(".box-wait").hide(); $(".game-swf").remove(); $(".box-game") .prepend("<iframe class=game-swf frameborder=0></iframe>") .find(".game-swf") .attr("src", "http://www.dmm.com/netgame/social/-/gadgets/=/app_id=854854/") .end() .show(); idleTimer = setInterval(idleFunction,1000); if(ConfigManager.alert_idle_counter) { $(".game-idle-timer").trigger("refresh-tick"); } } $(document).on("ready", function(){ // Initialize data managers ConfigManager.load(); KC3Master.init(); RemodelDb.init(); KC3Meta.init("../../../../data/"); KC3Meta.loadQuotes(); KC3QuestManager.load(); KC3Database.init(); KC3Translation.execute(); // Apply interface configs $(".box-wrap").css("margin-top", ConfigManager.api_margin+"px"); if(ConfigManager.api_bg_image === ""){ $("body").css("background", ConfigManager.api_bg_color); }else{ $("body").css("background-image", "url("+ConfigManager.api_bg_image+")"); $("body").css("background-color", ConfigManager.api_bg_color); $("body").css("background-size", ConfigManager.api_bg_size); $("body").css("background-position", ConfigManager.api_bg_position); $("body").css("background-repeat", "no-repeat"); } if(ConfigManager.api_subtitles){ $(".overlay_subtitles").css("font-family", ConfigManager.subtitle_font); $(".overlay_subtitles").css("font-size", ConfigManager.subtitle_size); if(ConfigManager.subtitle_bold){ $(".overlay_subtitles").css("font-weight", "bold"); } } $(".box-wait").show(); // Quick Play $(".play_btn").on('click', function(){ ActivateGame(); }); // Disable Quick Play (must panel) if(ConfigManager.api_mustPanel) { $(".play_btn") .off('click') .text(KC3Meta.term("APIWaitToggle")) .css('color','#f00') .css('width','40%'); } // Configure Refresh Toggle (using $(".game-refresh").trigger("click") is possible) $(".game-refresh").on("click",function(){ switch($(this).text()) { case("01"): $(".game-swf").attr("src","about:blank").attr("src",localStorage.absoluteswf); $(this).text("05"); break; default: $(this).text(($(this).text()-1).toDigits(2)); break; } }); // Configure Idle Timer /* unsafe-tick : remove the safe marker of API idle time refresh-tick : reset the timer and set the idle time as safe zone */ $(".game-idle-timer").on("unsafe-tick",function(){ $(".game-idle-timer").removeClass("safe-timer"); }).on("refresh-tick",function(){ clearTimeout(idleTimeout); $(".game-idle-timer").addClass("safe-timer"); idleTimeout = setTimeout(function(){ $(".game-idle-timer").trigger("unsafe-tick"); },localStorage.longestIdleTime); }); idleFunction = function(){ if(ConfigManager.alert_idle_counter) { $(".game-idle-timer").text(String(Math.floor((Date.now() - lastRequestMark) / 1000)).toHHMMSS()); } else { $(".game-idle-timer").text(String(NaN).toHHMMSS()); clearInterval(idleTimer); } }; // Enable Refresh Toggle if(ConfigManager.api_directRefresh) { $(".game-refresh").css("display","flex"); } // Show Idle Counter if(ConfigManager.alert_idle_counter > 1) { $(".game-idle-timer").show(); } // Exit confirmation window.onbeforeunload = function(){ ConfigManager.load(); // added waiting condition should be ignored if(ConfigManager.api_askExit==1 && !trustedExit && !waiting){ trustedExit = true; setTimeout(function(){ trustedExit = false; }, 100); return KC3Meta.term("UnwantedExitDMM"); } }; setInterval(function(){ if(autoFocus===0){ window.focus(); $(".focus_regain").hide(); }else{ $(".focus_regain").show(); $(".focus_val").css("width", (800*(autoFocus/20))+"px"); autoFocus--; } }, 1000); }); $(document).on("keydown", function(event){ switch(event.keyCode) { // F7: Toggle keyboard focus case(118): autoFocus = 20; return false; // F9: Screenshot case(120): (new KCScreenshot()).start("Auto", $(".box-wrap")); return false; // F10: Clear overlays case(121): interactions.clearOverlays({}, {}, function(){}); return false; // Other else default: break; } }); /* Invokable actions -----------------------------------*/ var interactions = { // Panel is opened, activate the game activateGame :function(request, sender, response){ if(waiting){ ActivateGame(); response({success:true}); }else{ response({success:false}); } }, // Cat Bomb Detection -> Enforced catBomb :function(request, sender, response){ try{ switch(ConfigManager.api_directRefresh) { case 0: throw new Error(""); case 1: $(".game-refresh").text((0).toDigits(2)).css('right','0px'); break; default: // TODO : Forced API Link Refresh $(".game-refresh").text((0).toDigits(2)).trigger('bomb-exploded'); break; } response({success:true}); }catch(e){ console.error(e); }finally{ response({success:false}); } }, // Request OK Marker goodResponses :function(request, sender, response){ if(request.tcp_status === 200 && request.api_status === 1) { localStorage.longestIdleTime = Math.max(localStorage.longestIdleTime,Date.now() - lastRequestMark); lastRequestMark = Date.now(); $(".game-idle-timer").trigger("refresh-tick"); clearInterval(idleTimer); idleTimer = setInterval(idleFunction,1000); idleFunction(); } else { clearInterval(idleTimer); clearTimeout(idleTimeout); $(".game-idle-timer").trigger("unsafe-tick"); console.error("API Link cease to functioning anymore after",String(Math.floor((Date.now() - lastRequestMark)/1000)).toHHMMSS(),"idle time"); } }, // Quest page is opened, show overlays questOverlay :function(request, sender, response){ //Only skip overlay generation if neither of the overlay features is enabled. if(!ConfigManager.api_translation && !ConfigManager.api_tracking){ response({success:false}); return true; } KC3QuestManager.load(); $.each(request.questlist, function( index, QuestRaw ){ // console.log("showing quest",QuestRaw); if( QuestRaw !=- 1 ){ var QuestBox = $("#factory .ol_quest_exist").clone().appendTo(".overlay_quests"); // Get quest data var QuestData = KC3QuestManager.get( QuestRaw.api_no ); // Show meta, title and description if( typeof QuestData.meta().available != "undefined" ){ if (ConfigManager.api_translation){ $(".name", QuestBox).text( QuestData.meta().name ); $(".desc", QuestBox).text( QuestData.meta().desc ); }else{ $(".content", QuestBox).css({opacity: 0}); } if(ConfigManager.api_tracking){ $(".tracking", QuestBox).html( QuestData.outputHtml() ); }else{ $(".tracking", QuestBox).hide(); } // Special Bw1 case multiple requirements if( QuestRaw.api_no == 214 ){ $(".tracking", QuestBox).addClass("small"); } }else{ QuestBox.css({ visibility: "hidden" }); } } }); response({success:true}); }, // Quest Progress Notification questProgress :function(request, sender, response){ response({success:true}); }, // In-game record screen translation recordOverlay :function(request, sender, response){ // app.Dom.applyRecordOverlay(request.record); response({success:true}); }, // Remove HTML overlays clearOverlays :function(request, sender, response){ // console.log("clearing overlays"); // app.Dom.clearOverlays(); $(".overlay_quests").html(""); $(".overlay_record").hide(); response({success:true}); }, // Screenshot triggered, capture the visible tab screenshot :function(request, sender, response){ // ~Please rewrite the screenshot script (new KCScreenshot()).start(request.playerName, $(".box-wrap")); response({success:true}); }, // Fit screen fitScreen :function(request, sender, response){ // Get browser zoon level for the page chrome.tabs.getZoom(null, function(ZoomFactor){ // Resize the window chrome.windows.getCurrent(function(wind){ chrome.windows.update(wind.id, { width: Math.ceil(800*ZoomFactor) + (wind.width- Math.ceil($(window).width()*ZoomFactor) ), height: Math.ceil(480*ZoomFactor) + (wind.height- Math.ceil($(window).height()*ZoomFactor) ) }); }); }); }, // Taiha Alert Start taihaAlertStart :function(request, sender, response){ $(".box-wrap").addClass("critical"); if(critAnim){ clearInterval(critAnim); } critAnim = setInterval(function() { $(".taiha_red").toggleClass("anim2"); }, 500); $(".taiha_blood").show(); $(".taiha_red").show(); }, // Taiha Alert Stop taihaAlertStop :function(request, sender, response){ $(".box-wrap").removeClass("critical"); if(critAnim){ clearInterval(critAnim); } $(".taiha_blood").hide(); $(".taiha_red").hide(); }, // Show subtitles subtitle :function(request, sender, response){ if(!ConfigManager.api_subtitles) return true; console.debug("subtitle", request); // Get subtitle text var subtitleText = false; var quoteIdentifier = ""; var quoteVoiceNum = request.voiceNum; switch(request.voicetype){ case "titlecall": quoteIdentifier = "titlecall_"+request.filename; break; case "npc": quoteIdentifier = "npc"; break; default: quoteIdentifier = request.shipID; break; } subtitleText = KC3Meta.quote( quoteIdentifier, quoteVoiceNum ); // hide first to fading will stop $(".overlay_subtitles").stop(true, true); $(".overlay_subtitles").hide(); // If subtitle removal timer is ongoing, reset if(subtitleVanishTimer){ clearTimeout(subtitleVanishTimer); } // Lazy init timing parameters if(!subtitleVanishBaseMillis){ subtitleVanishBaseMillis = Number(KC3Meta.quote("timing", "baseMillisVoiceLine")) || 2000; } if(!subtitleVanishExtraMillisPerChar){ subtitleVanishExtraMillisPerChar = Number(KC3Meta.quote("timing", "extraMillisPerChar")) || 50; } // If subtitles available for the voice if(subtitleText){ $(".overlay_subtitles").html(subtitleText); $(".overlay_subtitles").show(); var millis = subtitleVanishBaseMillis + (subtitleVanishExtraMillisPerChar * $(".overlay_subtitles").text().length); console.debug("vanish after", millis, "ms"); subtitleVanishTimer = setTimeout(function(){ subtitleVanishTimer = false; $(".overlay_subtitles").fadeOut(2000); }, millis); } }, // Dummy action dummy :function(request, sender, response){ } }; /* Listen to messaging triggers -----------------------------------*/ chrome.runtime.onMessage.addListener(function(request, sender, response){ // If request is for this script if((request.identifier||"") == "kc3_gamescreen"){ // If action requested is supported if(typeof interactions[request.action] !== "undefined"){ // Execute the action interactions[request.action](request, sender, response); return true; } } });
const gulp = require('gulp') const sass = require('gulp-sass') gulp.task('sass', function () { return gulp.src('./app/styles/index.scss') .pipe(sass({ outputStyle: 'compressed' }).on('error', sass.logError)) .pipe(gulp.dest('./app/dist')) }) gulp.task('sass:watch', function () { gulp.watch('./app/**/*.scss', ['sass']) }) gulp.task('default', ['sass'])
/* @flow */ ;(function (root) { "use strict"; let color_names = { "black": "#000000", "silver": "#c0c0c0", "gray": "#808080", "white": "#ffffff", "maroon": "#800000", "red": "#ff0000", "purple": "#800080", "fuchsia": "#ff00ff", "green": "#008000", "lime": "#00ff00", "olive": "#808000", "yellow": "#ffff00", "navy": "#000080", "blue": "#0000ff", "teal": "#008080", "aqua": "#00ffff", "orange": "#ffa500", "aliceblue": "#f0f8ff", "antiquewhite": "#faebd7", "aquamarine": "#7fffd4", "azure": "#f0ffff", "beige": "#f5f5dc", "bisque": "#ffe4c4", "blanchedalmond": "#ffebcd", "blueviolet": "#8a2be2", "brown": "#a52a2a", "burlywood": "#deb887", "cadetblue": "#5f9ea0", "chartreuse": "#7fff00", "chocolate": "#d2691e", "coral": "#ff7f50", "cornflowerblue": "#6495ed", "cornsilk": "#fff8dc", "crimson": "#dc143c", "darkblue": "#00008b", "darkcyan": "#008b8b", "darkgoldenrod": "#b8860b", "darkgray": "#a9a9a9", "darkgreen": "#006400", "darkgrey": "#a9a9a9", "darkkhaki": "#bdb76b", "darkmagenta": "#8b008b", "darkolivegreen": "#556b2f", "darkorange": "#ff8c00", "darkorchid": "#9932cc", "darkred": "#8b0000", "darksalmon": "#e9967a", "darkseagreen": "#8fbc8f", "darkslateblue": "#483d8b", "darkslategray": "#2f4f4f", "darkslategrey": "#2f4f4f", "darkturquoise": "#00ced1", "darkviolet": "#9400d3", "deeppink": "#ff1493", "deepskyblue": "#00bfff", "dimgray": "#696969", "dimgrey": "#696969", "dodgerblue": "#1e90ff", "firebrick": "#b22222", "floralwhite": "#fffaf0", "forestgreen": "#228b22", "gainsboro": "#dcdcdc", "ghostwhite": "#f8f8ff", "gold": "#ffd700", "goldenrod": "#daa520", "greenyellow": "#adff2f", "grey": "#808080", "honeydew": "#f0fff0", "hotpink": "#ff69b4", "indianred": "#cd5c5c", "indigo": "#4b0082", "ivory": "#fffff0", "khaki": "#f0e68c", "lavender": "#e6e6fa", "lavenderblush": "#fff0f5", "lawngreen": "#7cfc00", "lemonchiffon": "#fffacd", "lightblue": "#add8e6", "lightcoral": "#f08080", "lightcyan": "#e0ffff", "lightgoldenrodyellow": "#fafad2", "lightgray": "#d3d3d3", "lightgreen": "#90ee90", "lightgrey": "#d3d3d3", "lightpink": "#ffb6c1", "lightsalmon": "#ffa07a", "lightseagreen": "#20b2aa", "lightskyblue": "#87cefa", "lightslategray": "#778899", "lightslategrey": "#778899", "lightsteelblue": "#b0c4de", "lightyellow": "#ffffe0", "limegreen": "#32cd32", "linen": "#faf0e6", "mediumaquamarine": "#66cdaa", "mediumblue": "#0000cd", "mediumorchid": "#ba55d3", "mediumpurple": "#9370db", "mediumseagreen": "#3cb371", "mediumslateblue": "#7b68ee", "mediumspringgreen": "#00fa9a", "mediumturquoise": "#48d1cc", "mediumvioletred": "#c71585", "midnightblue": "#191970", "mintcream": "#f5fffa", "mistyrose": "#ffe4e1", "moccasin": "#ffe4b5", "navajowhite": "#ffdead", "oldlace": "#fdf5e6", "olivedrab": "#6b8e23", "orangered": "#ff4500", "orchid": "#da70d6", "palegoldenrod": "#eee8aa", "palegreen": "#98fb98", "paleturquoise": "#afeeee", "palevioletred": "#db7093", "papayawhip": "#ffefd5", "peachpuff": "#ffdab9", "peru": "#cd853f", "pink": "#ffc0cb", "plum": "#dda0dd", "powderblue": "#b0e0e6", "rosybrown": "#bc8f8f", "royalblue": "#4169e1", "saddlebrown": "#8b4513", "salmon": "#fa8072", "sandybrown": "#f4a460", "seagreen": "#2e8b57", "seashell": "#fff5ee", "sienna": "#a0522d", "skyblue": "#87ceeb", "slateblue": "#6a5acd", "slategray": "#708090", "slategrey": "#708090", "snow": "#fffafa", "springgreen": "#00ff7f", "steelblue": "#4682b4", "tan": "#d2b48c", "thistle": "#d8bfd8", "tomato": "#ff6347", "turquoise": "#40e0d0", "violet": "#ee82ee", "wheat": "#f5deb3", "whitesmoke": "#f5f5f5", "yellowgreen": "#9acd32", "rebeccapurple": "#663399", }; /** * Create a linear scaling function. * * Create a function that Interpolates a value in an output domain based on * a value in an input domain. * * The signature of the callback is f(outputValue, inputValue, inputDomain, outputDomain) * * @param {array} inputDomain - An array with lower and upper boundary * @param {array} outputDomain - An array with lower and upper boundary * @param {function} callback - A transformation to apply to the resulting value * @return {function} */ function get_scale(inputDomain, outputDomain, callback) { var i_start = 0 - inputDomain[0]; var i_end = inputDomain[1] - inputDomain[0]; var o_start = 0 - outputDomain[0]; var o_end = outputDomain[1] - outputDomain[0]; return function (input) { var output = (input + i_start) / i_end * o_end - o_start; return (typeof callback === "function") ? callback(output, input, inputDomain, outputDomain) : output; }; } /** * Map a value in the 0.0 to 1.0 range to the 0 to 255 range. * * @param {float} input - The input value. * @return {int} */ let to_255 = get_scale([0, 1], [0, 256], (o, i) => i == 1 ? 255 : Math.floor(o)); /** * Map a value in the 0 to 255 range to the 0.0 to 1.0 range. * * @param {int} input - The input value. * @return {float} */ let from_255 = get_scale([0, 256], [0, 1], (o, i) => i >= 255 ? 1.0 : o); /** * Obtain RGBA or HSLA values from a CSS string. * * @param {string} str - The CSS-formatted color. * @return {array} */ function extract_definition_values(str) { var matches = str.match(/[a-z]{3,4}\(([^)]+)\)/); if (!matches || typeof matches[1] === "undefined") { throw `Malformed RGB(A) or HSL(A) string: "${str}"`; } return matches[1].split(/,\s*/).map(n => parseFloat(n)); } /** * Split a hex color string into red, green, blue and alpha components. * * The R, G and B values returned range between 0 and 255, and the alpha value is a * floating-point number between 0 and 1. * * @param {string} hex - A 3, 4, 6 or 8 character-long CSS hex color. * @return {array} - An array with R, G, B and A values. */ function split_hex(hex) { var red, green, blue, alpha; var h = hex.replace("#", ""); if (h.length === 3 || h.length === 4) { [red, green, blue, alpha] = h.match(/.{1}/g).map(function (n) { return parseInt(n + n, 16); }); } else if (h.length === 6 || h.length === 8){ [red, green, blue, alpha] = h.match(/.{2}/g).map(function (n) { return parseInt(n, 16); }); } else { throw `Malformed hex string: "${hex}"`; } if (typeof alpha === "undefined") { alpha = 1; } else { alpha = from_255(alpha); } return [red, green, blue, alpha]; } /** * Converts an 8-bit integer value to its hexadecimal representation. * * @param {integer} rgbValue - A value from 0 to 255 * @param {integer} pad - An amount of hex digits to pad * @return {string} - A hexadecimal representation of the rgbValue */ function to_hex(rgbValue, pad) { var hex = to_255(rgbValue, 16).toString(16); pad = pad || 2; return ("0000000000" + hex).slice(-pad); } /** * Converts hue, saturation and lightness to red, green and blue. * * <http://en.wikipedia.org/wiki/HSL_and_HSV#From_HSL> * * @param {float} hue - Hue value (0-1) * @param {float} saturation - Saturation value (0-1) * @param {float} value - Lightness value (0-1) * @return {object} - Object with red, green and blue properties (0-1) */ function hsl_to_rgb(hue, saturation, lightness) { var chroma = (1 - Math.abs(2 * lightness - 1)) * saturation; var lower_hue = Math.round(hue * 360) / 60; var x = chroma * (1 - Math.abs(lower_hue % 2 - 1)); var r, g, b; if (lower_hue >= 0 && lower_hue < 1) { [r, g, b] = [chroma, x, 0]; } else if (lower_hue >= 1 && lower_hue < 2) { [r, g, b] = [x, chroma, 0]; } else if (lower_hue >= 2 && lower_hue < 3) { [r, g, b] = [0, chroma, x]; } else if (lower_hue >= 3 && lower_hue < 4) { [r, g, b] = [0, x, chroma]; } else if (lower_hue >= 4 && lower_hue < 5) { [r, g, b] = [x, 0, chroma]; } else if (lower_hue >= 5 && lower_hue < 6) { [r, g, b] = [chroma, 0, x]; } else { [r, g, b] = [0, 0, 0]; } var luma = lightness - 0.5 * chroma; return { "red": r + luma, "green": g + luma, "blue": b + luma, }; } /** * Converts red, green and blue to hue, saturation and lightness. * * @param {float} red - Red value (0-1) * @param {float} green - Green value (0-1) * @param {float} blue - Blue value (0-1) * @return {object} - Object with hue, saturation and value properties (0-1); */ function rgb_to_hsl(red, green, blue) { var rgb = [red, green, blue]; var hue, saturation, lightness; var c_max = Math.max.apply(root, rgb); var c_min = Math.min.apply(root, rgb); var dominant = rgb.indexOf(c_max); var delta = c_max - c_min; // calculate lightness lightness = (c_max + c_min) / 2; // calculate saturation if (delta === 0) { saturation = 0; } else if (lightness < 0.5) { saturation = delta / (c_max + c_min); } else { saturation = delta / (2 - c_max - c_min); } // calculate hue if (delta === 0) { hue = 0; } else { var delta_red = (((c_max - rgb[0]) / 6) + delta / 2) / delta; var delta_green = (((c_max - rgb[1]) / 6) + delta / 2) / delta; var delta_blue = (((c_max - rgb[2]) / 6) + delta / 2) / delta; if (dominant === 0) { hue = delta_blue - delta_green; } else if (dominant === 1) { hue = (1 / 3) + delta_red - delta_blue; } else if (dominant === 2) { hue = (2 / 3) + delta_green - delta_red; } else { hue = 0; } if (hue < 0) { hue += 1; } else if (hue > 1) { hue -= 1; } } return { "hue": hue, "saturation": saturation, "lightness": lightness, }; } /** * Ensures a number falls within a certain range. * * @param {number} value - Value to check * @param {number} min - Minimum accepted value * @param {number} max - Maximum accepted value * @return {number} - Clamped value */ function clamp(value, min, max) { min = (typeof min === "undefined") ? 0 : min; max = (typeof max === "undefined") ? 1 : max; return Math.min(Math.max(value, min), max); } /** * Build a color. * * @constructor * @param {integer} red - Red value (0-255) * @param {integer} green - Green value (0-255) * @param {integer} blue - Blue value (0-255) * @param {float} alpha - Alpha value (0-1) */ function Color(r, g, b, a) { if (typeof color_names[r] !== "undefined") { r = color_names[r]; } if (typeof r === "string") { let str = r; if (str[0] === "#") { [r, g, b, a] = split_hex(r); } else if (str.substring(0, 3) === "rgb") { let m = extract_definition_values(str); [r, g, b] = m; if (str.substring(0, 4) === "rgba") { a = m[3]; } } else if (str.substring(0, 3) === "hsl") { let m = extract_definition_values(str); let rgb = hsl_to_rgb(m[0] / 360, m[1] / 100, m[2] / 100); [r, g, b] = [rgb.red, rgb.green, rgb.blue].map(to_255); if (str.substring(0, 4) === "hsla") { a = parseFloat(m[3]); } } } a = typeof a === "undefined" ? 1.0 : a; this._red = from_255(r) || 0; this._green = from_255(g) || 0; this._blue = from_255(b) || 0; this._alpha = a; this.updateHsl(); this.phaseFunctions = {}; this.currentPhase = 0; } /** * Creates a random color. * * @static * @return {Color} */ Color.random = function () { let r = function () { return Math.floor(Math.random() * 256); }; return new Color(r(), r(), r()); }; /** * Creates a color with the specified red, green and blue values. * * @static * @param {integer} r - Red value, between 0 and 255 * @param {integer} g - Green value, between 0 and 255 * @param {integer} b - Blue value, between 0 and 255 * @return {Color} */ Color.fromRGB = function (r, g, b, a) { return new Color(r, g, b, a); }; /** * Creates a color with the specified hue, saturation and lightness values. * * @static * @param {integer} h - Hue value, between 0 and 360 * @param {integer} s - Saturation value, between 0 and 100 * @param {integer} l - Lightness value, between 0 and 100 * @return {Color} */ Color.fromHSL = function (h, s, l, a) { let c = new Color("#ffffff"); c.hue(h); c.saturation(s); c.lightness(l); c.alpha(typeof a === "undefined" ? 1.0 : a); return c; }; /** * Creates a color from a CSS string. * * @static * @param {string} str - Any valid CSS-formatted color. * @return {Color} */ Color.fromString = function (str) { return new Color(str); }; /** * Internal function to update the RBG values after the HSL values have * been set. */ Color.prototype.updateRgb = function () { var rgb = hsl_to_rgb(this._hue, this._saturation, this._lightness); this._red = rgb.red; this._green = rgb.green; this._blue = rgb.blue; }; /** * Internal function to update the HSL values after the RGB values have * been set. */ Color.prototype.updateHsl = function () { var hsl = rgb_to_hsl(this._red, this._green, this._blue); this._hue = hsl.hue; this._saturation = hsl.saturation; this._lightness = hsl.lightness; }; /** * Get or set the red value of the color. * * @param {int} val - New value of the red attribute. * @return {int|Color} - The color object is returned when calling this method as a setter. */ Color.prototype.red = function (red) { if (typeof red !== "undefined") { this._red = clamp(from_255(red)); this.updateHsl(); return this; } return to_255(this._red); }; /** * Get or set the green value of the color. * * @param {int} val - New value of the green attribute. * @return {int|Color} - The color object is returned when calling this method as a setter. */ Color.prototype.green = function (green) { if (typeof green !== "undefined") { this._green = clamp(from_255(green)); this.updateHsl(); return this; } return to_255(this._green); }; /** * Get or set the blue value of the color. * * @param {int} val - New value of the blue attribute. * @return {int|Color} - The color object is returned when calling this method as a setter. */ Color.prototype.blue = function (blue) { if (typeof blue !== "undefined") { this._blue = clamp(from_255(blue)); this.updateHsl(); return this; } return to_255(this._blue); }; /** * Get or set the hue value of the color. * * @param {int} val - New value of the hue attribute. * @return {int|Color} - The color object is returned when calling this method as a setter. */ Color.prototype.hue = function (hue) { if (typeof hue !== "undefined") { this._hue = clamp(hue % 360 / 360); this.updateRgb(); return this; } return Math.round(this._hue * 360); }; /** * Get or set the saturation value of the color. * * @param {int} val - New value of the saturation attribute. * @return {int|Color} - The color object is returned when calling this method as a setter. */ Color.prototype.saturation = function (saturation) { if (typeof saturation !== "undefined") { this._saturation = clamp(saturation / 100); this.updateRgb(); return this; } return Math.round(this._saturation * 100); }; /** * Get or set the lightness value of the color. * * @param {int} val - New value of the lightness attribute. * @return {int|Color} - The color object is returned when calling this method as a setter. */ Color.prototype.lightness = function (lightness) { if (typeof lightness !== "undefined") { this._lightness = clamp(lightness / 100); this.updateRgb(); return this; } return Math.round(this._lightness * 100); }; /** * Get or set the alpha value of the color. * * @param {float} val - New value of the alpha attribute. * @return {float|Color} - The color object is returned when calling this method as a setter. */ Color.prototype.alpha = function (alpha) { if (typeof alpha !== "undefined") { this._alpha = clamp(alpha); return this; } return this._alpha; }; /** * Get the chroma value of the color. * * @return {number} */ Color.prototype.chroma = function () { return (1 - Math.abs(2 * this._lightness - 1)) * this._saturation; }; /** * Get the luma value of the color. * * @return {number} */ Color.prototype.luma = function () { return this._lightness - 0.5 * this.chroma(); }; /** * Increase or decrease the value of the red attribute by an amount. * * @param {int} delta * @return {Color} */ Color.prototype.shiftRed = function (delta) { this.set(this.red() + delta); return this; }; /** * Increase or decrease the value of the green attribute by an amount. * * @param {int} delta * @return {Color} */ Color.prototype.shiftGreen = function (delta) { this.green(this.green() + delta); return this; }; /** * Increase or decrease the value of the blue attribute by an amount. * * @param {int} delta * @return {Color} */ Color.prototype.shiftBlue = function (delta) { this.blue(this.blue() + delta); return this; }; /** * Increase or decrease the value of the hue attribute by an amount. * * @param {int} delta * @return {Color} */ Color.prototype.shiftHue = function (delta) { this.hue(this.hue() + delta); return this; }; /** * Increase or decrease the value of the saturation attribute by an amount. * * @param {int} delta * @return {Color} */ Color.prototype.shiftSaturation = function (delta) { this.saturation(this.saturation() + delta); return this; }; /** * Increase or decrease the value of the lightness attribute by an amount. * * @param {int} delta * @return {Color} */ Color.prototype.shiftLightness = function (delta) { this.lightness(this.lightness() + delta); return this; }; /** * Increase or decrease the alpha value by an amount. * * @param {float} delta * @return {Color} */ Color.prototype.shiftAlpha = function (delta) { this.alpha(this.alpha() + delta); return this; }; /** * Set the red, green and blue values. * * @param {int} red * @param {int} green * @param {int} blue * @return {Color} */ Color.prototype.setRGB = function (red, green, blue) { this._red = clamp(from_255(red)); this._green = clamp(from_255(green)); this._blue = clamp(from_255(blue)); this.updateHsl(); return this; }; /** * Set the hue, saturation and lightness values. * * @param {int} hue * @param {int} saturation * @param {int} lightness * @return {Color} */ Color.prototype.setHSL = function (hue, saturation, lightness) { this._hue = clamp(hue % 360 / 360); this._saturation = clamp(saturation / 100); this._lightness = clamp(lightness / 100); this.updateRgb(); return this; }; /** * Mix a color into another. * * A weight of 0 will return the new color and a weight of 100 will return * the original color. * * This function returns a new Color object. * * @param {Color|string} color - Color to mix into the current * @param {number} weight - A value between 0 and 50 to balance the mix * @return {Color} */ Color.prototype.mix = function (color, weight = 50) { if (typeof color === "string") { color = new Color(color); } if (!(color instanceof Color)) { throw "Color.mix() requires a string or an instance of Color"; } let w = weight / 100; let _w = 1 - w; let red = this._red * w + color._red * _w; let green = this._green * w + color._green * _w; let blue = this._blue * w + color._blue * _w; let alpha = this._alpha * w + color._alpha * _w; return new Color(to_255(red), to_255(green), to_255(blue), alpha); }; /** * Mix a color into another, averaging saturation and lightness. * * A weight of 0 will return the new color and a weight of 100 will return * the original color. * * @param {Color|string} color - Color to mix into the current * @param {number} weight - A value between 0 and 50 to balance the mix * @return {Color} */ Color.prototype.average = function (color, weight = 50) { if (typeof color === "string") { color = new Color(color); } if (!(color instanceof Color)) { throw "Color.average() requires a string or an instance of Color"; } let w = weight / 100; let _w = 1 - w; let target_saturation = this._saturation * w + color._saturation * _w; let target_lightness = this._lightness * w + color._lightness * _w; let red = this._red * w + color._red * _w; let green = this._green * w + color._green * _w; let blue = this._blue * w + color._blue * _w; let alpha = this._alpha * w + color._alpha * _w; let result = new Color(to_255(red), to_255(green), to_255(blue), alpha); result._saturation = target_saturation; result._lightness = target_lightness; result.updateRgb(); return result; }; /** * Add a color to another. * * @param {Color|string} color * @param {number} strength * @return {Color} */ Color.prototype.add = function (color, strength) { if (typeof color === "string") { color = new Color(color); } if (!(color instanceof Color)) { throw "Color.add() requires a string or an instance of Color"; } if (typeof strength !== "number") { strength = 1.0; } let red = clamp(this._red + color._red * strength); let green = clamp(this._green + color._green * strength); let blue = clamp(this._blue + color._blue * strength); return new Color(to_255(red), to_255(green), to_255(blue), this._alpha); }; /** * Substract a color from another. * * @param {Color|string} color * @param {number} strength * @return {Color} */ Color.prototype.substract = function (color, strength) { if (typeof color === "string") { color = new Color(color); } if (!(color instanceof Color)) { throw "Color.substract() requires a string or an instance of Color"; } if (typeof strength !== "number") { strength = 1.0; } let red = clamp(this._red - color._red * strength); let green = clamp(this._green - color._green * strength); let blue = clamp(this._blue - color._blue * strength); return new Color(to_255(red), to_255(green), to_255(blue), this._alpha); }; /** * Get a copy of the current color. * * @return {Color} */ Color.prototype.clone = function () { var c = new Color( this.red(), this.green(), this.blue() ); c.alpha(this.alpha()); c.phaseFunctions = this.phaseFunctions; c.currentPhase = this.currentPhase; return c; }; /** * Get the color value in CSS hex format. * * @return {string} */ Color.prototype.hex = function () { return "#" + to_hex(this._red) + to_hex(this._green) + to_hex(this._blue); }; /** * Get the color value in CSS rgb format. * * @return {string} */ Color.prototype.rgb = function () { return "rgb(" + to_255(this._red) + ", " + to_255(this._green) + ", " + to_255(this._blue) + ")"; }; /** * Get the color value in CSS rgba format. * * @param {float} alpha - A value between 0 and 1 to override the current alpha value of the color. * @return {string} */ Color.prototype.rgba = function (alpha) { if (typeof alpha === "undefined") { alpha = this._alpha; } return "rgba(" + to_255(this._red) + ", " + to_255(this._green) + ", " + to_255(this._blue) + ", " + alpha + ")"; }; /** * Get the color value in CSS hsl format. * * @return {string} */ Color.prototype.hsl = function () { return "hsl(" + parseInt(this._hue * 360) + ", " + parseInt(this._saturation * 100) + "%, " + parseInt(this._lightness * 100) + "%)"; }; /** * Get the color value in CSS hsla format. * * @param {float} alpha - A value between 0 and 1 to override the current alpha value of the color. * @return {string} */ Color.prototype.hsla = function (alpha) { if (typeof alpha === "undefined") { alpha = this._alpha; } return "hsla(" + parseInt(this._hue * 360) + ", " + parseInt(this._saturation * 100) + "%, " + parseInt(this._lightness * 100) + "%, " + alpha + ")"; }; /** * Obtain a string representation of the color, in CSS rgba() format. * * @return {string} */ Color.prototype.toString = function () { return this.rgba(); }; /** * Attach a function to manipulate a color attribute in each phase change. * * The color attributes are red, green, blue, hue, saturation, lightness and alpha. * * The signature of the callback is f(currentValue, phase) * * For red, green and blue, currentValue is in the range from 0 to 255. * For hue, currentValue is in the range from 0 to 360 * For saturation and lightness, currentValue is in the range from 0 to 100 * For alpha, currentValue is a float in the range from 0 to 1 * * @param {string} attr - One of the color attrbutes * @param {function} callback - Callback to modifiy the attribute * @return {Color} */ Color.prototype.phase = function (attr, callback) { this.phaseFunctions[attr] = callback; return this; }; /** * Get the next color in the phase sequence. * * @param {Anything} phase - An override phase value for the phase function * @return {Color} */ Color.prototype.next = function (phase) { var result = this.clone(); phase = typeof phase === "undefined" ? this.currentPhase : phase; for (let attr in this.phaseFunctions) { let f = this.phaseFunctions[attr]; let v = this[attr](); let a = f.call(this, v, phase); result[attr](a); } result.currentPhase++; return result; }; if (typeof module === "object") { module.exports = Color; module.exports.getScale = get_scale; } else { root.Color = Color; root.Color.getScale = get_scale; } })(this);
module.exports = function(grunt) { // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), yuidoc: { compile: { name: '<%= pkg.name %>', description: '<%= pkg.description %>', version: '<%= pkg.version %>', url: '<%= pkg.homepage %>', options: { extension: '.js', paths: 'src/', outdir: 'docs/' } } }, uglify: { build: { files: { 'build/<%= pkg.filenameBase %>-<%= pkg.version %>.min.js': ['<%= pkg.main %>**/*.js'] } } }, concat: { build: { src:['src/*', 'src/*/**'], dest: 'build/<%= pkg.filenameBase %>-<%= pkg.version %>.js' } }, connect: { server: { options: { port: 9000, base: './' } } } }); grunt.loadNpmTasks('grunt-contrib-uglify'); grunt.loadNpmTasks('grunt-contrib-yuidoc'); grunt.loadNpmTasks('grunt-contrib-concat'); grunt.loadNpmTasks('grunt-contrib-connect'); grunt.registerTask("default", [ "uglify:build", "concat:build" ]); grunt.registerTask("full", [ "concat:build", "uglify:build", "yuidoc:compile" ]); grunt.registerTask('serve', [ 'connect:server:keepalive' ]); };
(function() { var storage = window.Cookie; var model = window.model; Object.assign(model, { init: function(callback) { var data = storage.getItem(model.TOKEN); try { if (data) model.data = JSON.parse(data); } catch (e) { console.error(e); } if (callback) callback(); }, flush: function(callback) { try { storage.setItem(model.TOKEN, JSON.stringify(model.data), {maxAge: 31536e3}); // 1 year } catch (e) { console.error(e); } if (callback) callback(); } }); })();
angular.module("flowApi", ['ui.router', 'ui.bootstrap.collapse', 'ui.bootstrap.pagination', 'uib/template/pagination/pagination.html']); angular.module('flowApi').config(['$stateProvider', function($stateProvider){ $stateProvider .state('releases',{ url: '/releases', abstract: true, template: "<section ui-view='main'></section", }) .state('releases.index',{ url: '', views: { 'main': { templateUrl: '/templates/releases.html', controllerAs: "releasesCtrl", controller: [ 'releaseResource', '$scope', function(releaseResource, $scope){ var _this = this; this.pageChanged = function(){ getReleases({ page: _this.currentPage }); } getReleases({}); function getReleases(params) { releaseResource.all(params).then(function(result){ _this.totalItems = result.data.pagination.totalResults; _this.currentPage = result.data.pagination.page; _this.perPage = result.data.pagination.perPage; _this.releases = result.data.releases; }); } }] } } }) .state('releases.show',{ url: '/:id', views: { 'main': { templateUrl: '/templates/release.html', controllerAs: "releaseCtrl", controller: [ 'releaseResource', '$stateParams', function(releaseResource, $stateParams){ var _this = this; var id = $stateParams.id; releaseResource.find(id).then(function(result){ _this.release = result.data[0]; }); }] } } }); }]); angular.module('flowApi').factory('releaseResource',['$http', function($http){ releaseResource = {}; releaseResource.all = function(params){ return $http.get('/releases', { params: (params || {}) }); }; releaseResource.find = function(id){ return $http.get('/releases/' + id); }; return releaseResource; }]); angular.module('flowApi').directive('storytypelabel',[function(){ return { restrict: 'E', replace: true, template: "<span class='label pull-right'> {{ storytype }}</span", scope: { storyType: '@' }, link: function(scope, elem, attrs, ctrl){ scope.storytype = attrs.storytype; switch(attrs.storytype){ case "feature" : elem.addClass("label-success") break; case "bug" : elem.addClass("label-warning") break; case "chore" : elem.addClass("label-info") break; } } } }]); angular.module('flowApi').directive('release',[function(){ return { restrict: 'EA', replace: true, templateUrl: "/templates/release_data.html", scope: { releaseData: '=' } } }]);
const authenticationErrors = [ 'Token invalid', 'Token missing', 'Username or password incorrect', ] export default (error) => authenticationErrors.includes(error.message) === true
//window._ = require('lodash'); /** * We'll load jQuery and the Bootstrap jQuery plugin which provides support * for JavaScript based Bootstrap features such as modals and tabs. This * code may be modified to fit the specific needs of your application. */ try { window.$ = window.jQuery = require('jquery'); window.Popper = require('popper.js').default; require('bootstrap'); } catch (e) {} /** * We'll load the axios HTTP library which allows us to easily issue requests * to our Laravel back-end. This library automatically handles sending the * CSRF token as a header based on the value of the "XSRF" token cookie. */ // window.axios = require('axios'); // window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'; /** * Next we will register the CSRF Token as a common header with Axios so that * all outgoing HTTP requests automatically have it attached. This is just * a simple convenience so we don't have to attach every token manually. */ // let token = document.head.querySelector('meta[name="csrf-token"]'); // if (token) { // window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content; // } else { // console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token'); // } /** * Echo exposes an expressive API for subscribing to channels and listening * for events that are broadcast by Laravel. Echo and event broadcasting * allows your team to easily build robust real-time web applications. */ // import Echo from 'laravel-echo' // window.Pusher = require('pusher-js'); // window.Echo = new Echo({ // broadcaster: 'pusher', // key: 'your-pusher-key' // });
const { getToken } = require('../utils'); const models = require('../models'); /** * Since this service provides public API, * we allow user who is also not authenticated. * For the admin routes, we add this policy/middleware */ module.exports = async (ctx, next) => { const token = getToken(ctx); if (!token) { return ctx.throw(401, 'Access Token is missing'); } try { const user = await models.accessToken.findOne({ token, include: [{ model: models.user }] }); if (!user) { ctx.status = 404; ctx.body = { message: 'User is not found' }; return next(); } ctx.options = { user: { username: user.username, email: user.email, createdAt: user.createdAt, updatedAt: user.updatedAt } }; return next(); } catch (e) { return ctx.throw(500, `${e} occured`); } };
export { default } from 'ember-materialize/components/em-phone-input';
'use strict'; const ServerGame = require('./ServerGame'); const Room = require('./Room'); const debug = require('debug'); const log = debug('game:server/server'); function Lobby ({ config }) { const rooms = new Map(); const clients = new Map(); function startGame (room) { room.startGame(); } function createGame (client) { const room = Room.create({ owner: client, game: ServerGame.create({ options: config }) }); rooms.set(room.getId(), room); client.setCurrentRoom(room); client.emit('onJoinedRoom', { room: room.toJSON() }); startGame(room); log('player ' + client.getId() + ' created a room with id ' + room.getId()); for (const lobbyClient of clients.values()) { lobbyClient.emit('roomCreated', { room: room.toJSON() }); } } // we are requesting to kill a game in progress. function endGame (roomId) { const room = rooms.get(roomId); if (room) { // stop the game updates immediate room.endGame(); for (const lobbyClient of clients.values()) { lobbyClient.emit('roomDeleted', { roomId }); lobbyClient.send('s.e'); } rooms.delete(roomId); log('game removed. there are now ' + rooms.size + ' rooms'); } else { log('that game was not found!'); } } function listenToClient (client) { client.on('clientPing', (data) => { client.emit('serverPing', data); }); client.emit('onConnected', { user: client.toJSON(), rooms: Array.from(rooms.values()).map(room => { return room.toJSON(); }) }); client.on('joinRoom', (data) => { const room = rooms.get(data.roomId); if (room && !client.isInRoom()) { room.join(client); client.setCurrentRoom(room); client.emit('onJoinedRoom', { room: room.toJSON() }); log('client joined room'); } }); client.on('leaveRoom', (data) => { const room = rooms.get(data.roomId); if (room) { room.leave(client); client.setCurrentRoom(null); if (room.getSize() === 0) { endGame(room.getId()); } client.emit('onLeftRoom', { room: room.toJSON() }); } }); client.on('createRoom', () => { createGame(client); }); log('\t socket.io:: player ' + client.getId() + ' connected'); client.on('message', (message) => { const parts = message.split('.'); const inputCommands = parts[0].split('-'); const inputTime = parts[1].replace('-', '.'); const inputSeq = parts[2]; const room = client.getCurrentRoom(); if (room && room.isGameStarted()) { room.receiveClientInput(client, inputCommands, inputTime, inputSeq); } else { log('no room to receive input'); } }); client.on('disconnect', function () { log('\t socket.io:: client disconnected ' + client.getId()); const room = client.getCurrentRoom(); if (room) { if (room.size === 1) { endGame(room.getId()); } client.emit('onLeftRoom', { room: room.toJSON() }); room.leave(client); client.setCurrentRoom(null); } clients.delete(client.getId()); }); } function addClient (client) { clients.set(client.getId(), client); listenToClient(client); } function removeClient (clientId) { clients.delete(clientId); } return { addClient, removeClient }; } module.exports = { create: Lobby };
//= require jquery_ujs var Responses = (function($){ var bindClicks = function(module) { $('.btn-show').on('click', function(){ var id = $(this).data('id'), content = $(this).data('content'); module.showResponse(id, content); return false; }); } function Module(baseUrl) { this.baseUrl = baseUrl; bindClicks(this); } Module.prototype.showResponse = function(id, content) { $.getJSON(this.baseUrl+'/'+id+'.json', function(data){ var showResponseHolder = $('#showResponseHolder'), display = content == 'data' ? data.data : data.error; if (content == 'params') display = JSON.parse(data.params_json); showResponseHolder.html(JSON.stringify(display)); $('.modal').modal({show: true}); }); }; return Module; })(jQuery);
const isPlainObject = require('lodash.isplainobject'); const { inherits } = require('./util'); const Collection = require('./collection'); function List(...args) { if (!(this instanceof List)) { throw new Error('Cannot call List() without new'); } Collection.apply(this, args); const [initialData] = args; if (initialData) { if (Array.isArray(initialData)) { const Map = require('./map');// eslint-disable-line no-shadow Object.keys(initialData).forEach((key) => { const value = initialData[key]; if (Array.isArray(value)) { this._data[key] = new List(value); } else if (isPlainObject(value)) { this._data[key] = new Map(value); } else this._data[key] = value; }); this._json = initialData; } else { throw new Error('Invalid initial data when creating list'); } } } inherits(List, Collection); List.prototype._type = 'list'; List.prototype.slice = function slice(start, end) { return this._fromJSON(this._data.slice(start, end)); }; // returns the index for which the callback returns true. // returns -1 other than undefined if none match List.prototype.findIndex = function findIndex(callback) { return this._data.findIndex(callback); }; // return new list other than length like array.push() List.prototype.push = function push(...args) { if (args.length <= 0) return this; const cloned = this._clone(); cloned._changed = true; cloned._json = null; args = args.map(arg => this._fromJSON(arg)); cloned._data = [...cloned._data, ...args]; return cloned; }; // return new list other than removed value like array.pop() List.prototype.pop = function pop() { return this.remove(-1); }; // return new list other than length like array.unshift() List.prototype.unshift = function unshift(...args) { if (args.length <= 0) return this; const cloned = this._clone(); cloned._changed = true; cloned._json = null; args = args.map(arg => this._fromJSON(arg)); cloned._data = [...args, ...cloned._data]; return cloned; }; // return new list other than removed value like array.shift() List.prototype.shift = function shift() { return this.remove(0); }; module.exports = List;
//= require ./ecm/core/application
var React = require('react') var Link = require('react-router').Link var MainContainer = require('./MainContainer') var Home = React.createClass({ render () { return ( <MainContainer> <img src='../fist_image.png' style={{height: 150, weight: 150}} /> <h1>Github Battle</h1> <p className="lead">A React.JS Project</p> <Link to='/playerOne'> <button type='button' className="btn btn-lg btn-success"> Get Started </button> </Link> </MainContainer> ) } }) module.exports = Home;
// client.spec.js describe('Sockly', function() { beforeEach(function() { sockly = new Sockly(); }) it('should have an instantiation', function() { expect(sockly).toBeDefined(); }); it('should have a connect method', function() { expect(sockly.connect).toBeDefined(); }); it('should have a send method', function() { expect(sockly.send).toBeDefined(); }); it('should have a subscribe method', function() { expect(sockly.subscribe).toBeDefined(); }); describe('connect', function() { }); describe('send', function() { }); describe('subscribe', function() { }); describe('setPrefix', function() { }); });
define(['exports'], function (exports) { 'use strict'; var frag = function (...children) { const documentFragment = document.createDocumentFragment(); for (let child of children) { if (typeof child === 'string') { documentFragment.appendChild(document.createTextNode(child)); } else { documentFragment.appendChild(child); } } return documentFragment; }; function isEventListener(attrName, attrValue) { attrValue; return attrName.substr(0, 2).toLowerCase() === 'on'; } var addAttributes = function (el, attr = {}) { for (let attrName in attr) { if (!attr.hasOwnProperty(attrName)) { continue; } const attrValue = attr[attrName]; if (isEventListener(attrName, attrValue)) { const eventName = attrName.substr(2).toLowerCase(); el.addEventListener(eventName, attrValue); continue; } el.setAttribute(attrName, attrValue); } }; function createElementWithAttributesAndChildren(tag, attr = {}, ...children) { const el = document.createElement(tag); addAttributes(el, attr); el.appendChild(frag(...children)); return el; } var createElement = function (tag, attrOrChild = {}, ...children) { if (attrOrChild instanceof HTMLElement || typeof attrOrChild === 'string') { return createElementWithAttributesAndChildren(tag, {}, attrOrChild, ...children); } return createElementWithAttributesAndChildren(tag, attrOrChild, ...children); }; var empty = function (el) { while (el.lastChild) { el.removeChild(el.lastChild); } }; const c = (tag) => createElement.bind(null, tag); const a = c('a'); const abbr = c('abbr'); const address = c('address'); const article = c('article'); const aside = c('aside'); const audio = c('audio'); const b = c('b'); const bdi = c('bdi'); const bdo = c('bdo'); const blockquote = c('blockquote'); const body = c('body'); const button = c('button'); const canvas = c('canvas'); const caption = c('caption'); const cite = c('cite'); const code = c('code'); const colgroup = c('colgroup'); const data = c('data'); const datalist = c('datalist'); const dd = c('dd'); const del = c('del'); const details = c('details'); const dfn = c('dfn'); const dialog = c('dialog'); const div = c('div'); const dl = c('dl'); const dt = c('dt'); const em = c('em'); const fieldset = c('fieldset'); const figcaption = c('figcaption'); const figure = c('figure'); const footer = c('footer'); const form = c('form'); const h1 = c('h1'); const h2 = c('h2'); const h3 = c('h3'); const h4 = c('h4'); const h5 = c('h5'); const h6 = c('h6'); const head = c('head'); const header = c('header'); const hgroup = c('hgroup'); const html = c('html'); const i = c('i'); const iframe = c('iframe'); const ins = c('ins'); const kbd = c('kbd'); const keygen = c('keygen'); const label = c('label'); const legend = c('legend'); const li = c('li'); const main = c('main'); const map = c('map'); const mark = c('mark'); const math = c('math'); const menu = c('menu'); const meter = c('meter'); const nav = c('nav'); const noscript = c('noscript'); const object = c('object'); const ol = c('ol'); const optgroup = c('optgroup'); const option = c('option'); const output = c('output'); const p = c('p'); const picture = c('picture'); const pre = c('pre'); const progress = c('progress'); const q = c('q'); const rb = c('rb'); const rp = c('rp'); const rt = c('rt'); const rtc = c('rtc'); const ruby = c('ruby'); const s = c('s'); const samp = c('samp'); const script = c('script'); const section = c('section'); const select = c('select'); const slot = c('slot'); const small = c('small'); const span = c('span'); const strong = c('strong'); const style = c('style'); const sub = c('sub'); const summary = c('summary'); const sup = c('sup'); const svg = c('svg'); const table = c('table'); const tbody = c('tbody'); const td = c('td'); const template = c('template'); const textarea = c('textarea'); const tfoot = c('tfoot'); const th = c('th'); const thead = c('thead'); const time = c('time'); const title = c('title'); const tr = c('tr'); const u = c('u'); const ul = c('ul'); const varr = c('var'); const video = c('video'); const area = c('area'); const base = c('base'); const br = c('br'); const col = c('col'); const embed = c('embed'); const hr = c('hr'); const img = c('img'); const input = c('input'); const link = c('link'); const meta = c('meta'); const param = c('param'); const source = c('source'); const track = c('track'); const wbr = c('wbr'); exports.empty = empty; exports.frag = frag; exports.a = a; exports.abbr = abbr; exports.address = address; exports.article = article; exports.aside = aside; exports.audio = audio; exports.b = b; exports.bdi = bdi; exports.bdo = bdo; exports.blockquote = blockquote; exports.body = body; exports.button = button; exports.canvas = canvas; exports.caption = caption; exports.cite = cite; exports.code = code; exports.colgroup = colgroup; exports.data = data; exports.datalist = datalist; exports.dd = dd; exports.del = del; exports.details = details; exports.dfn = dfn; exports.dialog = dialog; exports.div = div; exports.dl = dl; exports.dt = dt; exports.em = em; exports.fieldset = fieldset; exports.figcaption = figcaption; exports.figure = figure; exports.footer = footer; exports.form = form; exports.h1 = h1; exports.h2 = h2; exports.h3 = h3; exports.h4 = h4; exports.h5 = h5; exports.h6 = h6; exports.head = head; exports.header = header; exports.hgroup = hgroup; exports.html = html; exports.i = i; exports.iframe = iframe; exports.ins = ins; exports.kbd = kbd; exports.keygen = keygen; exports.label = label; exports.legend = legend; exports.li = li; exports.main = main; exports.map = map; exports.mark = mark; exports.math = math; exports.menu = menu; exports.meter = meter; exports.nav = nav; exports.noscript = noscript; exports.object = object; exports.ol = ol; exports.optgroup = optgroup; exports.option = option; exports.output = output; exports.p = p; exports.picture = picture; exports.pre = pre; exports.progress = progress; exports.q = q; exports.rb = rb; exports.rp = rp; exports.rt = rt; exports.rtc = rtc; exports.ruby = ruby; exports.s = s; exports.samp = samp; exports.script = script; exports.section = section; exports.select = select; exports.slot = slot; exports.small = small; exports.span = span; exports.strong = strong; exports.style = style; exports.sub = sub; exports.summary = summary; exports.sup = sup; exports.svg = svg; exports.table = table; exports.tbody = tbody; exports.td = td; exports.template = template; exports.textarea = textarea; exports.tfoot = tfoot; exports.th = th; exports.thead = thead; exports.time = time; exports.title = title; exports.tr = tr; exports.u = u; exports.ul = ul; exports.varr = varr; exports.video = video; exports.area = area; exports.base = base; exports.br = br; exports.col = col; exports.embed = embed; exports.hr = hr; exports.img = img; exports.input = input; exports.link = link; exports.meta = meta; exports.param = param; exports.source = source; exports.track = track; exports.wbr = wbr; Object.defineProperty(exports, '__esModule', { value: true }); });
import React from 'react'; import { Link } from 'react-router'; import { createFragmentContainer, graphql, } from 'react-relay/compat'; import NoteViewer from '../Note/NoteViewer'; class LessonListComponent extends React.Component { render() { const baseUrl = this.props.baseUrl; return ( <div> <h2><Link to={this.props.baseUrl + '/lesson/' + this.props.lesson.id}>LESSON: {this.props.lesson.order_by} ({this.props.lesson.notesCount} Notes)</Link></h2> <h3>{this.props.lesson.title}</h3> <p style={{ textAlign: 'center' }}>{this.props.lesson.summary}</p> {this.props.lesson.notes.edges.map(function (note) { return <NoteViewer key={note.node.id} note={note.node.note} baseUrl={baseUrl} />; })} </div> ); } } LessonListComponent.propTypes = { lesson: React.PropTypes.object.isRequired, }; export default createFragmentContainer(LessonListComponent, { /* TODO manually deal with: initialVariables: { courseId: '1', } */ lesson: graphql` fragment LessonListComponent_lesson on Lesson { id order_by title description }`, });
'use strict'; // Utilities: var _ = require('lodash'); var Promise = require('bluebird'); // Module: var Core = require('../Core'); // Dependencies: var camelcase = require('change-case').camel; var pascalcase = require('change-case').pascal; require('../Components/Notifier/NotifierService'); require('../Services/ValidationService'); var VariableNameValidator = function ( $rootScope, notifierService, validationService ) { var ModelChangeEvent = 'VariableNameValidator:ModelChange'; return { restrict: 'A', require: 'ngModel', scope: { variableValue: '=ngModel', allVariableNames: '&' }, link: link }; function link ($scope, element, attrs, ngModelController) { var destroy = $rootScope.$on(ModelChangeEvent, function (event, changing) { if (ngModelController !== changing) { ngModelController.$validate(); } }); $scope.$watch('variableValue', function () { $rootScope.$broadcast(ModelChangeEvent, ngModelController); }); $scope.$on('$destroy', function () { destroy(); }); ngModelController.$validators.variableNameUnique = function (value) { var variableName = $scope.$parent.isClass ? pascalcase(value) : camelcase(value); var allVariableNames = $scope.allVariableNames(); var result = !_.contains(allVariableNames, variableName); return result; }; ngModelController.$validators.variableNameValid = function (value) { var variableName = $scope.$parent.isClass ? pascalcase(value) : camelcase(value); if (variableName.length === 0) { return false; } return validationService.validateVariableName(variableName); }; } }; Core.directive('variableName', VariableNameValidator);
import registerGettextHelpers from 'django-ember-gettext/lib/main'; export default { name: 'register-django-gettext-helpers', initialize: function() { registerGettextHelpers(); } }
'use strict' const Transform = require('stream').Transform const StringDecoder = require('string_decoder').StringDecoder class WordFilter extends Transform { constructor(isWordChar, isWordEnd) { super({ readableObjectMode: true }) if (typeof isWordEnd !== 'function') { isWordEnd = () => false } this._isWordChar = isWordChar this._isWordEnd = isWordEnd this._word = '' this._decoder = new StringDecoder() } pushWord(str) { if (!str) return for (var c of str) { if (this._isWordChar(c)) { if (this._isWordEnd(this._word)) { this._pushWord() } this._word += c } else { this._pushWord() } } } _pushWord() { if (this._word) { this.push(this._word) this._word = '' } } _transform(buf, enc, next) { this.pushWord(this._decoder.write(buf)) next() } _flush(next) { this.pushWord(this._decoder.end()) this._pushWord() next() } static cjk() { return new WordFilter(charStr => { const code = charStr.charCodeAt(0) return code >= 0x4e00 && code <= 0x9fcc }, () => true) } static ascii() { return new WordFilter(c => /\w{1}/.test(c)) } } module.exports = WordFilter
'use strict'; var azure = require('azure-storage'); var pg = require('pg'); var request = require('request'); var parseString = require('xml2js').parseString; var conString = 'postgres://' + process.env.POSTGRES + '/postgres'; var retryOperations = new azure.ExponentialRetryPolicyFilter(); var blobSvc = azure.createBlobService().withFilter(retryOperations); blobSvc.createContainerIfNotExists('userpictures', {publicAccessLevel: 'blob'}, function(error, result, response) { if (!error) { console.log(result); console.log(response); } else { console.log('error creating azure blob container ', error); } }); /** * Returns tree data for a single tree (profile view). Function expects a treeid. * @param req * @param res */ exports.getTreeData = function(req, res) { var treeid = req.params.treeId; pg.connect(conString, function(err, client, done) { var selectMessages = 'SELECT tree.name, tree.treeid, q.qspecies, tree.plotsize, tree.qcaretaker, tree.plantdate, l.latitude, l.longitude, image.imageurl, image.imagewidth, image.imageheight, image.imagetype from qspecies q JOIN tree ON (q.qspeciesid = tree.qspeciesid) JOIN "location" l ON (l.locationid = tree.locationid) JOIN image ON (q.qspeciesid = image.qspeciesid) WHERE treeid = $1;'; client.query(selectMessages, [treeid], function(error, results) { if (error) { console.log(error, 'THERE WAS AN ERROR'); } else { res.json(results.rows[0]); } done(); }); }); }; /** * Get tree data for 250 trees (list view). * @param req * @param res */ exports.getAll = function(req, res) { pg.connect(conString, function(err, client, done) { // console.log(err); var selectTrees = 'SELECT tree.name, tree.treeid, q.qspecies, l.latitude, l.longitude, thumbnail.url, thumbnail.width, thumbnail.height, thumbnail.contenttype FROM qspecies q JOIN tree ON (q.qspeciesid = tree.qspeciesid) JOIN "location" l ON (l.locationid = tree.locationid) JOIN thumbnail ON (q.qspeciesid = thumbnail.qspeciesid) LIMIT 250;'; client.query(selectTrees, function(error, results) { }, function(error, results) { done(); if (error) { console.log('Error is ', error); } res.json(results.rows); }); }); }; /** * Gets tree's messages from database and sends it to client. Request is expecting a treeId. * @param req * @param res */ exports.getMessagesForTree = function(req, res) { var treeid = req.params.treeid; // console.log('in getMessageForTree and treeid is', treeid); pg.connect(conString, function(err, client, done) { console.log(err); var selectMessages = 'SELECT message.message, message.treeid, message.username, message.messageid, message.createdAt FROM message WHERE treeid = $1 LIMIT 100;'; client.query(selectMessages, [treeid], function(error, results) { res.json(results.rows); }); done(); }); }; /** * Gets messages from users and sends it to the database. Request is expecting an username. * @param req * @param res */ exports.getMessagesForUsers = function(req, res) { var username = req.params.userid; // console.log('in getMessageForUsers and username is', username); pg.connect(conString, function(err, client, done) { console.log(err); var selectMessages = 'SELECT message.message, message.treeid, tree.name, message.username, message.messageid, message.createdAt FROM message JOIN tree ON (tree.treeid = message.treeid) WHERE username = $1 LIMIT 100;'; client.query(selectMessages, [username], function(error, results) { console.log('error is ', error); res.json(results.rows); }); done(); }); }; /** * Gets messages from both users or trees and uploads them to the database. Request expecting treeName or userName, * and a treeId. * @param req * @param res */ // exports.postMessageFromUser = function(req, res) { console.log('got into postMessageFromUser'); var username = req.body.username; var message = req.body.message; var treeid = req.body.treeid; var returnMessages = []; var url = 'http://www.botlibre.com/rest/botlibre/form-chat?application=' + process.env.APPLICATIONID + '&message=' + message + '&instance=812292'; request(url, function(error, response, body) { console.log('body', body); if (!error && response.statusCode === 200) { parseString(body, function(error, result) { pg.connect(conString, function(err, client, done) { if (err) { console.log('error is', err); } else { var insertMessages = 'INSERT INTO message (message, username, treeid, createdat) values ($1, $2, $3, now()) RETURNING *;'; client.query(insertMessages, [message, username, treeid], function(error, results) { returnMessages.push(results.rows[0]); done(); }); var insertTreeMessages = 'INSERT INTO message (message, username, treeid, createdat) values ($1, $2, $3, now()) RETURNING *;'; client.query(insertTreeMessages, [result.response.message[0], 'unknown', treeid], function(error, results) { // console.log(error); returnMessages.push(results.rows[0]); res.send(returnMessages); done(); }); } }); }); } }); }; /** * Search tree return 250 results matching the search params. It takes a search param, and an offset. If offset is not * provided it will default to 0. * @param req * @param res */ exports.searchTrees = function(req, res) { var search = req.params.search; search = search.replace('%20', ' '); var offset = req.offset || 0; var searchString = typeof search === 'string' ? '%' + search + '%' : 'do not use'; var searchNum = typeof search === 'number' ? search : 0; pg.connect(conString, function(err, client, done) { console.log('in search trees'); // console.log(err); var selectTrees = 'SELECT tree.name, tree.treeid, q.qspecies, l.latitude, l.longitude, thumbnail.url, thumbnail.width, thumbnail.height, thumbnail.contenttype FROM qspecies q JOIN tree ON (q.qspeciesid = tree.qspeciesid) JOIN "location" l ON (l.locationid = tree.locationid) JOIN thumbnail ON (q.qspeciesid = thumbnail.qspeciesid) WHERE ' + 'tree.treeid = $1 OR tree.name LIKE $2 OR q.qspecies LIKE $2 OR q.qspeciesid = $1 LIMIT 250 OFFSET $3;'; // var selectTrees = 'SELECT tree.name, q.qspecies, l.latitude, l.longitude, thumbnail.url, thumbnail.width, ' + // 'thumbnail.height, thumbnail.contenttype FROM qspecies q JOIN tree ON (q.qspeciesid = tree.qspeciesid) JOIN ' + // '"location" l ON (l.locationid = tree.locationid) JOIN thumbnail ON (q.qspeciesid = thumbnail.qspeciesid) WHERE ' + // 'tree.treeid = $1 OR tree.name LIKE $2 OR q.qspecies LIKE $2 OR q.qspeciesid = $1 LIMIT 250 OFFSET $3;'; console.log(searchNum, searchString, offset); client.query(selectTrees, [searchNum, searchString, offset], function(error, results) { // console.log('error', error); //console.log('results', results); console.log(results.rows); res.json(results.rows); }); done(); }); }; /** * This function expects a treeid to insert messages. The userid will be saved with the value of -1 which means that * the message was sent by the tree. * @param req * @param res */ exports.insertMessagesFromTrees = function(req, res) { console.log('got into insertMessagesFromTrees is '); var treeid = req.body.treeid; var userid = -1; var message = req.body.message; // console.log(treeid, userid, message); pg.connect(conString, function(err, client, done) { // console.log(err); var selectMessages = 'INSERT INTO message (message, treeid, userid, createdat) values($1, $2, $3, now())'; client.query(selectMessages, [message, treeid, userid], function(error, results) { // console.log('results is ', results); res.send(results); done(); }); }); }; /** * Inserts likes into database. This takes username and treeid. * @param req * @param res */ exports.insertLikes = function(req, res) { var treeid = req.body.treeId; var username = req.body.username; pg.connect(conString, function(err, client, done) { // console.log(err); var insertLikes = 'INSERT INTO likes (username, treeid) values($1, $2)'; client.query(insertLikes, [username, treeid], function(error, results) { // console.log('results is ', results); res.send(results); done(); }); }); }; /** * This gets a list of trees that the user likes. It takes an username. * @param req * @param res */ exports.getTreeLikes = function(req, res) { var username = req.body.username; pg.connect(conString, function(err, client, done) { var selectLikes = 'SELECT tree.name, tree.treeid, q.qspecies, thumbnail.url, thumbnail.width, thumbnail.height, ' + 'thumbnail.contenttype FROM qspecies q JOIN tree ON (q.qspeciesid = tree.qspeciesid) JOIN thumbnail ON ' + '(q.qspeciesid = thumbnail.qspeciesid) JOIN likes ON (tree.treeid = likes.treeid)' + ' WHERE username = $1;'; client.query(selectLikes, [username], function(error, results) { console.log('err', error); console.log('results is ', results); res.send(results.rows); done(); }); }); }; /** * This gets a list of users which like a particular tree. It takes a treeid. * @param req * @param res */ exports.getUserLikes = function(req, res) { var treeid = '' + req.body.treeId; pg.connect(conString, function(err, client, done) { // console.log(err); var selectLikes = 'SELECT username from likes WHERE treeid = $1;'; client.query(selectLikes, [treeid], function(error, results) { console.log('results is ', results); res.send(results.rows); done(); }); }); }; /** * Insert comments for a message into comments table. This takes a username, comment, treeid, and messageid. * @param req * @param res */ exports.insertComments = function(req, res) { console.log('insert comments'); var username = req.body.username; var comment = req.body.comment; var treeid = req.body.treeid; var messageid = req.message.messageid; pg.connect(conString, function(err, client, done) { if (err) { console.log('error is', err); } else { var insertComments = 'INSERT INTO comment (comment, username, treeid, messageid, createdat) values ($1, $2, $3, $5, now) RETURNING *;'; client.query(insertComments, [comment, username, treeid, messageid], function(error, results) { console.log('postCommentFromUser result is ', results.rows); res.json(results.rows); done(); }); } }); }; /** * Gets comments from the database for a particular message. This takes a messageid. * @param req * @param res */ exports.getComments = function(req, res) { var messageid = req.params.messageid; console.log('in getComment'); pg.connect(conString, function(err, client, done) { // console.log(err); var selectMessages = 'SELECT comment.comment, message.treeid, message.username, comment.createdAt FROM comments WHERE messageid = $1 LIMIT 100;'; client.query(selectMessages, [messageid], function(error, results) { res.json(results.rows); }); done(); }); }; /** * This queries the database for a location withing 0.01 from the users longitude and latitude. It expects a latitude * and longitude. * @param req * @param res */ exports.findTreesByLocation = function(req, res) { console.log('find by loc'); var lat = parseFloat(req.query.latitude); var lng = parseFloat(req.query.longitude); var upperLongitude = lng + 0.001; var upperLatitude = lat + 0.001; var lowerLatitude = lat - 0.001; var lowerLongitude = lng - 0.001; pg.connect(conString, function(err, client, done) { var locationQuery = 'SELECT tree.name, tree.treeid, q.qspecies, l.latitude, l.longitude, thumbnail.url, thumbnail.width, thumbnail.height, thumbnail.contenttype FROM qspecies q JOIN tree ON (q.qspeciesid = tree.qspeciesid) JOIN "location" l ON (l.locationid = tree.locationid) JOIN thumbnail ON (q.qspeciesid = thumbnail.qspeciesid) WHERE ' + '(l.latitude BETWEEN $1 AND $2) AND (l.longitude BETWEEN $3 AND $4)'; client.query(locationQuery, [lowerLatitude, upperLatitude, lowerLongitude, upperLongitude], function(error, results) { // console.log('error', error); //console.log('results', results); // console.log(results.rows); res.json(results.rows); done(); }); }); }; /** * Return an image for a tree. This function takes a treeid. * @param req * @param res */ exports.getTreeImage = function(req, res) { var treeid = req.params.treeId; pg.connect(conString, function(err, client, done) { // console.log(err); var getImage = 'SELECT image.imageurl, image.imagewidth, image.imageheight, image.imagetype FROM image JOIN qspecies ON qspecies.qspeciesid = image.qspeciesid JOIN tree on tree.qspeciesid = qspecies.qspeciesid WHERE tree.treeid = $1;'; client.query(getImage, [treeid], function(error, results) { // console.log('err',error); // console.log('THESE results is ', results); res.send(results.rows[0]); done(); }); }); }; //This can be refactored to store image in DB instead of locally in folder /** * This function uploads a profile image to the azure cdn. * @param req * @param res * @param imageName * @param cb */ exports.uploadUserImage = function(req, res, imageName, cb) { //packages/articles/server/controllers/test/uploads/ var localPath = 'packages/theme/public/assets/img/uploads/' + imageName; blobSvc.createBlockBlobFromLocalFile('userpictures', imageName, localPath, function(error, result, response) { if (!error) { console.log('file uploaded'); cb(); } else { console.log('error on image upload is ', error); return error; } }); }; /** * Inserts a New Tree into DB with provided information. * @param req * @param res * * TODO: Hook up tree api to Angular Add Tree Form */ exports.addTree = function (req, res, next) { var locationQuery = 'INSERT INTO location (xcoord, ycoord , latitude, longitude) select $1, $2, $3, $4 WHERE NOT EXISTS (SELECT xcoord FROM location WHERE xcoord = $1 and ycoord = $2);'; var treeQuery = 'INSERT INTO tree (name, qspeciesid, siteorder, qsiteinfo, qcaretaker, plantdate, dbh, plotsize, permitnotes, treeid, locationid) SELECT $1, (select distinct qspeciesid from qspecies where qspecies = $2 limit 1), $3, $4, $5, $6, $7, $8, $9, $10, (select distinct locationid from location where xcoord = $11 limit 1) WHERE NOT EXISTS (SELECT treeid FROM tree WHERE treeid = $10);'; var qspeciesQuery = 'INSERT INTO qspecies (qspecies) SELECT $1 WHERE NOT EXISTS (SELECT qspecies FROM qspecies WHERE qspecies = $1);'; var tree = req.body; pg.connect(conString, function (err, client, done) { console.log('data rec from client', tree); var longitude = tree.location.longitude || '9999'; var latitude = tree.location.latitude || '9999'; var xcoord = tree.xcoord || '9999'; var ycoord = tree.ycoord || '9999'; client.query(locationQuery, [xcoord, ycoord, latitude, longitude], function (error, results) { console.log('Finished location inserts! for location', error, results); done(); }); var qspecies = tree.qspecies; client.query(qspeciesQuery, [tree.qspecies], function (error, results) { console.log('Finished tree inserts! for query', error, results); done(); }); var name = tree.name; var treeid = tree.treeid; var siteorder = tree.siteorder || 9999; var qsiteinfo = tree.qsiteinfo || 'unknown'; var qcaretaker = tree.qcaretaker || 'unknown'; var plantdate = tree.plantdate || new Date(0); var dbh = tree.dbh || 999; var plotsize = tree.plotsize || 'unknown'; var permitnotes = tree.permitnotes || 'unknown'; console.log(name, qspecies, longitude, latitude); client.query(treeQuery, [name, qspecies, siteorder, qsiteinfo, qcaretaker, plantdate, dbh, plotsize, permitnotes, treeid, xcoord], function (error, results) { console.log('Finished tree inserts!', error, results); res.json(results); done(); client.end(); }); }); };
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // // = require jquery2 // = require jquery_ujs // = require turbolinks // = require_tree . // = require_self
import {ConnectionManager, ContentDirectory} from '../services'; export default class MediaServer { constructor(player) { this.player = player; this.connectionManager = new ConnectionManager(player); this.contentDirectory = new ContentDirectory(player); } }
// Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. // Simple single page application framework // Author: andrew @ terrainformatica.com (function($,window){ window.pageHandlers = {}; var currentPage; // show the "page" with optional parameter function show(pageName,param) { // invoke page handler var ph = pageHandlers[pageName]; if( ph ) { var $page = $("section#" + pageName); ph.call( $page.length ? $page[0] : null,param ); // call "page" handler } // activate the page $("#sidebar-wrapper li.active").removeClass("active"); $("#sidebar-wrapper li a[href=#"+pageName+"]").closest("li").addClass("active"); $(document.body).attr("page",pageName) .find("section").removeClass("active") .filter("section#" + pageName).addClass("active"); } // "page" loader function app(pageName,param) { var $page = $(document.body).find("section#" + pageName); var src = $page.attr("src"); if( src && $page.find(">:first-child").length == 0) { $.get(src, "html") // it has src and is empty - load it .done(function(html){ currentPage = pageName; $page.html(html); show(pageName,param); }) .fail(function(){ $page.html("failed to get:" + src); }); } else show(pageName,param); } // register page handler app.handler = function(handler) { var $page = $(document.body).find("section#" + currentPage); pageHandlers[currentPage] = handler.call($page[0]); } function onhashchange() { var hash = location.hash || "#start_work"; var re = /#([-_0-9A-Za-z]+)(\:(.+))?/; var match = re.exec(hash); hash = match[1]; var param = match[3]; app(hash,param); // navigate to the page } window.addEventListener('popstate', function(event) { if(window.location.hash) { onhashchange() } }); window.app = app; // setup the app as global object $(function(){ onhashchange() }); // initial state setup })(jQuery,this);
import { Prism } from 'global'; import React from 'react'; import PropTypes from 'prop-types'; export class Code extends React.Component { componentDidMount() { this.highlight(); } componentDidUpdate() { this.highlight(); } highlight() { if (typeof Prism !== 'undefined') { Prism.highlightAll(); } } render() { const codeStyle = { fontFamily: 'Menlo, Monaco, "Courier New", monospace', backgroundColor: '#fafafa', }; const preStyle = { fontFamily: 'Menlo, Monaco, "Courier New", monospace', backgroundColor: '#fafafa', padding: '.5rem', lineHeight: 1.5, overflowX: 'scroll', }; const className = this.props.language ? `language-${this.props.language}` : ''; return ( <pre style={preStyle} className={className}> <code style={codeStyle} className={className}> {this.props.code} </code> </pre> ); } } Code.propTypes = { language: PropTypes.string, code: PropTypes.node, }; Code.defaultProps = { language: null, code: null, }; export function Pre(props) { const style = { fontSize: '.88em', fontFamily: 'Menlo, Monaco, "Courier New", monospace', backgroundColor: '#fafafa', padding: '.5rem', lineHeight: 1.5, overflowX: 'scroll', }; return ( <pre style={style}> {props.children} </pre> ); } Pre.propTypes = { children: PropTypes.node }; Pre.defaultProps = { children: null }; export function Blockquote(props) { const style = { fontSize: '1.88em', fontFamily: 'Menlo, Monaco, "Courier New", monospace', borderLeft: '8px solid #fafafa', padding: '1rem', }; return ( <blockquote style={style}> {props.children} </blockquote> ); } Blockquote.propTypes = { children: PropTypes.node }; Blockquote.defaultProps = { children: null };
/** * Printdata component to wrap all printdata specified stuff together. This component is divided to following logical components: * * Controllers * Models * * All of these are wrapped to 'frontend.production.printdata' angular module. */ (function() { 'use strict'; // Define frontend.production.printdata angular module angular.module('frontend.production.printdata', []); // Module configuration angular.module('frontend.production.printdata') .config([ '$stateProvider', function config($stateProvider) { $stateProvider // Printdata list .state('production.printdatas', { url: '/production/printdatas', views: { 'content@': { templateUrl: '/frontend/production/printdata/list.html', controller: 'PrintdataListController', resolve: { _items: [ 'ListConfig', 'PrintdataModel', function resolve( ListConfig, PrintdataModel ) { var config = ListConfig.getConfig(); var parameters = { limit: config.itemsPerPage, sort: 'releaseDate DESC' }; return PrintdataModel.load(parameters); } ], _count: [ 'PrintdataModel', function resolve(PrintdataModel) { return PrintdataModel.count(); } ], _products: [ 'ProductModel', function resolve(ProductModel) { return ProductModel.load(); } ] } } } }) // Single printdata .state('production.printdata', { url: '/production/printdata/:id', views: { 'content@': { templateUrl: '/frontend/production/printdata/printdata.html', controller: 'PrintdataController', resolve: { _printdata: [ '$stateParams', 'PrintdataModel', function resolve( $stateParams, PrintdataModel ) { return PrintdataModel.fetch($stateParams.id, {populate: 'product'}); } ] } } } }) // Add new printdata .state('production.printdata.add', { url: '/production/printdata/add', data: { access: 2 }, views: { 'content@': { templateUrl: '/frontend/production/printdata/add.html', controller: 'PrintdataAddController', resolve: { _products: [ 'ProductModel', function resolve(ProductModel) { return ProductModel.load(); } ] } } } }) ; } ]) ; }());
version https://git-lfs.github.com/spec/v1 oid sha256:f80970c8d813a430aa8dcf69cbf9390003f0ae722ce11063876fbd1163dfaad7 size 29464
"use strict"; var config = require('./config.json'), async = require('async'), crypto = require('crypto'), Db = require('mongodb').Db, Server = require('mongodb').Server, ObjectID = require('mongodb').ObjectID; async.waterfall([ function openDb(callback) { var db = new Db( config.mongo.db_name, new Server(config.mongo.host, config.mongo.port, {auto_reconnect: true}, {}), {safe: true}), context = {}; db.open(function (error, db) { if (error) { console.error(error); callback('unable to open mongodb'); return; } context.dbConnection = db; process.on('exit', function () { db.close(function (error) { if (error) { console.error(error, 'error closing database'); } }); }); callback(null, context); }); }, function getCollection(context, callback) { context.dbConnection.collection(config.crashtest.col_name, function (error, coll) { if (error) { console.error(error, 'unable to get collection'); callback(error); } else { context.dbCollection = coll; callback(null, context); } }); }, function createHugeString(context, callback) { var byteCount = 10 + Math.floor(config.crashtest.docSize * 3 / 4); crypto.randomBytes(byteCount, function (ex, buf) { if (ex) { callback(ex); } else { context.hugeString = buf.toString('base64').substring(0, config.crashtest.docSize); callback(null, context); } }); }, function insertDocuments(context, callback) { async.timesSeries(config.crashtest.docCount, function (n, next) { createAndQueryDoc(n, context, next); }, function (err, results) { if (err) { callback(err); } else { callback(null, context); } }); }, function closeDb(context, callback) { context.dbConnection.close(callback); } ], function (err) { if (err) { console.error('an error occurred', err); } process.exit(1); }); function createAndQueryDoc(counter, context, callback) { var doc = { _id: new ObjectID(), counter: counter, content: context.hugeString }; if ((counter + 1) % 100 === 0) { console.log('create doc ' + counter); } context.dbCollection.insert(doc, {safe: true}, function (error, result) { if (error) { callback(error); return; } var insertedDoc = result[0]; context.dbCollection.findOne({_id: insertedDoc._id}, function (err, doc) { if (err) { console.log('couldn\'t find doc ' + insertedDoc._id); callback(err); return; } if (insertedDoc._id.toHexString() !== doc._id.toHexString()) { callback('something wrong with insert/find'); return; } callback(null); }); }); }
var loaderUtil = require('loader-utils'); var filewalker = require('filewalker'); var async = require('async'); var fs = require('fs'); var pathUtil = require('path'); module.exports = function(source, map) { var self = this; if(typeof self.options.staticSiteLoader === 'undefined') { self.emitError('You must define the staticSiteLoader options object to use this loader.'); } var myOptions = self.options.staticSiteLoader; //declare as cacheable self.cacheable(); //declare as async and save function call for later var callback = self.async(); var contentPath = pathUtil.dirname(self.resourcePath); //Pre-Processor function call if(typeof myOptions.preProcess === 'function') { myOptions.preProcess.apply(self, [source, contentPath]); } //Assemble the paths async.waterfall([ function(doneWithDirectory) { var files = []; filewalker(contentPath) .on('file', function(path, stats, absPath) { if(typeof myOptions.testToInclude === 'function') { //test if we should include file if(myOptions.testToInclude.apply(self, [path, stats, absPath])) { //rewrite URL path if(typeof myOptions.rewriteUrlPath === 'function') { var urlPath = myOptions.rewriteUrlPath.apply(self, [path, stats, absPath]); } else { var urlPath = path; } //push file to be processed files.push({ urlPath: urlPath, path: path, absPath: absPath }); } } else { self.emitError('You must set a function to staticSiteLoader.testToInclude in your webpack config to use this loader.') } }) .on('done', function() { doneWithDirectory(null, files); }) .walk(); }, function(files, filesDone) { async.each(files, function(file, fileEmitted){ fs.readFile(file.absPath, 'utf8', function(err, content) { var outputFileName = pathUtil.join(file.urlPath, '/index.html') .replace(/^(\/|\\)/, ''); // Remove leading slashes for webpack-dev-server //rewrite files contents if(typeof myOptions.processFile === 'function') { //callback provided if(myOptions.processFile.length === 3) { myOptions.processFile.apply(self, [file, content, function(content){ self.emitFile(outputFileName, content); fileEmitted(); }]); } else { //no callback content = myOptions.processFile.apply(self, [file, content]); self.emitFile(outputFileName, content); fileEmitted(); } } else { //no changes to content - output directly self.emitFile(outputFileName, content); fileEmitted(); } }); }, function() { if(typeof myOptions.postProcess === 'function') { myOptions.postProcess.apply(self, [files]); } filesDone(); }); } ], function() { //console.log('Content Processing Done'); callback(null, source); }); };
var mongoose = require('mongoose'); mongoose.set('debug', true); //Mongo var uristring = process.env.MONGOLAB_URI || process.env.MONGOHQ_URL || 'mongodb://localhost/dances'; mongoose.connect(uristring, function (err) { if (err) { console.log ('ERROR connecting to: ' + uristring + '. ' + err); } else { console.log ('Succeeded connected to: ' + uristring); } }); var db = mongoose.connection;
// http://hyperphysics.phy-astr.gsu.edu/hbase/electronic/jkflipflop.html#c3 var NoR = require('../lib/NoR.js') var NAND = NoR(function(a, b, q){ q( !( a() && b() ) ) }, function(){ this.q.isOutput = true // dont trigger execution if q changes }) var NAND3 = NoR(function(a, b, c, q){ q( !( a() && b() && c() ) ) }, function(){ this.q.isOutput = true // dont trigger execution if q changes }) var JK = NoR(function(clock, j, k, q, Q){}, function(clock, j, k, q, Q){ var A = NAND3(), B = NAND3(), C = NAND(), D = NAND() A.a.bind(clock) A.b.bind(j) A.c.bind(Q) B.a.bind(clock) B.b.bind(k) B.c.bind(q) C.a.bind(A.q) C.b.bind(D.q) C.q.bind(q) D.a.bind(B.q) D.b.bind(C.q) D.q.bind(Q) }) var Clock = NoR(function(signal, enable){}, function(time){ var timeout, enable = this.enable, signal = this.signal tick = function() { signal(! signal() ) timeout = setTimeout(tick, time()) } enable.subscribe(function(enable){ if(enable) { tick() } else if(timeout){ clearTimeout(timeout) } }) }) var clock = Clock(false, false, 800) var jk = JK(clock.signal) clock.signal.subscribe(function(){ console.log("CLOCK SIGNAL", jk) }) clock.enable(true) var set = function(j, k, should, after){ setTimeout(function(){ console.log("\n\nSetting J="+j+" K="+k+" ... q="+should) jk.j(j) jk.k(k) }, after) } set(false, true, false, 2000) // reset set(true, false, true, 4000) // set set(true, true, "be toggling", 8000) // toggle set(true, true, "be toggling", 10000) // toggle set(true, false, true, 12000) // set setTimeout(function(){ console.log("\n\nOk, done.") clock.enable(false) }, 15000)
const { ArgumentError } = require('rest-facade'); const Auth0RestClient = require('../Auth0RestClient'); const RetryRestClient = require('../RetryRestClient'); /** * Auth0 Grants Manager. * * See {@link https://auth0.com/docs/api/v2#!/Grants Grants} */ class GrantsManager { /** * @param {object} options The client options. * @param {string} options.baseUrl The URL of the API. * @param {object} [options.headers] Headers to be included in all requests. * @param {object} [options.retry] Retry Policy Config */ constructor(options) { if (options === null || typeof options !== 'object') { throw new ArgumentError('Must provide client options'); } if (options.baseUrl === null || options.baseUrl === undefined) { throw new ArgumentError('Must provide a base URL for the API'); } if ('string' !== typeof options.baseUrl || options.baseUrl.length === 0) { throw new ArgumentError('The provided base URL is invalid'); } /** * Options object for the Rest Client instance. * * @type {object} */ const clientOptions = { errorFormatter: { message: 'message', name: 'error' }, headers: options.headers, query: { repeatParams: false }, }; /** * Provides an abstraction layer for consuming the * {@link https://auth0.com/docs/api/v2#!/Grants Auth0 Grants endpoint}. * * @type {external:RestClient} */ const auth0RestClient = new Auth0RestClient( `${options.baseUrl}/grants/:id`, clientOptions, options.tokenProvider ); this.resource = new RetryRestClient(auth0RestClient, options.retry); } /** * Get all Auth0 Grants. * * @example * var params = { * per_page: 10, * page: 0, * include_totals: true, * user_id: 'USER_ID', * client_id: 'CLIENT_ID', * audience: 'AUDIENCE' * }; * * management.getGrants(params, function (err, grants) { * console.log(grants.length); * }); * @param {object} params Grants parameters. * @param {number} params.per_page Number of results per page. * @param {number} params.page Page number, zero indexed. * @param {boolean} params.include_totals true if a query summary must be included in the result, false otherwise. Default false; * @param {string} params.user_id The user_id of the grants to retrieve. * @param {string} params.client_id The client_id of the grants to retrieve. * @param {string} params.audience The audience of the grants to retrieve. * @param {Function} [cb] Callback function. * @returns {Promise|undefined} */ getAll(...args) { return this.resource.getAll(...args); } /** * Delete an Auth0 grant. * * @example * var params = { * id: 'GRANT_ID', * user_id: 'USER_ID' * }; * * management.deleteGrant(params, function (err) { * if (err) { * // Handle error. * } * * // Grant deleted. * }); * @param {object} params Grant parameters. * @param {string} params.id Grant ID. * @param {string} params.user_id The user_id of the grants to delete. * @param {Function} [cb] Callback function. * @returns {Promise|undefined} */ delete(...args) { return this.resource.delete(...args); } } module.exports = GrantsManager;
(function($) { "use strict"; //----------------------------------------// // Variable //----------------------------------------// var variable = { width : 0, height : 0, selector : '.item-point', styleSelector : 'circle', animationSelector : '', animationPopoverIn : '', animationPopoverOut : '', onInit : null, getSelectorElement : null, getValueRemove : null } //----------------------------------------// // Scaling //----------------------------------------// var scaling = { settings : null, //----------------------------------------// // Initialize //----------------------------------------// init: function(el, options){ this.settings = $.extend(variable, options); this.event(el); scaling.layout(el); $(window).on('load', function(){ scaling.layout(el); }); $(el).find('.target').on('load', function(){ scaling.layout(el); }); $(window).on('resize', function(){ scaling.layout(el); }); }, //----------------------------------------// // Event //----------------------------------------// event : function(elem){ // Set Style Selector if ( this.settings.styleSelector ) { $(this.settings.selector).addClass( this.settings.styleSelector ); } // Set Animation if ( this.settings.animationSelector ) { if( this.settings.animationSelector == 'marker' ){ $(this.settings.selector).addClass( this.settings.animationSelector ); $(this.settings.selector).append('<div class="pin"></div>') $(this.settings.selector).append('<div class="pulse"></div>') }else{ $(this.settings.selector).addClass( this.settings.animationSelector ); } } // Event On Initialize if ( $.isFunction( this.settings.onInit ) ) { this.settings.onInit(); } // Content add class animated element $(elem).find('.content').addClass('animated'); // Wrapper selector $(this.settings.selector).wrapAll( "<div class='wrap-selector' />"); // Event Selector $(this.settings.selector).each(function(){ // Toggle $('.toggle', this).on('click', function(e){ e.preventDefault(); $(this).closest(scaling.settings.selector).toggleClass('active'); // Selector Click var content = $(this).closest(scaling.settings.selector).data('popover'), id = $(content); if($(this).closest(scaling.settings.selector).hasClass('active') && !$(this).closest(scaling.settings.selector).hasClass('disabled')){ if ( $.isFunction( scaling.settings.getSelectorElement ) ) { scaling.settings.getSelectorElement($(this).closest(scaling.settings.selector)); } id.fadeIn(); scaling.layout(elem); id.removeClass(scaling.settings.animationPopoverOut); id.addClass(scaling.settings.animationPopoverIn); }else{ if($.isFunction( scaling.settings.getValueRemove )){ scaling.settings.getValueRemove($(this).closest(scaling.settings.selector)); } id.removeClass(scaling.settings.animationPopoverIn); id.addClass(scaling.settings.animationPopoverOut); id.delay(500).fadeOut(); } }); // Exit var target = $(this).data('popover'), idTarget = $(target); idTarget.find('.exit').on('click', function(e){ e.preventDefault(); // selector.removeClass('active'); $('[data-popover="'+ target +'"]').removeClass('active'); idTarget.removeClass(scaling.settings.animationPopoverIn); idTarget.addClass(scaling.settings.animationPopoverOut); idTarget.delay(500).fadeOut(); }); }); }, //----------------------------------------// // Layout //----------------------------------------// layout : function(elem){ // Get Original Image var image = new Image(); image.src = elem.find('.target').attr("src"); // Variable var width = image.naturalWidth, height = image.naturalHeight, getWidthLess = $(elem).width(), setPersenWidth = getWidthLess/width * 100, setHeight = height * setPersenWidth / 100; // Set Heigh Element $(elem).css("height", setHeight); // Resize Width if( $(window).width() < width ){ $(elem).stop().css("width","100%"); }else{ $(elem).stop().css("width",width); } // Set Position Selector $(this.settings.selector).each(function(){ if( $(window).width() < width ){ var getTop = $(this).data("top") * setPersenWidth / 100, getLeft = $(this).data("left") * setPersenWidth / 100; }else{ var getTop = $(this).data("top"), getLeft = $(this).data("left"); } $(this).css("top", getTop + "px"); $(this).css("left", getLeft + "px"); // Target Position var target = $(this).data('popover'), allSize = $(target).find('.head').outerHeight() + $(target).find('.body').outerHeight() + $(target).find('.footer').outerHeight(); $(target).css("left", getLeft + "px"); $(target).css("height", allSize + "px"); if($(target).hasClass('bottom')){ var getHeight = $(target).outerHeight(), getTopBottom = getTop - getHeight; $(target).css("top", getTopBottom + "px"); }else if($(target).hasClass('center')){ var getHeight = $(target).outerHeight() * 0.50, getTopBottom = getTop - getHeight; $(target).css("top", getTopBottom + "px"); }else{ $(target).css("top", getTop + "px"); } $('.toggle', this).css('width', $(this).outerWidth()); $('.toggle', this).css('height', $(this).outerHeight()); // Toggle Size if($(this).find('.pin')){ var widthThis = $('.pin', this).outerWidth(), heightThis = $('.pin', this).outerHeight(); $('.toggle', this).css('width', widthThis); $('.toggle', this).css('height', heightThis); } }); } }; //----------------------------------------// // Scalize Plugin //----------------------------------------// $.fn.scalize = function(options){ return scaling.init(this, options); }; }(jQuery));
#!/usr/bin/env node 'use strict' // Vendor includes const chalk = require('chalk'); const fs = require('fs'); const yargs = require('yargs'); const path = require('path'); const HTMLtoJSX = require('htmltojsx'); const jsdom = require('jsdom-no-contextify'); // Language files const content = require('./lang/en'); // Local includes const createComponentName = require('./src/createComponentName'); const formatSVG = require('./src/formatSVG'); const generateComponent = require('./src/generateComponent'); const printErrors = require('./src/output').printErrors; const removeStyle = require('./src/removeStyle'); // Argument setup const args = yargs .option('format', { default: true }) .option('output', { alias: 'o' }) .option('rm-style', { default: false }) .option('force', { alias: 'f', default: false }) .argv; // Resolve arguments const firstArg = args._[0]; const newFileName = args._[1] || 'MyComponent'; const outputPath = args.output; const rmStyle = args.rmStyle; const format = args.format; // Bootstrap base variables const converter = new HTMLtoJSX({ createClass: false }); const svg = `./${firstArg}.svg`; let fileCount = 0; const writeFile = (processedSVG, fileName) => { let file; let filesWritten = 0; if (outputPath){ file = path.resolve(process.cwd(), outputPath, `${fileName}.js`); } else { file = path.resolve(process.cwd(), `${fileName}.js`); } fs.writeFile(file, processedSVG, { flag: args.force ? 'w' : 'wx' }, function (err) { if (err) { if(err.code === 'EEXIST') { printErrors(`Output file ${file} already exists. Use the force (--force) flag to overwrite the existing files`); } else { printErrors(`Output file ${file} not writable`); } return; } filesWritten++; console.log('File written to -> ' + file); if (filesWritten === fileCount) { console.log(`${filesWritten} components created. That must be some kind of record`); console.log(); console.log(content.processCompleteText); console.log(); } }); }; const runUtil = (fileToRead, fileToWrite) => { fs.readFile(fileToRead, 'utf8', function (err, file) { if (err) { printErrors(err); return; } let output = file; jsdom.env(output, (err, window) => { const body = window.document.getElementsByTagName('body')[0]; if(rmStyle) { removeStyle(body); } // Add width and height // The order of precedence of how width/height is set on to an element is as follows: // 1st - passed in props are always priority one. This gives run time control to the container // 2nd - svg set width/height is second priority // 3rd - if no props, and no svg width/height, use the viewbox width/height as the width/height // 4th - if no props, svg width/height or viewbox, simlpy set it to 50px/50px let defaultWidth = '50px'; let defaultHeight = '50px'; if(body.firstChild.hasAttribute('viewBox')) { const [minX, minY, width, height] = body.firstChild.getAttribute('viewBox').split(/[,\s]+/); defaultWidth = width; defaultHeight = height; } if(! body.firstChild.hasAttribute('width')) { body.firstChild.setAttribute('width', defaultWidth); } if(! body.firstChild.hasAttribute('height')) { body.firstChild.setAttribute('height', defaultHeight); } // Add generic props attribute to parent element, allowing props to be passed to the svg // such as className body.firstChild.setAttribute(':props:', ''); // Now that we are done with manipulating the node/s we can return it back as a string output = body.innerHTML; // Convert from HTML to JSX output = converter.convert(output); // jsdom and htmltojsx will automatically (and correctly) wrap attributes in double quotes, // and generally just dislikes all the little markers used by react, such as the spread // operator. We will sub those back in manually now output = output.replace(/:props:/g, '{...props}'); // Format / Prettify JSX if(format) { output = formatSVG(output); } // Wrap it up in a React component output = generateComponent(output, fileToWrite); writeFile(output, fileToWrite); }); }); }; const runUtilForAllInDir = () => { fs.readdir(process.cwd(), (err, files) => { if (err) { return console.log(err); } files.forEach((file, i) => { const extention = path.extname(file); const fileName = path.basename(file); if (extention === '.svg') { // variable instantiated up top const componentName = createComponentName(file, fileName); runUtil(fileName, componentName); fileCount++; } }); }); }; // Exit out early arguments if (args.help) { console.log(content.helptext); process.exit(1); } if (args.example) { console.log(content.exampleText); process.exit(1); } // Main entry point if (firstArg === 'dir') { runUtilForAllInDir(); } else { fileCount++; runUtil(svg, newFileName); }
module.exports = { "Layouts.Main.welcomeMessage": "Welcome to the M+ Collections Spelunker!", }
// Returns the data tables: // get global database object var db = require('../../../database/pgp_db'); var pgp = db.$config.pgp; // Defining the query function: function dbtables (req, res, next) { var tableparam = !!req.query.table; if (tableparam) { var queryTable = { queryTable: 'ndb.' + String(req.query.table).toLowerCase().replace(/\s/g, '') }; var query = 'SELECT * FROM ${queryTable:raw};' } else { query = "SELECT tablename FROM pg_tables WHERE schemaname='ndb';"; } db.any(query, queryTable) .then(function (data, queryTable) { res.status(200) .json({ status: 'success', data: data, message: 'Retrieved all tables' }); }) .catch(function (err) { if (err.message.includes('does not exist')) { res.status(200) .json({ status: 'success', data: [], message: err.message }); } else { res.status(500) .json({ status: 'failure', data: err.message, message: 'Ran into an error.' }); } }); }; module.exports.dbtables = dbtables;
const parentMixin = { mounted() { if (this.value >= 0) { this.currentIndex = this.value } }, methods: { updateIndex() { if (this.$children && this.$children.length) { this.childLength = this.$children.length let children = this.$children for (let i = 0; i < children.length; i++) { children[i].currentIndex = i if (children[i].currentSelected) { this.index = i } } } } }, props: { value: { type: Number, default: 0 } }, watch: { currentIndex(val, oldVal) { oldVal > -1 && this.$children[oldVal] && (this.$children[oldVal].currentSelected = false) val > -1 && this.$children[val] && (this.$children[val].currentSelected = true) this.$emit('input', val) this.$emit('on-change', val, oldVal) }, index(val) { this.currentIndex = val }, value(val) { this.index = val } }, data() { return { index: -1, currentIndex: this.index, childLength: this.$children.length } } } const childMixin = { props: { selected: { type: Boolean, default: false } }, mounted() { this.$parent.updateIndex() }, beforeDestroy() { const $parent = this.$parent this.$nextTick(() => { $parent.updateIndex() }) }, methods: { onItemClick() { if (typeof this.disabled === 'undefined' || this.disabled === false) { this.currentSelected = true this.$parent.currentIndex = this.currentIndex this.$nextTick(() => { this.$emit('on-item-click', this.currentIndex) }) } } }, watch: { currentSelected(val) { if (val) { this.$parent.index = this.currentIndex } }, selected(val) { this.currentSelected = val } }, data() { return { currentIndex: -1, currentSelected: this.selected } } } export { parentMixin, childMixin }
describe('Deck JS Menu', function() { var $d = $(document); var dsc = defaults.selectors.container; beforeEach(function() { loadFixtures('standard.html'); if (Modernizr.history) { history.replaceState({}, "", "#") } else { window.location.hash = '#'; } $.deck('.slide'); }); describe('showMenu()', function() { it('should show the menu', function() { expect($(dsc)).not.toHaveClass(defaults.classes.menu); $.deck('showMenu'); expect($(dsc)).toHaveClass(defaults.classes.menu); }); it('should do nothing if menu is already showing', function() { if (Modernizr.csstransforms) { $.deck('showMenu'); $.deck('showMenu'); $.deck('hideMenu'); expect($('.slide').attr('style')).toBeFalsy(); } }); }); describe('hideMenu()', function() { it('should hide the menu', function() { $.deck('showMenu'); $.deck('hideMenu'); expect($(dsc)).not.toHaveClass(defaults.classes.menu); }); }); describe('toggleMenu()', function() { it('should toggle menu on and off', function() { expect($(dsc)).not.toHaveClass(defaults.classes.menu); $.deck('toggleMenu'); expect($(dsc)).toHaveClass(defaults.classes.menu); $.deck('toggleMenu'); expect($(dsc)).not.toHaveClass(defaults.classes.menu); }); }); describe('key bindings', function() { var e; beforeEach(function() { e = jQuery.Event('keydown.deckmenu'); }); it('should toggle the menu if the specified key is pressed', function() { e.which = 77; // m $d.trigger(e); expect($(dsc)).toHaveClass(defaults.classes.menu); $d.trigger(e); expect($(dsc)).not.toHaveClass(defaults.classes.menu); }); }); describe('touch bindings', function() { var estart, eend; beforeEach(function() { estart = jQuery.Event('touchstart.deckmenu'); eend = jQuery.Event('touchend.deckmenu'); }); it('should toggle the menu if the screen is touched', function() { $.deck('getOptions').touch.doubletapWindow = Date.now() + 100000; $.deck('getContainer').trigger(estart); $.deck('getContainer').trigger(eend); expect($(dsc)).toHaveClass(defaults.classes.menu); }); }); });
/** * Created by chriscai on 2014/10/14. */ var MongoClient = require('mongodb').MongoClient, connect = require('connect'); var log4js = require('log4js'), logger = log4js.getLogger(); var fs = require("fs"); var path = require("path"); var cacheTotal = require('../service/cacheTotal'); var cacheCount = require('../service/cacheErrorCount'); var url = global.MONGDO_URL; var mongoDB; // Use connect method to connect to the Server MongoClient.connect(url, function (err, db) { if (err) { logger.info("failed connect to server"); } else { logger.info("Connected correctly to server"); } mongoDB = db; }); var dateFormat = function (date, fmt) { var o = { "M+": date.getMonth() + 1, //月份 "d+": date.getDate(), //日 "h+": date.getHours(), //小时 "m+": date.getMinutes(), //分 "s+": date.getSeconds(), //秒 "q+": Math.floor((date.getMonth() + 3) / 3), //季度 "S": date.getMilliseconds() //毫秒 }; if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length)); for (var k in o) if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length))); return fmt; } var validateDate = function (date) { var startDate = new Date(date - 0) - 0; if (isNaN(startDate)) { return {ok: false, msg: 'date error'}; } } var validate = function (req, rep) { var json = req.query; var id; if (isNaN(( id = req.query.id - 0)) || id <= 0 || id >= 9999) { return {ok: false, msg: 'id is required'}; } if (!json.startDate || !json.endDate) { return {ok: false, msg: 'startDate or endDate is required'}; } try { var startDate = new Date(json.startDate - 0); var endDate = new Date(json.endDate - 0); json.startDate = startDate; json.endDate = endDate; } catch (e) { return {ok: false, msg: 'startDate or endDate parse error'}; } try { if (json.include) { json.include = JSON.parse(json.include) } else { json.include = []; } if (json.exclude) { json.exclude = JSON.parse(json.exclude) } else { json.exclude = []; } } catch (e) { return {ok: false, msg: 'include or exclude parse error'}; } try { if (json.level) { if (toString.apply(json.level) == "[object Array]") { } else { json.level = JSON.parse(json.level); } } else { json.level = []; } } catch (e) { return {ok: false, msg: 'level parse error'}; } return {ok: true}; } var totalKey = dateFormat(new Date, "yyyy-MM-dd"); var errorMsgTop = function (json, cb) { var id; if (isNaN(( id = json.id - 0)) || id <= 0 || id >= 9999) { cb({ok: false, msg: 'id is required'}); } var oneDate = new Date(json.startDate); if (isNaN(+oneDate)) { cb({ok: false, msg: 'startDate or endDate parse error'}); return; } var nowDate = new Date(dateFormat(new Date, "yyyy-MM-dd")) - 0; if (( +oneDate ) > (+nowDate )) { cb({ok: false, msg: 'can not found today'}); return; } var startDate = oneDate; var endDate = new Date(+startDate + 86400000); var queryJSON = {date: {$lt: endDate, $gte: startDate}, level: 4}; var limit = json.limit || 50; var outResult = {startDate: +startDate, endDate: +endDate, item: []}; /* mongoDB.collection('badjslog_' + id).find(queryJSON).count(function(error, doc){ if(error){ cb(error) return ; }*/ var cursor = mongoDB.collection('badjslog_' + id).aggregate( [ {$match: queryJSON}, {$group: {_id: "$msg", total: {$sum: 1}}}, {$sort: {total: -1}}, {$limit: limit} ], {allowDiskUse: true} ); cacheTotal.getTotal({id: id, key: totalKey}, function (err, total) { logger.info('[query total] ' + '{id:' + id + ', key:' + totalKey + ', err:'+ err + ', total:' + total + '}'); if (err) { logger.error('the cache total is err,the err is' + err); cb(err); return; } cursor.toArray(function (err, docs) { if (err) { cb(err) return; } outResult.item = docs; outResult.pv = total; cb(err, outResult); }); }); // }); } var getErrorMsgFromCache = function (query, isJson, cb) { var fileName = dateFormat(new Date(query.startDate), "yyyy-MM-dd") + "__" + query.id; var filePath = path.join(".", "cache", "errorMsg", fileName); logger.info('the file name is ' + filePath + '; query:' + query + '; isJson:' + isJson); var returnValue = function (err, doc) { if (query.noReturn) { cb(err); } else { cb(err, doc); } }; try{ var cacheData; if (fs.existsSync(filePath)) { logger.info("get ErrorMsg from cache id=" + query.id); if (isJson) { cacheData =JSON.parse(fs.readFileSync(filePath)); } else { cacheData = fs.readFileSync(filePath); } if(cacheData){ returnValue(null, cacheData); return; } } }catch(e){ logger.error("get ErrorMsg from cache id=" + query.id + ';' + e.message); } errorMsgTop(query, function (err, doc) { if (err) { logger.info("cache errorMsgTop error fileName=" + fileName + " " + err) } returnValue(err, isJson ? doc : JSON.stringify(doc)); }); }; var formateArr = function (result, startDateTime) { var resArr = [], dateObj = {}; result && result.map(function (item) { item.time = new Date(item._id.time); var tag = item.time.getHours() + ":" + item.time.getMinutes(); item.time = item.time.getTime() + 28800000; dateObj[tag] = Array.isArray(dateObj[tag]) ? dateObj[tag] : []; dateObj[tag].push(item.count); delete item._id; }); for (var value in dateObj) { console.log(dateObj[value].reduce(function (x, y) { return x + y }) / dateObj[value].length); var returnObj = { time: Date.parse(startDateTime + ' ' + value), count: dateObj[value].reduce(function (x, y) { return x + y }) / dateObj[value].length } resArr.push(returnObj); } resArr = resArr.sort(function (pre, nex) { return pre.time - nex.time; }); return resArr; } module.exports = function () { connect() .use('/query', connect.query()) .use('/query', function (req, res) { //校验查询req的格式 var result = validate(req, res); if (!result.ok) { res.writeHead(403, { 'Content-Type': 'text/html' }); res.statusCode = 403; res.write(JSON.stringify(result)); return; } //构造查询json var json = req.query; var id = json.id, startDate = json.startDate, endDate = json.endDate; var queryJSON = {all: {}}; var includeJSON = []; json.include.forEach(function (value, key) { includeJSON.push(new RegExp(value)); }); if (includeJSON.length > 0) { queryJSON.all.$all = includeJSON; } var excludeJSON = []; json.exclude.forEach(function (value, key) { excludeJSON.push(new RegExp(value)); }); if (excludeJSON.length > 0) { queryJSON.all.$not = {$in: excludeJSON}; } if (includeJSON.length <= 0 && excludeJSON.length <= 0) { delete queryJSON.all; } json.level.forEach(function (value, key) { json.level[key] = value - 0; }) queryJSON.date = {$lt: endDate, $gt: startDate}; queryJSON.level = {$in: json.level}; var limit = 500; if (json.index - 0) { json.index = (json.index - 0); } else { json.index = 0 } if (global.debug == true) { logger.debug("query logs id=" + id + ",query=" + JSON.stringify(queryJSON)) } mongoDB.collection('badjslog_' + id).find(queryJSON, function (error, cursor) { res.writeHead(200, { 'Content-Type': 'text/json' }); cursor.sort({'date': -1}).skip(json.index * limit).limit(limit).toArray(function (err, item) { res.write(JSON.stringify(item)); res.end(); }); }); }) .use('/queryCount', connect.query()) .use('/queryCount', function (req, res) { try{ logger.info('query start time,queryCount'+ JSON.stringify(req.query) + Date.now()); }catch(e){ logger.error('[error] query start time,queryCount'+ ';;JSON.stringify Error'); } //校验查询req的格式 var result = validate(req, res); if (!result.ok) { res.writeHead(403, { 'Content-Type': 'text/html' }); res.statusCode = 403; res.write(JSON.stringify(result)); return; } var json = req.query, id = json.id, startDate = json.startDate, endDate = json.endDate, dateNow = new Date(); if (new Date(startDate).getDate() - dateNow.getDate() > 1) { var dateTody = dateNow.getFullYear() + '/' + dateNow.getMonth() + '/' + dateNow.getDate(), startTime = startDate, endTime = startDate = Date.parse(dateTody) - 1 * 24 * 60 * 60 * 1000, cacheResultArr = cacheCount.getCount(id, startTime, endTime); } var cursor = mongoDB.collection('badjslog_' + id).aggregate([ {$match: {'date': {$lt: endDate, $gt: startDate}}}, { $group: { _id: { time: {$dateToString: {format: "%Y-%m-%d %H:%M", date: '$date'}} }, count: {$sum: 1} } }, {$sort: {"_id": 1}} ]); /*cursor.each(function(err,items){ if(!items) return; console.log(items); items.time = new Date(items._id.time).getTime()+28800000; delete items._id; })*/ cursor.toArray(function (err, result) { logger.info('query cost time,queryCount' + Date.now()); if (global.debug == true) { logger.debug("query error is=" + JSON.stringify(err)); logger.debug("query result is=" + JSON.stringify(result)); } if (err) { logger.info('query cost time,[error] queryCount' + JSON.stringify(err)); res.write(JSON.stringify(err)); res.end(); return; } result.forEach(function (item) { item.time = new Date(item._id.time).getTime() + 28800000; delete item._id; }); if (cacheResultArr) { result = cacheResultArr.concat(result); } res.write(JSON.stringify(result)); res.end(); }); /*mongoDB.collection('badjslog_' + id).group( function (data) { var date = new Date(data.date); var dateKey = "" + date.getFullYear() + "-" + date.getMonth() + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes(); return {'day': dateKey}; }, {date: {$lt: endDate, $gt: startDate}}, {count: 0}, function Reduce(data, out) { if (data.level == 4) { out.count++; } }, true, function (err, result) { if (global.debug == true) { logger.debug("query error is=" + JSON.stringify(err)); logger.debug("query result is=" + JSON.stringify(result)) } if (err) { res.write(JSON.stringify(err)); res.end(); return; } res.write(JSON.stringify(result)); res.end(); });*/ }) .use('/errorMsgTop', connect.query()) .use('/errorMsgTop', function (req, res) { var error = validateDate(req.query.startDate) if (error) { res.end(JSON.stringify(error)); return; } req.query.startDate = req.query.startDate - 0; getErrorMsgFromCache(req.query, false, function (error, doc) { logger.info('[errorMsgTop http response] error:'+ error /*+ ', data:' + doc.toString()*/); res.writeHead(200, { 'Content-Type': 'text/json' }); try{ res.write(doc.toString()); }catch(e){ logger.error('/errorMsgTop' + JSON.stringify(req.query) + 'doc: ' + doc); } res.end(); }); }) .use('/errorMsgTopCache', connect.query()) .use('/errorMsgTopCache', function (req, res) { var error = validateDate(req.query.startDate) if (error) { res.end(JSON.stringify(error)); return; } req.query.startDate = req.query.startDate - 0; var startDate = req.query.startDate; res.end(); totalKey = dateFormat(new Date(startDate), "yyyy-MM-dd"); //trigger cacheTotal load in menory from disk cacheTotal.getTotal({id: 0, key: totalKey}); req.query.ids.split("_").forEach(function (value, key) { var fileName = dateFormat(new Date(startDate), "yyyy-MM-dd") + "__" + value; var filePath = path.join(".", "cache", "errorMsg", fileName); logger.info("start cache id=" + value); if (fs.existsSync(filePath)) { logger.info("id=" + value + " had cached"); return; } getErrorMsgFromCache({id: value, startDate: startDate}, false, function (err, doc) { if (err) { logger.info("cache errorMsgTop error fileName=" + fileName + " " + err) } else { logger.info("id = " + value + "cache success"); fs.writeFileSync(filePath, doc); } }); }); }) .use('/errorCountSvg', connect.query()) .use('/errorCountSvg', function (req, res) { logger.info('query start time' + Date.now()); var datePeriod = (parseInt(req.query.datePeriod) || 5) - -1, oneDay = 24 * 60 * 60 * 1000, startTime = req.query.startDate, endTime = req.query.endDate, startDateTime = dateFormat(new Date(startTime -= 0), "yyyy-MM-dd"); req.query.startDate = startTime - datePeriod * oneDay; req.query.endDate = endTime - oneDay; //校验查询req的格式 var result = validate(req, res), resArr = []; if (!result.ok) { res.writeHead(403, { 'Content-Type': 'text/html' }); res.statusCode = 403; res.write(JSON.stringify(result)); return; } var json = req.query, id = json.id, startDate = json.startDate, endDate = json.endDate; cacheCount.getCount(id, startDate, endDate, function (err, result) { result = JSON.parse(result); if (err) { res.write(JSON.stringify(err)); res.end(); return; } if (global.debug == true) { logger.debug('the cache error count query result is ' + JSON.stringify(result)); } if (result.length != 0) { resArr = formateArr(result, startDateTime); if (global.debug == true) { logger.debug('the svg query result is ' + JSON.stringify(resArr.reverse())); } res.write(JSON.stringify(resArr.reverse())); res.end(); return; } var cursor = mongoDB.collection('badjslog_' + id).aggregate([ {$match: {'date': {$lt: endDate, $gt: startDate}}}, { $group: { _id: { time: {$dateToString: {format: "%Y-%m-%d %H:%M", date: '$date'}} }, count: {$sum: 1} } }, {$sort: {"_id": 1}}, ]); cursor.toArray(function (err, result) { logger.info('query cost time' + Date.now()); if (global.debug == true) { logger.debug("query error is=" + JSON.stringify(err)); } if (err) { res.write(JSON.stringify(err)); res.end(); return; } resArr = formateArr(result, startDateTime); if (global.debug == true) { logger.debug('the svg query result is ' + JSON.stringify(resArr.reverse())); } res.write(JSON.stringify(resArr.reverse())); res.end(); return; }); }); }).listen(9000); logger.info('query server start ... ') };
#!/usr/local/bin/node var fs = require("fs"); var args = process.argv.slice(2); fs.writeFileSync("_drafts/" + args[0] + ".md", fs.readFileSync("_drafts/draft-skeleton.md"));
var test = require("tape"), Sandal = require('../sandal.js'); test('Resolve transient factory with singleton dependencies twice', function (t) { var sandal = new Sandal(); var i = 0; var factory1 = function (factory2) { i++; return '' + i + factory2; }; var j = 0; var factory2 = function () { j++; return j.toString(); }; sandal.factory('factory1', factory1, true); sandal.factory('factory2', factory2); t.plan(2); sandal.resolve(function(err, factory1) { t.equal(factory1, '11', 'Should get a new result and dependency result'); }); sandal.resolve(function(err, factory1) { t.equal(factory1,'21', 'Should get a new result and old dependency result'); }); });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require_tree . //= require routesjs-rails
// Writen by Mr.Lu /** * Routes */ var User = require("./user"); var Blog = require("./blog"); var Comment = require("./comment"); var Setting = require("./setting"); module.exports = function(app) { app.get("/", function(req, res) { res.redirect("/home"); }); app.get("/settings", Setting.settingPage); app.get("/user/login", User.loginPage); app.post("/user/login", User.doLogin); app.get("/user/information", User.userInfoPage); app.post("/user/information", User.saveUserInfo); app.get("/user/logout", User.logout); app.get("/user/register", User.registerPage); app.post("/user/register", User.doRegister); app.get("/home", Blog.homePage); app.get("/blog/show/:id", Blog.showBlog); app.get("/blog/new", checkLogin, Blog.newBlogPage); app.post("/blog/new", checkLogin, Blog.newBlog); app.get("/blog/modify/:id", checkLogin, Blog.modifyBlogPage); app.post("/blog/modify/:id", checkLogin, Blog.modifyBlog); app.post("/comment/new", Comment.addComment); function checkLogin(req, res, next) { if(!req.session.user) { return res.redirect("/user/login"); } next(); } }
const crypto = require('crypto'); const { render, redirect } = require('@kelpjs/next/response'); const Application = require('../models/application'); const Authorization = require('../models/authorization'); class App { async index() { const apps = await Application.findAll(); return render('app/index', { apps }); } async create(body) { body.secret = crypto.randomBytes(16).toString('hex'); const app = await Application.create(body); return redirect(`/app/${app.id}`); } async auth(user, query) { const app = await Application.findOne({ where: { id: query.client_id } }); if (!app) return 404; return render('app/auth', { app }); } async accept(query, user) { if (!user) return 403; // res.status(403).send('login required'); const token = crypto.randomBytes(16).toString('hex'); const app = await Application.findOne({ where: { id: query.client_id } }); const auth = await Authorization.create({ appId: app.id, userId: user.id, token }); await user.addSession(auth); return redirect(`${app.callback}?code=${auth.id}`); } async token(query) { // eslint-disable-next-line const { client_id, client_secret, code } = query; const app = await Application.findOne({ where: { id: client_id } }); const auth = await Authorization.findOne({ where: { id: code } }); // eslint-disable-next-line if (app && app.secret === client_secret && auth) { return auth; } return 401; } } module.exports = App;