code
stringlengths
2
1.05M
var Value = require('basis.data').Value; var LS_KEY_HIDE_3RD_PARTY_MODULES = 'wraHide3rdPartyModules'; var hide3rdPartyModules = new Value({ handler: { change: function() { localStorage.setItem(LS_KEY_HIDE_3RD_PARTY_MODULES, this.value); } }, init: function() { Value.prototype.init.call(this); var savedValue = localStorage.getItem(LS_KEY_HIDE_3RD_PARTY_MODULES); var value = true; if (savedValue == 'false') { value = false; } this.set(value); } }); module.exports = { hide3rdPartyModules: hide3rdPartyModules };
var PIXI = require('pixi.js'); var Config = require('../Config'); var Button = require('./Button'); var Intro = function() { this.view = new PIXI.DisplayObjectContainer(); var size = Config.layout.worldSize; this.bg = new PIXI.Graphics(); this.bg.beginFill(0xFFcc00); this.bg.drawRect(-size.w/2, -size.h/2, size.w, size.h); this.bg.endFill(); this.view.addChild(this.bg); this.btnPlay = new Button('play'); this.view.addChild(this.btnPlay.view); this.view.visible = false; } Intro.prototype.show = function() { this.view.visible = true; } Intro.prototype.hide = function() { this.view.visible = false; } Intro.prototype.update = function() { } module.exports = Intro;
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'templates', 'fo', { button: 'Skabelónir', emptyListMsg: '(Ongar skabelónir tøkar)', insertOption: 'Yvirskriva núverandi innihald', options: 'Møguleikar fyri Template', selectPromptMsg: 'Vinarliga vel ta skabelón, ið skal opnast í tekstviðgeranum<br>(Hetta yvirskrivar núverandi innihald):', title: 'Innihaldsskabelónir' } );
/* eslint react/no-array-index-key: "off" */ import PropTypes from 'prop-types'; import React from 'react'; import VideoCardContent from './VideoCardContent'; const VideoCardAttachment = ({ attachment: { content }, disabled }) => ( <VideoCardContent content={content} disabled={disabled} /> ); VideoCardAttachment.defaultProps = { disabled: undefined }; VideoCardAttachment.propTypes = { attachment: PropTypes.shape({ content: PropTypes.shape({ autoloop: PropTypes.bool, autostart: PropTypes.bool, image: PropTypes.shape({ url: PropTypes.string.isRequired }), media: PropTypes.arrayOf( PropTypes.shape({ profile: PropTypes.string.isRequired, url: PropTypes.string }) ) }) }).isRequired, disabled: PropTypes.bool }; export default VideoCardAttachment;
describe('Functional', function() { var data, bindData, el, input; beforeEach(function() { adapter = { subscribe: function(obj, keypath, callback) { obj.on(keypath, callback); }, unsubscribe: function(obj, keypath, callback) { obj.off(keypath, callback); }, read: function(obj, keypath) { return obj.get(keypath); }, publish: function(obj, keypath, value) { attributes = {}; attributes[keypath] = value; obj.set(attributes); } }; rivets.adapters[':'] = adapter; rivets.configure({preloadData: true}); data = new Data({ foo: 'bar', items: [{name: 'a'}, {name: 'b'}] }); bindData = {data: data}; el = document.createElement('div'); input = document.createElement('input'); input.setAttribute('type', 'text'); }); describe('Adapter', function() { it('should read the initial value', function() { spyOn(data, 'get'); el.setAttribute('data-text', 'data:foo'); rivets.bind(el, bindData); expect(data.get).toHaveBeenCalledWith('foo'); }); it('should read the initial value unless preloadData is false', function() { rivets.configure({preloadData: false}); spyOn(data, 'get'); el.setAttribute('data-value', 'data:foo'); rivets.bind(el, bindData); expect(data.get).not.toHaveBeenCalled(); }); it('should subscribe to updates', function() { spyOn(data, 'on'); el.setAttribute('data-value', 'data:foo'); rivets.bind(el, bindData); expect(data.on).toHaveBeenCalled(); }); }); describe('Binds', function() { describe('Text', function() { it('should set the text content of the element', function() { el.setAttribute('data-text', 'data:foo'); rivets.bind(el, bindData); debugger expect(el.textContent || el.innerText).toBe(data.get('foo')); }); it('should correctly handle HTML in the content', function() { el.setAttribute('data-text', 'data:foo'); value = '<b>Fail</b>'; data.set({foo: value}); rivets.bind(el, bindData); expect(el.textContent || el.innerText).toBe(value); }); }); describe('HTML', function() { it('should set the html content of the element', function() { el.setAttribute('data-html', 'data:foo'); rivets.bind(el, bindData); expect(el).toHaveTheTextContent(data.get('foo')); }); it('should correctly handle HTML in the content', function() { el.setAttribute('data-html', 'data:foo'); value = '<b>Fail</b>'; data.set({foo: value}); rivets.bind(el, bindData); expect(el.innerHTML).toBe(value); }); }); describe('Value', function() { it('should set the value of the element', function() { input.setAttribute('data-value', 'data:foo'); rivets.bind(input, bindData); expect(input.value).toBe(data.get('foo')); }); }); describe('Multiple', function() { it('should bind a list of multiple elements', function() { el.setAttribute('data-html', 'data:foo'); input.setAttribute('data-value', 'data:foo'); rivets.bind([el, input], bindData); expect(el).toHaveTheTextContent(data.get('foo')); expect(input.value).toBe(data.get('foo')); }); }); describe('Iteration', function() { beforeEach(function(){ list = document.createElement('ul'); el.appendChild(list); listItem = document.createElement('li'); listItem.setAttribute('data-each-item', 'data:items'); list.appendChild(listItem); }); it('should loop over a collection and create new instances of that element + children', function() { expect(el.getElementsByTagName('li').length).toBe(1); rivets.bind(el, bindData); expect(el.getElementsByTagName('li').length).toBe(2); }); it('should not fail if the collection being bound to is null', function() { data.set({ items: null}); rivets.bind(el, bindData); expect(el.getElementsByTagName('li').length).toBe(0); }); it('should re-loop over the collection and create new instances when the array changes', function() { rivets.bind(el, bindData); expect(el.getElementsByTagName('li').length).toBe(2); newItems = [{name: 'a'}, {name: 'b'}, {name: 'c'}]; data.set({items: newItems}); expect(el.getElementsByTagName('li').length).toBe(3); }); it('should allow binding to the iterated item as well as any parent contexts', function() { span1 = document.createElement('span'); span1.setAttribute('data-text', 'item.name') span2 = document.createElement('span'); span2.setAttribute('data-text', 'data:foo') listItem.appendChild(span1); listItem.appendChild(span2); rivets.bind(el, bindData); expect(el.getElementsByTagName('span')[0]).toHaveTheTextContent('a'); expect(el.getElementsByTagName('span')[1]).toHaveTheTextContent('bar'); }); it('should allow binding to the iterated element directly', function() { listItem.setAttribute('data-text', 'item.name'); listItem.setAttribute('data-class', 'data:foo'); rivets.bind(el, bindData); expect(el.getElementsByTagName('li')[0]).toHaveTheTextContent('a'); expect(el.getElementsByTagName('li')[0].className).toBe('bar'); }); it('should insert items between any surrounding elements', function(){ firstItem = document.createElement('li'); lastItem = document.createElement('li'); firstItem.textContent = 'first'; lastItem.textContent = 'last'; list.appendChild(lastItem); list.insertBefore(firstItem, listItem); listItem.setAttribute('data-text', 'item.name'); rivets.bind(el, bindData); expect(el.getElementsByTagName('li')[0]).toHaveTheTextContent('first'); expect(el.getElementsByTagName('li')[1]).toHaveTheTextContent('a'); expect(el.getElementsByTagName('li')[2]).toHaveTheTextContent('b'); expect(el.getElementsByTagName('li')[3]).toHaveTheTextContent('last'); }); it('should allow binding to the iterated element index', function() { listItem.setAttribute('data-index', 'index'); rivets.bind(el, bindData); expect(el.getElementsByTagName('li')[0].getAttribute('index')).toBe('0') expect(el.getElementsByTagName('li')[1].getAttribute('index')).toBe('1') }); }); }); describe('Updates', function() { it('should change the value', function() { el.setAttribute('data-text', 'data:foo'); rivets.bind(el, bindData); data.set({foo: 'some new value'}); expect(el).toHaveTheTextContent(data.get('foo')); }); }); describe('Input', function() { it('should update the model value', function() { input.setAttribute('data-value', 'data:foo'); rivets.bind(input, bindData); input.value = 'some new value'; var event = document.createEvent('HTMLEvents') event.initEvent('change', true, true); input.dispatchEvent(event); expect(input.value).toBe(data.get('foo')); }); }); });
import _ from 'lodash' import * as actions from 'redux/actions' export default ( dispatch, tournament, startDate, endDate ) => { let body = _.cloneDeep(tournament) body.startDate = startDate body.endDate = endDate dispatch(actions.tournaments.current.update(tournament._id, body)) }
"use strict"; let aliasConf = require('../../../conf/alias.conf'); let path = require('path'); let commandLoader = require('../module/command.loader'); let commandPath = path.join('..', '..'); let commandBlackList = ['core']; /** * 命令别名 * @param argv */ module.exports = (argv) => { commandLoader.loadCommandList(commandPath, commandBlackList, (cmdSettings) => { if (cmdSettings.alias) { for (let i in cmdSettings.alias) if (cmdSettings.alias.hasOwnProperty(i)) { aliasConf[i] = cmdSettings.alias[i]; } } }); let aliasKey = argv.params[0]; if (!aliasConf[aliasKey]) throw new Error('别名 ' + aliasKey + ' 不存在。'); let aliasValue = aliasConf[aliasKey].command || undefined; let commandNPath = path.join(commandPath, aliasValue[0]); let aliasValueClone = aliasValue.concat(); aliasValueClone.unshift('alias'); require(commandNPath)({ argv: aliasValueClone, params: aliasValue.splice(1) }); };
import Code from '../../components/Code' import {Button,SelectTime,Toast} from 'candy-mobile' export default ()=>{ return ( <div> <div className="ct-page__title">时间选择器:</div> <Code>{` <Button type="primary" size="small" onClick={function(){ new SelectTime({ title:'时间选择器', onChange:function(value){ new Toast(value,{type:'success'}); } }); }}>打开选择器</Button> `}</Code> <Button type="primary" size="small" onClick={function(){ new SelectTime({ title:'时间选择器', onChange:function(value){ new Toast(value,{type:'success'}); } }); }}>打开选择器</Button> <div className="ct-page__title">设置开始时间:</div> <Code>{` <Button type="primary" size="small" onClick={function(){ new SelectTime({ start:new Date(), title:'时间选择器', onChange:function(value){ new Toast(value,{type:'success'}); } }); }}>设置开始时间</Button> `}</Code> <Button type="primary" size="small" onClick={function(){ new SelectTime({ start:new Date(), title:'时间选择器', onChange:function(value){ new Toast(value,{type:'success'}); } }); }}>设置开始时间</Button> <div className="ct-page__title">设置结束时间:</div> <Code>{` <Button type="primary" size="small" onClick={function(){ new SelectTime({ end:new Date(), title:'时间选择器', onChange:function(value){ new Toast(value,{type:'success'}); } }); }}>设置结束时间</Button> `}</Code> <Button type="primary" size="small" onClick={function(){ new SelectTime({ end:new Date(), title:'时间选择器', onChange:function(value){ new Toast(value,{type:'success'}); } }); }}>设置结束时间</Button> <div className="ct-page__title">设置当前时间:</div> <Code>{` <Button type="primary" size="small" onClick={function(){ new SelectTime({ current:'10:30', title:'时间选择器', onChange:function(value){ new Toast(value,{type:'success'}); } }); }}>设置当前时间</Button> `}</Code> <Button type="primary" size="small" onClick={function(){ new SelectTime({ current:'10:30', title:'时间选择器', onChange:function(value){ new Toast(value,{type:'success'}); } }); }}>设置当前时间</Button> </div> ); }
import { combine as $combine, pool } from "kefir"; import { isStream, noop } from "./utils"; import combineMiddleware from "./combineMiddleware"; // --- export default function createStore( actions$, reducerInitializers, initialState = {}, { middleware = [] } = {} ) { const stateSources = pool(); const state$ = stateSources .scan( (prev, next = prev) => next, initialState ) .onAny(noop); // activate stream immediately, so store will receive all dispatched actions const reducerParams$ = $combine( [ actions$.filter(({ type }) => type in reducerInitializers) ], // use "passive obs" Kefir feature: // state should be always available in reducer, // but reducers shouldn't run on state update. Only on action dispatched. [ state$.ignoreErrors() ], // ignore errors, because `.combine` does not emit if some of combined streams contains error (action, state) => [ state, action ] ); createReducers( reducerParams$, reducerInitializers, combineMiddleware(middleware) ).forEach(x => stateSources.plug(x)); return state$; } // --- function createReducers(params$, initializers, middleware) { return Object.keys(initializers).map(actionType => initReducer( params$.filter(([ , { type } ]) => type === actionType), initializers[actionType], middleware, actionType // just for debugging )); } function initReducer(params$, initializer, middleware, actionType) { // Whatever happens inside reducer, don't allow for exceptions to ruin app. // So catch everything and pass to errors channel const reducer = initializer(middleware(catchErrors(params$))); if (!isStream(reducer)) { throw new Error(`[init reducer '${actionType}'] Initializer should return stream, but got ${reducer}`); } return reducer; } function catchErrors(stream$) { return stream$.withHandler((emitter, event) => { try { emitter.emitEvent(event); } catch (e) { emitter.error(e); } }); }
var hammerhead = window.getTestCafeModule('hammerhead'); var browserUtils = hammerhead.utils.browser; var featureDetection = hammerhead.utils.featureDetection; var testCafeCore = window.getTestCafeModule('testCafeCore'); var styleUtils = testCafeCore.get('./utils/style'); var testCafeAutomation = window.getTestCafeModule('testCafeAutomation'); var getOffsetOptions = testCafeAutomation.getOffsetOptions; var ClickAutomation = testCafeAutomation.Click; var ClickOptions = testCafeAutomation.get('../../test-run/commands/options').ClickOptions; testCafeCore.preventRealEvents(); $(document).ready(function () { var $el = null; //constants var TEST_ELEMENT_CLASS = 'testElement'; var TEST_DIV_CONTAINER_CLASS = 'testContainer'; //utils var addInputElement = function (type, id, x, y) { var elementString = ['<input type="', type, '" id="', id, '" value="', id, '" />'].join(''); return $(elementString) .css({ position: 'absolute', marginLeft: x + 'px', marginTop: y + 'px' }) .addClass(type) .addClass(TEST_ELEMENT_CLASS) .appendTo('body'); }; var createDiv = function () { return $('<div />'); }; var addDiv = function (x, y) { return createDiv() .css({ position: 'absolute', left: x, top: y, border: '1px solid black' }) .width(150) .height(150) .addClass(TEST_ELEMENT_CLASS) .appendTo('body'); }; var addContainer = function (width, height, outerElement) { return createDiv() .css({ border: '1px solid black', padding: '5px', overflow: 'auto' }) .width(width) .height(height) .addClass(TEST_ELEMENT_CLASS) .addClass(TEST_DIV_CONTAINER_CLASS) .appendTo(outerElement); }; var startNext = function () { if (browserUtils.isIE) { removeTestElements(); window.setTimeout(start, 30); } else start(); }; var removeTestElements = function () { $('.' + TEST_ELEMENT_CLASS).remove(); }; $('<div></div>').css({ width: 1, height: 1500, position: 'absolute' }).appendTo('body'); $('body').css('height', '1500px'); //tests QUnit.testStart(function () { $el = addInputElement('button', 'button1', Math.floor(Math.random() * 100), Math.floor(Math.random() * 100)); }); QUnit.testDone(function () { if (!browserUtils.isIE) removeTestElements(); }); module('dom events tests'); asyncTest('mouse events raised', function () { var mousedownRaised = false; var mouseupRaised = false; var clickRaised = false; $el.mousedown(function () { mousedownRaised = true; ok(!mouseupRaised && !clickRaised, 'mousedown event was raised first'); }); $el.mouseup(function () { mouseupRaised = true; ok(mousedownRaised && !clickRaised, 'mouseup event was raised second'); }); $el.click(function () { clickRaised = true; ok(mousedownRaised && mouseupRaised, 'click event was raised third '); }); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(mousedownRaised && mousedownRaised && clickRaised, 'mouse events were raised'); startNext(); }); }); if (!featureDetection.isTouchDevice) { asyncTest('over and move events on elements during moving', function () { var overed = false; var entered = false; var moved = false; $el .css({ marginTop: '100px', marginLeft: '100px', zIndex: 2 }) .mouseover(function () { overed = true; }) .mouseenter(function () { //B234358 entered = true; }) .mousemove(function () { moved = true; }); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(overed && moved && entered, 'mouse moving events were raised'); startNext(); }); }); } module('click on scrollable element in some scrolled containers'); asyncTest('scroll down and click with offset', function () { var clicked = false; removeTestElements(); var $div1 = addContainer(500, 200, 'body'); var $div2 = addContainer(450, 510, $div1); var $div3 = addContainer(400, 620, $div2); var $div4 = addContainer(350, 1230, $div3); var offsetY = 2350; var containerBorders = styleUtils.getBordersWidth($div4[0]); var containerPadding = styleUtils.getElementPadding($div4[0]); createDiv() .addClass(TEST_ELEMENT_CLASS) .css({ marginTop: offsetY - containerPadding.top - containerBorders.top + 'px', width: '100%', height: '1px', backgroundColor: '#ff0000' }) .bind('mousedown', function () { clicked = true; }) .appendTo($div4); createDiv() .addClass(TEST_ELEMENT_CLASS) .css({ height: '20px', width: '20px', marginTop: 50 + 'px', backgroundColor: '#ffff00' }) .appendTo($div4); var click = new ClickAutomation($div4[0], new ClickOptions({ offsetX: 100, offsetY: offsetY })); click .run() .then(function () { ok(clicked, 'click was raised'); startNext(); }); }); asyncTest('an active input should be blurred and a parent of a disabled input should be focused after a click on the disabled input', function () { var activeInput = document.createElement('input'); var disabledInput = document.createElement('input'); var disabledInputParent = document.createElement('div'); disabledInput.setAttribute('disabled', 'disabled'); disabledInputParent.setAttribute('tabindex', '0'); activeInput.className = disabledInputParent.className = TEST_ELEMENT_CLASS; document.body.appendChild(activeInput); document.body.appendChild(disabledInputParent); disabledInputParent.appendChild(disabledInput); var isActiveInputFocused = false; var isActiveInputBlurred = false; var isDisabledInputParentFocused = false; activeInput.onfocus = function () { isActiveInputFocused = true; }; activeInput.onblur = function () { isActiveInputBlurred = true; }; disabledInputParent.onfocus = function () { isDisabledInputParentFocused = true; }; activeInput.focus(); var click = new ClickAutomation(disabledInput, new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(isActiveInputFocused); ok(isActiveInputBlurred); ok(isDisabledInputParentFocused); startNext(); }); }); asyncTest('scroll up and click with offset', function () { var clicked = false; removeTestElements(); var $div1 = addContainer(500, 200, 'body'); var $div2 = addContainer(450, 510, $div1); var $div3 = addContainer(400, 620, $div2); var $div4 = addContainer(350, 1230, $div3); var offsetY = 50; var containerBorders = styleUtils.getBordersWidth($div4[0]); var containerPadding = styleUtils.getElementPadding($div4[0]); createDiv() .addClass(TEST_ELEMENT_CLASS) .css({ marginTop: offsetY - containerPadding.top - containerBorders.top + 'px', width: '100%', height: '1px', backgroundColor: '#ff0000' }) .bind('mousedown', function () { clicked = true; }) .appendTo($div4); createDiv() .addClass(TEST_ELEMENT_CLASS) .css({ height: '20px', width: '20px', marginTop: 2350 + 'px', backgroundColor: '#ffff00' }) .appendTo($div4); $div1.scrollTop(322); $div2.scrollTop(322); $div3.scrollTop(322); $div4.scrollTop(1186); var click = new ClickAutomation($div4[0], new ClickOptions({ offsetX: 100, offsetY: offsetY })); click .run() .then(function () { ok(clicked, 'click was raised'); startNext(); }); }); module('other functional tests'); asyncTest('click on element in scrolled container', function () { var clicked = false; var $div = addDiv(200, 200) .width(150) .height(150) .css({ overflow: 'scroll' }); var $button = $('<input type="button">') .addClass(TEST_ELEMENT_CLASS) .css({ marginTop: '400px', marginLeft: '80px' }) .bind('mousedown', function () { clicked = true; }) .appendTo($div); var click = new ClickAutomation($button[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(clicked, 'click was raised'); startNext(); }); }); asyncTest('click after scrolling', function () { var clicked = false; $el.css({ 'marginTop': '1000px' }) .click(function () { clicked = true; }); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(clicked, 'click after scrolling was raised'); //moving scroll to start position for a next test var restoreScrollClick = new ClickAutomation(addDiv(200, 500)[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); return restoreScrollClick.run(); }) .then(function () { start(); }); }); asyncTest('focusing on click', function () { var focused = false; $el.css({ display: 'none' }); var $input = addInputElement('text', 'input', 150, 150); $input.focus(function () { focused = true; }); var click = new ClickAutomation($input[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(focused, 'clicked element focused'); startNext(); }); }); asyncTest('double click in the same position', function () { var clicksCount = 0; var el = $el[0]; $el.click(function () { clicksCount++; }); var firstClick = new ClickAutomation(el, new ClickOptions({ offsetX: 5, offsetY: 5 })); firstClick .run() .then(function () { var secondClick = new ClickAutomation(el, new ClickOptions({ offsetX: 5, offsetY: 5 })); return secondClick.run(); }) .then(function () { equal(clicksCount, 2, 'click event was raised twice'); startNext(); }); }); asyncTest('click with options keys', function () { var focused = false; var alt = false; var shift = false; var ctrl = false; var meta = false; $el.css({ display: 'none' }); var $input = addInputElement('text', 'input', 150, 150); $input.focus(function () { focused = true; }); $input.click(function (e) { alt = e.altKey; ctrl = e.ctrlKey; shift = e.shiftKey; meta = e.metaKey; }); var click = new ClickAutomation($input[0], new ClickOptions({ modifiers: { alt: true, ctrl: true, shift: true, meta: true }, offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(focused, 'clicked element focused'); ok(alt, 'alt key is pressed'); ok(shift, 'shift key is pressed'); ok(ctrl, 'ctrl key is pressed'); ok(meta, 'meta key is pressed'); startNext(); }); }); asyncTest('cancel bubble', function () { var divClicked = false; var btnClicked = false; $el.css({ marginTop: '100px', marginLeft: '100px' }); $el[0].onclick = function (e) { e = e || window.event; e.cancelBubble = true; btnClicked = true; }; var $div = addDiv(100, 100) .width(150) .height(150) .click(function () { divClicked = true; }); $el.appendTo($div); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { equal(btnClicked, true, 'button clicked'); equal(divClicked, false, 'bubble canceled'); startNext(); }); }); asyncTest('click on outer element raises event for inner element', function () { var divClicked = false; var btnClicked = false; var $div = addDiv(400, 400) .width(70) .height(30) .click(function () { divClicked = true; }); $el .css({ marginTop: '10px', marginLeft: '10px', position: 'relative' }) .click(function () { btnClicked = true; }) .appendTo($div); var click = new ClickAutomation($div[0], new ClickOptions({ offsetX: 15, offsetY: 15 })); click .run() .then(function () { equal(btnClicked, true, 'button clicked'); equal(divClicked, true, 'div clicked'); startNext(); }); }); asyncTest('click with positive offsets', function () { var eventPoint = null; $el.css({ width: '100px', height: '100px', border: '0px' }); $el.click(function (e) { eventPoint = { x: e.pageX, y: e.pageY }; }); var el = $el[0]; var offsets = getOffsetOptions($el[0], 20, 20); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: offsets.offsetX, offsetY: offsets.offsetY })); click .run() .then(function () { var expectedPoint = { x: el.offsetLeft + 20, y: el.offsetTop + 20 }; deepEqual(eventPoint, expectedPoint, 'event point is correct'); startNext(); }); }); asyncTest('click with negative offsets', function () { var eventPoint = null; $el.css({ width: '100px', height: '100px', border: '0px' }); $el.click(function (e) { eventPoint = { x: e.pageX, y: e.pageY }; }); var el = $el[0]; var offsets = getOffsetOptions($el[0], -20, -20); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: offsets.offsetX, offsetY: offsets.offsetY })); click .run() .then(function () { var expectedPoint = { x: el.offsetLeft + el.offsetWidth - 20, y: el.offsetTop + el.offsetHeight - 20 }; deepEqual(eventPoint, expectedPoint, 'event point is correct'); startNext(); }); }); module('regression'); asyncTest('Q558721 - Test running hangs if element is hidden in non-scrollable container', function () { var clickRaised = false; var $container = $('<div></div>') .addClass(TEST_ELEMENT_CLASS) .css({ width: 100, height: 100, overflow: 'hidden', border: '1px solid green', marginLeft: 50 }) .appendTo('body'); var $button = $('<button>Button</button>') .css({ position: 'relative', left: -60 }).appendTo($container); $(document).click(function () { clickRaised = true; }); var click = new ClickAutomation($button[0], new ClickOptions({ offsetX: 10, offsetY: 10 })); click .run() .then(function () { equal(clickRaised, true, 'button clicked'); startNext(); }); }); asyncTest('B253520 - Blur event is not raised during click playback if previous active element becomes invisible via css on mousedown handler in IE9', function () { var $input = $('<input type="text"/>').addClass(TEST_ELEMENT_CLASS).appendTo('body'); var $button = $('<input type="button"/>').addClass(TEST_ELEMENT_CLASS).appendTo('body'); var inputBlurHandled = false; var waitUntilCssApply = function () { if ($input[0].getBoundingClientRect().width > 0) { var timeout = 2; var startSeconds = (new Date()).getSeconds(); var endSeconds = (startSeconds + timeout) % 60; while ($input[0].getBoundingClientRect().width > 0) { if ((new Date()).getSeconds() > endSeconds) break; } } }; $input.blur(function () { inputBlurHandled = true; }); $button.mousedown(function () { $input.css('display', 'none'); //sometimes (in IE9 for example) element becomes invisible not immediately after css set, we should stop our code and wait waitUntilCssApply(); }); $input[0].focus(); var click = new ClickAutomation($button[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(inputBlurHandled, 'check that input blur event was handled'); startNext(); }); }); asyncTest('mouseup should be called asynchronously after mousedown', function () { var timeoutCalled = false; var mouseupCalled = false; $el.bind('mousedown', function () { window.setTimeout(function () { timeoutCalled = true; }, 0); }); $el.bind('mouseup', function () { mouseupCalled = true; ok(timeoutCalled, 'check timeout setted in mousedown handler was called before mouseup'); }); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(mouseupCalled, 'check mouseup was called'); startNext(); }); }); asyncTest('T163678 - A Click action on a link with a line break does not work', function () { var $box = $('<div></div>').css('width', '128px').appendTo($('body')); var $link = $('<a href="javascript:void(0);">why do I have to break</a>').appendTo($box); var clicked = false; $box.addClass(TEST_ELEMENT_CLASS); $link.click(function () { clicked = true; }); var click = new ClickAutomation($link[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(clicked, 'check mouseup was called'); startNext(); }); }); asyncTest('T224332 - TestCafe problem with click on links in popup menu (click on link with span inside without offset)', function () { var $box = $('<div></div>').css('width', '128px').appendTo($('body')); var $link = $('<a href="javascript:void(0);"></a>').appendTo($box); $('<span>why do I have to break</span>').appendTo($link); var clicked = false; $('input').remove(); $box.addClass(TEST_ELEMENT_CLASS); $link.click(function () { clicked = true; }); var click = new ClickAutomation($link[0], new ClickOptions()); click .run() .then(function () { ok(clicked, 'check mouseup was called'); startNext(); }); }); asyncTest('T224332 - TestCafe problem with click on links in popup menu (click on span inside the link without offset)', function () { var $box = $('<div></div>').css('width', '128px').appendTo($('body')); var $link = $('<a href="javascript:void(0);"></a>').appendTo($box); var $span = $('<span>why do I have to break</span>').appendTo($link); var clicked = false; $box.addClass(TEST_ELEMENT_CLASS); $link.click(function () { clicked = true; }); var click = new ClickAutomation($span[0], new ClickOptions()); click .run() .then(function () { ok(clicked, 'check mouseup was called'); startNext(); }); }); asyncTest('T191183 - pointer event properties are fixed', function () { var mousedownRaised = false; var mouseupRaised = false; var clickRaised = false; $el .mousedown(function (e) { mousedownRaised = true; equal(e.button, 0); if (!browserUtils.isSafari) equal(e.buttons, 1); ok(!mouseupRaised && !clickRaised, 'mousedown event was raised first'); }) .mouseup(function (e) { mouseupRaised = true; equal(e.button, 0); if (!browserUtils.isSafari) equal(e.buttons, 0); ok(mousedownRaised && !clickRaised, 'mouseup event was raised second'); }) .click(function (e) { clickRaised = true; equal(e.button, 0); if (!browserUtils.isSafari) equal(e.buttons, 0); ok(mousedownRaised && mouseupRaised, 'click event was raised third '); }); var pointerHandler = function (e) { equal(e.pointerType, browserUtils.version > 10 ? 'mouse' : 4); equal(e.button, 0); if (e.type === 'pointerdown') equal(e.buttons, 1); if (e.type === 'pointerup') equal(e.buttons, 0); }; if (browserUtils.isIE && browserUtils.version > 11) { $el[0].onpointerdown = pointerHandler; $el[0].onpointerup = pointerHandler; } else { $el[0].onmspointerdown = pointerHandler; $el[0].onmspointerup = pointerHandler; } if (browserUtils.isIE) expect(16); else if (browserUtils.isSafari) expect(7); else expect(10); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(mousedownRaised && mousedownRaised && clickRaised, 'mouse events were raised'); startNext(); }); }); asyncTest('T253883 - Playback - It is impossible to type a password', function () { $el.css({ display: 'none' }); var $label = $('<label></label>') .attr('for', 'input').addClass(TEST_ELEMENT_CLASS) .appendTo('body'); $('<span>label for input</span>') .addClass(TEST_ELEMENT_CLASS) .appendTo($label); var $input = $('<input />') .attr('id', 'input') .addClass(TEST_ELEMENT_CLASS) .appendTo($label); var click = new ClickAutomation($input[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { equal(document.activeElement, $input[0]); startNext(); }); }); asyncTest('T299665 - Incorrect click on image with associated map element in Mozilla', function () { var $map = $('<map name="map"></map>') .appendTo('body') .addClass(TEST_ELEMENT_CLASS); var $area = $('<area shape="rect" coords="0,0,200,200" title="Area"/>').appendTo($map); var $img = $('<img usemap="#map"/>') .attr('src', window.QUnitGlobals.getResourceUrl('../../data/runner/img.png')) .css({ width: '200px', height: '200px' }) .appendTo('body') .addClass(TEST_ELEMENT_CLASS); function clickHandler (e) { if (this === e.target) $(this).data('clicked', true); } $('#button1').remove(); $area.click(clickHandler); $img.click(clickHandler); window.setTimeout(function () { var click = new ClickAutomation($area[0], new ClickOptions({ offsetX: 10, offsetY: 10 })); click .run() .then(function () { ok($area.data('clicked'), 'area element was clicked'); notOk($img.data('clicked'), 'img element was not clicked'); startNext(); }); }, 1500); }); module('touch devices test'); if (featureDetection.isTouchDevice) { asyncTest('touch event on click', function () { var event = null; var events = { ontouchstart: false, ontouchend: false, onmousedown: false, onmouseup: false, onclick: false }; var bind = function (eventName) { $el[0][eventName] = function () { events[eventName] = true; }; }; for (event in events) bind(event); var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { for (event in events) ok(events[event], event + ' raised'); startNext(); }); }); asyncTest('event touch lists length (T170088)', function () { var raisedEvents = []; var touchEventHandler = function (ev) { raisedEvents.push(ev.type); equal(ev.touches.length, ev.type === 'touchend' ? 0 : 1); equal(ev.targetTouches.length, ev.type === 'touchend' ? 0 : 1); equal(ev.changedTouches.length, 1); }; $el[0].ontouchstart = $el[0].ontouchmove = $el[0].ontouchend = touchEventHandler; var click = new ClickAutomation($el[0], new ClickOptions({ offsetX: 5, offsetY: 5 })); click .run() .then(function () { ok(raisedEvents.indexOf('touchstart') >= 0); ok(raisedEvents.indexOf('touchend') >= 0); startNext(); }); }); } });
/*! Hammer.JS - v2.0.4 - 2014-09-28 * http://hammerjs.github.io/ * * Copyright (c) 2014 Jorik Tangelder; * Licensed under the MIT license */ if (Object.create) { !function (a, b, c, d) { "use strict"; function e(a, b, c) { return setTimeout(k(a, c), b) } function f(a, b, c) { return Array.isArray(a) ? (g(a, c[b], c), !0) : !1 } function g(a, b, c) { var e; if (a) if (a.forEach) a.forEach(b, c); else if (a.length !== d) for (e = 0; e < a.length;) b.call(c, a[e], e, a), e++; else for (e in a) a.hasOwnProperty(e) && b.call(c, a[e], e, a) } function h(a, b, c) { for (var e = Object.keys(b), f = 0; f < e.length;) (!c || c && a[e[f]] === d) && (a[e[f]] = b[e[f]]), f++; return a } function i(a, b) { return h(a, b, !0) } function j(a, b, c) { var d, e = b.prototype; d = a.prototype = Object.create(e), d.constructor = a, d._super = e, c && h(d, c) } function k(a, b) { return function () { return a.apply(b, arguments) } } function l(a, b) { return typeof a == kb ? a.apply(b ? b[0] || d : d, b) : a } function m(a, b) { return a === d ? b : a } function n(a, b, c) { g(r(b), function (b) { a.addEventListener(b, c, !1) }) } function o(a, b, c) { g(r(b), function (b) { a.removeEventListener(b, c, !1) }) } function p(a, b) { for (; a;) { if (a == b) return !0; a = a.parentNode } return !1 } function q(a, b) { return a.indexOf(b) > -1 } function r(a) { return a.trim().split(/\s+/g) } function s(a, b, c) { if (a.indexOf && !c) return a.indexOf(b); for (var d = 0; d < a.length;) { if (c && a[d][c] == b || !c && a[d] === b) return d; d++ } return -1 } function t(a) { return Array.prototype.slice.call(a, 0) } function u(a, b, c) { for (var d = [], e = [], f = 0; f < a.length;) { var g = b ? a[f][b] : a[f]; s(e, g) < 0 && d.push(a[f]), e[f] = g, f++ } return c && (d = b ? d.sort(function (a, c) { return a[b] > c[b] }) : d.sort()), d } function v(a, b) { for (var c, e, f = b[0].toUpperCase() + b.slice(1), g = 0; g < ib.length;) { if (c = ib[g], e = c ? c + f : b, e in a) return e; g++ } return d } function w() { return ob++ } function x(a) { var b = a.ownerDocument; return b.defaultView || b.parentWindow } function y(a, b) { var c = this; this.manager = a, this.callback = b, this.element = a.element, this.target = a.options.inputTarget, this.domHandler = function (b) { l(a.options.enable, [a]) && c.handler(b) }, this.init() } function z(a) { var b, c = a.options.inputClass; return new (b = c ? c : rb ? N : sb ? Q : qb ? S : M)(a, A) } function A(a, b, c) { var d = c.pointers.length, e = c.changedPointers.length, f = b & yb && d - e === 0, g = b & (Ab | Bb) && d - e === 0; c.isFirst = !!f, c.isFinal = !!g, f && (a.session = {}), c.eventType = b, B(a, c), a.emit("hammer.input", c), a.recognize(c), a.session.prevInput = c } function B(a, b) { var c = a.session, d = b.pointers, e = d.length; c.firstInput || (c.firstInput = E(b)), e > 1 && !c.firstMultiple ? c.firstMultiple = E(b) : 1 === e && (c.firstMultiple = !1); var f = c.firstInput, g = c.firstMultiple, h = g ? g.center : f.center, i = b.center = F(d); b.timeStamp = nb(), b.deltaTime = b.timeStamp - f.timeStamp, b.angle = J(h, i), b.distance = I(h, i), C(c, b), b.offsetDirection = H(b.deltaX, b.deltaY), b.scale = g ? L(g.pointers, d) : 1, b.rotation = g ? K(g.pointers, d) : 0, D(c, b); var j = a.element; p(b.srcEvent.target, j) && (j = b.srcEvent.target), b.target = j } function C(a, b) { var c = b.center, d = a.offsetDelta || {}, e = a.prevDelta || {}, f = a.prevInput || {}; (b.eventType === yb || f.eventType === Ab) && (e = a.prevDelta = { x: f.deltaX || 0, y: f.deltaY || 0 }, d = a.offsetDelta = {x: c.x, y: c.y}), b.deltaX = e.x + (c.x - d.x), b.deltaY = e.y + (c.y - d.y) } function D(a, b) { var c, e, f, g, h = a.lastInterval || b, i = b.timeStamp - h.timeStamp; if (b.eventType != Bb && (i > xb || h.velocity === d)) { var j = h.deltaX - b.deltaX, k = h.deltaY - b.deltaY, l = G(i, j, k); e = l.x, f = l.y, c = mb(l.x) > mb(l.y) ? l.x : l.y, g = H(j, k), a.lastInterval = b } else c = h.velocity, e = h.velocityX, f = h.velocityY, g = h.direction; b.velocity = c, b.velocityX = e, b.velocityY = f, b.direction = g } function E(a) { for (var b = [], c = 0; c < a.pointers.length;) b[c] = { clientX: lb(a.pointers[c].clientX), clientY: lb(a.pointers[c].clientY) }, c++; return {timeStamp: nb(), pointers: b, center: F(b), deltaX: a.deltaX, deltaY: a.deltaY} } function F(a) { var b = a.length; if (1 === b) return {x: lb(a[0].clientX), y: lb(a[0].clientY)}; for (var c = 0, d = 0, e = 0; b > e;) c += a[e].clientX, d += a[e].clientY, e++; return {x: lb(c / b), y: lb(d / b)} } function G(a, b, c) { return {x: b / a || 0, y: c / a || 0} } function H(a, b) { return a === b ? Cb : mb(a) >= mb(b) ? a > 0 ? Db : Eb : b > 0 ? Fb : Gb } function I(a, b, c) { c || (c = Kb); var d = b[c[0]] - a[c[0]], e = b[c[1]] - a[c[1]]; return Math.sqrt(d * d + e * e) } function J(a, b, c) { c || (c = Kb); var d = b[c[0]] - a[c[0]], e = b[c[1]] - a[c[1]]; return 180 * Math.atan2(e, d) / Math.PI } function K(a, b) { return J(b[1], b[0], Lb) - J(a[1], a[0], Lb) } function L(a, b) { return I(b[0], b[1], Lb) / I(a[0], a[1], Lb) } function M() { this.evEl = Nb, this.evWin = Ob, this.allow = !0, this.pressed = !1, y.apply(this, arguments) } function N() { this.evEl = Rb, this.evWin = Sb, y.apply(this, arguments), this.store = this.manager.session.pointerEvents = [] } function O() { this.evTarget = Ub, this.evWin = Vb, this.started = !1, y.apply(this, arguments) } function P(a, b) { var c = t(a.touches), d = t(a.changedTouches); return b & (Ab | Bb) && (c = u(c.concat(d), "identifier", !0)), [c, d] } function Q() { this.evTarget = Xb, this.targetIds = {}, y.apply(this, arguments) } function R(a, b) { var c = t(a.touches), d = this.targetIds; if (b & (yb | zb) && 1 === c.length) return d[c[0].identifier] = !0, [c, c]; var e, f, g = t(a.changedTouches), h = [], i = this.target; if (f = c.filter(function (a) { return p(a.target, i) }), b === yb) for (e = 0; e < f.length;) d[f[e].identifier] = !0, e++; for (e = 0; e < g.length;) d[g[e].identifier] && h.push(g[e]), b & (Ab | Bb) && delete d[g[e].identifier], e++; return h.length ? [u(f.concat(h), "identifier", !0), h] : void 0 } function S() { y.apply(this, arguments); var a = k(this.handler, this); this.touch = new Q(this.manager, a), this.mouse = new M(this.manager, a) } function T(a, b) { this.manager = a, this.set(b) } function U(a) { if (q(a, bc)) return bc; var b = q(a, cc), c = q(a, dc); return b && c ? cc + " " + dc : b || c ? b ? cc : dc : q(a, ac) ? ac : _b } function V(a) { this.id = w(), this.manager = null, this.options = i(a || {}, this.defaults), this.options.enable = m(this.options.enable, !0), this.state = ec, this.simultaneous = {}, this.requireFail = [] } function W(a) { return a & jc ? "cancel" : a & hc ? "end" : a & gc ? "move" : a & fc ? "start" : "" } function X(a) { return a == Gb ? "down" : a == Fb ? "up" : a == Db ? "left" : a == Eb ? "right" : "" } function Y(a, b) { var c = b.manager; return c ? c.get(a) : a } function Z() { V.apply(this, arguments) } function $() { Z.apply(this, arguments), this.pX = null, this.pY = null } function _() { Z.apply(this, arguments) } function ab() { V.apply(this, arguments), this._timer = null, this._input = null } function bb() { Z.apply(this, arguments) } function cb() { Z.apply(this, arguments) } function db() { V.apply(this, arguments), this.pTime = !1, this.pCenter = !1, this._timer = null, this._input = null, this.count = 0 } function eb(a, b) { return b = b || {}, b.recognizers = m(b.recognizers, eb.defaults.preset), new fb(a, b) } function fb(a, b) { b = b || {}, this.options = i(b, eb.defaults), this.options.inputTarget = this.options.inputTarget || a, this.handlers = {}, this.session = {}, this.recognizers = [], this.element = a, this.input = z(this), this.touchAction = new T(this, this.options.touchAction), gb(this, !0), g(b.recognizers, function (a) { var b = this.add(new a[0](a[1])); a[2] && b.recognizeWith(a[2]), a[3] && b.requireFailure(a[3]) }, this) } function gb(a, b) { var c = a.element; g(a.options.cssProps, function (a, d) { c.style[v(c.style, d)] = b ? a : "" }) } function hb(a, c) { var d = b.createEvent("Event"); d.initEvent(a, !0, !0), d.gesture = c, c.target.dispatchEvent(d) } var ib = ["", "webkit", "moz", "MS", "ms", "o"], jb = b.createElement("div"), kb = "function", lb = Math.round, mb = Math.abs, nb = Date.now, ob = 1, pb = /mobile|tablet|ip(ad|hone|od)|android/i, qb = "ontouchstart" in a, rb = v(a, "PointerEvent") !== d, sb = qb && pb.test(navigator.userAgent), tb = "touch", ub = "pen", vb = "mouse", wb = "kinect", xb = 25, yb = 1, zb = 2, Ab = 4, Bb = 8, Cb = 1, Db = 2, Eb = 4, Fb = 8, Gb = 16, Hb = Db | Eb, Ib = Fb | Gb, Jb = Hb | Ib, Kb = ["x", "y"], Lb = ["clientX", "clientY"]; y.prototype = { handler: function () { }, init: function () { this.evEl && n(this.element, this.evEl, this.domHandler), this.evTarget && n(this.target, this.evTarget, this.domHandler), this.evWin && n(x(this.element), this.evWin, this.domHandler) }, destroy: function () { this.evEl && o(this.element, this.evEl, this.domHandler), this.evTarget && o(this.target, this.evTarget, this.domHandler), this.evWin && o(x(this.element), this.evWin, this.domHandler) } }; var Mb = {mousedown: yb, mousemove: zb, mouseup: Ab}, Nb = "mousedown", Ob = "mousemove mouseup"; j(M, y, { handler: function (a) { var b = Mb[a.type]; b & yb && 0 === a.button && (this.pressed = !0), b & zb && 1 !== a.which && (b = Ab), this.pressed && this.allow && (b & Ab && (this.pressed = !1), this.callback(this.manager, b, { pointers: [a], changedPointers: [a], pointerType: vb, srcEvent: a })) } }); var Pb = {pointerdown: yb, pointermove: zb, pointerup: Ab, pointercancel: Bb, pointerout: Bb}, Qb = { 2: tb, 3: ub, 4: vb, 5: wb }, Rb = "pointerdown", Sb = "pointermove pointerup pointercancel"; a.MSPointerEvent && (Rb = "MSPointerDown", Sb = "MSPointerMove MSPointerUp MSPointerCancel"), j(N, y, { handler: function (a) { var b = this.store, c = !1, d = a.type.toLowerCase().replace("ms", ""), e = Pb[d], f = Qb[a.pointerType] || a.pointerType, g = f == tb, h = s(b, a.pointerId, "pointerId"); e & yb && (0 === a.button || g) ? 0 > h && (b.push(a), h = b.length - 1) : e & (Ab | Bb) && (c = !0), 0 > h || (b[h] = a, this.callback(this.manager, e, { pointers: b, changedPointers: [a], pointerType: f, srcEvent: a }), c && b.splice(h, 1)) } }); var Tb = { touchstart: yb, touchmove: zb, touchend: Ab, touchcancel: Bb }, Ub = "touchstart", Vb = "touchstart touchmove touchend touchcancel"; j(O, y, { handler: function (a) { var b = Tb[a.type]; if (b === yb && (this.started = !0), this.started) { var c = P.call(this, a, b); b & (Ab | Bb) && c[0].length - c[1].length === 0 && (this.started = !1), this.callback(this.manager, b, { pointers: c[0], changedPointers: c[1], pointerType: tb, srcEvent: a }) } } }); var Wb = { touchstart: yb, touchmove: zb, touchend: Ab, touchcancel: Bb }, Xb = "touchstart touchmove touchend touchcancel"; j(Q, y, { handler: function (a) { var b = Wb[a.type], c = R.call(this, a, b); c && this.callback(this.manager, b, { pointers: c[0], changedPointers: c[1], pointerType: tb, srcEvent: a }) } }), j(S, y, { handler: function (a, b, c) { var d = c.pointerType == tb, e = c.pointerType == vb; if (d) this.mouse.allow = !1; else if (e && !this.mouse.allow) return; b & (Ab | Bb) && (this.mouse.allow = !0), this.callback(a, b, c) }, destroy: function () { this.touch.destroy(), this.mouse.destroy() } }); var Yb = v(jb.style, "touchAction"), Zb = Yb !== d, $b = "compute", _b = "auto", ac = "manipulation", bc = "none", cc = "pan-x", dc = "pan-y"; T.prototype = { set: function (a) { a == $b && (a = this.compute()), Zb && (this.manager.element.style[Yb] = a), this.actions = a.toLowerCase().trim() }, update: function () { this.set(this.manager.options.touchAction) }, compute: function () { var a = []; return g(this.manager.recognizers, function (b) { l(b.options.enable, [b]) && (a = a.concat(b.getTouchAction())) }), U(a.join(" ")) }, preventDefaults: function (a) { if (!Zb) { var b = a.srcEvent, c = a.offsetDirection; if (this.manager.session.prevented) return void b.preventDefault(); var d = this.actions, e = q(d, bc), f = q(d, dc), g = q(d, cc); return e || f && c & Hb || g && c & Ib ? this.preventSrc(b) : void 0 } }, preventSrc: function (a) { this.manager.session.prevented = !0, a.preventDefault() } }; var ec = 1, fc = 2, gc = 4, hc = 8, ic = hc, jc = 16, kc = 32; V.prototype = { defaults: {}, set: function (a) { return h(this.options, a), this.manager && this.manager.touchAction.update(), this }, recognizeWith: function (a) { if (f(a, "recognizeWith", this)) return this; var b = this.simultaneous; return a = Y(a, this), b[a.id] || (b[a.id] = a, a.recognizeWith(this)), this }, dropRecognizeWith: function (a) { return f(a, "dropRecognizeWith", this) ? this : (a = Y(a, this), delete this.simultaneous[a.id], this) }, requireFailure: function (a) { if (f(a, "requireFailure", this)) return this; var b = this.requireFail; return a = Y(a, this), -1 === s(b, a) && (b.push(a), a.requireFailure(this)), this }, dropRequireFailure: function (a) { if (f(a, "dropRequireFailure", this)) return this; a = Y(a, this); var b = s(this.requireFail, a); return b > -1 && this.requireFail.splice(b, 1), this }, hasRequireFailures: function () { return this.requireFail.length > 0 }, canRecognizeWith: function (a) { return !!this.simultaneous[a.id] }, emit: function (a) { function b(b) { c.manager.emit(c.options.event + (b ? W(d) : ""), a) } var c = this, d = this.state; hc > d && b(!0), b(), d >= hc && b(!0) }, tryEmit: function (a) { return this.canEmit() ? this.emit(a) : void(this.state = kc) }, canEmit: function () { for (var a = 0; a < this.requireFail.length;) { if (!(this.requireFail[a].state & (kc | ec))) return !1; a++ } return !0 }, recognize: function (a) { var b = h({}, a); return l(this.options.enable, [this, b]) ? (this.state & (ic | jc | kc) && (this.state = ec), this.state = this.process(b), void(this.state & (fc | gc | hc | jc) && this.tryEmit(b))) : (this.reset(), void(this.state = kc)) }, process: function () { }, getTouchAction: function () { }, reset: function () { } }, j(Z, V, { defaults: {pointers: 1}, attrTest: function (a) { var b = this.options.pointers; return 0 === b || a.pointers.length === b }, process: function (a) { var b = this.state, c = a.eventType, d = b & (fc | gc), e = this.attrTest(a); return d && (c & Bb || !e) ? b | jc : d || e ? c & Ab ? b | hc : b & fc ? b | gc : fc : kc } }), j($, Z, { defaults: {event: "pan", threshold: 10, pointers: 1, direction: Jb}, getTouchAction: function () { var a = this.options.direction, b = []; return a & Hb && b.push(dc), a & Ib && b.push(cc), b }, directionTest: function (a) { var b = this.options, c = !0, d = a.distance, e = a.direction, f = a.deltaX, g = a.deltaY; return e & b.direction || (b.direction & Hb ? (e = 0 === f ? Cb : 0 > f ? Db : Eb, c = f != this.pX, d = Math.abs(a.deltaX)) : (e = 0 === g ? Cb : 0 > g ? Fb : Gb, c = g != this.pY, d = Math.abs(a.deltaY))), a.direction = e, c && d > b.threshold && e & b.direction }, attrTest: function (a) { return Z.prototype.attrTest.call(this, a) && (this.state & fc || !(this.state & fc) && this.directionTest(a)) }, emit: function (a) { this.pX = a.deltaX, this.pY = a.deltaY; var b = X(a.direction); b && this.manager.emit(this.options.event + b, a), this._super.emit.call(this, a) } }), j(_, Z, { defaults: {event: "pinch", threshold: 0, pointers: 2}, getTouchAction: function () { return [bc] }, attrTest: function (a) { return this._super.attrTest.call(this, a) && (Math.abs(a.scale - 1) > this.options.threshold || this.state & fc) }, emit: function (a) { if (this._super.emit.call(this, a), 1 !== a.scale) { var b = a.scale < 1 ? "in" : "out"; this.manager.emit(this.options.event + b, a) } } }), j(ab, V, { defaults: {event: "press", pointers: 1, time: 500, threshold: 5}, getTouchAction: function () { return [_b] }, process: function (a) { var b = this.options, c = a.pointers.length === b.pointers, d = a.distance < b.threshold, f = a.deltaTime > b.time; if (this._input = a, !d || !c || a.eventType & (Ab | Bb) && !f) this.reset(); else if (a.eventType & yb) this.reset(), this._timer = e(function () { this.state = ic, this.tryEmit() }, b.time, this); else if (a.eventType & Ab) return ic; return kc }, reset: function () { clearTimeout(this._timer) }, emit: function (a) { this.state === ic && (a && a.eventType & Ab ? this.manager.emit(this.options.event + "up", a) : (this._input.timeStamp = nb(), this.manager.emit(this.options.event, this._input))) } }), j(bb, Z, { defaults: {event: "rotate", threshold: 0, pointers: 2}, getTouchAction: function () { return [bc] }, attrTest: function (a) { return this._super.attrTest.call(this, a) && (Math.abs(a.rotation) > this.options.threshold || this.state & fc) } }), j(cb, Z, { defaults: {event: "swipe", threshold: 10, velocity: .65, direction: Hb | Ib, pointers: 1}, getTouchAction: function () { return $.prototype.getTouchAction.call(this) }, attrTest: function (a) { var b, c = this.options.direction; return c & (Hb | Ib) ? b = a.velocity : c & Hb ? b = a.velocityX : c & Ib && (b = a.velocityY), this._super.attrTest.call(this, a) && c & a.direction && a.distance > this.options.threshold && mb(b) > this.options.velocity && a.eventType & Ab }, emit: function (a) { var b = X(a.direction); b && this.manager.emit(this.options.event + b, a), this.manager.emit(this.options.event, a) } }), j(db, V, { defaults: { event: "tap", pointers: 1, taps: 1, interval: 300, time: 250, threshold: 2, posThreshold: 10 }, getTouchAction: function () { return [ac] }, process: function (a) { var b = this.options, c = a.pointers.length === b.pointers, d = a.distance < b.threshold, f = a.deltaTime < b.time; if (this.reset(), a.eventType & yb && 0 === this.count) return this.failTimeout(); if (d && f && c) { if (a.eventType != Ab) return this.failTimeout(); var g = this.pTime ? a.timeStamp - this.pTime < b.interval : !0, h = !this.pCenter || I(this.pCenter, a.center) < b.posThreshold; this.pTime = a.timeStamp, this.pCenter = a.center, h && g ? this.count += 1 : this.count = 1, this._input = a; var i = this.count % b.taps; if (0 === i) return this.hasRequireFailures() ? (this._timer = e(function () { this.state = ic, this.tryEmit() }, b.interval, this), fc) : ic } return kc }, failTimeout: function () { return this._timer = e(function () { this.state = kc }, this.options.interval, this), kc }, reset: function () { clearTimeout(this._timer) }, emit: function () { this.state == ic && (this._input.tapCount = this.count, this.manager.emit(this.options.event, this._input)) } }), eb.VERSION = "2.0.4", eb.defaults = { domEvents: !1, touchAction: $b, enable: !0, inputTarget: null, inputClass: null, preset: [[bb, {enable: !1}], [_, {enable: !1}, ["rotate"]], [cb, {direction: Hb}], [$, {direction: Hb}, ["swipe"]], [db], [db, { event: "doubletap", taps: 2 }, ["tap"]], [ab]], cssProps: { userSelect: "none", touchSelect: "none", touchCallout: "none", contentZooming: "none", userDrag: "none", tapHighlightColor: "rgba(0,0,0,0)" } }; var lc = 1, mc = 2; fb.prototype = { set: function (a) { return h(this.options, a), a.touchAction && this.touchAction.update(), a.inputTarget && (this.input.destroy(), this.input.target = a.inputTarget, this.input.init()), this }, stop: function (a) { this.session.stopped = a ? mc : lc }, recognize: function (a) { var b = this.session; if (!b.stopped) { this.touchAction.preventDefaults(a); var c, d = this.recognizers, e = b.curRecognizer; (!e || e && e.state & ic) && (e = b.curRecognizer = null); for (var f = 0; f < d.length;) c = d[f], b.stopped === mc || e && c != e && !c.canRecognizeWith(e) ? c.reset() : c.recognize(a), !e && c.state & (fc | gc | hc) && (e = b.curRecognizer = c), f++ } }, get: function (a) { if (a instanceof V) return a; for (var b = this.recognizers, c = 0; c < b.length; c++) if (b[c].options.event == a) return b[c]; return null }, add: function (a) { if (f(a, "add", this)) return this; var b = this.get(a.options.event); return b && this.remove(b), this.recognizers.push(a), a.manager = this, this.touchAction.update(), a }, remove: function (a) { if (f(a, "remove", this)) return this; var b = this.recognizers; return a = this.get(a), b.splice(s(b, a), 1), this.touchAction.update(), this }, on: function (a, b) { var c = this.handlers; return g(r(a), function (a) { c[a] = c[a] || [], c[a].push(b) }), this }, off: function (a, b) { var c = this.handlers; return g(r(a), function (a) { b ? c[a].splice(s(c[a], b), 1) : delete c[a] }), this }, emit: function (a, b) { this.options.domEvents && hb(a, b); var c = this.handlers[a] && this.handlers[a].slice(); if (c && c.length) { b.type = a, b.preventDefault = function () { b.srcEvent.preventDefault() }; for (var d = 0; d < c.length;) c[d](b), d++ } }, destroy: function () { this.element && gb(this, !1), this.handlers = {}, this.session = {}, this.input.destroy(), this.element = null } }, h(eb, { INPUT_START: yb, INPUT_MOVE: zb, INPUT_END: Ab, INPUT_CANCEL: Bb, STATE_POSSIBLE: ec, STATE_BEGAN: fc, STATE_CHANGED: gc, STATE_ENDED: hc, STATE_RECOGNIZED: ic, STATE_CANCELLED: jc, STATE_FAILED: kc, DIRECTION_NONE: Cb, DIRECTION_LEFT: Db, DIRECTION_RIGHT: Eb, DIRECTION_UP: Fb, DIRECTION_DOWN: Gb, DIRECTION_HORIZONTAL: Hb, DIRECTION_VERTICAL: Ib, DIRECTION_ALL: Jb, Manager: fb, Input: y, TouchAction: T, TouchInput: Q, MouseInput: M, PointerEventInput: N, TouchMouseInput: S, SingleTouchInput: O, Recognizer: V, AttrRecognizer: Z, Tap: db, Pan: $, Swipe: cb, Pinch: _, Rotate: bb, Press: ab, on: n, off: o, each: g, merge: i, extend: h, inherit: j, bindFn: k, prefixed: v }), typeof define == kb && define.amd ? define(function () { return eb }) : "undefined" != typeof module && module.exports ? module.exports = eb : a[c] = eb }(window, document, "Hammer"); }
const balboa = require('..') balboa().listen(3000) console.log('Proxy server listening on port:', 3000)
module.exports = { 'apisModel': require('./lampAPI'), 'accountsModel': require('./accounts') }
import { normalize, schema } from 'normalizr'; const users = [ { id: 1, name: 'Roza', avatar: 'https://pickaface.net/assets/images/slides/slide1.png', }, { id: 2, name: 'Peter', avatar: 'https://pickaface.net/assets/images/slides/slide2.png', }, { id: 3, name: 'Sam', avatar: 'https://pickaface.net/assets/images/slides/slide4.png', }, { id: 4, name: 'Jane', avatar: 'https://pickaface.net/assets/images/slides/slide3.png', } ]; const usersSchema = new schema.Entity('users'); export function getUsers() { return normalize(users, [usersSchema]).entities.users; }
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _propTypes = require('prop-types'); var _propTypes2 = _interopRequireDefault(_propTypes); var _classnames = require('classnames'); var _classnames2 = _interopRequireDefault(_classnames); var _index = require('../../../index.js'); require('../../blok.css'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Footer = function Footer(props) { var color = props.color, link = props.link, text = props.text, transparent = props.transparent; var blokFooterClass = (0, _classnames2.default)({ 'blok-footer': true, 'transparent': transparent }); var blokFooterLinkClass = (0, _classnames2.default)({ 'blok-footer-link': true, 'blok-footer-nav': true }); var linkData = link.map(function (data, key) { return _react2.default.createElement(_index.Link, { key: key, text: data.text, linkRef: data.linkRef, active: data.active, type: 'nav' }); }); return _react2.default.createElement( _index.Grid, { color: color, className: blokFooterClass }, _react2.default.createElement( _index.Grid.Row, null, _react2.default.createElement( _index.Grid.Column, { width: 12, textAlign: 'middle', className: blokFooterLinkClass }, linkData ), _react2.default.createElement( _index.Grid.Column, { width: 12, textAlign: 'middle' }, _react2.default.createElement(_index.Text, { tag: 'p', font: 'body', size: 'text', text: text }) ) ) ); }; Footer.propTypes = { /* Set The Color Scheme - REPLACE WITH THEME */ color: _propTypes2.default.string, /* Create The Footer Navigation */ link: _propTypes2.default.array, /* Set The Content For Text Message */ text: _propTypes2.default.string, /* Set Transparency Of Background */ transparent: _propTypes2.default.bool }; Footer.defaultProps = { color: 'white' }; exports.default = Footer;
var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var User = require('../models/User.js'); var auth = require('../auth/auth.js'); var tokenHelper = require('../auth/tokenHelper.js'); var nodemailer = require('nodemailer'); // create reusable transporter object using SMTP transport var transporter = nodemailer.createTransport({ host: '10.10.10.231', port: 25, tls:{rejectUnauthorized: false} }); /* GET /user/info. */ router.get('/info', auth.verify, function(req, res, next) { User.findById( req._user.id, 'username fullname email is_admin settings favoriteRecipes', function (err, user) { if (err) return next(err); res.json(user); }); }); /* PUT /user/info */ router.put('/info/:id', auth.verify, function(req, res, next) { var fullname = req.body.fullname || ''; var settings = req.body.settings || ''; if (fullname == '' || settings == '') { return res.send(401); } var userInfo = {fullname: req.body.fullname, settings: req.body.settings}; User.findByIdAndUpdate(req._user.id, userInfo, { 'new': true}).select('username fullname email is_admin settings favoriteRecipes').exec( function (err, user) { if (err) return next(err); res.json(user); }); }); /* GET /user/info/id */ router.get('/info/:id', auth.verify, function(req, res, next) { User.findById(req.params.id, 'fullname', function (err, user) { if (err) return next(err); res.json(user); }); }); /* ADD or DELETE /user/favorites/:id */ router.put('/favorites/:id', auth.verify, function(req, res, next) { if (req.body.method == "delete"){ User.findByIdAndUpdate(req._user.id, {$pull: {favoriteRecipes: req.params.id}}, { 'new': true}).select('username fullname email is_admin settings favoriteRecipes').exec( function (err, user) { if (err) return next(err); res.json(user); }); } else if (req.body.method == "add"){ User.findByIdAndUpdate(req._user.id, {$push: {favoriteRecipes: req.params.id}}, { 'new': true}).select('username fullname email is_admin settings favoriteRecipes').exec( function (err, user) { if (err) return next(err); res.json(user); }); } }); /* GET /user/check */ router.get('/check', auth.verify, function(req, res, next) { return res.sendStatus(200); }); /* LOGIN */ router.post('/login', function(req, res, next) { //verify credential (use POST) var username = req.body.username.toLowerCase() || ''; var password = req.body.password || ''; var autologin = req.body.autologin || false; if (username == '' || password == '') { return res.send(401); } User.findOne({username_lower: username}, function (err, user) { if (err) { console.log(err); return res.sendStatus(401); } if (user == undefined) { console.log("User undefined"); return res.sendStatus(401); } if (user.is_activated === false) { console.log("User not activated"); return res.sendStatus(401); } console.log(user); user.comparePassword(password, function(isMatch) { if (!isMatch) { console.log("Attempt failed to login with " + user.username); return res.sendStatus(401); } var userDataForRedis = {id: user._id, username: user.username, is_admin: user.is_admin, autologin: autologin}; var userData = user; var expiration = 300; // 5 minutes if (autologin === true) { expiration = 60*60*24*30; //30 days } auth.createAndStoreToken(userDataForRedis, expiration, function(err, token) { if (err) { console.log(err); return res.sendStatus(400); } //Send back token return res.json({token: token, is_admin: userData.is_admin, email: userData.email, fullname: userData.fullname, _id: userData._id, username: userData.username, settings: userData.settings}); }); }); }); }); /* LOGOUT */ router.get('/logout', auth.verify, function(req, res) { auth.expireToken(req.headers); return res.sendStatus(200); }); /* REGISTER */ router.post('/register', function(req, res, next) { var username = req.body.username || ''; var username_lower = username.toLowerCase(); var password = req.body.password || ''; var passwordConfirmation = req.body.passwordConfirmation || ''; var email = req.body.email || ''; var emailConfirmation = req.body.emailConfirmation || ''; var fullname = req.body.fullname || ''; var preferredLanguage = req.body.settings.preferredLanguage || 'en'; var spokenLanguages = req.body.settings.spokenLanguages || ['en']; if (username == '' || password == '' || password != passwordConfirmation || email == '' || fullname == '' || email != emailConfirmation) { return res.sendStatus(400); } var userData = {username: username, username_lower: username_lower, password: password, emailNotConfirmed:email, fullname:fullname, settings: { preferredLanguage: preferredLanguage, spokenLanguages: spokenLanguages, autoupdate: true, preferredWeekStartDay: 1, categoryOrder: ["Obst \u0026 Gem\xFCse","Fr\xFChst\xFCck","Servicetheke","Nahrungsmittel","Weitere Bereiche","Drogerie","Baby \u0026 Kind","K\xFChlprodukte","S\xFCssigkeiten","Getr\xE4nke","Haushalt","Tiefk\xFChl"] } }; tokenHelper.createToken(function(err, token) { if (err) callback(err); userData.emailConfirmationToken = token; User.create(userData, function(err) { if (err) return next(err); User.count(function(err, counter) { if (err) return next(err); if (counter == 1) { User.update({username: username}, {is_admin:true, is_activated: true}, function(err, nbRow) { if (err) return next(err); console.log('First user created as an Admin'); return res.sendStatus(200); }); } else { var mailOptions = { from: 'rezept-planer.de <info@rezept-planer.de>', // sender address to: email, // list of receivers subject: 'Confirm Email', // Subject line text: 'Please, use the following link to confirm your email address:\n\nhttps://www.rezept-planer.de/#/user/confirm/'+userData.emailConfirmationToken+'\n\nYour rezept-planer.de Team', // plaintext body }; transporter.sendMail(mailOptions, function(err, info){ if (err) return next(err); console.log('Message sent: ' + info.response); var mailOptions = { from: 'rezept-planer.de <info@rezept-planer.de>', // sender address to: 'admin@rezept-planer.de', // list of receivers subject: 'New User', // Subject line text: 'New user has registered:\n\n'+JSON.stringify(userData)+'\n\nYour rezept-planer.de Team', // plaintext body }; transporter.sendMail(mailOptions, function(err, info){ if (err) return next(err); console.log('Message sent: ' + info.response); return res.sendStatus(200); }); }); } }); }); }); }); /* CONFIRM EMAIL ADDRESS */ router.get('/confirm/:token', function(req, res, next) { User.findOne({emailConfirmationToken: req.params.token}, function (err, user) { if (err) return next(err); if (user == undefined) { console.log("User undefined"); return res.sendStatus(401); } user.is_activated = true; user.email = user.emailNotConfirmed; user.emailConfirmationToken = null; user.save(user, function (err, updatedUser) { if (err) return next(err); return res.sendStatus(200); }); }); }); /* RESET PASSWORD */ router.post('/forgot', function(req, res) { //verify credential (use POST) var username = req.body.username.toLowerCase() || ''; if (username == '') { return res.send(401); } User.findOne({username_lower: username}, function (err, user) { if (err) { console.log(err); return res.sendStatus(401); } if (user == undefined) { console.log("User undefined"); return res.sendStatus(401); } if (user.is_activated === false) { console.log("User not activated"); return res.sendStatus(401); } tokenHelper.createToken(function(err, token) { if (err) callback(err); resetPasswordExpires = Date.now() + 3600000; // 1 hour User.findByIdAndUpdate(user.id, {resetPasswordToken: token, resetPasswordExpires: resetPasswordExpires}, { 'new': true}, function (err, user) { if (err) return next(err); var mailOptions = { from: 'rezept-planer.de <admin@rezept-planer.de>', // sender address to: user.email, // list of receivers subject: 'Reset Password', // Subject line text: 'Please, use the following link to reset your password:\n\nhttps://www.rezept-planer.de/#/user/reset/'+user.resetPasswordToken+'\n\nYour rezept-planer.de Team', // plaintext body }; transporter.sendMail(mailOptions, function(error, info){ if(error){ return console.log(error); } console.log('Message sent: ' + info.response); return res.sendStatus(200); }); }); }); }); }); /* RESET PASSWORD FINAL */ router.put('/reset/:token', function(req, res, next) { var password = req.body.password || ''; var passwordConfirmation = req.body.passwordConfirmation || ''; if (password == '' || password != passwordConfirmation) { return res.sendStatus(400); } // { resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() }}, function (err, user) { //return res.json(user); if (err) { console.log(err); return res.sendStatus(401); } if (user == undefined) { console.log("User undefined"); return res.sendStatus(401); } if (user.is_activated === false) { console.log("User not activated"); return res.sendStatus(401); } user.password = req.body.password; user.resetPasswordToken = undefined; user.resetPasswordExpires = Date.now(); var userToUpdate = new User(user); userToUpdate.isNew = false; userToUpdate.save(user, function (err, user) { if (err) return next(err); return res.sendStatus(200); }); }); }); module.exports = router;
/* WARNING!!! THIS IS NOT FUNCTIONAL */ module.exports = require('ridge/view').extend({ template: 'admin/models/user', events: { 'click': 'toggle' }, elements: { info: '.info' }, toggle: function() { if(this.elements.info.children().length > 0) this.elements.info.toggleClass('visible'); } });
/** * Collects the informations required for the overview json file */ module.exports = function(router, plugins) { router.get('/overview', function(req, res) { var info = []; plugins.forEach(function(plugin) { info.push(plugin.overview()); }); res.send(info); }); };
export const FIND_BEERS = 'findBeers'; export const GET_BEER = 'getBeer'; export const SHOW_LOADING = 'showLoading';
'use strict' // var $ = require('jquery'), // _ = require('lodash'), // Firebase = require('firebase'); angular .module('anyPlane', ['ui.router']) .constant('BASE_URL', 'https://any-plane.firebaseio.com') .config(function($stateProvider, $urlRouterProvider){ $urlRouterProvider.otherwise('/'); $stateProvider .state('home', {url:'/', templateUrl:'views/home.html'}) .state('login', {url:'/login', templateUrl:'views/login.html', controller:'LoginCtrl'}) .state('sabre', {url:'/sabre', templateUrl:'views/sabre.html', controller:'SabreCtrl'}); });
import { Component } from 'react'; import filter from 'lodash/filter'; import isEqual from 'lodash/isEqual'; import withOptions from 'hoc/withOptions'; import withTheme from 'hoc/withTheme'; import { getUrl, loadBackground } from 'lib/api'; import removeAllElements from 'utils/removeAllElements'; import FaviconImage from 'assets/images/favicon.png'; import injectElement from 'utils/injectElement'; const OPTION_ID = 'favicon'; const ICON_STORAGE = 'PM_ICON'; @withTheme @withOptions class Favicon extends Component { updateFavicon = async (accent, useAccent) => { const stored = localStorage.getItem(ICON_STORAGE) ? JSON.parse(localStorage.getItem(ICON_STORAGE)) : undefined; const cached = stored && stored.accent === accent; const data = { url: getUrl(FaviconImage), accent, }; const createIcon = href => { // Remove Old Favicon removeAllElements('link[rel="SHORTCUT ICON"], link[rel="shortcut icon"], link[rel="icon"], link[href $= ".ico"]'); // Create Link Element injectElement('link', { id: `play-midnight-${OPTION_ID}`, rel: 'icon', type: 'image/png', href }, 'head'); }; if (!useAccent) { return createIcon(data.url); } else { if (cached) { createIcon(stored.url); } else { try { const { url } = await loadBackground(data); localStorage.setItem( ICON_STORAGE, JSON.stringify({ url, accent, }) ); createIcon(url); } catch (e) { // Console error for now, Modal seems too intrusive for favicon console.error( `Play Midnight - Issue communcating with background page \ to update favicon. Refreshing page should fix this.` ); } } } }; shouldComponentUpdate({ theme: prevTheme, options: prevOptions }) { const { theme, options } = this.props; const prevFavicon = [prevOptions.favicon, prevOptions.faviconAccent]; const favicon = [options.favicon, options.faviconAccent]; return !isEqual(prevTheme.A500, theme.A500) || !isEqual(prevFavicon, favicon); } render() { const { theme, options } = this.props; if (options[OPTION_ID]) this.updateFavicon(theme.A500, options.faviconAccent); return null; } } export default Favicon;
(function () { 'use strict'; xdescribe('Async Test', function () { it('should catch async errors', function (done) { setTimeout(function () { throw new Error('Async error!'); }, 100); }); }); })();
'use strict'; const Location = require('../../../models/location'); exports.create = (payload) => { return new Location().save(payload) .then((location) => new Location({ id: location.id }).fetch()); };
// Creates the document that will be returned in the search // results. There may be cases where the document that is searchable // is not the same as the document that is returned const Transform = require('stream').Transform const util = require('util') const CreateStoredDocument = function (options) { Transform.call(this, { objectMode: true }) } module.exports = CreateStoredDocument util.inherits(CreateStoredDocument, Transform) CreateStoredDocument.prototype._transform = function (doc, encoding, end) { var options = Object.assign({}, { fieldOptions: {}, storeable: true }, doc.options || {}) for (var fieldName in doc.raw) { var fieldOptions = Object.assign({}, { // Store a cache of this field in the index storeable: options.storeable }, options.fieldOptions[fieldName]) if (fieldName === 'id') fieldOptions.storeable = true if (fieldOptions.storeable) { doc.stored[fieldName] = JSON.parse(JSON.stringify(doc.raw[fieldName])) } } this.push(doc) return end() }
import test from 'ava'; import sinon from 'sinon'; import subject from '../../lib/createDepsProxy'; import mock from 'mock-require'; import chanceFactory from 'chance'; const chance = chanceFactory(); const sandbox = sinon.sandbox.create(); test.afterEach(() => { sandbox.reset(); }); test('native modules are added to deps', t => { const nativeModules = {'fs': require('fs')}; const moduleGroups = [{}, nativeModules, {}]; const appDeps = subject(moduleGroups); t.is(appDeps['fs'], require('fs')); }); test('dependency modules are added to deps', t => { const nodeModules = {'chance': require('chance')}; const moduleGroups = [nodeModules, {}, {}]; const appDeps = subject(moduleGroups); t.is(appDeps['chance'], require('chance')); }); test('app modules as factories are added to deps', t => { const fakeAppModuleKey = `/${chance.word()}`; const fakeAppModuleFactory = sandbox.stub(); const fakeAppModule = {}; const appModules = {[fakeAppModuleKey]: '../spec/fixtures/fakeBreadboardModule'}; const moduleGroups = [{}, {}, appModules]; let appDeps; fakeAppModuleFactory.returns(fakeAppModule); mock('../fixtures/fakeBreadboardModule', fakeAppModuleFactory); appDeps = subject(moduleGroups); t.is(appDeps[fakeAppModuleKey], fakeAppModule); }); test('app modules as values are added to deps', t => { const fakeAppModuleKey = `/${chance.word()}`; const fakeAppModuleValue = {}; const appModules = {[fakeAppModuleKey]: '../spec/fixtures/fakeBreadboardModule'}; const moduleGroups = [{}, {}, appModules]; let appDeps; mock('../fixtures/fakeBreadboardModule', fakeAppModuleValue); appDeps = subject(moduleGroups); t.is(appDeps[fakeAppModuleKey], fakeAppModuleValue); mock.stopAll(); }); test('throws if requiring non-existing app module', t => { const fakeAppModuleKey = `/${chance.word()}`; const moduleGroups = [{}, {}, {}]; const appDeps = subject(moduleGroups); t.throws(() => appDeps[fakeAppModuleKey], `Cannot resolve app module ${fakeAppModuleKey}`); }); test('deps are frozen', t => { const moduleGroups = [{}, {}, {}]; const deps = subject(moduleGroups); t.throws(() => { deps.foo = 'update'; }, 'Runtime changes to dependencies not supported'); }); test('deps are required only when accessed', t => { const moduleGroups = [{}, {}, { '/entry': '../spec/fixtures/fakeBreadboardEntryModule.js', '/fakeBreadboardModule': '../spec/fixtures/fakeBreadboardModule.js' }]; const isFakeBreadboardModule = modulePath => /fakeBreadboardModule\.js$/.test(modulePath); const fakeBreadboardModuleKey = Object.keys(require.cache).filter(isFakeBreadboardModule); let fakeBreadboardModuleCached; delete require.cache[fakeBreadboardModuleKey]; subject(moduleGroups); fakeBreadboardModuleCached = Object.keys(require.cache).some(isFakeBreadboardModule); t.false(fakeBreadboardModuleCached); }); test('accepts explicit substitutes for modules', t => { const fakeFs = {}; const fakeAppModule = {}; const fakeDepModule = {}; const moduleGroups = [{'fs': 'fs'}, {'debug': 'debug'}, {'/foo': '../spec/fixtures/fakeBreadboardModule.js'}]; const deps = subject(moduleGroups, { substitutes: { 'fs': fakeFs, 'debug': fakeDepModule, '/foo': fakeAppModule } }); t.is(deps['fs'], fakeFs); t.is(deps['debug'], fakeDepModule); t.is(deps['/foo'], fakeAppModule); });
"use strict" var http = require('http'); var shoe = require('shoe') var ecstatic = require('ecstatic')({ root : __dirname, baseDir : '/', cache : 3600, showDir :true, autoIndex :true, defaultExt : 'html', gzip : false }); var server = http.createServer(ecstatic); server.on('request', function(req) { console.log(req.url) }) server.listen(9002, function() { console.log('ready') process.send && process.send(server.address()) }) var sock = shoe(function (stream) { console.log('new stream') var iv = setInterval(function () { stream.write(Math.floor(Math.random() * 2)); }, 250); stream.on('close', function() { console.log('stream close') }) stream.on('end', function () { console.log('stream end') clearInterval(iv); }); stream.pipe(process.stdout, { end : false }); }); sock.install(server, '/invert');
$(function () { 'use strict'; $.get('/list', function (list) { var $ul = $('#list'); var $lis = []; for (var i=0, l=list.length; i<l; i++) { var item = list[i], $li = $('<li></li>'), $a = $('<a></a>'); $a.text(item).attr('href', '/download/' + encodeURIComponent(item)); $lis.push($li.append($a)); } $ul.append($lis); }); });
export function locations () { return [ { id: 1, address: 'Praça Dos Omaguas, 34 - Pinheiros - São Paulo - SP', city: 'Pinheiros', state: 'SP', }, { id: 2, address: 'Av. Pulista, 901 - Bela Vista - São Paulo - SP', city: 'Bela Vista', state: 'SP', }, { id: 3, address: 'Av. Roque Petroni Júnior, 1089 - Vila Gertrudes - São Paulo - SP', city: 'Vila Gertrudes', state: 'SP', }, { id: 4, address: 'Av. Guillerme Campos, 500 - Santa Genebra - Campinas - SP', city: 'Campinas', state: 'SP', }, { id: 5, address: 'Rodovia BR-356, 3049 - BELVEDERE - Belo Horizonte - MG', city: 'Belo Horizonte', state: 'MG', }, { id: 6, address: 'Av. das Américas, 4666 - Barra da Tijuca - Rio de Janeiro - RJ', city: 'Barra da Tijuca', state: 'RJ', }, { id: 7, address: 'Rua Prof. Pedro Viriato Parigot de Souza, 600 - Barigui - Curitiba - PR', city: 'Curitiba', state: 'PR', }, { id: 8, address: 'Sai/SO Área 6580 LUC 149P, - Guará - Brasília - DF', city: 'Brasília', state: 'DF', }, { id: 9, address: 'Av. Diário de Notícias, 300 - Cristal - Porto Alegre - RS', city: 'Porto Alegre', state: 'RS', }, { id: 10, address: 'Av. Coronel Fernando Ferreira Leite, 1540 - Jd. Califórnia - Ribeirão Preto - SP', city: 'Ribeirão Preto', state: 'SP', }, { id: 11, address: 'Av. Jamel Cecílio, 3300 - Jardim Goiás - Goiânia - GO', city: 'Goiânia', state: 'GO', }, ] }
module.exports = function() { return { // Prepare app HTML for production dist_template: { src: ['ng-templates/ng-apps.html.template'], dest: 'ng-templates/ng-apps.html', replacements: [{ from: '<!-- replace-tag -->', to: '<script src="{{ NG_APP_PREFIX }}dist/scripts/<%= distJsName %>"></script>' }] }, // Prepare app HTML for development dev_template: { src: ['ng-templates/ng-apps.html.template'], dest: 'ng-templates/ng-apps.html', replacements: [{ from: '<!-- replace-tag -->', to: '<script src="{{ NG_APP_PREFIX }}components/jquery/dist/jquery.min.js"></script>' + '<script src="{{ NG_APP_PREFIX }}components/requirejs/require.js" ' + 'data-main="{{ NG_APP_PREFIX }}scripts/main"></script>' }] } }; };
define(() => { 'use strict'; return class BoardRenderer { constructor() { this.width = 0; this.height = 0; } clear() { this.width = 0; this.height = 0; } updateGameConfig({width, height}) { if(width !== this.width || height !== this.height) { this.width = width; this.height = height; } } getSize() { return { width: this.width, height: this.height, }; } }; });
/** * @copyright Copyright 2006-2013, Miles Johnson - http://milesj.me * @license http://opensource.org/licenses/mit-license.php - Licensed under the MIT License * @link http://milesj.me/code/cakephp/forum */ 'use strict'; var Forum = { /** * Update an input with a characters remaining info box. * * @param {Element} input * @param {int} max */ charsRemaining: function(input, max) { input = $(input); var target = $('#' + input.attr('id') + 'CharsRemaining'), current = max - input.val().length; if (current < 0) { current = 0; input.val(input.val().substr(0, max)); } target.html(current); }, /** * Toggle a buried post. * * @param {int} post_id * @returns {boolean} */ toggleBuried: function(post_id) { $('#post-buried-' + post_id).toggle(); return false; }, /** * Toggle all checkboxes. * * @param {Element} self */ toggleCheckboxes: function(self) { $(self).parents('form') .find('input[type="checkbox"]').prop('checked', self.checked); }, /** * AJAX call to subscribe to a topic. Use the button's href attribute as the AJAX URL. * * @param {Element} self */ subscribe: function(self) { var node = $(self); if (node.hasClass('is-disabled')) { return false; } $.ajax({ type: 'POST', url: node.attr('href') }).done(function(response) { $('.subscription').text(response.data).addClass('is-disabled'); }); return false; }, /** * Unsubscribe from a topic. * * @param {Element} self */ unsubscribe: function(self) { return Forum.subscribe(self); }, /** * Rate a post. * * @param {int} post_id * @param {String} type * @returns {boolean} */ ratePost: function(post_id, type) { $.ajax({ type: 'POST', url: '/forum/posts/rate/' + post_id + '/' + (type == 'up' ? 1 : 0) }).done(function(response) { var parent = $('#post-ratings-' + post_id), rating = parent.find('.rating'); parent.find('a').remove(); // parse json if not submitted as json, can happen due to server settings if (typeof response == 'string') { response = JSON && JSON.parse(response) || $.parseJSON(response); } if (response.success) { if (rating.length) { parent.addClass('has-rated'); rating.text(parseInt(rating.text()) + (type == 'up' ? 1 : -1)); } else { parent.remove(); } } }); return false; } }; $(function() { /* $('.js-tooltip').tooltip({ position: 'topCenter' }); */ });
Object.defineProperty(exports, "__esModule", { value: true }); var date_reg = /^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$/; var email_reg = /([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)/; var phone_reg = /(^[1][3][0-9]{9}$)|(^[1][4][0-9]{9}$)|(^[1][5][0-9]{9}$)|(^[1][7][0-9]{9}$)|(^[1][8][0-9]{9}$)/; var IP_reg = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])((\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){3}|(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){5})$/; var verifyAccount_reg = /^[a-zA-Z][a-zA-Z0-9_]{5,14}$/; var IDcard_reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; var url_reg = /[a-zA-z]+:\/\/[^\s]/; var trim_reg = /(^\s*)|(\s*$)/g; var clearSpace_reg = /[ ]/g; var existCN_reg = /.*[\u4e00-\u9fa5]+.*$/; var num_reg = /[^\d]/g; var CN_reg = /[^\u4e00-\u9fa5\uf900-\ufa2d]/g; var HTMLTag_reg = /<\/?[^>]*>/g; var HTMLStyle_reg = / style\s*?=\s*?(['"])[\s\S]*?\1/g; var nbsp_reg = /&nbsp;/ig; var Reg = (function () { function Reg() { } Reg.prototype._testType = function (obj) { return Object.prototype.toString.call(obj); }; Reg.prototype.isNull = function (obj) { return obj === '' || obj === undefined || obj === null ? true : false; }; Reg.prototype.isArray = function (arr) { var typeName = '[object Array]'; return (this._testType(arr) === typeName); }; Reg.prototype.isFunction = function (func) { var typeName = '[object Function]'; return (this._testType(func) === typeName); }; Reg.prototype.isObject = function (obj) { var typeName = '[object Object]'; return (this._testType(obj) === typeName); }; Reg.prototype.isString = function (str) { var typeName = '[object String]'; return (this._testType(str) === typeName); }; Reg.prototype.isNumber = function (num) { var typeName = '[object Number]'; return (this._testType(num) === typeName); }; Reg.prototype.isBoolean = function (flag) { var typeName = '[object Boolean]'; return (this._testType(flag) === typeName); }; Reg.prototype.isEmpty = function (obj) { var flag = true; if (this.isArray(obj) || this.isNumber(obj) || this.isString(obj)) { flag = obj.length === 0 ? true : false; } else { for (var p in obj) { if (obj.hasOwnProperty(p)) { flag = false; } } } return flag; }; Reg.prototype._testRE = function (reg, obj) { return reg.test(obj); }; Reg.prototype._replaceRE = function (reg, str, rStr) { return str.toString().replace(reg, rStr); }; Reg.prototype.isDate = function (time) { return this._testRE(date_reg, time); }; Reg.prototype.isPhone = function (phone) { return this._testRE(phone_reg, phone); }; Reg.prototype.isEmail = function (email) { return this._testRE(email_reg, email); }; Reg.prototype.isIP = function (ip) { return this._testRE(IP_reg, ip); }; Reg.prototype.isVerifyAccount = function (account) { return this._testRE(verifyAccount_reg, account); }; Reg.prototype.isIDcard = function (cardNo) { return this._testRE(IDcard_reg, cardNo); }; Reg.prototype.isUrl = function (url) { return this._testRE(url_reg, url); }; Reg.prototype.existCN = function (text) { return this._testRE(existCN_reg, text); }; Reg.prototype.trim = function (text) { return this._replaceRE(trim_reg, text, ''); }; Reg.prototype.clearSpace = function (text) { return this._replaceRE(clearSpace_reg, text, ''); }; Reg.prototype.getNum = function (text) { return parseInt(this._replaceRE(num_reg, text, '')); }; Reg.prototype.getCN = function (text) { return this._replaceRE(CN_reg, text, ''); }; Reg.prototype.excludeHTML = function (html) { var reHTML = this._replaceRE(HTMLTag_reg, html, ''); return this._replaceRE(nbsp_reg, reHTML, ''); }; Reg.prototype.excludeStyle = function (html) { return this._replaceRE(HTMLStyle_reg, html, ''); }; return Reg; }()); exports.default = Reg;
!function() { var createDirective = function(type) { return ['$uiHighChartsManager', function(highChartsManager) { return { restrict: 'EAC', transclude: true, replace: true, template: '<div></div>', scope: { options: '=?', series: '=', redraw: '=', loading: '=', start: '=', end: '=', pointClick: '&', pointSelect: '&', pointUnselect: '&', pointMouseout: '&', pointMousemove: '&', legendItemClick: '&', }, link: function($scope, $element, $attrs, $ctrl, $transclude) { highChartsManager.createInstance(type, $element, $scope, $attrs, $transclude); }, }; }, ]; }; angular.module('ui-highcharts') .directive('uiChart', createDirective('Chart')) .directive('uiStockChart', createDirective('StockChart')) .directive('uiMap', createDirective('Map')); }();
import Ember from "ember"; export default Ember.Component.extend({ gridOptions: { columnDefs: [ { headerName: "Product", field: "name" }, { headerName: 'Units', field: 'units' }, { headerName: 'Sales', field: 'sales' }, { headerName: 'Profit', field: 'profit' }], rowData: [ { name: 'Chips', units: '223', sales: '$54,335', profit: '$545,454' }, { name: 'Towels', units: '965', sales: '$1,900', profit: '$800' }, { name: 'Gloves', units: '213', sales: '$100,032', profit: '$22,004' }, { name: 'Soap', units: '100', sales: '$1,0695', profit: '$5,112' }, { name: 'Toys', units: '708', sales: '$14,430', profit: '$1,030' }, { name: 'Mirrors', units: '9,901', sales: '$600', profit: '$30' }, { name: 'Games', units: '5,000', sales: '$12,115', profit: '$15,321' }, { name: 'Bicycles', units: '670', sales: '$2,00', profit: '$301' }, { name: 'Helmets', units: '600', sales: '$200', profit: '$40' }, { name: 'Shirts', units: '8,530', sales: '$5,465', profit: '$1,554' }], showToolPanel: true } });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ts = require("typescript"); var TypeGuard_1 = require("./TypeGuard"); function getPropName(node) { if (!TypeGuard_1.isJsxAttribute(node)) { throw new Error('The node must be a JsxAttribute collected by the AST parser.'); } return node.name ? node.name.text : undefined; } exports.getPropName = getPropName; function getStringLiteral(node) { if (!TypeGuard_1.isJsxAttribute(node)) { throw new Error('The node must be a JsxAttribute collected by the AST parser.'); } var initializer = node == null ? null : node.initializer; if (!initializer) { return ''; } else if (TypeGuard_1.isStringLiteral(initializer)) { return initializer.text.trim(); } else if (TypeGuard_1.isJsxExpression(initializer) && TypeGuard_1.isStringLiteral(initializer.expression)) { return initializer.expression.text; } else if (TypeGuard_1.isJsxExpression(initializer) && !initializer.expression) { return ''; } else { return undefined; } } exports.getStringLiteral = getStringLiteral; function getBooleanLiteral(node) { if (!TypeGuard_1.isJsxAttribute(node)) { throw new Error('The node must be a JsxAttribute collected by the AST parser.'); } var initializer = node == null ? null : node.initializer; var getBooleanFromString = function (value) { if (value.toLowerCase() === 'true') { return true; } else if (value.toLowerCase() === 'false') { return false; } else { return undefined; } }; if (TypeGuard_1.isStringLiteral(initializer)) { return getBooleanFromString(initializer.text); } else if (TypeGuard_1.isJsxExpression(initializer)) { var expression = initializer.expression; if (TypeGuard_1.isStringLiteral(expression)) { return getBooleanFromString(expression.text); } else { if (TypeGuard_1.isTrueKeyword(expression)) { return true; } else if (TypeGuard_1.isFalseKeyword(expression)) { return false; } else { return undefined; } } } return false; } exports.getBooleanLiteral = getBooleanLiteral; function isEmpty(node) { var initializer = node == null ? null : node.initializer; if (initializer == null) { return true; } else if (TypeGuard_1.isStringLiteral(initializer)) { return initializer.text.trim() === ''; } else if (initializer.kind === ts.SyntaxKind.Identifier) { return initializer.getText() === 'undefined'; } else if (initializer.kind === ts.SyntaxKind.NullKeyword) { return true; } else if (initializer.expression != null) { var expression = initializer.expression; if (expression.kind === ts.SyntaxKind.Identifier) { return expression.getText() === 'undefined'; } else if (expression.kind === ts.SyntaxKind.NullKeyword) { return true; } } return false; } exports.isEmpty = isEmpty; function getNumericLiteral(node) { if (!TypeGuard_1.isJsxAttribute(node)) { throw new Error('The node must be a JsxAttribute collected by the AST parser.'); } var initializer = node == null ? null : node.initializer; return TypeGuard_1.isJsxExpression(initializer) && TypeGuard_1.isNumericLiteral(initializer.expression) ? initializer.expression.text : undefined; } exports.getNumericLiteral = getNumericLiteral; function getAllAttributesFromJsxElement(node) { var attributes; if (node == null) { return []; } else if (TypeGuard_1.isJsxElement(node)) { attributes = node.openingElement.attributes.properties; } else if (TypeGuard_1.isJsxSelfClosingElement(node)) { attributes = node.attributes.properties; } else if (TypeGuard_1.isJsxOpeningElement(node)) { attributes = node.attributes.properties; } else { throw new Error('The node must be a JsxElement, JsxSelfClosingElement or JsxOpeningElement.'); } return attributes; } exports.getAllAttributesFromJsxElement = getAllAttributesFromJsxElement; function getJsxAttributesFromJsxElement(node) { var attributesDictionary = {}; getAllAttributesFromJsxElement(node).forEach(function (attr) { if (TypeGuard_1.isJsxAttribute(attr)) { attributesDictionary[getPropName(attr).toLowerCase()] = attr; } }); return attributesDictionary; } exports.getJsxAttributesFromJsxElement = getJsxAttributesFromJsxElement; function getJsxElementFromCode(code, exceptTagName) { var sourceFile = ts.createSourceFile('test.tsx', code, ts.ScriptTarget.ES2015, true); return delintNode(sourceFile, exceptTagName); } exports.getJsxElementFromCode = getJsxElementFromCode; function delintNode(node, tagName) { if (TypeGuard_1.isJsxElement(node) && node.openingElement.tagName.getText() === tagName) { return node; } else if (TypeGuard_1.isJsxSelfClosingElement(node) && node.tagName.getText() === tagName) { return node; } else if (!node || node.getChildCount() === 0) { return undefined; } return ts.forEachChild(node, function (childNode) { return delintNode(childNode, tagName); }); } function getAncestorNode(node, ancestorTagName) { if (!node) { return undefined; } var ancestorNode = node.parent; if (TypeGuard_1.isJsxElement(ancestorNode) && ancestorNode.openingElement.tagName.getText() === ancestorTagName) { return ancestorNode; } else { return getAncestorNode(ancestorNode, ancestorTagName); } } exports.getAncestorNode = getAncestorNode; //# sourceMappingURL=JsxAttribute.js.map
import _ from 'lodash' import PropTypes from 'prop-types' import React, { Component } from 'react' import { customPropTypes, eventStack, getElementType, getUnhandledProps, isBrowser, META, } from '../../lib' /** * Responsive can control visibility of content. */ export default class Responsive extends Component { static propTypes = { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Primary content. */ children: PropTypes.node, /** Fires callbacks immediately after mount. */ fireOnMount: PropTypes.bool, /** The maximum width at which content will be displayed. */ maxWidth: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** The minimum width at which content will be displayed. */ minWidth: PropTypes.oneOfType([ PropTypes.number, PropTypes.string, ]), /** * Called on update. * * @param {SyntheticEvent} event - The React SyntheticEvent object * @param {object} data - All props and the event value. */ onUpdate: PropTypes.func, } static _meta = { name: 'Responsive', type: META.TYPES.ADDON, } static onlyMobile = { minWidth: 320, maxWidth: 767 } static onlyTablet = { minWidth: 768, maxWidth: 991 } static onlyComputer = { minWidth: 992 } static onlyLargeScreen = { minWidth: 1200, maxWidth: 1919 } static onlyWidescreen = { minWidth: 1920 } constructor(...args) { super(...args) this.state = { width: isBrowser() ? window.innerWidth : 0 } } componentDidMount() { const { fireOnMount } = this.props eventStack.sub('resize', this.handleResize, { target: 'window' }) if (fireOnMount) this.handleUpdate() } componentWillUnmount() { eventStack.unsub('resize', this.handleResize, { target: 'window' }) } // ---------------------------------------- // Helpers // ---------------------------------------- fitsMaxWidth = () => { const { maxWidth } = this.props const { width } = this.state return _.isNil(maxWidth) ? true : width <= maxWidth } fitsMinWidth = () => { const { minWidth } = this.props const { width } = this.state return _.isNil(minWidth) ? true : width >= minWidth } isVisible = () => this.fitsMinWidth() && this.fitsMaxWidth() // ---------------------------------------- // Event handlers // ---------------------------------------- handleResize = (e) => { if (this.ticking) return this.ticking = true requestAnimationFrame(() => this.handleUpdate(e)) } handleUpdate = (e) => { this.ticking = false const width = window.innerWidth this.setState({ width }) _.invoke(this.props, 'onUpdate', e, { ...this.props, width }) } // ---------------------------------------- // Render // ---------------------------------------- render() { const { children } = this.props const ElementType = getElementType(Responsive, this.props) const rest = getUnhandledProps(Responsive, this.props) if (this.isVisible()) return <ElementType {...rest}>{children}</ElementType> return null } }
module.exports = { 'A': 'Å', 'a': 'ª', 'B': 'ß', 'b': 'Ь', 'C': 'Ç', 'c': '¢', 'D': 'Ð', 'd': 'ð', 'E': 'É', 'e': 'ë', 'F': 'F', 'f': 'ƒ', 'G': 'Ĝ', 'g': 'ğ', 'H': 'Ħ', 'h': 'λ', 'I': '1', 'i': 'ï', 'J': 'Ĵ', 'j': 'ĵ', 'K': 'Ķ', 'k': 'к', 'L': '£', 'l': 'ł', 'M': 'M', 'm': 'ḿ', 'N': 'И', 'n': 'ñ', 'O': 'Ö', 'o': 'ø', 'P': 'P', 'p': 'Þ', 'Q': 'Q', 'q': 'ǫ', 'R': 'Я', 'r': '®', 'S': '§', 's': 'ȿ', 'T': 'ʈ', 't': 'ŧ', 'U': 'Ц', 'u': 'ü', 'V': 'Ѵ', 'v': 'ν', 'W': 'Ŵ', 'w': 'ʬ', 'X': 'Χ', 'x': 'χ', 'Y': 'Y', 'y': 'ÿ', 'Z': 'Ȥ', 'z': 'z' };
import React from 'react' import PropTypes from 'prop-types' export default class LoadMoreButton extends React.Component { static propTypes = { hasMore: PropTypes.bool, isActive: PropTypes.bool, activeDescriptionText: PropTypes.string, normalDescriptionText: PropTypes.string, noMoreDescriptionText: PropTypes.string, onClick: PropTypes.func, type: PropTypes.oneOf(['circle', 'ballspin','linespinfade']), } static defaultProps = { type: 'circle', hasMore: true, isActive: false, activeDescriptionText: '正在加载...', normalDescriptionText: '点击加载更多...', noMoreDescriptionText: '没有更多了...' } constructor(props) { super(props) this.state = { rotateDegree: 0, clockID: null, } } componentWillReceiveProps(nextProps) { const { isActive } = nextProps if (isActive) { const clockID = setInterval(_ => { this.setState((preState) => ({ rotateDegree: (preState.rotateDegree + 1) % 360 })) }, 1000 / 360) this.setState({ clockID: clockID }) } else { clearInterval(this.state.clockID) } } render() { const styles = require('./LoadMoreButton.scss') const { hasMore, isActive, activeDescriptionText, normalDescriptionText, noMoreDescriptionText } = this.props const nonActiveDescriptionText = hasMore ? normalDescriptionText : noMoreDescriptionText const descriptionText = isActive ? activeDescriptionText : nonActiveDescriptionText const imageStyle = { transform: 'rotate(' + this.state.rotateDegree + 'deg)' }; const buttonStyle = { display: hasMore ? 'block' : 'none' }; return ( <div style={buttonStyle} className={styles.loading}> <div className={styles.loadingWrap} onClick={this.props.onClick}> <img style={imageStyle} className={styles.loadingImage} src={`/loading/${this.props.type}.png`} alt="loading" /> <span className={styles.loadingText}>{descriptionText}</span> </div> </div> ); } }
import addons from '@kadira/storybook-addons'; const ADDON_ID = "storybook-addon-style"; const PANEL_ID = `${ADDON_ID}/style-panel` function register() { addons.register(ADDON_ID, api => { // addons.addPanel can be used to add a new panel to storybook manager // The `title` field will be used as the tab title and the `render` field // will be executed to render the tab content. addons.addPanel(PANEL_ID, { title: 'Styles', render: () => <h1>Hello World</h1> }); }) } register();
// Configuration // The `/ytdl` folder that is hosted on your site const endpoint = "https://de.surge.sh/ytdl" // See https://console.developers.google.com/apis/api/urlshortener const googlApiKey = "YOUR-GOOGLE-API-KEY"; export { endpoint, googlApiKey }
importScripts('serviceworker-cache-polyfill.js'); var CACHE_NAME = 'statistika-v1'; // File want to cache var urlsToCache = [ './', './index.html', './manifest.json', './serviceworker-cache-polyfill.js', './src/assets/img/blank-thumbnail.png', './src/assets/img/favicon.png', './src/assets/img/icon-48.png', './src/assets/img/icon-96.png', './src/assets/img/icon-128.png', './src/assets/img/icon-144.png', './src/assets/img/icon-152.png', './src/assets/img/icon-196.png', './src/assets/img/icon-384.png', './src/vendor/bootstrap/css/bootstrap.min.css', './src/vendor/ionicons/css/ionicons.min.css', './src/vendor/ionicons/fonts/ionicons.ttf', './src/vendor/ionicons/fonts/ionicons.woff', './build/build.css', './build/main.js', // './build/1.js', // './build/2.js' ]; // Set the callback for the install step self.oninstall = function (e) { console.log('[serviceWorker]: Installing...'); // perform install steps e.waitUntil( caches.open(CACHE_NAME) .then(function (cache) { console.log('[serviceWorker]: Cache All'); return cache.addAll(urlsToCache); }) .then(function () { console.log('[serviceWorker]: Intalled And Skip Waiting on Install'); return self.skipWaiting(); }) ); }; self.onfetch = function (e) { console.log('[serviceWorker]: Fetching ' + e.request.url); var raceUrl = 'API/'; if(e.request.url.indexOf(raceUrl) > -1){ e.respondWith( caches.open(CACHE_NAME).then(function (cache) { return fetch(e.request).then(function (res) { cache.put(e.request.url, res.clone()); return res; }).catch(err => { console.log('[serviceWorker]: Fetch Error ' + err); }); }) ); } else if (e.request.url.indexOf('src/assets/img-content') > -1) { e.respondWith( caches.match(e.request).then(function (res) { if(res) return res return fetch(e.request.clone(), { mode: 'no-cors' }).then(function (newRes) { if(!newRes || newRes.status !== 200 || newRes.type !== 'basic') { return newRes; } caches.open(CACHE_NAME).then(function (cache) { cache.put(e.request, newRes.clone()); }).catch(err => { console.log('[serviceWorker]: Fetch Error ' + err); }); return newRes; }); }) ); } else { e.respondWith( caches.match(e.request).then(function (res) { return res || fetch(e.request) }) ); } }; self.onactivate = function (e) { console.log('[serviceWorker]: Actived'); var whiteList = ['statistika-v1']; e.waitUntil( caches.keys().then(function (cacheNames) { return Promise.all( cacheNames.map(function (cacheName) { if (whiteList.indexOf(cacheName) === -1) { return caches.delete(cacheName); } }) ) }).then(function () { console.log('[serviceWorker]: Clients Claims'); return self.clients.claim(); }) ); };
/** * @license Highcharts JS v4.0.0 (2014-04-22) * * Standalone Highcharts Framework * * License: MIT License */ /*global Highcharts */ var HighchartsAdapter = (function () { var UNDEFINED, doc = document, emptyArray = [], timers = [], timerId, Fx; Math.easeInOutSine = function (t, b, c, d) { return -c / 2 * (Math.cos(Math.PI * t / d) - 1) + b; }; /** * Extend given object with custom events */ function augment(obj) { function removeOneEvent(el, type, fn) { el.removeEventListener(type, fn, false); } function IERemoveOneEvent(el, type, fn) { fn = el.HCProxiedMethods[fn.toString()]; el.detachEvent('on' + type, fn); } function removeAllEvents(el, type) { var events = el.HCEvents, remove, types, len, n; if (el.removeEventListener) { remove = removeOneEvent; } else if (el.attachEvent) { remove = IERemoveOneEvent; } else { return; // break on non-DOM events } if (type) { types = {}; types[type] = true; } else { types = events; } for (n in types) { if (events[n]) { len = events[n].length; while (len--) { remove(el, n, events[n][len]); } } } } if (!obj.HCExtended) { Highcharts.extend(obj, { HCExtended: true, HCEvents: {}, bind: function (name, fn) { var el = this, events = this.HCEvents, wrappedFn; // handle DOM events in modern browsers if (el.addEventListener) { el.addEventListener(name, fn, false); // handle old IE implementation } else if (el.attachEvent) { wrappedFn = function (e) { e.target = e.srcElement || window; // #2820 fn.call(el, e); }; if (!el.HCProxiedMethods) { el.HCProxiedMethods = {}; } // link wrapped fn with original fn, so we can get this in removeEvent el.HCProxiedMethods[fn.toString()] = wrappedFn; el.attachEvent('on' + name, wrappedFn); } if (events[name] === UNDEFINED) { events[name] = []; } events[name].push(fn); }, unbind: function (name, fn) { var events, index; if (name) { events = this.HCEvents[name] || []; if (fn) { index = HighchartsAdapter.inArray(fn, events); if (index > -1) { events.splice(index, 1); this.HCEvents[name] = events; } if (this.removeEventListener) { removeOneEvent(this, name, fn); } else if (this.attachEvent) { IERemoveOneEvent(this, name, fn); } } else { removeAllEvents(this, name); this.HCEvents[name] = []; } } else { removeAllEvents(this); this.HCEvents = {}; } }, trigger: function (name, args) { var events = this.HCEvents[name] || [], target = this, len = events.length, i, preventDefault, fn; // Attach a simple preventDefault function to skip default handler if called preventDefault = function () { args.defaultPrevented = true; }; for (i = 0; i < len; i++) { fn = events[i]; // args is never null here if (args.stopped) { return; } args.preventDefault = preventDefault; args.target = target; // If the type is not set, we're running a custom event (#2297). If it is set, // we're running a browser event, and setting it will cause en error in // IE8 (#2465). if (!args.type) { args.type = name; } // If the event handler return false, prevent the default handler from executing if (fn.call(this, args) === false) { args.preventDefault(); } } } }); } return obj; } return { /** * Initialize the adapter. This is run once as Highcharts is first run. */ init: function (pathAnim) { /** * Compatibility section to add support for legacy IE. This can be removed if old IE * support is not needed. */ if (!doc.defaultView) { this._getStyle = function (el, prop) { var val; if (el.style[prop]) { return el.style[prop]; } else { if (prop === 'opacity') { prop = 'filter'; } /*jslint unparam: true*/ val = el.currentStyle[prop.replace(/\-(\w)/g, function (a, b) { return b.toUpperCase(); })]; if (prop === 'filter') { val = val.replace( /alpha\(opacity=([0-9]+)\)/, function (a, b) { return b / 100; } ); } /*jslint unparam: false*/ return val === '' ? 1 : val; } }; this.adapterRun = function (elem, method) { var alias = { width: 'clientWidth', height: 'clientHeight' }[method]; if (alias) { elem.style.zoom = 1; return elem[alias] - 2 * parseInt(HighchartsAdapter._getStyle(elem, 'padding'), 10); } }; } if (!Array.prototype.forEach) { this.each = function (arr, fn) { // legacy var i = 0, len = arr.length; for (; i < len; i++) { if (fn.call(arr[i], arr[i], i, arr) === false) { return i; } } }; } if (!Array.prototype.indexOf) { this.inArray = function (item, arr) { var len, i = 0; if (arr) { len = arr.length; for (; i < len; i++) { if (arr[i] === item) { return i; } } } return -1; }; } if (!Array.prototype.filter) { this.grep = function (elements, callback) { var ret = [], i = 0, length = elements.length; for (; i < length; i++) { if (!!callback(elements[i], i)) { ret.push(elements[i]); } } return ret; }; } //--- End compatibility section --- /** * Start of animation specific code */ Fx = function (elem, options, prop) { this.options = options; this.elem = elem; this.prop = prop; }; Fx.prototype = { update: function () { var styles, paths = this.paths, elem = this.elem, elemelem = elem.element; // if destroyed, it is null // Animating a path definition on SVGElement if (paths && elemelem) { elem.attr('d', pathAnim.step(paths[0], paths[1], this.now, this.toD)); // Other animations on SVGElement } else if (elem.attr) { if (elemelem) { elem.attr(this.prop, this.now); } // HTML styles } else { styles = {}; styles[this.prop] = this.now + this.unit; Highcharts.css(elem, styles); } if (this.options.step) { this.options.step.call(this.elem, this.now, this); } }, custom: function (from, to, unit) { var self = this, t = function (gotoEnd) { return self.step(gotoEnd); }, i; this.startTime = +new Date(); this.start = from; this.end = to; this.unit = unit; this.now = this.start; this.pos = this.state = 0; t.elem = this.elem; if (t() && timers.push(t) === 1) { timerId = setInterval(function () { for (i = 0; i < timers.length; i++) { if (!timers[i]()) { timers.splice(i--, 1); } } if (!timers.length) { clearInterval(timerId); } }, 13); } }, step: function (gotoEnd) { var t = +new Date(), ret, done, options = this.options, elem = this.elem, i; if (elem.stopAnimation || (elem.attr && !elem.element)) { // #2616, element including flag is destroyed ret = false; } else if (gotoEnd || t >= options.duration + this.startTime) { this.now = this.end; this.pos = this.state = 1; this.update(); this.options.curAnim[this.prop] = true; done = true; for (i in options.curAnim) { if (options.curAnim[i] !== true) { done = false; } } if (done) { if (options.complete) { options.complete.call(elem); } } ret = false; } else { var n = t - this.startTime; this.state = n / options.duration; this.pos = options.easing(n, 0, 1, options.duration); this.now = this.start + ((this.end - this.start) * this.pos); this.update(); ret = true; } return ret; } }; /** * The adapter animate method */ this.animate = function (el, prop, opt) { var start, unit = '', end, fx, args, name; el.stopAnimation = false; // ready for new if (typeof opt !== 'object' || opt === null) { args = arguments; opt = { duration: args[2], easing: args[3], complete: args[4] }; } if (typeof opt.duration !== 'number') { opt.duration = 400; } opt.easing = Math[opt.easing] || Math.easeInOutSine; opt.curAnim = Highcharts.extend({}, prop); for (name in prop) { fx = new Fx(el, opt, name); end = null; if (name === 'd') { fx.paths = pathAnim.init( el, el.d, prop.d ); fx.toD = prop.d; start = 0; end = 1; } else if (el.attr) { start = el.attr(name); } else { start = parseFloat(HighchartsAdapter._getStyle(el, name)) || 0; if (name !== 'opacity') { unit = 'px'; } } if (!end) { end = parseFloat(prop[name]); } fx.custom(start, end, unit); } }; }, /** * Internal method to return CSS value for given element and property */ _getStyle: function (el, prop) { return window.getComputedStyle(el, undefined).getPropertyValue(prop); }, /** * Downloads a script and executes a callback when done. * @param {String} scriptLocation * @param {Function} callback */ getScript: function (scriptLocation, callback) { // We cannot assume that Assets class from mootools-more is available so instead insert a script tag to download script. var head = doc.getElementsByTagName('head')[0], script = doc.createElement('script'); script.type = 'text/javascript'; script.src = scriptLocation; script.onload = callback; head.appendChild(script); }, /** * Return the index of an item in an array, or -1 if not found */ inArray: function (item, arr) { return arr.indexOf ? arr.indexOf(item) : emptyArray.indexOf.call(arr, item); }, /** * A direct link to adapter methods */ adapterRun: function (elem, method) { return parseInt(HighchartsAdapter._getStyle(elem, method), 10); }, /** * Filter an array */ grep: function (elements, callback) { return emptyArray.filter.call(elements, callback); }, /** * Map an array */ map: function (arr, fn) { var results = [], i = 0, len = arr.length; for (; i < len; i++) { results[i] = fn.call(arr[i], arr[i], i, arr); } return results; }, /** * Get the element's offset position, corrected by overflow:auto. Loosely based on jQuery's offset method. */ offset: function (el) { var docElem = document.documentElement, box = el.getBoundingClientRect(); return { top: box.top + (window.pageYOffset || docElem.scrollTop) - (docElem.clientTop || 0), left: box.left + (window.pageXOffset || docElem.scrollLeft) - (docElem.clientLeft || 0) }; }, /** * Add an event listener */ addEvent: function (el, type, fn) { augment(el).bind(type, fn); }, /** * Remove event added with addEvent */ removeEvent: function (el, type, fn) { augment(el).unbind(type, fn); }, /** * Fire an event on a custom object */ fireEvent: function (el, type, eventArguments, defaultFunction) { var e; if (doc.createEvent && (el.dispatchEvent || el.fireEvent)) { e = doc.createEvent('Events'); e.initEvent(type, true, true); e.target = el; Highcharts.extend(e, eventArguments); if (el.dispatchEvent) { el.dispatchEvent(e); } else { el.fireEvent(type, e); } } else if (el.HCExtended === true) { eventArguments = eventArguments || {}; el.trigger(type, eventArguments); } if (eventArguments && eventArguments.defaultPrevented) { defaultFunction = null; } if (defaultFunction) { defaultFunction(eventArguments); } }, washMouseEvent: function (e) { return e; }, /** * Stop running animation */ stop: function (el) { el.stopAnimation = true; }, /** * Utility for iterating over an array. Parameters are reversed compared to jQuery. * @param {Array} arr * @param {Function} fn */ each: function (arr, fn) { // modern browsers return Array.prototype.forEach.call(arr, fn); } }; }());
import Handler from '../handlers/signup'; import Response from '../responses/signup'; import Validation from '../validation/signup'; export default [ { method: 'POST', path: '/signup', config: { auth: false, handler: Handler.signup, response: { schema: Response.signup }, validate: Validation.signup } } ];
// ==UserScript== // @name adarkroom_doublespeakgames_com // @namespace http://www.subtl.fr/ // @description Colorize resources changes. // @downloadURL https://github.com/flowgunso/greasemonkeyScripts/ // @version 1.0 // @include /[(http(s)?):\/\/[]{2,256}?(adarkroom.doublespeakgames.com)\b[-a-zA-Z0-9@:%_\+.~#?&/=]*/ // @require https://code.jquery.com/jquery-2.2.4.min.js // @grant GM_setValue // @grant GM_listValues // ==/UserScript== function main() { } // initialise current resources found function init() { // gather number of #storesContainer childs GM_setValue('stores', $('#storesContainer').children().length) // loop over #storesContainer childs $('#storesContainer').children().each(function(store_index, store){ // gather number of items in store GM_setValue($(store).attr('id'), $(store).length); // if current store is actually the store if($(store).attr('id') == "stores"){ // loop over subchilds $(store).children().children().each(function(item_index, item){ // gather items values GM_setValue($(item).attr('id'), $(item).children('.row_val').html()); }); // otherwise loop over items regurlarly } else { // loop over items $(store).children().each(function(item_index, item){ // gather items values GM_setValue($(item).attr('id'), $(item).children('.row_val').html()); }); } }); } document.addEventListener('DOMNodeInserted', init(), false); document.addEventListener('DOMNodeInserted', console.log(GM_listValues()), false);
var s1 = 'Hallo, '; var s2 = "Olli's Oma"; // === JavaScript ~ == Java // == JavaScript ~ Obskure Typkonvertierung in Java var s3 = s1 + s2; //console.log(s3); // immer (!) === nehmen //console.log(s3 === "Hallo, Olli's Oma"); // true s3[1] === "a"; console.log(s3[1]); console.log(typeof s3[1]); s3.charAt(1) === s3[1]; // Ersatz für StringBuilder und StringBuffer var builder = ["a", "b", "c"]; var s4 = builder.join(""); console.log(s4);
(function() { var BrowserWorker, Point, Report, Sequelize, Utils, sequelize; Utils = require('./utils'); Sequelize = require('sequelize'); sequelize = Utils.connect(); Report = sequelize.define('Report', { metric: { type: Sequelize.STRING, allowNull: false }, key: { type: Sequelize.STRING, allowNull: false }, sha: { type: Sequelize.STRING, allowNull: false }, human: { type: Sequelize.STRING, allowNull: false }, userAgent: { type: Sequelize.STRING, allowNull: false }, os: { type: Sequelize.STRING, allowNull: false } }, { underscore: true, classMethods: { truncateKeyPattern: function(key) { var query; query = Report.findAll({ where: { key: "LIKE '%" + key + "%'" } }).on('success', function(reports) { var report, _i, _len, _results; _results = []; for (_i = 0, _len = reports.length; _i < _len; _i++) { report = reports[_i]; _results.push(report.destroyWithPoints()); } return _results; }); return query; }, getAvailableKeys: function() { return sequelize.query("SELECT DISTINCT `key` FROM `Reports`;", { build: function(x) { return x.key; } }); } }, instanceMethods: { destroyWithPoints: function() { var _this = this; return this.getPoints().on('success', function(points) { var point, _i, _len; for (_i = 0, _len = points.length; _i < _len; _i++) { point = points[_i]; point.destroy(); } return _this.destroy(); }); } } }); Point = sequelize.define('Point', { x: { type: Sequelize.FLOAT, allowNull: false }, y: { type: Sequelize.FLOAT, allowNull: false }, note: { type: Sequelize.STRING, allowNull: true } }, { underscore: true }); BrowserWorker = sequelize.define('BrowserWorker', { token: { type: Sequelize.STRING, allowNull: false }, worker_id: { type: Sequelize.STRING, allowNull: false }, note: { type: Sequelize.STRING, allowNull: true } }, { underscore: true }); Report.hasMany(Point); Point.belongsTo(Report); module.exports = { Report: Report, Point: Point, BrowserWorker: BrowserWorker }; }).call(this);
const DEFAULT_SUBREDDITS = [ "/r/askscience", "/r/explainlikeimfive", "/r/todayilearned", ]; export { DEFAULT_SUBREDDITS };
// Blockly workspace var workspace; window.addEventListener('load', function() { // To remember the control_if blockId var controlBlockId = ''; // Change the if block to be more cheerful Blockly.Msg.LOGIC_HUE = '#24c74f'; // Remote previous and next statement from control_if block Blockly.defineBlocksWithJsonArray([ { "type": "controls_if", "message0": "%{BKY_CONTROLS_IF_MSG_IF} %1", "args0": [ { "type": "input_value", "name": "IF0", "check": "Boolean" } ], "message1": "%{BKY_CONTROLS_IF_MSG_THEN} %1", "args1": [ { "type": "input_statement", "name": "DO0" } ], "colour": "%{BKY_LOGIC_HUE}", "helpUrl": "%{BKY_CONTROLS_IF_HELPURL}", "mutator": "controls_if_mutator", "extensions": ["controls_if_tooltip"] } ]); // Make control_if mutator icon bigger Blockly.Icon.prototype.renderIcon = function(cursorX) { if (this.collapseHidden && this.block_.isCollapsed()) { this.iconGroup_.setAttribute('display', 'none'); return cursorX; } this.iconGroup_.setAttribute('display', 'block'); var SIZE = 1.7; var TOP_MARGIN = 2; var LEFT_MARGIN = 5; var width = this.SIZE; if (this.block_.RTL) { cursorX -= width; } this.iconGroup_.setAttribute('transform', 'translate(' + LEFT_MARGIN + ',' + TOP_MARGIN + ') scale(' + SIZE + ')'); this.computeIconLocation(); if (this.block_.RTL) { cursorX -= Blockly.BlockSvg.SEP_SPACE_X; } else { cursorX += width + Blockly.BlockSvg.SEP_SPACE_X; } return cursorX; }; // When mouse click occures on Blockly workspace Blockly.utils.isRightButton = function(e) { var target = e.target; // When control_if block is in use if (controlBlockId != '') { // When the user clicks anywhere outside the mutator and not on the mutator icon if (!$(target).is('.blocklyBubbleCanvas') && !$(target).parents().is('.blocklyBubbleCanvas')) { if (!$(target).is('.blocklyIconGroup') && !$(target).parents().is('.blocklyIconGroup')) { // Hide the mutator workspace.getBlockById(controlBlockId).mutator.setVisible(false); } } } // Disable right click on Blockly workspace return false; }; Blockly.Blocks['sumorobot_sleep'] = { init: function() { this.setColour('#e98017'); this.appendDummyInput() .appendField('sleep') .appendField(new Blockly.FieldTextInput('1000', Blockly.FieldNumber.numberValidator), 'SLEEP'); this.setPreviousStatement(true); this.setNextStatement(true); } }; Blockly.Blocks['sumorobot_move'] = { init: function() { var OPERATORS = [ ['move stop', 'STOP'], ['move left', 'LEFT'], ['move right', 'RIGHT'], ['move search', 'SEARCH'], ['move forward', 'FORWARD'], ['move backward', 'BACKWARD'] ]; this.setColour('#d6382d'); var dropdown = new Blockly.FieldDropdown(OPERATORS); this.appendDummyInput().appendField(dropdown, 'MOVE'); this.setPreviousStatement(true); this.setNextStatement(true); } }; Blockly.Blocks['sumorobot_opponent'] = { init: function() { this.setColour('#0099E6'); this.appendDummyInput().appendField('opponent'); this.setOutput(true, 'Boolean'); } }; Blockly.Blocks['sumorobot_line'] = { init: function() { var OPERATORS = [ ['line left', 'LEFT'], ['line right', 'RIGHT'] ]; this.setColour('#E6BF00'); var dropdown = new Blockly.FieldDropdown(OPERATORS); this.appendDummyInput().appendField(dropdown, 'LINE'); this.setOutput(true, 'Boolean'); } }; Blockly.Python['sumorobot_sleep'] = function(block) { var code = 'sumorobot.sleep(' + parseFloat(block.getFieldValue('SLEEP')) + ');;' + block.id + '\n'; return code; }; Blockly.Python['sumorobot_move'] = function(block) { var code = 'sumorobot.move(' + block.getFieldValue('MOVE') + ');;' + block.id + '\n'; return code; }; Blockly.Python['sumorobot_opponent'] = function(block) { var code = 'sumorobot.is_opponent();;' + block.id; return [code, Blockly.Python.ORDER_ATOMIC]; }; Blockly.Python['sumorobot_line'] = function(block) { var code = 'sumorobot.is_line(' + block.getFieldValue('LINE') + ');;' + block.id; return [code, Blockly.Python.ORDER_ATOMIC]; }; // Inject Blockly var blocklyArea = document.getElementById('blocklyArea'); var blocklyDiv = document.getElementById('blocklyDiv'); workspace = Blockly.inject(blocklyDiv, { media: 'assets/blockly/media/', scrollbars: false, trashcan: true, sounds: true, zoom: { controls: true, startScale: 1.2 }, toolbox: document.getElementById('toolbox') }); // On Blockly resize var onresize = function(e) { // Compute the absolute coordinates and dimensions of blocklyArea. var element = blocklyArea; var x = 0; var y = 0; do { x += element.offsetLeft; y += element.offsetTop; element = element.offsetParent; } while (element); // Position blocklyDiv over blocklyArea blocklyDiv.style.left = x + 'px'; blocklyDiv.style.top = y + 'px'; blocklyDiv.style.width = blocklyArea.offsetWidth + 'px'; blocklyDiv.style.height = blocklyArea.offsetHeight + 'px'; // Resize the blockly svg Blockly.svgResize(workspace); }; window.addEventListener('resize', onresize, false); onresize(); // Retrieve the blocks var code = getLocalStorageItem('sumorobot.blockly'); // When there is code if (code) { // Convert it to XML var xml = Blockly.Xml.textToDom(code); // Resume the blocks from the XML Blockly.Xml.domToWorkspace(xml, workspace); } // On Blockly code change function onCodeChanged(event) { // When the if condition block was created if (event.type == Blockly.Events.CREATE && event.xml.getAttributeNode('type').nodeValue == 'controls_if') { // Remember the control_if block id controlBlockId = event.blockId; // Get the control_if block object var block = workspace.getBlockById(event.blockId); // When the control_if block doesn't already have an else if (block.elseCount_ == 0) { // Automatically add the else statement input block.elseCount_ = 1; block.updateShape_(); } // When the if condition block was removed } else if (event.type == Blockly.Events.DELETE && event.oldXml.getAttributeNode('type').nodeValue == 'controls_if') { // Remove the control_if block id controlBlockId = ''; // Enable the if condition block workspace.updateToolbox(document.getElementById('toolbox')); } // Only process change and move commands if (event.type != Blockly.Events.CHANGE && event.type != Blockly.Events.MOVE) return; // Show the code in the ace editor, filter out block IDs readOnlyCodingEditor.setValue(Blockly.Python.workspaceToCode(workspace).replace(/;;.{20}/g, '')); readOnlyCodingEditor.clearSelection(); // Save the code to the local storage var xml = Blockly.Xml.workspaceToDom(workspace); localStorage.setItem('sumorobot.blockly', Blockly.Xml.domToText(xml)); // When control_if block is used if (controlBlockId != '') { // Disable the if condition block workspace.updateToolbox(document.getElementById('toolbox_no_if')); } } // Add the change listener to Blockly workspace.addChangeListener(onCodeChanged); // Set a click listener on the document $(document).click(function(e) { // Get the event target var target = e.target; // When control_if block is in use if (controlBlockId != '') { // When the user clicks anywhere outside the mutator and not on the mutator icon if (!$(target).is('.blocklyBubbleCanvas') && !$(target).parents().is('.blocklyBubbleCanvas')) { if (!$(target).is('.blocklyIconGroup') && !$(target).parents().is('.blocklyIconGroup')) { // Hide the mutator workspace.getBlockById(controlBlockId).mutator.setVisible(false); } } } }); });
export function callIfExists(func, ...args) { return (typeof func === 'function') && func(...args); } export function hasOwnProp(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } export function uniqueId() { return Math.random().toString(36).substring(7); } export const cssClasses = { menu: 'react-contextmenu', menuVisible: 'react-contextmenu--visible', menuWrapper: 'react-contextmenu-wrapper', menuItem: 'react-contextmenu-item', menuItemActive: 'react-contextmenu-item--active', menuItemDisabled: 'react-contextmenu-item--disabled', menuItemDivider: 'react-contextmenu-item--divider', menuItemSelected: 'react-contextmenu-item--selected', subMenu: 'react-contextmenu-submenu' }; export const store = {}; export const canUseDOM = Boolean( typeof window !== 'undefined' && window.document && window.document.createElement );
var util = require('util'); var Q = require('q'); var jwt = require('jsonwebtoken'); var BaseCipher = require('./BaseCipher'); /** * Secret key for symmetric encoding * @type {String} * @private */ var SECRET_KEY = "53c5ec198c6f51575796da791e5350cd6362bb3c7953f7c259ac792b7a93265d"; /** * Algorithm that using for signing JWT * @type {String} * @private */ var ALGORITHM = "HS256"; /** * Time interval in minutes when token will be expired or false if not expires * @type {Number} * @private */ var EXPIRES = 60 * 24; util.inherits(JwtCipher, BaseCipher); /** * Create new JWT Cipher instance * @constructor */ function JwtCipher() { // TODO: think about token and payload attributes in object BaseCipher.apply(this, arguments); } /** * Sign payload with JSON Web Token * @returns {String} Returns JSON Web Token in string format */ JwtCipher.prototype.hashSync = function () { return jwt.sign(this.getContent(), SECRET_KEY, { algorithm: ALGORITHM, expiresInMinutes: EXPIRES }); }; /** * Verify token and returns decoded payload * @returns {Promise} */ JwtCipher.prototype.verify = function () { var defer = Q.defer(); jwt.verify(this.getContent(), SECRET_KEY, function (error, decoded) { if (error) { defer.reject(error); } else { defer.resolve(decoded); } }); return defer.promise; }; /** * Decode token without verification * @returns {Object} */ JwtCipher.prototype.decodeSync = function () { return jwt.decode(this.getContent()); }; module.exports = JwtCipher;
"enable aexpr"; import AbstractAstNode from './abstract-ast-node.js' export default class CompoundNodeCallFunctionShorthand extends AbstractAstNode { async initialize() { await super.initialize(); this.windowTitle = "CompoundNodeCallFunctionShorthand"; } async updateProjection() { await this.createSubElementForPath(this.path.get('body.callee.property'), 'property'); } }
seajs.config({ base: '../' }); define(function(require) { var test = require('../../../test'); var program = require('package/order-no-matter/program'); test.assert(program.result === 11, 'math program'); test.next() });
const copy = require("../../copy"); const path = require("path"); const fs = require("fs"); const { promisify } = require("util"); const templates = { test: { filename: path.join(__dirname, "templates", "example.js"), variable: "example" }, contract: { filename: path.join(__dirname, "templates", "Example.sol"), name: "Example", license: "MIT", variable: "example" }, migration: { filename: path.join(__dirname, "templates", "migration.js") } }; const replaceContents = (filePath, find, replacement) => { const data = fs.readFileSync(filePath, { encoding: "utf8" }); if (typeof find === "string") { find = new RegExp(find, "g"); } const result = data.replace(find, replacement); fs.writeFileSync(filePath, result, { encoding: "utf8" }); }; const toUnderscoreFromCamel = (string) => { string = string.replace(/([A-Z])/g, function ($1) { return "_" + $1.toLowerCase(); }); if (string[0] === "_") { string = string.substring(1); } return string; }; // getLicense return the license property value from Truffle config first and // in case that the file doesn't exist it will fallback to package.json const getLicense = (options) => { try { if ((license = require("@truffle/config").detect(options).license)) { return license; } } catch (err) { console.log(err); } try { return require(path.join(process.cwd(), "package.json")).license; } catch {} } const Create = { contract: async function (directory, name, options) { const from = templates.contract.filename; const to = path.join(directory, name + ".sol"); if (!options.force && fs.existsSync(to)) { throw new Error("Can not create " + name + ".sol: file exists"); } await promisify(copy.file.bind(copy))(from, to); replaceContents(to, templates.contract.name, name); if ((license = getLicense(options))) { replaceContents(to, templates.contract.license, license); } }, test: async function (directory, name, options) { let underscored = toUnderscoreFromCamel(name); underscored = underscored.replace(/\./g, "_"); const from = templates.test.filename; const to = path.join(directory, underscored + ".js"); if (!options.force && fs.existsSync(to)) { throw new Error("Can not create " + underscored + ".js: file exists"); } await promisify(copy.file.bind(copy))(from, to); replaceContents(to, templates.contract.name, name); replaceContents(to, templates.contract.variable, underscored); }, migration: async function (directory, name, options) { let underscored = toUnderscoreFromCamel(name || ""); underscored = underscored.replace(/\./g, "_"); const from = templates.migration.filename; let filename = (new Date().getTime() / 1000) | 0; // Only do seconds. if (name != null && name !== "") { filename += "_" + underscored; } filename += ".js"; const to = path.join(directory, filename); if (!options.force && fs.existsSync(to)) { throw new Error("Can not create " + filename + ": file exists"); } return await promisify(copy.file.bind(copy))(from, to); } }; module.exports = Create;
// helpers for getting information about DOM nodes class ElementQuery { constructor (el) { this.el = el; } get nodeName () { return this.el.nodeName.toLowerCase(); } get firstTextNodeValue () { const textNodes = Array.from(this.el.childNodes).filter(el => el.nodeType === 3); return textNodes.length ? textNodes[0].nodeValue : undefined; }; // returns the elements attributes as an object hasAttributesSetTo (mappings) { if (!this.el.hasAttributes()) { return false; } const keys = Object.keys(mappings); let matches = 0; keys.forEach(key => { if (this.el.hasAttribute(key) && (this.el.attributes[key].value === mappings[key])) { matches++; } }); return matches === keys.length; } hasClass (classToken) { return Array.from(this.el.classList).includes(classToken); } is (state) { const test = `_is${state.charAt(0).toUpperCase()}${state.slice(1)}`; if (ElementQuery.prototype.hasOwnProperty(test)) { return this[test](); } } // looks for a sibling before the el that matches the supplied test function // the test function gets sent each sibling, wrapped in an Element instance getPreviousSibling (test) { let node = this.el.previousElementSibling; let el; while(node) { el = element(node); if (test(el)) { return node; } node = node.previousElementSibling; } return null; } _isHidden () { const display = window.getComputedStyle(this.el).getPropertyValue('display'); return display === 'none'; } } // function to ask certain questions of a DOM Element function element (el) { return new ElementQuery(el); } exports.element = element;
/* eslint new-cap: [2, {"capIsNewExceptions": ["Match.ObjectIncluding", "Match.Optional"]}] */ import { Meteor } from 'meteor/meteor'; import { Match, check } from 'meteor/check'; Meteor.methods({ 'livechat:saveCustomField'(_id, customFieldData) { if (!Meteor.userId() || !RocketChat.authz.hasPermission(Meteor.userId(), 'view-livechat-manager')) { throw new Meteor.Error('error-not-allowed', 'Not allowed', { method: 'livechat:saveCustomField' }); } if (_id) { check(_id, String); } check(customFieldData, Match.ObjectIncluding({ field: String, label: String, scope: String, visibility: String })); if (!/^[0-9a-zA-Z-_]+$/.test(customFieldData.field)) { throw new Meteor.Error('error-invalid-custom-field-nmae', 'Invalid custom field name. Use only letters, numbers, hyphens and underscores.', { method: 'livechat:saveCustomField' }); } if (_id) { const customField = RocketChat.models.LivechatCustomField.findOneById(_id); if (!customField) { throw new Meteor.Error('error-invalid-custom-field', 'Custom Field Not found', { method: 'livechat:saveCustomField' }); } } return RocketChat.models.LivechatCustomField.createOrUpdateCustomField(_id, customFieldData.field, customFieldData.label, customFieldData.scope, customFieldData.visibility); }, });
'use strict' const vm = require('vm') const fs = require('fs') const callsite = require('callsite') const path = require('path') const threePath = path.join(require.resolve('three'), '..', '..') const context = {} Object.assign(context, global) context.console = { // disable console for new modules log: function () {}, time: function () {}, timeEnd: function () {}, error: function () {}, info: function () {}, warn: function () {} } /** * Loads a Javascript module * @param {String} src the path to the Javascript module * @returns {void} */ function loadModule (src) { const script = fs.readFileSync(src) vm.runInNewContext(script, context, src) } /** * Loads a internal THREE.js module from `node_modules` folder * @param {String} src the module path relative to the `node_modules/three` folder * @returns {void} */ function loadInternalModule (src) { const fullPath = path.join(threePath, src) loadModule(fullPath) } /** * Loads a local module relative to the calling file. * @param {String} src the module path relative to the calling file * @returns {void} */ function loadLocalModule (src) { const stack = callsite() const callerPath = stack[1].getFileName() const callerDirectory = path.dirname(callerPath) const fullPath = path.join(callerDirectory, src) loadModule(fullPath) } module.exports = { loadLocal: loadLocalModule, loadInternal: loadInternalModule }
var sl = require('sugarlisp-core/sl-types'), reader = require('sugarlisp-core/reader'); // the opening paren is treated as an operator in sugarscript // A normal parenthesized expression "(x)" is considered a prefix operator // But when used postfix e.g. "fn(x)" this is understood to be a function // call read in as an s-expression list of the form "(fn x)". And likewise // something more complex e.g. "obj.fn(x)" gets read as "((. obj fn) x)". // // Note the reader already understands that spaces *are* significant with postfix // operators i.e. "fn(x)" will be seen as a call whereas "fn (x)" will not for // the same reason "i++ j" is not confused with "i ++j". exports['('] = reader.operator({ prefix: reader.operator('prefix', 'unary', readparenthesizedlist, 1), // 17.5 is lower precedence than '.' and '~' (this is important!) postfix: reader.operator('postfix', 'binary', tradfncalltosexpr, 17.5) }); // this is just a helper for the above function readparenthesizedlist(lexer, opSpec, openingParenForm) { // note since '(' is defined as a prefix operator the '(' has already been read // read_delimited_list infers this because we pass openingParenForm below return reader.read_delimited_list(lexer, openingParenForm, ')'); } // NOT SURE WE NEEDED THIS AFTER ALL // sugarscript (esp) has customized read handlers for paren-free // "function(", "if(", etc. This "beforeRead" function makes sure // the reader doesn't treat those as normal function calls. // function noCustomReader(lexer, opSpec, leftForm) { // var retry; // var dialect = reader.get_current_dialect(lexer); // if(sl.isAtom(leftForm) && // dialect.syntax[leftForm.text] && // !dialect.syntax[leftForm.text] == reader.symbol) // { // // let the other handlers take it: // retry = reader.retry; // } // return retry; // } // postfix: reader.operator('postfix', 'unary', tradfncalltosexpr, 17.5, {altprefix: "fncall("}) // this is just a helper for the above // note the reader calls tradfncalltosexpr *after* reading the opening paren function tradfncalltosexpr(lexer, opSpec, leftForm, openingParenForm) { // do we really need this? // if(opSpec.options.altprefix) { // opForm = utils.clone(opForm); // opForm.value = opSpec.options.altprefix; // opForm.text = opSpec.options.altprefix; // } // whatever preceded the opening paren becomes the beginning of the list: return reader.read_delimited_list(lexer, openingParenForm, ')', [leftForm]); } // parenfree function declarations function handleFuncs(lexer, text) { // note we use "text" so we can handle both "function" and "function*" var functionToken = lexer.next_token(text); var list = sl.list(sl.atom(text, {token: functionToken})); // the next form tells if it's a named, anonymous, or match function // note the use of next_token here (as oppsed to reader.read) ensures "fn(x)" // in e.g. "function fn(x)" isn't read as a *call* i.e. "(fn x)". var fName; // note here we can only allow valid *javascript* function names // (because this ultimately generates real javascript named functions) if(lexer.on(/[a-zA-Z_$][0-9a-zA-Z_$\.]*/g)) { var token = lexer.next_token(/[a-zA-Z_$][0-9a-zA-Z_$\.]*/g); fName = sl.atom(token.text, {token: token}); list.push(fName); } // args if(lexer.on('(')) { var fArgs = reader.read_delimited_list(lexer, '(', ')', undefined); list.push(fArgs); } else if(lexer.on('~')) { // a macro declaring a function with unquoted args: list.push(reader.read(lexer)); } var fBody; if(lexer.on('{')) { // read what's inside the curly braces as a (begin..) block: fBody = reader.read_delimited_list(lexer, '{', '}', ["begin"]); list.push(fBody); } else if(lexer.on('(')) { fBody = reader.read(lexer); list.push(fBody); } if(!(fName || fBody)) { lexer.error("malformed function declaration - missing arguments or body"); } list.__parenoptional = true; return list; }; // named and anonymous functions exports['function'] = handleFuncs; // es6 generator functions exports['function*'] = handleFuncs; // parenfree yield exports['yield'] = reader.parenfree(1); exports['yield*'] = reader.parenfree(1); // sugarscript lets them omit parens on "export" exports['export'] = reader.parenfree(2); // "var" precedes a comma separated list of either: // name // or: // name = val // exports['var'] = function(lexer, text) { var varToken = lexer.next_token(text); var list = sl.list(sl.atom("var", {token: varToken})); var moreVars = true; while(moreVars) { var varNameToken = lexer.next_token(); var validName = /^[a-zA-Z_$][0-9a-zA-Z_$]*$/; if (!validName.test(varNameToken.text)) { lexer.error("Invalid character in var name", varNameToken); } var varNameSym = sl.atom(varNameToken); list.push(varNameSym); if(lexer.on('=')) { // it's got an initializer lexer.skip_text('='); list.push(reader.read(lexer)); } else { list.push("undefined"); } moreVars = lexer.on(','); if(moreVars) { lexer.skip_text(','); } } return list; }; exports['let'] = exports['var']; exports['const'] = exports['var']; // paren-free new keyword // note lispy core expects e.g. (new Date), (new Date "October 13, 1975 11:13") exports['new'] = function(lexer, text) { var newToken = lexer.next_token(text); var list = sl.list(sl.atom("new", {token: newToken})); var classConstructor = reader.read(lexer); // if(sl.isList(classConstructor)) { // // splice the values in // list.pushFromArray(classConstructor); // } // else { // push in the class name list.push(classConstructor); // } return list; }; // parenfree template declarations // note: the "template" overlaps the newer html dialect, but // we still support "template" for backward compatibility. exports['template'] = function(lexer) { var templateToken = lexer.next_token('template'); var list = sl.list(sl.atom("template", {token: templateToken})); var tName; if(lexer.on(/[a-zA-Z_$][0-9a-zA-Z_$\.]*/g)) { var token = lexer.next_token(/[a-zA-Z_$][0-9a-zA-Z_$\.]*/g); tName = sl.atom(token.text, {token: token}); list.push(tName); } else { lexer.error("invalid template name"); } // args if(lexer.on('(')) { list.push(reader.read(lexer)); } else { lexer.error("template arguments should be enclosed in parentheses"); } if(lexer.on('{')) { var tBody = reader.read(lexer); tBody.forEach(function(expr,i) { if(i > 0) { list.push(expr); } }); } else { lexer.error("template bodies in sugarscript are enclosed in {}"); } list.__parenoptional = true; return list; }; // parenfree macro declarations exports['macro'] = function(lexer) { var macroToken = lexer.next_token('macro'); var list = sl.list(sl.atom("macro", {token: macroToken})); // the next form tells if it's a named or anonymous macro var mName; // note here we do allow "lispy names" (i.e. more legal chars than javascript) if(lexer.on(/[a-zA-Z_$][0-9a-zA-Z_$\.\?\-\>]*/g)) { var token = lexer.next_token(/[a-zA-Z_$][0-9a-zA-Z_$\.\?\-\>]*/g); mName = sl.atom(token.text, {token: token}); list.push(mName); } // args are surrounded by parens (even in sugarlisp core) if(lexer.on('(')) { list.push(reader.read(lexer)); } else { lexer.error("a macro declaration's arguments should be enclosed in ()"); } // in sugarscript the macro body is wrapped in {...} // note this is purely a grammar thing (it is *not* saying every macro is a "do") // also note that the reading of the macro body uses whatever dialects are // current i.e. the macro body is written in the dialect of the containing file. if(lexer.on('{')) { list.push(reader.read_wrapped_delimited_list(lexer, '{', '}')); } else { lexer.error("a macro declaration's body should be enclosed in {}"); } list.__parenoptional = true; return list; }; // sugarscript's "cond" and "switch" are paren free but they put {} around the body // and use case/default in front of each condition // note: text will be either "cond" or "switch" /* DELETE? handleCondCase = function(lexer, text) { var condToken = lexer.next_token(text); var list = sl.list(sl.atom(text, {token: condToken})); if(text === "case") { // switch has the item to match (cond does not) // as with javascript - the switch value is wrapped in parens list.push(reader.read_wrapped_delimited_list(lexer, '(',')')); } if(lexer.on('{')) { var body = reader.read_delimited_list(lexer, '{', '}'); if((body.length % 2) === 0) { body.forEach(function(caseForm) { // the body has pairs: if(sl.isList(caseForm)) { if(sl.valueOf(caseForm[0]) === 'case') { list.push(caseForm[1]); list.push(caseForm[2]); } else if(sl.valueOf(caseForm[0]) === 'default') { list.push(sl.atom(true)); list.push(caseForm[1]); } else { lexer.error('a ' + text + ' expects "case" or "default" in its body'); } } else { lexer.error('a ' + text + ' expects "case" or "default" in its body'); } }) } else { lexer.error("a " + text + " requires an even number of match pairs in it's body"); } } else { lexer.error("a " + text + " body should be enclosed in {}"); } list.__parenoptional = true; return list; }; exports['cond'] = handleCondCase; exports['case'] = handleCondCase; */ // we're doing cond and case in a *slightly* more javascripty syntax like e.g. // cond { (x === 0) "zero"; (x > 0) "positive"; } // and // case(x) { 0 "zero"; 1 "one"; true "other"; } exports['cond'] = reader.parenfree(1, { bracketed: 1, validate: function(lexer, forms) { // note the forms list *starts* with 'cond' hence the -1: if(((forms.length-1) % 2) !== 0) { lexer.error("a cond requires an even number of match pairs in it's body"); } } }); exports['case'] = reader.parenfree(2, { parenthesized: 1, bracketed: 2, validate: function(lexer, forms) { // note the forms list *starts* with 'case' and match hence the -2: if(((forms.length-2) % 2) !== 0) { lexer.error("a case requires an even number of match pairs in it's body"); } } }); // sugarscript's "match" is paren free except for parens around // the thing to match (like the parens in "switch", "if", etc) exports['match'] = function(lexer) { var matchToken = lexer.next_token('match'); var matchAgainstList = reader.read(lexer); if(!(sl.isList(matchAgainstList))) { lexer.error("the expression to match must be surrounded by parentheses"); } // the parens are just syntax sugar - reach inside: var matchAgainst = matchAgainstList[0]; var list = sl.list(sl.atom("match", {token: matchToken})); list.push(matchAgainst); // the match cases are expected to be a single form surrounded by {} list.push(reader.read(lexer)); list.__parenoptional = true; return list; }; // match case/default do not need parens in sugarscript: //exports['case'] = reader.parenfree(2); //exports['default'] = reader.parenfree(1); // sugarscript's "try" is paren free // note: lispy core's treats all but the final catch function as the body // but sugarscript requires that a multi-expression body be wrapped in {} exports['try'] = function(lexer) { var tryToken = lexer.next_token('try'); var tryBody = reader.read(lexer); if(!(sl.isList(tryBody))) { lexer.error("try expects a body enclosed in () or {}"); } var catchToken = lexer.next_token('catch'); var catchArgs = reader.read(lexer); if(!(sl.isList(catchArgs))) { lexer.error("give a name to the exception to catch enclosed in ()"); } var catchBody = reader.read(lexer); if(!(sl.isList(catchBody))) { lexer.error("the catch body must be enclosed in () or {}"); } var list = sl.list(sl.atom("try", {token: tryToken})); list.push(tryBody); list.push(sl.list(sl.atom('function'), catchArgs, catchBody)); list.__parenoptional = true; return list; }; exports['throw'] = reader.parenfree(1); // assignment exports['='] = reader.infix(6, {altprefix:"set"}); // the following can be used infix or prefix // precedence from: http://www.scriptingmaster.com/javascript/operator-precedence.asp // since for us higher precedence is a higher (not lower) number, ours are // 20 - the numbers you see in the table on the page above exports['*'] = reader.infix(17); // DELETE exports['/'] = reader.infix(17); // what about regexes !!?? exports['%'] = reader.infix(17); exports['+'] = reader.infix(16); // note that right now in sugarscript e.g. "(- 1 5)" gets parsed as "((- 1) 5)" // have not found an easy fix - ignoring for now (after all they would most likely // use infix in sugarscript anyway). Possibly some special case handling is // needed - though it may be best in the end to *not* support prefix notation // in sugarscript at all ("simplicity" and "reliability" > "flexibility"!!) exports['-'] = reader.operator({ prefix: reader.prefix(18, { assoc: "right" }), infix: reader.infix(16) }); exports[">>"] = reader.infix(15); exports["<<"] = reader.infix(15); exports[">>>"] = reader.infix(15); exports[">"] = reader.infix(14); exports[">="] = reader.infix(14); exports["<"] = reader.infix(14); exports["<="] = reader.infix(14); exports['==='] = reader.infix(13); exports['=='] = reader.infix(13); exports['!='] = reader.infix(13); exports['!=='] = reader.infix(13); exports["&&"] = reader.infix(9); exports["||"] = reader.infix(8); exports["+="] = reader.infix(7); exports["-="] = reader.infix(7); exports["*="] = reader.infix(7); exports["/="] = reader.infix(7); exports["%="] = reader.infix(7); exports["<<="] = reader.infix(7); exports[">>="] = reader.infix(7); exports[">>>="] = reader.infix(7); exports['/'] = reader.operator({ prefix: reader.operator('prefix', 'unary', regex2expr, 18, { assoc: "right" }), infix: reader.infix(17) }); function regex2expr(lexer, opSpec, openingSlashForm) { // desugar to core (regex ..) return sl.list("regex", sl.addQuotes(sl.valueOf(reader.read_delimited_text(lexer, undefined, "/", {includeDelimiters: false})))); } exports["?"] = reader.operator('infix', 'binary', ternary2prefix, 7); function ternary2prefix(lexer, opSpec, conditionForm, questionMarkForm) { var thenForm = reader.read(lexer); lexer.skip_token(":"); var elseForm = reader.read(lexer, opSpec.precedence-1); return sl.list("ternary", conditionForm, thenForm, elseForm); } // if? expression exports['if?'] = function(lexer) { var ifToken = lexer.next_token('if?'); // OLD DELETE var condition = reader.read(lexer); // as with javascript - the condition is wrapped in parens var condition = reader.read_wrapped_delimited_list(lexer, '(',')'); // if in core *is* an expression (a ternary) var list = sl.list(sl.atom("if?", {token: ifToken})); list.push(condition); list.push(reader.read(lexer)); // note: if there's an else they *must* use the keyword "else" if(lexer.on('else')) { // there's an else clause lexer.skip_text('else'); list.push(reader.read(lexer)); } list.__parenoptional = true; return list; }; // statements /////////////////////////////////////////////////////// // the following are paren-free readers for commands that support use // of javascript *statements*. Even "return" is supported. And yes - // this is really weird for a "lisp"! // if statement exports['if'] = function(lexer) { var ifToken = lexer.next_token('if'); condition = reader.read_wrapped_delimited_list(lexer, '(', ')'); // note: scripty generates if *statements* - so we use "ifs" (not just "if") var list = sl.list(sl.atom("if", {token: ifToken})); list.push(condition); if(lexer.on('{')) { // we use "begin" here to avoid an an IIFE wrapper: list.push(reader.read_delimited_list(lexer, '{', '}', [sl.atom('begin')])); } else { // a single form for the true path: list.push(reader.read(lexer)); } // note: if there's an else they *must* use the keyword "else" if(lexer.on('else')) { // there's an else clause lexer.skip_text('else'); if(lexer.on('{')) { // we use "begin" here to avoid an an IIFE wrapper: list.push(reader.read_delimited_list(lexer, '{', '}', [sl.atom('begin')])); } else { // a single form for the else path: list.push(reader.read(lexer)); } } list.__parenoptional = true; return list; }; // return // it's odd to even consider having return in a lisp (where everything // is an expression). Yet the statement/expression distinction is // ingrained in javascript programmers. And the lack of statements // makes sugarlisp's generated code more complex (lots of IIFEs) where // it has to ensure everything can compose as an expression. exports['return'] = function(lexer) { // is this a "return <value>" or a "return;" (i.e. return undefined)? // note: we *require* the semicolon if they're returning undefined // (otherwise they can literally do "return undefined") var returnNothing = lexer.on("return;"); var list = sl.list(sl.atom("return", {token: lexer.next_token('return')})); if(!returnNothing) { list.push(reader.read(lexer)); } list.__parenoptional = true; return list; }; // for statement exports['for'] = function(lexer) { var forToken = lexer.next_token('for'); var list = sl.list(sl.atom("for", {token: forToken})); if(lexer.on('(')) { lexer.skip_text('('); // initializer list.push(reader.read(lexer)); // condition list.push(reader.read(lexer)); // final expr list.push(reader.read(lexer)); if(!lexer.on(')')) { lexer.error("Missing expected ')'" + lexer.snoop(10)); } lexer.skip_text(')'); if(lexer.on('{')) { list.push(reader.read_delimited_list(lexer, '{', '}', [sl.atom("begin")])); } else { list.push(reader.read(lexer)); } } else { lexer.error("A for loop must be surrounded by ()"); } list.__parenoptional = true; return list; }; // switch statement exports['switch'] = function(lexer) { var switchToken = lexer.next_token('switch'); var switchon = reader.read_wrapped_delimited_list(lexer, '(', ')'); var list = sl.list(sl.atom("switch", {token: switchToken})); list.push(switchon); if(!lexer.on('{')) { lexer.error("The body of a switch must be wrapped in {}"); } lexer.skip_token('{'); var read_case_body = function(lexer) { var body = sl.list(sl.atom("begin")); // read up till the *next* case/default or the end: while(!lexer.eos() && !lexer.on(/case|default|}/g)) { var nextform = reader.read(lexer); // some "directives" don't return an actual form: if(!reader.isignorableform(nextform)) { body.push(nextform); } } return body; }; var token; while (!lexer.eos() && (token = lexer.peek_token()) && token && token.text !== '}') { // the s-expression is like cond - in pairs: // (note the default can't be "true" like cond - switches match *values*) var casetoken = lexer.next_token(); var caseval = casetoken.text === 'case' ? reader.read(lexer) : sl.atom('default'); if(!lexer.on(":")) { lexer.error('Missing ":" after switch case?'); } lexer.skip_token(":"); list.push(caseval); list.push(read_case_body(lexer)); } if (!token || lexer.eos()) { lexer.error('Missing "}" on switch body?', switchToken); } var endToken = lexer.next_token('}'); // skip the '}' token list.setClosing(endToken); return list; }; exports['do'] = reader.parenfree(1, {bracketed: 1}); // paren free "while" takes a condition and a body exports['while'] = reader.parenfree(2, {parenthesized: 1, bracketed: 2}); // paren free "dotimes" takes (var, count) then body exports['dotimes'] = reader.parenfree(2, {parenthesized: 1, bracketed: 2}); // paren free "each" takes a list/array plus a function called with: each element, // the position in the list, and the whole list. exports['each'] = reader.parenfree(2);
'use strict'; angular.module('activities').controller('ActivitiesController', [ '$scope', '$stateParams', '$state', '$location', '$timeout', 'Authentication', 'Activities', 'FileUploader', function($scope, $stateParams, $state, $location, $timeout, Authentication, Activities, FileUploader) { $scope.authentication = Authentication; $scope.uploader = new FileUploader({ url: 'activities/' + $stateParams.activityId + '/upload', onSuccessItem: function () { $state.go('app.editActivity', { activityId: $scope.activity._id}) } }); // Create $scope.activity = new Activities(); $scope.create = function() { $scope.activity.$save(function(response) { $state.go('app.listActivities'); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; $scope.isCreate = false; if ($state.current.url === '/activities/create') { $scope.isCreate = true; } // Remove $scope.remove = function() { $scope.activity.$remove(function() { $state.go('app.listActivities'); }); }; // Update $scope.update = function() { $scope.activity.$update(function() { $state.go('app.viewActivity', { activityId: $scope.activity._id}) }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; // View $scope.printQR = function() { var dataUrl = document.getElementsByTagName('canvas')[0].toDataURL(); var windowContent = ['<!DOCTYPE html>', '<html>', '<head><title>Print QR Code</title></head>', '<body>', '<img src="' + dataUrl + '">', '</body>', '</html>' ].join(''); var printWin = window.open('','','width=800,height=600'); printWin.document.open(); printWin.document.write(windowContent); printWin.document.close(); printWin.focus(); printWin.print(); printWin.close(); } $scope.findOne = function(disabled) { if(typeof(disabled) !== 'undefined') { $scope.viewPage = true; } Activities.get({ activityId: $stateParams.activityId }, function(response) { $scope.activity = response; $scope.qrOptions = { data: 'a-' + $scope.activity._id, version: 2, errorCorrectionLevel: 'M', size: 200 // px size }; }); }; // List $timeout(function(){ var activitiesTable; if ( ! $.fn.dataTable ) return; activitiesTable = $('#activitiesTable').dataTable({ 'paging': true, // Table pagination 'ordering': true, // Column ordering 'info': true, // Bottom left status text // Text translation options // Note the required keywords between underscores (e.g _MENU_) oLanguage: { sSearch: 'Search: ', sLengthMenu: '_MENU_ records per page', info: 'Showing page _PAGE_ of _PAGES_', zeroRecords: 'Nothing found - sorry', infoEmpty: 'No records available', infoFiltered: '(filtered from _MAX_ total records)' } }); $scope.activities = Activities.query(function(items) { var data = []; var editRoute = ''; var editAction = ''; var removeAction = ''; var action = ''; var image = ''; angular.forEach(items, function(value, key) { action = '<div class="pull-left">'; editRoute = '#!/activities/' + value._id + '/edit'; editAction = '<a style="display:inline; margin-right: 2px;" class="btn btn-primary" href="' + editRoute + '"><i class="fa fa-edit"></i></a>'; action += editAction + '</div>'; if (value.image) { image = '<img height="60" width="60" src="' + value.image + '"/>'; } data[key] = [ '<a href="#!/activities/' + value._id + '">' + value.name + '</a>', value.actionLabel, value.points, value.description, image, action ]; }); if (data.length) { activitiesTable.fnAddData(data); } }); var inputSearchClass = 'datatable_input_col_search'; var columnInputs = $('tfoot .'+inputSearchClass); // On input keyup trigger filtering columnInputs .keyup(function () { activitiesTable.fnFilter(this.value, columnInputs.index(this)); }); $scope.$on('$destroy', function(){ activitiesTable.fnDestroy(); $('[class*=ColVis]').remove(); }); }); } ]);
const expect = require("expect.js"); const eio = require("../"); const { isIE11, isAndroid, isEdge, isIPad } = require("./support/env"); const FakeTimers = require("@sinonjs/fake-timers"); describe("Socket", function() { this.timeout(10000); describe("filterUpgrades", () => { it("should return only available transports", () => { const socket = new eio.Socket({ transports: ["polling"] }); expect(socket.filterUpgrades(["polling", "websocket"])).to.eql([ "polling" ]); socket.close(); }); }); it("throws an error when no transports are available", done => { const socket = new eio.Socket({ transports: [] }); let errorMessage = ""; socket.on("error", error => { errorMessage = error; }); socket.open(); setTimeout(() => { expect(errorMessage).to.be("No transports available"); socket.close(); done(); }); }); describe("fake timers", function() { before(function() { if (isIE11 || isAndroid || isEdge || isIPad) { this.skip(); } }); it("uses window timeout by default", done => { const clock = FakeTimers.install(); const socket = new eio.Socket({ transports: [] }); let errorMessage = ""; socket.on("error", error => { errorMessage = error; }); socket.open(); clock.tick(1); // Should trigger error emit. expect(errorMessage).to.be("No transports available"); clock.uninstall(); socket.close(); done(); }); it.skip("uses custom timeout when provided", done => { const clock = FakeTimers.install(); const socket = new eio.Socket({ transports: [], useNativeTimers: true }); let errorMessage = ""; socket.on("error", error => { errorMessage = error; }); socket.open(); // Socket should not use the mocked clock, so this should have no side // effects. clock.tick(1); expect(errorMessage).to.be(""); clock.uninstall(); setTimeout(() => { try { expect(errorMessage).to.be("No transports available"); socket.close(); done(); } finally { } }, 1); }); }); });
/* ======================================================================== * DOM-based Routing * Based on http://goo.gl/EUTi53 by Paul Irish * * Only fires on body classes that match. If a body class contains a dash, * replace the dash with an underscore when adding it to the object below. * * .noConflict() * The routing is enclosed within an anonymous function so that you can * always reference jQuery with $, even when in .noConflict() mode. * * Google CDN, Latest jQuery * To use the default WordPress version of jQuery, go to lib/config.php and * remove or comment out: add_theme_support('jquery-cdn'); * ======================================================================== */ (function($) { function getCookie(name) { var matches = document.cookie.match(new RegExp( "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)" )); return matches ? decodeURIComponent(matches[1]) : undefined; } // options - объект с свойствами cookie (expires, path, domain, secure) function setCookie(name, value, options) { options = options || {}; var expires = options.expires; if (typeof expires === "number" && expires) { var d = new Date(); d.setTime(d.getTime() + expires*1000); expires = options.expires = d; } if (expires && expires.toUTCString) { options.expires = expires.toUTCString(); } value = encodeURIComponent(value); var updatedCookie = name + "=" + value; for(var propName in options) { updatedCookie += "; " + propName; var propValue = options[propName]; if (propValue !== true) { updatedCookie += "=" + propValue; } } document.cookie = updatedCookie; } function deleteCookie(name) { setCookie(name, "", { expires: -1 }); } var debounce = function(func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate){ func.apply(context, args); } }; if (immediate && !timeout){ func.apply(context, args); } clearTimeout(timeout); timeout = setTimeout(later, wait); }; }; function initCrewPersons(holder){ var crewTiles = $(holder).find('.item'); var persons = $(holder).find('.persons'); if(crewTiles.length){ crewTiles.each(function(i){ i++; $(this).hover(function(){ persons.toggleClass('active-'+i); }); if(i === crewTiles.length){ $('body').data('crew_persons_loaded', true); } }); } } function initCreationBottles(holder){ var creationBottles = $(holder).find('.item'); var timeout = $(holder).data('timeout'); if(creationBottles.length && !$('body').data('creation_bottles_loaded')){ creationBottles.each(function(i){ i++; var range = $(this).find('.range'); setTimeout(function(){ range.css('height' , '0').animate({ 'height' : range.data('perc') }, timeout, 'easeInOutQuart'); }, i*200); if(i === creationBottles.length){ $('body').data('creation_bottles_loaded', true); } }); } } function initializeMaps(selector, myLatlng, image, zoom) { var mapOptions = { scrollwheel: false, center: myLatlng, zoom: zoom, mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'tehgrayz'] } }; var stylez = [ { featureType: "all", elementType: "all", stylers: [ { saturation: -100 } ] } ]; var map = new google.maps.Map(document.getElementById(selector.substr(1) + "-wrapper"), mapOptions); var mapType = new google.maps.StyledMapType(stylez, { name:"Grayscale" }); map.mapTypes.set('tehgrayz', mapType); map.setMapTypeId('tehgrayz'); // To add the marker to the map, use the 'map' property var marker = new google.maps.Marker({ position: myLatlng, title:"Nielsen Design", animation: google.maps.Animation.DROP, icon: image }); google.maps.event.addListener(marker, 'click', function(){ toggleBounce(marker); }); marker.setMap(map); } function toggleBounce(marker) { if (marker.getAnimation() != null) { marker.setAnimation(null); } else { marker.setAnimation(google.maps.Animation.BOUNCE); } } function showGmaps(selector){ // Google Maps if(typeof google !== "undefined"){ var mapHolder = $(selector); var myLatlng = new google.maps.LatLng(mapHolder.data('latitude'), mapHolder.data('longitude')); var image = mapHolder.data('marker'); var zoom = mapHolder.data('zoom'); mapHolder.removeAttr('data-latitude'); mapHolder.removeAttr('data-longitude'); mapHolder.removeAttr('data-marker'); mapHolder.removeAttr('data-zoom'); /* google.maps.event.addDomListener(window, 'load', initialize); */ $(selector).find('img').waypoint(function() { if(!$(this).data('map_loaded')){ initializeMaps(selector, myLatlng, image, zoom); $(this).data('map_loaded', true); } }, { offset: 'bottom-in-view'}); } } function requiredFieldsText(text){ var required_fields = $('.gfield_required'); if(required_fields.length){ required_fields.text(text); } } // Init tiles grid function initTiles(element) { $(element).each(function(i){ var dataTemplate = $(this).data('template'); var demoTemplateRows = [ [ " A A A A B B B B B B C C C F F F F F F F F F I I I I I I J J J J L L L L L M M M M M M", " A A A A B B B B B B C C C F F F F F F F F F I I I I I I J J J J L L L L L M M M M M M", " A A A A B B B B B B C C C F F F F F F F F F I I I I I I J J J J L L L L L M M M M M M", " A A A A B B B B B B C C C F F F F F F F F F I I I I I I J J J J L L L L L M M M M M M", " A A A A B B B B B B C C C F F F F F F F F F I I I I I I J J J J L L L L L N N N N N N", " D D D D E E E E E E E E E F F F F F F F F F I I I I I I J J J J L L L L L N N N N N N", " D D D D E E E E E E E E E F F F F F F F F F I I I I I I K K K K K K K K K N N N N N N", " D D D D E E E E E E E E E G G G G G H H H H I I I I I I K K K K K K K K K N N N N N N", " D D D D E E E E E E E E E G G G G G H H H H I I I I I I K K K K K K K K K O O O O O O", " D D D D E E E E E E E E E G G G G G H H H H I I I I I I K K K K K K K K K O O O O O O", " D D D D E E E E E E E E E G G G G G H H H H I I I I I I K K K K K K K K K O O O O O O", " D D D D E E E E E E E E E G G G G G H H H H I I I I I I K K K K K K K K K O O O O O O" ] ]; demoTemplateRows.push(dataTemplate); $(this).removeAttr('data-template'); var el = $(this), grid = new Tiles.Grid(el), tiles = el.children('.tile'); var TILE_IDS = el.data('ids-array'); $(this).removeAttr('data-ids-array'); // template is selected by user, not generated so just // return the number of columns in the current template grid.resizeColumns = function() { return this.template.numCols; }; grid.cellPadding = 0; // by default, each tile is an empty div, we'll override creation // to add a tile number to each div grid.createTile = function(tileId) { var tile = new Tiles.Tile(tileId); tile.$el.append(tiles[tileId]); return tile; }; function updateTemplate(template){ // get the JSON rows for the selection var rows = template[1] ? template[1] : template[0]; // set the new template and resize the grid grid.template = Tiles.Template.fromJSON(rows); grid.isDirty = true; grid.resize(); // adjust number of tiles to match selected template var ids = TILE_IDS.slice(0, grid.template.rects.length); grid.updateTiles(ids); grid.redraw(true); } // wait until users finishes resizing the browser var debouncedResize = debounce(function() { updateTemplate(demoTemplateRows); }, 100); // when the window resizes, redraw the grid $(window).resize(debouncedResize).trigger('resize'); }); } function productsLightbox(selector){ var el = $(selector); var data = {}; var output; data.action = 'getProducts'; $.post('/wp-admin/admin-ajax.php', data, function(response) { showModal(response, 'products'); }); } function showModal(response, id){ var _modal = $(response); _modal.prop('id', 'modal-'+id); _modal.modal(); } function initProductsModal(selector){ $(selector).on('click', function(e){ e.preventDefault(); var url = $(this).attr('href'); if ($(url).length) { $(url).modal('show'); } else { productsLightbox(this); } }); } function resizeBanner(top){ var slider = $('#home-slider'); if(slider.length){ var sliderOffset = slider.offset(); var sliderHeight = $.waypoints('viewportHeight') - $('#mainnav').outerHeight() - top; slider.css({ 'height' : Math.round(sliderHeight) + 'px' }); } slider.find('.item:not(.active) .text').css({ 'opacity' : 0 }); slider .on('slide.bs.carousel', function () { $(this).find('.item:not(.active) .text') .css({ 'opacity' : 0 }); }) .on('slid.bs.carousel', function () { var activeSlide = $(this).find('.item.active'); activeSlide.find('.text') .animate({ 'opacity' : 1 }, 500, 'easeInExpo'); /*if(activeSlide.siblings().length === activeSlide.index()){ slider.carousel('pause'); }*/ }); } function panelShowCallback(target){ $(target) .each(function(){ var id = this.id.replace(/panel-/g, ''); if(id === 'creation'){ initCreationBottles('#creation-bottles'); } if(!$('body').data(id + '-shown')){ $(this).addClass('animated'); $('body').data(id + '-shown', true); } }); } function fitScreen(el){ var top = $('#navbar').outerHeight() + $('.navbar-brand').outerHeight(); if(el === 'panel'){ $('.panel').each(function(i){ var self = $(this); self.css({ 'padding-top' : (i === 0) ? top : 0, 'min-height' : $.waypoints('viewportHeight') - top }); }); }else if(el === 'page'){ $('.main').css({ 'padding-top' : top, 'padding-bottom' : $('#mainnav').outerHeight() + $('.content-info').outerHeight() }); $('#mainnav').css({ 'margin-bottom' : $('.content-info').outerHeight() }); } resizeBanner(top); } function replaceHash(hash){ //hash = hash.replace( /^#/, '' ); var fx, node = $( '#' + hash ); if ( node.length ) { node.attr( 'id', '' ); fx = $( '<div></div>' ) .css({ position:'absolute', visibility:'hidden', top: $(document).scrollTop() + 'px' }) .attr( 'id', hash ) .appendTo( document.body ); } window.location.hash = hash; if ( node.length ) { fx.remove(); node.attr( 'id', hash ); } } function initWaypoints(){ $('.panel') .waypoint(function(direction) { $('body').toggleClass(this.id + '-visible', direction === 'down'); $(this).toggleClass('visible', direction === 'down'); $('a[href="#' + this.id + '"]').parent().toggleClass('active', direction === 'down'); if($(window).width() > 480){ panelShowCallback(this); } if(direction === 'down' && !$('body').data('animated')){ if($(window).width() > 480){ replaceHash(this.id); } } }, { offset: '49%' }) .waypoint(function(direction) { $('body').toggleClass(this.id + '-visible', direction === 'up'); $(this).toggleClass('visible', direction === 'up'); $('a[href="#' + this.id + '"]').parent().toggleClass('active', direction === 'up'); if(direction === 'up' && !$('body').data('animated')){ if($(window).width() > 480){ replaceHash(this.id); } } }, { offset: function() { return $.waypoints('viewportHeight') / 2 - $(this).outerHeight(); } }); /* Show/hide menu */ $('.wrap') .waypoint(function(direction) { $('#mainnav').toggleClass('hidden', direction === 'down'); }, { offset: 'bottom-in-view' }); } function prepareNav(selector){ $(selector).find('ul.navbar-nav li a').each(function(){ var re = /\w*-?\w*(?=\/$)/gi; var hash = $(this).attr('href').match(re)[0]; $(this).attr('href', '#panel-' + hash); }); } function smoothScroll(selector){ $(selector).each(function(i) { var $panel = $(this); var hash = this.id; $('a[href="' + '#' + hash + '"]').on('click', function(event){ var offset = $panel.offset(); var top = Math.round(offset.top) - ($('#navbar').outerHeight() + $('.navbar-brand').outerHeight()); $('body').data('animated', true); $('html, body').stop().animate({ scrollTop: top }, 1000, 'easeOutExpo', function() { replaceHash(hash); $('body').removeData('animated'); }); event.preventDefault(); }); }); } // Use this variable to set up the common and page specific functions. If you // rename this variable, you will also need to rename the namespace below. var Roots = { // All pages common: { init: function() { // JavaScript to be fired on all pages // Replacement for required text requiredFieldsText('(Required)'); // crew persons highlight initCrewPersons('#crew-tiles'); if(!$('body.home').length){ // creation bottles animation initCreationBottles('#creation-bottles'); $(window) .resize(function(){ fitScreen('page'); }) .load(function(){ $(this).trigger('resize'); }); } // google maps showGmaps('#map'); // tile grid gallery initTiles('.tile-grid'); // lightbox for 'view all products' link initProductsModal('a[rel=gallery-2]'); //init showcase gallery coockie navigation if($('#showcase-gallery').length){ var id = getCookie('galleryID'), galleryCont = $('#showcase-gallery'), tiles = galleryCont.find('a.caption'), items = galleryCont.find('.item'), options = { 'expires' : 0, 'path' : '/' }; if(id){ galleryCont.carousel(+id); } tiles.on('click', function(){ var activeItemID = items.filter('.active').index(); setCookie('galleryID', activeItemID, options); }); } } }, // Home page home: { init: function() { //var templatePath = $('body').data('template-path'); prepareNav('#mainnav'); smoothScroll('.panel'); /* Force snap to panel on resize. */ var timer; $(window) .resize(function() { fitScreen('panel'); window.clearTimeout(timer); timer = window.setTimeout(function() { var hash = window.location.hash ? window.location.hash : '#panel-home'; var $panel = $(hash); var offset = $panel.offset(); var top = Math.round(offset.top) - ($('#navbar').outerHeight() + $('.navbar-brand').outerHeight()); $('body').data('animated', true); $('html, body').stop().animate({ scrollTop: top }, 1000, 'easeOutExpo', function() { $('body').removeData('animated'); }); }, 100); }) .load(function(){ if($(window).width() <= 480){ panelShowCallback('.panel'); } initWaypoints(); $(this).trigger('resize'); }); } } }; // The routing fires all common scripts, followed by the page specific scripts. // Add additional events for more control over timing e.g. a finalize event var UTIL = { fire: function(func, funcname, args) { var namespace = Roots; funcname = (funcname === undefined) ? 'init' : funcname; if (func !== '' && namespace[func] && typeof namespace[func][funcname] === 'function') { namespace[func][funcname](args); } }, loadEvents: function() { UTIL.fire('common'); $.each(document.body.className.replace(/-/g, '_').split(/\s+/),function(i,classnm) { UTIL.fire(classnm); }); } }; $(document).ready(UTIL.loadEvents); })(jQuery); // Fully reference jQuery after this point.
import './announcements.users.component.css'; export const AnnouncementUsersComponent = { template: require('./announcements.users.component.html'), controllerAs: 'vm', controller: class AnnouncementUsersComponent { constructor(AnnouncementService, $stateParams, $scope) { 'ngInject'; this.announcementService = AnnouncementService; this.$stateParams = $stateParams; this.$scope = $scope; } $onInit() { this.users = []; this.announcementService.getUsers(this.$stateParams.id, (user)=> { this.$scope.$apply(()=>{ this.users.push(user); }); }); } } };
function HTMLActuator() { this.tileContainer = document.querySelector(".tile-container"); this.scoreContainer = document.querySelector(".score-container"); this.bestContainer = document.querySelector(".best-container"); this.messageContainer = document.querySelector(".game-message"); this.score = 0; } HTMLActuator.prototype.actuate = function (grid, metadata) { var self = this; window.requestAnimationFrame(function () { self.clearContainer(self.tileContainer); grid.cells.forEach(function (column) { column.forEach(function (cell) { if (cell) { self.addTile(cell); } }); }); self.updateScore(metadata.score); self.updateBestScore(metadata.bestScore); if (metadata.terminated) { if (metadata.over) { self.message(false); // You lose } else if (metadata.won) { self.message(true); // You win! } } }); }; // Continues the game (both restart and keep playing) HTMLActuator.prototype.continueGame = function () { this.clearMessage(); }; HTMLActuator.prototype.clearContainer = function (container) { while (container.firstChild) { container.removeChild(container.firstChild); } }; HTMLActuator.prototype.addTile = function (tile) { var self = this; var wrapper = document.createElement("div"); var inner = document.createElement("div"); var position = tile.previousPosition || { x: tile.x, y: tile.y }; var positionClass = this.positionClass(position); // for later use -- dotted notes... var valueRounded = Math.pow(2, Math.floor(Math.log(tile.value) / Math.log(2))) // We can't use classlist because it somehow glitches when replacing classes var classes = ["tile", "tile-" + valueRounded, positionClass]; if (tile.value > 2048) classes.push("tile-super"); this.applyClasses(wrapper, classes); inner.classList.add("tile-inner"); var tileCharacters = ["\uE95F", "\uE93C", "\uE95E", "\uE95D", "\uE95C", "\uE955", "\uE954", "\uE953", "\uE952", "\uE951", "\uE950", "\uE92C", "\uE92D"]; inner.textContent = tileCharacters[(Math.log(valueRounded) / Math.log(2)) - 1]; if (tile.previousPosition) { // Make sure that the tile gets rendered in the previous position first window.requestAnimationFrame(function () { classes[2] = self.positionClass({ x: tile.x, y: tile.y }); self.applyClasses(wrapper, classes); // Update the position }); } else if (tile.mergedFrom) { classes.push("tile-merged"); this.applyClasses(wrapper, classes); // Render the tiles that merged tile.mergedFrom.forEach(function (merged) { self.addTile(merged); }); } else { classes.push("tile-new"); this.applyClasses(wrapper, classes); } // Add the inner part of the tile to the wrapper wrapper.appendChild(inner); // Put the tile on the board this.tileContainer.appendChild(wrapper); }; HTMLActuator.prototype.applyClasses = function (element, classes) { element.setAttribute("class", classes.join(" ")); }; HTMLActuator.prototype.normalizePosition = function (position) { return { x: position.x + 1, y: position.y + 1 }; }; HTMLActuator.prototype.positionClass = function (position) { position = this.normalizePosition(position); return "tile-position-" + position.x + "-" + position.y; }; HTMLActuator.prototype.updateScore = function (score) { this.clearContainer(this.scoreContainer); var difference = score - this.score; this.score = score; this.scoreContainer.textContent = this.score; if (difference > 0) { var addition = document.createElement("div"); addition.classList.add("score-addition"); addition.textContent = "+" + difference; this.scoreContainer.appendChild(addition); } }; HTMLActuator.prototype.updateBestScore = function (bestScore) { this.bestContainer.textContent = bestScore; }; HTMLActuator.prototype.message = function (won) { var type = won ? "game-won" : "game-over"; var message = won ? "You win!" : "Game over!"; this.messageContainer.classList.add(type); this.messageContainer.getElementsByTagName("p")[0].textContent = message; }; HTMLActuator.prototype.clearMessage = function () { // IE only takes one value to remove at a time. this.messageContainer.classList.remove("game-won"); this.messageContainer.classList.remove("game-over"); };
var Show = require('../models/show'); var Season = require('../models/season'); var Episode = require('../models/episode'); var webParser = require('../modules/webParser'); var baseUrl = "http://www.imdb.com/"; module.exports.get = function(req, res, next) { var id = req.params.id; webParser.getAndParse( baseUrl + "title/" + id + '/', function (err, window) { var show = new Show(id); var title = window.$('#title-overview-widget > div.vital > div.title_block > div > div.titleBar > div.title_wrapper > h1').text().trim(); show.setTitle(title); var rating = window.$('#title-overview-widget > div.vital > div.title_block > div > div.ratings_wrapper > div.imdbRating > div.ratingValue > strong > span').text().trim(); show.setRating(parseFloat(rating)); webParser.getAndParse( baseUrl + "title/" + id + '/episodes', function (err, window) { var seasons = window.$('#bySeason > option'); seasons.each(function() { sId = parseInt(window.$(this).attr('value')); if(sId > 0) { var season = new Season(sId); show.addSeason(season); } }); show.getSeasons().sort(function(a, b) { return a.getNumber() - b.getNumber(); }) var finish = function() { var number = 1; show.clearSeasons(); show.getSeasons().forEach(function(season) { season.getEpisodes().sort(function(a, b) { return a.getNumberInSeason() - b.getNumberInSeason(); }) season.getEpisodes().forEach(function(episode) { episode.setNumber(number++); }) season.calculateTrendline(); }) show.calculateTrendline(); res.json(show); } parseEpisodes(show, finish, function() {res.redirect('/')}); }, function() { res.json({}); } ); }, function() { res.json({}); } ); } function parseEpisodes(show, callback, error) { webParser.getAndParse( baseUrl + 'title/' + show.getId() + '/epdate', function (err, window) { var elements = window.$('#tn15content > table > tbody > tr:not(:nth-child(1))'); elements.each(function() { var regex = /title\/(.+)\// var result = window.$(this).find('td:nth-child(2) > a').attr('href').match(regex); var episode = new Episode(result[1]); regex = /(\d+)\.(\d+)/ result = window.$(this).find('td:nth-child(1)').text().match(regex); if(result !== null) { episode.setNumberInSeason(result[2]); episode.setTitle(window.$(this).find('td:nth-child(2) > a').text()); episode.setRating(parseFloat(window.$(this).find('td:nth-child(3)').text())); show.getSeasons()[parseInt(result[1]) - 1].addEpisode(episode); } }) callback(); }, error ); }
(function() { var navBarModule = angular.module("hel-navbar", ["hel-services"]); navBarModule.service("hel-navbar-service", function($location, $rootScope){ this.pages = config.navbar; this.currentPage = this.pages[0]; this.currentSubPage = null; this.editorOn = false; this.filesOn = false; this.profileOn = false; this.articleOn = false; this.simplePages = function(){ return $.grep(this.pages, function(p) { return p.type == 1; }); }; this.hideAll = function() { this.editorOn = false; this.filesOn = false; this.profileOn = false; this.articleOn = false; this.currentPage = null; this.currentSubPage = null; }; this.showEditor = function(show) { this.hideAll(); this.editorOn = show; if(show == true) this.currentPage = this.pages[0]; }; this.showFiles = function(show) { this.hideAll(); this.filesOn = show; if(show == true) this.currentPage = this.pages[0]; }; this.showProfile = function(show) { this.hideAll(); this.profileOn = show; if(show == true) this.currentPage = this.pages[0]; }; this.getArticleContentUrl = function(id) { return "/partial/article/" + id; }; this.isCurrentPageDynamic = function() { if(this.editorOn || this.filesOn || this.profileOn) return false; return (this.currentPage != null && this.currentPage.type != 0) || this.articleOn; }; this.isCurrentPage = function(pageId) { return this.currentPage != null && this.currentPage.id == pageId && !this.editorOn && !this.filesOn && !this.profileOn; }; this.getCurrentPageType = function() { if(this.editorOn || this.filesOn || this.profileOn || this.currentPage == null) return -1; return this.currentPage.type; }; }); navBarModule.directive("helNavbar", ["hel-navbar-service", "hel-user-service", function(navbarService, userService){ return { restrict: "E", templateUrl: "/templates/front/navbar.html", controller: function($rootScope){ this.navbarService = navbarService; this.userService = userService; }, controllerAs: "navbarCtrl" } }]); navBarModule.directive("helNavbarUser", ["$http", "hel-user-service", "hel-navbar-service", function($http, userService, navbarService){ return { restrict: "E", templateUrl: "/templates/front/navbar_menu_user.html", controller: function($scope){ this.navbarService = navbarService; this.userService = userService; this.signOut = function() { $http.get('/auth/signout'). success(function(data, status, headers, config) { if(data.code == 0) { userService.signOut(); navbarService.showEditor(false); navbarService.showFiles(false); $.notify("Signed out", {autoHideDelay: 2000, globalPosition: 'top center', className: 'success'}); window.location = "/"; } else { $.notify(data.message, {autoHideDelay: 2000, globalPosition: 'top center', className: 'error'}); } }). error(function(data, status, headers, config) { $.notify("Sign out error. Code " + status, {autoHideDelay: 2000, globalPosition: 'top center', className: 'error'}); }); }; this.write = function() { navbarService.showEditor(true); //TODO Consider making this more user friendly $("#dynamicContent").empty(); }; this.files = function() { navbarService.showFiles(true); //TODO Consider making this more user friendly $("#dynamicContent").empty(); }; this.profile = function() { navbarService.showProfile(true); $scope.$emit('populateProfileDetails'); //TODO Consider making this more user friendly $("#dynamicContent").empty(); } }, controllerAs: "navbarUserCtrl" }; }]); })();
/* Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojo.dnd.Container"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dojo.dnd.Container"] = true; dojo.provide("dojo.dnd.Container"); dojo.require("dojo.dnd.common"); dojo.require("dojo.parser"); /* Container states: "" - normal state "Over" - mouse over a container Container item states: "" - normal state "Over" - mouse over a container item */ /*===== dojo.declare("dojo.dnd.__ContainerArgs", [], { creator: function(){ // summary: // a creator function, which takes a data item, and returns an object like that: // {node: newNode, data: usedData, type: arrayOfStrings} }, // skipForm: Boolean // don't start the drag operation, if clicked on form elements skipForm: false, // dropParent: Node||String // node or node's id to use as the parent node for dropped items // (must be underneath the 'node' parameter in the DOM) dropParent: null, // _skipStartup: Boolean // skip startup(), which collects children, for deferred initialization // (this is used in the markup mode) _skipStartup: false }); dojo.dnd.Item = function(){ // summary: // Represents (one of) the source node(s) being dragged. // Contains (at least) the "type" and "data" attributes. // type: String[] // Type(s) of this item, by default this is ["text"] // data: Object // Logical representation of the object being dragged. // If the drag object's type is "text" then data is a String, // if it's another type then data could be a different Object, // perhaps a name/value hash. this.type = type; this.data = data; } =====*/ dojo.declare("dojo.dnd.Container", null, { // summary: // a Container object, which knows when mouse hovers over it, // and over which element it hovers // object attributes (for markup) skipForm: false, /*===== // current: DomNode // The DOM node the mouse is currently hovered over current: null, // map: Hash<String, dojo.dnd.Item> // Map from an item's id (which is also the DOMNode's id) to // the dojo.dnd.Item itself. map: {}, =====*/ constructor: function(node, params){ // summary: // a constructor of the Container // node: Node // node or node's id to build the container on // params: dojo.dnd.__ContainerArgs // a dictionary of parameters this.node = dojo.byId(node); if(!params){ params = {}; } this.creator = params.creator || null; this.skipForm = params.skipForm; this.parent = params.dropParent && dojo.byId(params.dropParent); // class-specific variables this.map = {}; this.current = null; // states this.containerState = ""; dojo.addClass(this.node, "dojoDndContainer"); // mark up children if(!(params && params._skipStartup)){ this.startup(); } // set up events this.events = [ dojo.connect(this.node, "onmouseover", this, "onMouseOver"), dojo.connect(this.node, "onmouseout", this, "onMouseOut"), // cancel text selection and text dragging dojo.connect(this.node, "ondragstart", this, "onSelectStart"), dojo.connect(this.node, "onselectstart", this, "onSelectStart") ]; }, // object attributes (for markup) creator: function(){ // summary: // creator function, dummy at the moment }, // abstract access to the map getItem: function(/*String*/ key){ // summary: // returns a data item by its key (id) return this.map[key]; // dojo.dnd.Item }, setItem: function(/*String*/ key, /*dojo.dnd.Item*/ data){ // summary: // associates a data item with its key (id) this.map[key] = data; }, delItem: function(/*String*/ key){ // summary: // removes a data item from the map by its key (id) delete this.map[key]; }, forInItems: function(/*Function*/ f, /*Object?*/ o){ // summary: // iterates over a data map skipping members that // are present in the empty object (IE and/or 3rd-party libraries). o = o || dojo.global; var m = this.map, e = dojo.dnd._empty; for(var i in m){ if(i in e){ continue; } f.call(o, m[i], i, this); } return o; // Object }, clearItems: function(){ // summary: // removes all data items from the map this.map = {}; }, // methods getAllNodes: function(){ // summary: // returns a list (an array) of all valid child nodes return dojo.query("> .dojoDndItem", this.parent); // NodeList }, sync: function(){ // summary: // sync up the node list with the data map var map = {}; this.getAllNodes().forEach(function(node){ if(node.id){ var item = this.getItem(node.id); if(item){ map[node.id] = item; return; } }else{ node.id = dojo.dnd.getUniqueId(); } var type = node.getAttribute("dndType"), data = node.getAttribute("dndData"); map[node.id] = { data: data || node.innerHTML, type: type ? type.split(/\s*,\s*/) : ["text"] }; }, this); this.map = map; return this; // self }, insertNodes: function(data, before, anchor){ // summary: // inserts an array of new nodes before/after an anchor node // data: Array // a list of data items, which should be processed by the creator function // before: Boolean // insert before the anchor, if true, and after the anchor otherwise // anchor: Node // the anchor node to be used as a point of insertion if(!this.parent.firstChild){ anchor = null; }else if(before){ if(!anchor){ anchor = this.parent.firstChild; } }else{ if(anchor){ anchor = anchor.nextSibling; } } if(anchor){ for(var i = 0; i < data.length; ++i){ var t = this._normalizedCreator(data[i]); this.setItem(t.node.id, {data: t.data, type: t.type}); this.parent.insertBefore(t.node, anchor); } }else{ for(var i = 0; i < data.length; ++i){ var t = this._normalizedCreator(data[i]); this.setItem(t.node.id, {data: t.data, type: t.type}); this.parent.appendChild(t.node); } } return this; // self }, destroy: function(){ // summary: // prepares this object to be garbage-collected dojo.forEach(this.events, dojo.disconnect); this.clearItems(); this.node = this.parent = this.current = null; }, // markup methods markupFactory: function(params, node){ params._skipStartup = true; return new dojo.dnd.Container(node, params); }, startup: function(){ // summary: // collects valid child items and populate the map // set up the real parent node if(!this.parent){ // use the standard algorithm, if not assigned this.parent = this.node; if(this.parent.tagName.toLowerCase() == "table"){ var c = this.parent.getElementsByTagName("tbody"); if(c && c.length){ this.parent = c[0]; } } } this.defaultCreator = dojo.dnd._defaultCreator(this.parent); // process specially marked children this.sync(); }, // mouse events onMouseOver: function(e){ // summary: // event processor for onmouseover // e: Event // mouse event var n = e.relatedTarget; while(n){ if(n == this.node){ break; } try{ n = n.parentNode; }catch(x){ n = null; } } if(!n){ this._changeState("Container", "Over"); this.onOverEvent(); } n = this._getChildByEvent(e); if(this.current == n){ return; } if(this.current){ this._removeItemClass(this.current, "Over"); } if(n){ this._addItemClass(n, "Over"); } this.current = n; }, onMouseOut: function(e){ // summary: // event processor for onmouseout // e: Event // mouse event for(var n = e.relatedTarget; n;){ if(n == this.node){ return; } try{ n = n.parentNode; }catch(x){ n = null; } } if(this.current){ this._removeItemClass(this.current, "Over"); this.current = null; } this._changeState("Container", ""); this.onOutEvent(); }, onSelectStart: function(e){ // summary: // event processor for onselectevent and ondragevent // e: Event // mouse event if(!this.skipForm || !dojo.dnd.isFormElement(e)){ dojo.stopEvent(e); } }, // utilities onOverEvent: function(){ // summary: // this function is called once, when mouse is over our container }, onOutEvent: function(){ // summary: // this function is called once, when mouse is out of our container }, _changeState: function(type, newState){ // summary: // changes a named state to new state value // type: String // a name of the state to change // newState: String // new state var prefix = "dojoDnd" + type; var state = type.toLowerCase() + "State"; //dojo.replaceClass(this.node, prefix + newState, prefix + this[state]); dojo.replaceClass(this.node, prefix + newState, prefix + this[state]); this[state] = newState; }, _addItemClass: function(node, type){ // summary: // adds a class with prefix "dojoDndItem" // node: Node // a node // type: String // a variable suffix for a class name dojo.addClass(node, "dojoDndItem" + type); }, _removeItemClass: function(node, type){ // summary: // removes a class with prefix "dojoDndItem" // node: Node // a node // type: String // a variable suffix for a class name dojo.removeClass(node, "dojoDndItem" + type); }, _getChildByEvent: function(e){ // summary: // gets a child, which is under the mouse at the moment, or null // e: Event // a mouse event var node = e.target; if(node){ for(var parent = node.parentNode; parent; node = parent, parent = node.parentNode){ if(parent == this.parent && dojo.hasClass(node, "dojoDndItem")){ return node; } } } return null; }, _normalizedCreator: function(/*dojo.dnd.Item*/ item, /*String*/ hint){ // summary: // adds all necessary data to the output of the user-supplied creator function var t = (this.creator || this.defaultCreator).call(this, item, hint); if(!dojo.isArray(t.type)){ t.type = ["text"]; } if(!t.node.id){ t.node.id = dojo.dnd.getUniqueId(); } dojo.addClass(t.node, "dojoDndItem"); return t; } }); dojo.dnd._createNode = function(tag){ // summary: // returns a function, which creates an element of given tag // (SPAN by default) and sets its innerHTML to given text // tag: String // a tag name or empty for SPAN if(!tag){ return dojo.dnd._createSpan; } return function(text){ // Function return dojo.create(tag, {innerHTML: text}); // Node }; }; dojo.dnd._createTrTd = function(text){ // summary: // creates a TR/TD structure with given text as an innerHTML of TD // text: String // a text for TD var tr = dojo.create("tr"); dojo.create("td", {innerHTML: text}, tr); return tr; // Node }; dojo.dnd._createSpan = function(text){ // summary: // creates a SPAN element with given text as its innerHTML // text: String // a text for SPAN return dojo.create("span", {innerHTML: text}); // Node }; // dojo.dnd._defaultCreatorNodes: Object // a dictionary that maps container tag names to child tag names dojo.dnd._defaultCreatorNodes = {ul: "li", ol: "li", div: "div", p: "div"}; dojo.dnd._defaultCreator = function(node){ // summary: // takes a parent node, and returns an appropriate creator function // node: Node // a container node var tag = node.tagName.toLowerCase(); var c = tag == "tbody" || tag == "thead" ? dojo.dnd._createTrTd : dojo.dnd._createNode(dojo.dnd._defaultCreatorNodes[tag]); return function(item, hint){ // Function var isObj = item && dojo.isObject(item), data, type, n; if(isObj && item.tagName && item.nodeType && item.getAttribute){ // process a DOM node data = item.getAttribute("dndData") || item.innerHTML; type = item.getAttribute("dndType"); type = type ? type.split(/\s*,\s*/) : ["text"]; n = item; // this node is going to be moved rather than copied }else{ // process a DnD item object or a string data = (isObj && item.data) ? item.data : item; type = (isObj && item.type) ? item.type : ["text"]; n = (hint == "avatar" ? dojo.dnd._createSpan : c)(String(data)); } if(!n.id){ n.id = dojo.dnd.getUniqueId(); } return {node: n, data: data, type: type}; }; }; }
/* An evenly spaced set of labels. */ //(function () { core.require(function () { var item = svg.Element.mk('<g/>'); item.width = 1000; item.height = 500; item.centerLabels = true; // possible orientation values: 'horizontal' and 'vertical' item.orientation = 'horizontal'; //label prototype //var labelP = svg.Element.mk('<text font-size="25" fill="black" text-anchor="middle"/>'); item.set('labelP', svg.Element.mk('<text font-size="16" font-family="Arial" fill="black" text-anchor="middle"/>').hide()); //item.labelP.setExtent = item.labelP.__adjustExtent; item.resizable = true; item.labelGap = 10;// along the direction of the item(horizontal or vertical) item.labelSep = Point.mk(0,0); // the whole label set is displaced by this much; item.set("labels",codeRoot.Spread.mk()); item.labels.unselectable = true; item.unselectable = true; item.labels.generator = function (parent,name,data,index) { var labels = this.__parent; var label = labels.labelP.instantiate().show(); parent.set(name,label); var gap = labels.labelGap; var labelHeight,labelWidth,labelBBox,x,y; label.setText(data); labelBBox = label.getBBox(); labelWidth= labelBBox.width; labels.maxLabelWidth = Math.max(item.maxLabelWidth,labelWidth); labelHeight = label["font-size"]; if (labels.orientation === 'vertical') { // label's left is at zero in the vertical case x = labelWidth/2; y = index * gap; } else { x = index * gap; y =0; } label.moveto(x,y); label.show(); return label; } item.update = function () { let thisHere = this, horizontal = this.orientation === 'horizontal', categories,cnt,max; if (!this.data) return; if (!this.__element) return; // this is something that should not be inherited if (!this.hasOwnProperty('labelSep')) { this.set("labelSep",this.labelSep.copy()); } var L = this.data.length; this.maxLabelWidth = 0; if (horizontal) { this.labelGap = this.width/(L-1); } else { this.labelGap = this.height/(L-1); } this.labelP.center(); this.labels.masterPrototype = this.labelP; this.labels.moveto(this.labelSep); this.labelP.editPanelName = 'Prototype for all labels on this axis' this.labels.setData(this.data); if (horizontal) { // prevent labels from crowding var crowding =this.maxLabelWidth/this.labelGap; if (crowding > 0.9) { var fontSize = this.labelP['font-size']; this.labelP['font-size'] = Math.floor(fontSize * 0.9/crowding); this.update(); } } } item.labelP.dragStart = function (refPoint) { var itm = this.__parent.__parent.__parent; itm.dragStart = refPoint.copy(); itm.startLabelSep = itm.labelSep.copy(); } item.labelP.dragStep = function (pos) { var itm = this.__parent.__parent.__parent; var diff = pos.difference(itm.dragStart); itm.labelSep.copyto(itm.startLabelSep.plus(diff)); itm.labels.moveto(itm.labelSep); } item.reset = function () { this.labels.reset(); } /** * Set accessibility and notes for the UI */ ui.hide(item,['width','height','orientation', 'labelGap','labelSep','maxLabelWidth']); ui.hide(item.labelP,['text','text-anchor','y']); ui.hide(item.labels,['byCategory']); //core.returnValue(undefined,item); return item; }); //)();
/* jshint node: true */ 'use strict'; var readEnvironmentConfig = require('./lib/environment-config').read; var fastbootTransform = require('fastboot-transform'); module.exports = { name: 'ember-cli-bugsnag', options: { nodeAssets: { 'bugsnag-js': { vendor: { srcDir: 'src', destDir: 'bugsnag-js', include: ['bugsnag.js'], processTree(input) { return fastbootTransform(input); } } } } }, config: function() { return { bugsnag: readEnvironmentConfig(process.env) }; }, treeForAddon: function() { if (this._includeBugsnag) { return this._super.treeForAddon.apply(this, arguments); } }, treeForApp: function() { if (this._includeBugsnag) { return this._super.treeForApp.apply(this, arguments); } }, included: function(app) { this._includeBugsnag = this.isDevelopingAddon() || process.env.EMBER_ENV !== 'test'; this._super.included.apply(this, arguments); if (this._includeBugsnag) { app.import('vendor/bugsnag-js/bugsnag.js'); app.import('vendor/bugsnag/shim.js', { type: 'vendor', exports: { bugsnag: ['default'] } }); } } };
// [Working example](/serviceworker-cookbook/offline-status/). var CACHE_NAME = 'dependencies-cache'; // Files required to make this app work offline var REQUIRED_FILES = [ 'random-1.png', 'random-2.png', 'random-3.png', 'random-4.png', 'random-5.png', 'random-6.png', 'style.css', 'index.html', 'index.js', 'app.js' ]; self.addEventListener('install', function(event) { // Perform install step: loading each required file into cache event.waitUntil( caches.open(CACHE_NAME) .then(function(cache) { // Add all offline dependencies to the cache console.log('[install] Caches opened, adding all core components to cache'); return cache.addAll(REQUIRED_FILES); }) .then(function() { console.log('[install] All required resources have been cached, we\'re good!'); return self.skipWaiting(); }) ); }); self.addEventListener('fetch', function(event) { event.respondWith( caches.match(event.request) .then(function(response) { // Cache hit - return the response from the cached version if (response) { console.log('[fetch] Returning from ServiceWorker cache: ', event.request.url); return response; } // Not in cache - return the result from the live server // `fetch` is essentially a "fallback" console.log('[fetch] Returning from server: ', event.request.url); return fetch(event.request); } ) ); }); self.addEventListener('activate', function(event) { console.log('[activate] Activating ServiceWorker!'); // Calling claim() to force a "controllerchange" event on navigator.serviceWorker console.log('[activate] Claiming this ServiceWorker!'); event.waitUntil(self.clients.claim()); });
angular .module( 'app', ['uiSwitch'] ) .controller( 'MyController', function( $scope ) { $scope.enabled = true; $scope.onOff = true; $scope.yesNo = true; $scope.disabledTrue = true; $scope.disabledFalse = false; $scope.changeCallback = function() { console.log( 'This is the state of my model: ' + $scope.enabled ); }; } );
(function() { // Initialize o. this.o = o = {}; // Initialize the o configuration object. o.config = {}; // // Utils. // // Some configuration. o.config.utils = { // XML sanitization rules. sanitizationRules: [ [/&/g, '&amp;'], [/</g, '&lt;'], [/>/g, '&gt;'], [/"/g, '&quot;'] ] }; // Common utilities o.utils = { // Checks if a string contains a HTTP(s) url. isUrl: function(string) { return !! string.match(/^http(?:s)?:\/\//); }, // Creates a tag with some content. // // tag('dim', 'Hello World'); // //=> '<dim>Hello World</dim>' // // Returns a String. tag: function(tag, content) { return '<' + tag + '>' + content + '</' + tag + '>'; }, // Wrappes substrings in <match> tags. highlight: function(string, query) { if (query === '') return string; query = query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&'); return string.replace(RegExp(query, 'gi'), this.tag('match', '$&')); }, // Sanitizes the argument. Returns a string. sanitize: function(obj) { if (obj === null || obj === undefined) { return ''; } if (typeof(obj) !== 'string') { obj = String(obj); } o.config.utils.sanitizationRules.forEach(function(rule) { obj = obj.replace(rule[0], rule[1]); }); return obj; }, // Returns an array of all sanitized arguments. sanitizeAll: function() { return Array.prototype.map.call(arguments, function(arg) { return this.sanitize(arg); }, this); }, // Debounces a function. debounce: function(callback, delay) { var timeout; return function() { var self = this, args = arguments; clearTimeout(timeout); timeout = setTimeout(function() { callback.apply(self, args); }, delay); return this; }; } }; // // Cache. // // Cache configuration. o.config.cache = { // Invalidate cached item after 24 hours. ttl: 1000 * 60 * 60 * 24, // Suffix for timestamp keys. timestampSuffix: '%timestamp' }; // Cache. o.cache = { // Retrieves an item from the cache. get: function(key, callback) { var timestampKey = this.timestampKeyFor(key); chrome.storage.local.get([key, timestampKey], function(results) { if (results[timestampKey] > +new Date() - o.config.cache.ttl) { callback(results[key] || null); } else { callback(null); } }); }, // Stores an item in the cache. set: function(key, value) { var item = {}; item[key] = value; item[this.timestampKeyFor(key)] = +new Date(); chrome.storage.local.set(item); }, // Returns the timestamp key for a key. timestampKeyFor: function(key) { return key + o.config.cache.timestampSuffix; } }; // // Ajax. // // Some ajax coniguration. o.config.ajax = { // Try to parse responses. json: true }; // The o ajax module. o.ajax = { // Gets some data. get: function(url, callback) { o.cache.get(url, function(value) { if (value) { return callback(value); } var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.send(); xhr.onreadystatechange = function() { if (xhr.readyState !== 4) return; if ((xhr.status < 200 || xhr.status > 299) && xhr.status !== 304) { return console.log('[Ajax] Error ' + xhr.status + ': ' + url); } if ( ! o.config.ajax.json) { callback(xhr.responseText); return o.cache.set(url, xhr.responseText); } try { value = JSON.parse(xhr.responseText); } catch (_) { return console.log('[Ajax] Invalid JSON: ' + xhr.responseText); } callback(value); o.cache.set(url, value); }; }); } }; // // History. // // History configuration. o.config.history = { // Store max 100 items in the history. length: 100, // Find max 5 results. maxResults: 5, // localStorage key. storageKey: 'history.history' }; // History class. var History = function() { this.key = o.config.history.storageKey; try { this.history = JSON.parse(localStorage.getItem(this.key)); } catch(_) {}; if ( ! (this.history instanceof Array)) { this.history = []; } // Pushes a value into the history. this.push = function(value) { var i = this.history.indexOf(value); if (i > -1) { this.history.splice(i, 1); } this.history.push(value); if (this.history.length > o.config.history.length) { this.history.shift(); } this.save(); }; // Finds some history items. this.find = function(query, callback) { callback(this.history.filter(function(value) { return value.toLowerCase().indexOf(query) > -1; }).slice(- o.config.history.maxResults).reverse()); }; // Stores the history. this.save = function() { try { localStorage.setItem(this.key, JSON.stringify(this.history)); } catch (_) { console.log('[History] Could not save history: ' + this.history); } }; }; o.history = new History(); }).call(this);
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), Schema = mongoose.Schema; /** * User Schema */ var MessageFixSchema = new Schema({ message : String, messageFix : String }); module.exports = mongoose.model('MessageFix', MessageFixSchema);
var express = require('express'); var app = express(); app.set('view engine', 'ejs'); app.use(express.static('public')) // Routes app.get('/', function(req, res) { res.render('index'); }) // Port for AWS deployment or local var port = process.env.PORT || 3000; app.listen(port, function() { console.log('App launched on port 3000.') })
/*jshint node:true, indent:2, curly:false, eqeqeq:true, immed:true, latedef:true, newcap:true, noarg:true, regexp:true, undef:true, strict:true, trailing:true, white:true */ /*global X:true */ (function () { "use strict"; var nodemailer = require("nodemailer"), smtpOptions = { host: X.options.datasource.smtpHost, secureConnection: false, port: X.options.datasource.smtpPort }; // if the smtp server trusts us we don't need any authentication, so // don't send any if it's not in our configuration if (X.options.datasource.smtpUser) { smtpOptions.auth = { user: X.options.datasource.smtpUser, pass: X.options.datasource.smtpPassword }; } X.smtpTransport = nodemailer.createTransport("SMTP", smtpOptions); }());
import appendFlagToRegularExpression from 'helper/reg_exp/append_flag_to_reg_exp'; import coerceToString from 'helper/string/coerce_to_string'; import escapeRegExp from 'escape/escape_reg_exp'; /** * Returns a new string where all matches of `pattern` are replaced with `replacement`. <br/> * * @function replaceAll * @static * @since 1.0.0 * @memberOf Manipulate * @param {string} [subject=''] The string to verify. * @param {string|RegExp} pattern The pattern which match is replaced. If `pattern` is a string, a simple string match is evaluated. * All matches are replaced. * @param {string|Function} replacement The string or function which invocation result replaces `pattern` match. * @return {string} Returns the replacement result. * @example * as.replaceAll('good morning', 'o', '*'); * // => 'g**d m*rning' * as.replaceAll('evening', /n/, 's'); * // => 'evesisg' * */ export default function replaceAll(subject, pattern, replacement) { const subjectString = coerceToString(subject); let regExp = pattern; if (!(pattern instanceof RegExp)) { regExp = new RegExp(escapeRegExp(pattern), 'g'); } else if (!pattern.global) { regExp = appendFlagToRegularExpression(pattern, 'g'); } return subjectString.replace(regExp, replacement); }
var jshint = require('gulp-jshint') var shell = require('gulp-shell') var gulp = require('gulp') var paths = { solutions:'./exercises/*/solution/solution.js', exercises:'./exercises/*/exercise.js', scripts: './exercises/**/*.js' } gulp.task('lint', function() { return gulp.src(paths.scripts) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) }) // WHY U NO FAIL ON ERRORS!? gulp.task('verify-solutions', function() { return gulp.src(paths.solutions, {read: false}) .pipe( shell( ['node verify-solutions.js <%= file.path %>'], {cwd: __dirname + '/tests'})) .on('error', function (err) { process.exit(-1) }) }) gulp.task('default', ['lint', 'verify-solutions'], function() { // place code for your default task here })
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; 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; }; 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 _react = require('react'); var _react2 = _interopRequireDefault(_react); var _d = require('d3'); var _d2 = _interopRequireDefault(_d); var _index = require('../index.js'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (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 BarChart = function (_React$Component) { _inherits(BarChart, _React$Component); function BarChart(props) { _classCallCheck(this, BarChart); var _this = _possibleConstructorReturn(this, Object.getPrototypeOf(BarChart).call(this, props)); _this._defineScales(); _this.state = { animate: true, rectanglesAttributes: _this._buildRectangles(), xLabelsAttributes: _this._buildXLabels(), yLabelsAttributes: _this._buildYLabels() }; return _this; } _createClass(BarChart, [{ key: 'componentWillReceiveProps', value: function componentWillReceiveProps() { this._defineScales(); this.setState({ animate: true, rectanglesAttributes: this._buildRectangles(), xLabelsAttributes: this._buildXLabels(), yLabelsAttributes: this._buildYLabels() }); } }, { key: '_defineScales', value: function _defineScales() { this.xScale = _d2.default.scale.ordinal().domain(_d2.default.range(this.props.data.length)).rangeBands([0, this.props.width]); this.yScale = _d2.default.scale.linear().domain([0, _d2.default.max(this.props.data)]).range([0, this.props.height - 50]); } }, { key: '_buildData', value: function _buildData() { var _this2 = this; return this.props.data.map(function (value, index) { return { key: index, x: _this2.xScale(index), y: _this2.props.height - _this2.yScale(value) - 20, width: _this2.props.width / _this2.props.data.length - 8, height: _this2.yScale(value), style: _this2.props.style, value: value, fill: 'green' }; }); } }, { key: '_buildRectangles', value: function _buildRectangles() { var _this3 = this; var newData = this._cloneNestedArray(this._buildData()); return newData.map(function (field) { field.onMouseOver = function (e) { var key = e.target.attributes['data-reactid'].value.split('$')[1]; var newFormattedData = newData.slice(); newFormattedData[key] = Object.assign(newFormattedData[key], { style: { fill: 'purple' } }, newFormattedData[key].style); _this3.setState({ animate: false, rectanglesAttributes: newFormattedData }); }; field.onMouseLeave = function (e) { var key = e.target.attributes['data-reactid'].value.split('$')[1]; var newFormattedData = newData.slice(); newFormattedData[key] = Object.assign(newFormattedData[key], { style: { fill: 'green', stroke: 'black' } }); _this3.setState({ animate: false, rectanglesAttributes: newFormattedData }); }; return field; }); } }, { key: '_buildXLabels', value: function _buildXLabels() { var _this4 = this; var newData = this._cloneNestedArray(this._buildData()); return newData.map(function (field, index) { field.y = _this4.props.height; field.value = index; return field; }); } }, { key: '_buildYLabels', value: function _buildYLabels() { var newData = this._cloneNestedArray(this._buildData()); return newData.map(function (field) { field.dy = '-0.5em'; field.x = field.x + field.width / 2; field.style.textAnchor = 'middle'; return field; }); } }, { key: '_cloneNestedArray', value: function _cloneNestedArray(nestedArray) { var copyArray = nestedArray.slice(); return copyArray.map(function (dataObject) { dataObject = Object.assign({}, dataObject); for (var i in dataObject) { if (dataObject.hasOwnProperty(i) && _typeof(dataObject[i]) === 'object') { dataObject[i] = Object.assign({}, dataObject[i]); } } return dataObject; }); } }, { key: '_changeColor', value: function _changeColor() { this.setState({ fill: 'red' }); } }, { key: '_animations', value: function _animations() { var _this5 = this; return { duration: 1000, childrenPropsToAnimate: 'attrs', delay: 10, attributes: [{ name: 'y', from: this.props.height, to: function to(elementAttributes) { return _this5.props.height - _this5.yScale(elementAttributes.value) - 20; } }, { name: 'height', from: this.yScale(0) - 20, to: function to(elementAttributes) { return _this5.yScale(elementAttributes.value); } }] }; } }, { key: 'render', value: function render() { return _react2.default.createElement( _index.SVGContainer, { width: this.props.width, height: this.props.height }, _react2.default.createElement( _index.Animate, _extends({}, this._animations(), { animate: this.state.animate }), _react2.default.createElement(_index.Rectangles, { attrs: this.state.rectanglesAttributes, onClick: this._changeColor.bind(this) }) ), _react2.default.createElement(_index.Texts, { attrs: this.state.xLabelsAttributes }), _react2.default.createElement(_index.Texts, { attrs: this.state.yLabelsAttributes }) ); } }]); return BarChart; }(_react2.default.Component); exports.default = BarChart; BarChart.propTypes = { data: _react2.default.PropTypes.array.isRequired, width: _react2.default.PropTypes.number, height: _react2.default.PropTypes.number, style: _react2.default.PropTypes.object }; BarChart.defaultProps = { width: 600, height: 300, style: { fill: 'green' } };
Meteor.startup(function () { // New user email Router.route('/email/new-user/:id?', { name: 'newUser', where: 'server', action: function() { var user = Meteor.users.findOne(this.params.id); var emailProperties = { profileUrl: getProfileUrl(user), username: getUserName(user) }; html = getEmailTemplate('emailNewUser')(emailProperties); this.response.write(buildEmailTemplate(html)); this.response.end(); } }); // New post email Router.route('/email/new-post/:id?', { name: 'newPost', where: 'server', action: function() { var post = Posts.findOne(this.params.id); if (!!post) { html = getEmailTemplate('emailNewPost')(getPostProperties(post)); } else { html = "<h3>没有相关帖子.</h3>" } this.response.write(buildEmailTemplate(html)); this.response.end(); } }); });
import React, { PropTypes } from 'react'; import { GridTile } from 'material-ui/GridList'; class SearchGifView extends React.Component { constructor(props) { super(props); this.handleMouseOver = this.handleMouseOver.bind(this); this.handleMouseOut = this.handleMouseOut.bind(this); this.state = { url: props.gif.images.downsized_still.url }; } handleMouseOver() { const gif = this.props.gif; this.setState({ url: gif.images.downsized.url }); } handleMouseOut() { const gif = this.props.gif; this.setState({ url: gif.images.downsized_still.url }); } render() { let gif = this.props.gif; return ( <GridTile onClick={() => {this.props.onSelect(gif)}} onMouseOver={this.handleMouseOver} onMouseOut={this.handleMouseOut} style={{ cursor: "pointer" }} > <img src={this.state.url} role="presentation" /> </GridTile> ); } }; SearchGifView.propTypes = { gif: PropTypes.object.isRequired, onSelect: PropTypes.func.isRequired }; export default SearchGifView;
import Promise from 'bluebird'; import mongoose from 'mongoose'; import httpStatus from 'http-status'; import APIError from '../helpers/APIError'; /** * Url Schema */ const UrlSchema = new mongoose.Schema({ reportId: { type: String, required: true }, url: { type: String, required: true }, codes: { type: [String], required: true }, nErrors: { type: Number, required: true }, nWarnings: { type: Number, required: true }, nNotices: { type: Number, required: true } }); /** * Methods */ UrlSchema.method({ }); UrlSchema.query.byCode = function byCode(code) { return this.find({ code: new RegExp(code, 'i') }); }; UrlSchema.query.byReport = function byReport(reportId) { return this.find({ reportId: new RegExp(reportId, 'i') }); }; /** * Statics */ UrlSchema.statics = { /** * Get Url * @param {ObjectId} id - The objectId of issue. * @returns {Promise<Url, APIError>} */ get(id) { return this.findById(id) .exec() .then((url) => { if (url) { return url; } const err = new APIError('No such url exists!', httpStatus.NOT_FOUND); return Promise.reject(err); }); }, /** * List urls which have a specific code. * @param {number} skip - Number of issues to be skipped. * @param {number} limit - Limit number of issues to be returned. * @returns {Promise<Issue[]>} */ list({ limit = 50, skip = 0, reportId = '', code = '' } = {}) { return this.find() .sort({ createdAt: -1 }) .byCode(code) .byReport(reportId) .skip(+skip) .limit(+limit) .exec(); } }; /** * @typedef Url */ export default mongoose.model('Url', UrlSchema);
"use strict"; var __extends = (this && this.__extends) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; var CMLFormulaElem_1 = require("./CMLFormulaElem"); var CMLFormulaOperator = (function (_super) { __extends(CMLFormulaOperator, _super); function CMLFormulaOperator(opr, isSingle) { if (opr === void 0) { opr = ""; } if (isSingle === void 0) { isSingle = false; } _super.call(this); this.priorL = 0; this.priorR = 0; this.oprcnt = 0; this.opr0 = null; this.opr1 = null; this.func = null; if (opr.length == 0) return; if (isSingle) { this.oprcnt = 1; if (opr == "(") { this.func = null; this.priorL = 1; this.priorR = 99; } else if (opr == ")") { this.func = null; this.priorL = 99; this.priorR = 1; } else if (opr == "-") { this.func = CMLFormulaOperator.neg; this.priorL = 10; this.priorR = 11; } else if (opr == "!") { this.func = CMLFormulaOperator.bnt; this.priorL = 10; this.priorR = 11; } else if (opr == "$sin") { this.func = CMLFormulaOperator.snd; this.priorL = 10; this.priorR = 11; } else if (opr == "$cos") { this.func = CMLFormulaOperator.csd; this.priorL = 10; this.priorR = 11; } else if (opr == "$tan") { this.func = CMLFormulaOperator.tnd; this.priorL = 10; this.priorR = 11; } else if (opr == "$asn") { this.func = CMLFormulaOperator.asn; this.priorL = 10; this.priorR = 11; } else if (opr == "$acs") { this.func = CMLFormulaOperator.acs; this.priorL = 10; this.priorR = 11; } else if (opr == "$atn") { this.func = CMLFormulaOperator.atn; this.priorL = 10; this.priorR = 11; } else if (opr == "$sqr") { this.func = CMLFormulaOperator.sqr; this.priorL = 10; this.priorR = 11; } else if (opr == "$int") { this.func = CMLFormulaOperator.ind; this.priorL = 10; this.priorR = 11; } else if (opr == "$abs") { this.func = CMLFormulaOperator.abb; this.priorL = 10; this.priorR = 11; } else if (opr == "$i?") { this.func = CMLFormulaOperator.ird; this.priorL = 10; this.priorR = 11; } else if (opr == "$i??") { this.func = CMLFormulaOperator.srd; this.priorL = 10; this.priorR = 11; } } else { this.oprcnt = 2; if (opr == "+") { this.func = CMLFormulaOperator.adb; this.priorL = 7; this.priorR = 6; } else if (opr == "-") { this.func = CMLFormulaOperator.sub; this.priorL = 7; this.priorR = 6; } else if (opr == "*") { this.func = CMLFormulaOperator.mul; this.priorL = 9; this.priorR = 8; } else if (opr == "/") { this.func = CMLFormulaOperator.div; this.priorL = 9; this.priorR = 8; } else if (opr == "%") { this.func = CMLFormulaOperator.sup; this.priorL = 9; this.priorR = 8; } else if (opr == ">") { this.func = CMLFormulaOperator.grt; this.priorL = 5; this.priorR = 4; } else if (opr == ">=") { this.func = CMLFormulaOperator.geq; this.priorL = 5; this.priorR = 4; } else if (opr == "<") { this.func = CMLFormulaOperator.les; this.priorL = 5; this.priorR = 4; } else if (opr == "<=") { this.func = CMLFormulaOperator.leq; this.priorL = 5; this.priorR = 4; } else if (opr == "==") { this.func = CMLFormulaOperator.eqr; this.priorL = 5; this.priorR = 4; } else if (opr == "!=") { this.func = CMLFormulaOperator.neq; this.priorL = 5; this.priorR = 4; } } } CMLFormulaOperator.prototype.calc = function (fbr) { return this.func(this.opr0.calc(fbr), (this.oprcnt == 2) ? (this.opr1.calc(fbr)) : 0); }; CMLFormulaOperator.adb = function (r0, r1) { return r0 + r1; }; CMLFormulaOperator.sub = function (r0, r1) { return r0 - r1; }; CMLFormulaOperator.mul = function (r0, r1) { return r0 * r1; }; CMLFormulaOperator.div = function (r0, r1) { return r0 / r1; }; CMLFormulaOperator.sup = function (r0, r1) { return r0 % r1; }; CMLFormulaOperator.neg = function (r0, r1) { return -r0; }; CMLFormulaOperator.bnt = function (r0, r1) { return (r0 == 0) ? 1 : 0; }; CMLFormulaOperator.snd = function (r0, r1) { var st = CMLFormulaElem_1.default._globalVariables._sin; return st[st.index(r0)]; }; CMLFormulaOperator.csd = function (r0, r1) { var st = CMLFormulaElem_1.default._globalVariables._sin; return st[st.index(r0) + st.cos_shift]; }; CMLFormulaOperator.tnd = function (r0, r1) { return Math.tan(r0 * 0.017453292519943295); }; CMLFormulaOperator.asn = function (r0, r1) { return Math.asin(r0) * 57.29577951308232; }; CMLFormulaOperator.acs = function (r0, r1) { return Math.acos(r0) * 57.29577951308232; }; CMLFormulaOperator.atn = function (r0, r1) { return Math.atan(r0) * 57.29577951308232; }; CMLFormulaOperator.sqr = function (r0, r1) { return Math.sqrt(r0); }; CMLFormulaOperator.ind = function (r0, r1) { return Number(Math.floor(r0)); }; CMLFormulaOperator.abb = function (r0, r1) { return (r0 < 0) ? (-r0) : (r0); }; CMLFormulaOperator.ird = function (r0, r1) { return Number(Math.floor(CMLFormulaElem_1.default._globalVariables.rand() * r0)); }; CMLFormulaOperator.srd = function (r0, r1) { return Number(Math.floor(CMLFormulaElem_1.default._globalVariables.rand() * (r0 * 2 + 1)) - r0); }; CMLFormulaOperator.grt = function (r0, r1) { return (r0 > r1) ? 1 : 0; }; CMLFormulaOperator.geq = function (r0, r1) { return (r0 >= r1) ? 1 : 0; }; CMLFormulaOperator.les = function (r0, r1) { return (r0 < r1) ? 1 : 0; }; CMLFormulaOperator.leq = function (r0, r1) { return (r0 <= r1) ? 1 : 0; }; CMLFormulaOperator.neq = function (r0, r1) { return (r0 != r1) ? 1 : 0; }; CMLFormulaOperator.eqr = function (r0, r1) { return (r0 == r1) ? 1 : 0; }; CMLFormulaOperator.prefix_rex = "([-!(]|\\$sin|\\$cos|\\$tan|\\$asn|\\$acs|\\$atn|\\$sqr|\\$i\\?|\\$i\\?\\?|\\$int|\\$abs)"; CMLFormulaOperator.postfix_rex = "(\\))"; return CMLFormulaOperator; }(CMLFormulaElem_1.default)); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = CMLFormulaOperator;
import Bundler from './lib/bundler'; module.exports = Bundler;
import React from 'react'; import { mount } from 'enzyme'; import { isEnzymeTestkitExists, isUniEnzymeTestkitExists, } from 'wix-ui-test-utils/enzyme'; import { isTestkitExists, isUniTestkitExists } from 'wix-ui-test-utils/vanilla'; import AllComponents from './all-components'; import COMPONENT_DEFINITIONS from './component-definitions.js'; import TESTKIT_DEFINITIONS from '../.wuf/testkits/definitions'; import * as reactTestUtilsTestkitFactories from './index'; import * as enzymeTestkitFactories from './enzyme'; import * as unidriverFactories from './unidriver'; const noop = () => {}; const lowerFirst = a => a.charAt(0).toLowerCase().concat(a.slice(1)); const attachHooks = (beforeAllHook, afterAllHook) => { beforeAll(async () => await beforeAllHook()); afterAll(async () => await afterAllHook()); }; const DATA_HOOK_PROP_NAME = 'dataHook'; const DRIVER_ASSERTS = { enzyme: ({ name, component, props, beforeAllHook, afterAllHook }) => { describe('Enzyme testkits', () => { attachHooks(beforeAllHook, afterAllHook); it(`Enzyme testkit exists (deprecated) - <${name}/>`, () => expect( isEnzymeTestkitExists( React.createElement(component, props), enzymeTestkitFactories[`${lowerFirst(name)}TestkitFactory`], mount, { dataHookPropName: DATA_HOOK_PROP_NAME }, ), ).toBe(true)); }); }, vanilla: ({ name, component, props, beforeAllHook, afterAllHook }) => { describe('ReactTestUtils testkits', () => { attachHooks(beforeAllHook, afterAllHook); it(`ReactTestUtils testkit exists (deprecated) - <${name}/>`, () => expect( isTestkitExists( React.createElement(component, props), reactTestUtilsTestkitFactories[`${lowerFirst(name)}TestkitFactory`], { dataHookPropName: DATA_HOOK_PROP_NAME }, ), ).toBe(true)); }); }, }; const UNIDRIVER_ASSERTS = { enzyme: ({ name, component, props, beforeAllHook, afterAllHook }) => { describe('Enzyme unidriver testkits', () => { attachHooks(beforeAllHook, afterAllHook); it(`Enzyme testkit exists - <${name}/>`, () => expect( isUniEnzymeTestkitExists( React.createElement(component, props), enzymeTestkitFactories[`${name}Testkit`], mount, { dataHookPropName: DATA_HOOK_PROP_NAME }, ), ).resolves.toBe(true)); }); }, vanilla: ({ name, component, props, beforeAllHook, afterAllHook }) => { describe('ReactTestUtils unidriver testkits', () => { attachHooks(beforeAllHook, afterAllHook); it(`ReactTestUtils testkit exists - <${name}/>`, () => expect( isUniTestkitExists( React.createElement(component, props), reactTestUtilsTestkitFactories[`${name}Testkit`], { dataHookPropName: DATA_HOOK_PROP_NAME }, ), ).resolves.toBe(true)); }); }, initialize: ({ name, beforeAllHook, afterAllHook }) => { // Checks that unidriver can initialize even when the element is not found describe('Unidriver can initialize', () => { attachHooks(beforeAllHook, afterAllHook); it(`Testkit initialize - <${name}/>`, async () => { const factory = reactTestUtilsTestkitFactories[`${name}Testkit`]; const testkit = factory({ wrapper: document.createElement('div'), dataHook: 'non-existing-data-hook', }); expect(await testkit.exists()).toBe(false); }); }); }, }; const EXPORT_ASSERTS = { enzyme: (name, noUnidriver) => { const testkit = noUnidriver ? `${lowerFirst(name)}TestkitFactory` : `${name}Testkit`; describe('Enzyme testkit exports', () => { it(`Enzyme testkit exported - <${name}/>`, () => expect(typeof enzymeTestkitFactories[testkit]).toBe('function')); }); }, vanilla: (name, noUnidriver) => { const testkit = noUnidriver ? `${lowerFirst(name)}TestkitFactory` : `${name}Testkit`; describe('ReactTestUtils testkit exports', () => { it(`ReactTestUtils testkit exported - <${name}/>`, () => expect(typeof reactTestUtilsTestkitFactories[testkit]).toBe( 'function', )); }); }, unidriver: (name, noUnidriver) => { if (noUnidriver) { return; } const driver = `${name}UniDriver`; describe('Unidriver exports', () => { it(`Unidriver exported - <${name}/>`, () => expect(typeof unidriverFactories[driver]).toBe('function')); }); }, }; Object.keys({ ...AllComponents, ...COMPONENT_DEFINITIONS, ...TESTKIT_DEFINITIONS, }).forEach(name => { const definition = TESTKIT_DEFINITIONS[name] || {}; const config = { beforeAllHook: noop, afterAllHook: noop, props: COMPONENT_DEFINITIONS[name] ? COMPONENT_DEFINITIONS[name].props : {}, ...definition, name, component: AllComponents[name], }; if (!definition.skipSanityTest) { const sanityAsserts = definition.noUnidriver ? DRIVER_ASSERTS : UNIDRIVER_ASSERTS; Object.keys(sanityAsserts).forEach(driver => sanityAsserts[driver](config)); } if (!definition.noTestkit) { EXPORT_ASSERTS.vanilla( definition.exportName || name, definition.noUnidriver, ); EXPORT_ASSERTS.enzyme( definition.exportName || name, definition.noUnidriver, ); EXPORT_ASSERTS.unidriver( definition.exportName || name, definition.noUnidriver, ); } });
// Boilerplate Canvas Code var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); var canvasUi = document.getElementById("canvasUi"); var ctxUi = canvasUi.getContext("2d"); var canvasHeight = canvas.height; var canvasWidth = canvas.width; var requestAnimationFrame = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; window.requestAnimationFrame = requestAnimationFrame; function animate(time) { // Animation loop update(time); draw(time); // A function that draws the current animation frame requestAnimationFrame(animate); // Keep the animation going }; // Classes Player = function(name, x, y) { this.name = name; this.x = x; this.y = y; this.gX = x; this.gY = y; this.rect = new Rectangle(x,y,32,32); this.img; this.sprite = "default"; this.moving = false; } Sprite = function(x, y, w, h, imgIn) { this.rect = new Rectangle(x, y, w, h) this.image = imgIn; this.SetPosition = function(x, y) { this.rect.x = x; this.rect.y = y; }; this.Draw = function(ctx) { ctx.drawImage(this.image, this.rect.x, this.rect.y); } this.changeImg = function(imgIn) { this.image = imgIn; } }; // Socket.io Initilization var socket = io.connect(); // Store loggedIn Status var loggedIn = false; // Triggers name selection hide var initilized = false; // Checks to see if the player list has been retrieved var localPlayer = new Rectangle(0,0,0,0); var username = null; var pSprite; // Store game game timings; var gameTime; var nTime = new Date(); var dTime = 1; var pTime = new Date(); var fps; // Store player sprites var maleSprite = "img/psprite1.png"; var femaleSprite = "img/psprite2.png"; // Store Interface Status (focus) var gameFocus = true; var enterChatTime = new Date(); // Prevents the submit enter from self triggering // jQuery event Handlers $(document).ready(function(){ $('#canvasWrapper').hide(); $('#loginForm').submit(function(e){ // Get the list of players: socket.emit('get players'); for (i = 0; i < players.length; i++) { if ($("#nameField").val() === players[i].name) { return; } } e.preventDefault(); username = $("#nameField").val(); pSprite = $('input:radio[name=sprite]:checked').val(); loggedIn = true; $('#canvasWrapper').show(); $('#loginWrapper').hide(); // The local player is the first player in the local array // push local player onto the local stack and to the server players.push(new Player(username, 100, 100)); players[players.length-1].sprite = pSprite; if (pSprite === "male") { playersAnimation.push(new Animation(32, 32, 0, 0, 3, maleSprite, 3, 3, 4)); } else if (pSprite === "female") { playersAnimation.push(new Animation(32, 32, 0, 0, 3, femaleSprite, 3, 3, 4)); } else { playersAnimation.push(new Animation(32, 32, 0, 0, 3, femaleSprite, 3, 3, 4)); } localPlayer = players[players.length-1]; localPlayerAni = playersAnimation[playersAnimation.length-1]; localPlayerAni.position.x = localPlayer.rect.x; localPlayerAni.position.y = localPlayer.rect.y; socket.emit('player joined', players[players.length-1]); }); $('#msgForm').submit(function(e){ e.preventDefault(); if ($('#msgField').val() === "") { $('#msgField').blur(); return; } socket.emit('send dialog', username, $('#msgField').val()); $('#msgField').val(""); $('#canvas').focus(); $('#msgField').blur(); enterChatTime = new Date(); gameFocus = true; }); $('#msgField').focusin(function(){ gameFocus = false; }); $('#msgField').focusout(function(){ gameFocus = true; }); //}); }); // Game Code Begins Here: // players array to hold the Rectangles of all connected players var players = []; // parallel array for Animation classes var playersAnimation = []; // Holds the player properties. var playerSpeed = 150; // holds the messages var messages = []; // Sprites // Maps / Backgrounds: var testBg = new Image(); testBg.src = "img/testBg.jpg"; var testBgSprite = new Sprite(0, 0, 1216, 964, testBg); // Current map var currentMap = testBgSprite; // Server Updates (remember, async); socket.on('new player', function(data){ // Pushes the player object and parallel animation object players.push(new Player(data.name, data.x, data.y)); players[players.length-1].sprite = data.sprite; if (data.sprite === "male") { playersAnimation.push(new Animation(32, 32, 0, 0, 3, maleSprite, 3, 3, 4)); } else if (data.sprite === "female") { playersAnimation.push(new Animation(32, 32, 0, 0, 3, femaleSprite, 3, 3, 4)); } else { playersAnimation.push(new Animation(32, 32, 0, 0, 3, femaleSprite, 3, 3, 4)); } }); // Grabs a list of all of the current players and their location socket.on('player list', function(data) { if (initilized === false) { for (i = 0; i < data.length; i++) { if (data[i].name != username) { players.push(new Player(data[i].name, data[i].x, data[i].y)); players[players.length-1].sprite = data[i].sprite; if (data[i].sprite === "male") { playersAnimation.push(new Animation(32, 32, 0, 0, 3, maleSprite, 3, 3, 4)); } else if (data[i].sprite === "female") { playersAnimation.push(new Animation(32, 32, 0, 0, 3, femaleSprite, 3, 3, 4)); } else { playersAnimation.push(new Animation(32, 32, 0, 0, 3, femaleSprite, 3, 3, 4)); } playersAnimation[playersAnimation.length-1].position.x = data[i].rect.x; playersAnimation[playersAnimation.length-1].position.y = data[i].rect.y; players[players.length-1].gX = data[i].gX; players[players.length-1].gY = data[i].gY; } } initilized = true; } }); // A new global message (for message box) socket.on('new message', function(data){ messages.push(data); }); // A new "/say" from a player socket.on('new dialog', function(name, msg){ messages.push(name + ": " + msg); }); // Moves a player based on the player object passed from the server socket.on('move player', function(data, direction){ for(i = 0; i < players.length; i++) { if (players[i].name === data.name) { players[i].gX = data.gX; players[i].gY = data.gY; players[i].moving = data.moving; if (direction == "left") { playersAnimation[i].SetRow(1); } else if (direction == "right") { playersAnimation[i].SetRow(2); } else if (direction == "up") { playersAnimation[i].SetRow(3); } else if (direction == "down") { playersAnimation[i].SetRow(0); } } } }); // Removes a disconnected player from the local client socket.on('player disconnect', function(data){ for(i = 0; i < players.length; i++) { if (players[i].name === data){ players.splice(i, 1); playersAnimation.splice(i, 1); } } }) // Auxilary update functions: function gLocationUpdate() { localPlayer.gX = localPlayer.rect.x - currentMap.rect.x; localPlayer.gY = localPlayer.rect.y - currentMap.rect.y; } function gPlayerUpdate() { for(i = 0; i < players.length; i++) { if (players[i].name != localPlayer.name) { players[i].rect.x = currentMap.rect.x + players[i].gX; players[i].rect.y = currentMap.rect.y + players[i].gY; playersAnimation[i].position.x = players[i].rect.x; playersAnimation[i].position.y = players[i].rect.y; } } } // Local Updates function update() { // Calculates the time delta for fps independence cTime = new Date(); dTime = (cTime - pTime) / 1000; fps = Math.round(1 / dTime); pTime = cTime; // Stop the player animation if the player isn't moving // If logged in, start the canvas update game block if (loggedIn == true) { // Movement if (input.d === true && gameFocus === true) { localPlayer.moving = true; localPlayerAni.SetRow(2); if (localPlayer.rect.x > 430 && currentMap.rect.x + currentMap.rect.width > 580) { currentMap.rect.x -= Math.round(playerSpeed * dTime); } else { if (localPlayer.rect.x + 25 < 580) { localPlayer.rect.x += Math.round(playerSpeed * dTime); } } gLocationUpdate(); socket.emit('player moved', localPlayer, "right"); } else if (input.a === true && gameFocus === true) { localPlayer.moving = true; localPlayerAni.SetRow(1); if (localPlayer.rect.x < 150 && currentMap.rect.x < 0) { currentMap.rect.x += Math.round(playerSpeed * dTime); } else { localPlayer.rect.x -= Math.round(playerSpeed * dTime); } gLocationUpdate(); socket.emit('player moved', localPlayer, "left"); } else if (input.w === true && gameFocus === true) { localPlayer.moving = true; localPlayerAni.SetRow(3); if (localPlayer.rect.y < 120 && currentMap.rect.y < 0) { currentMap.rect.y += Math.round(playerSpeed * dTime); } else { localPlayer.rect.y -= Math.round(playerSpeed * dTime); } gLocationUpdate(); socket.emit('player moved', localPlayer, "up"); } else if (input.s === true && gameFocus === true) { localPlayer.moving = true; localPlayerAni.SetRow(0); if (localPlayer.rect.y > 350 && currentMap.rect.y + currentMap.rect.height > 500) { currentMap.rect.y -= Math.round(playerSpeed * dTime); } else { localPlayer.rect.y += Math.round(playerSpeed * dTime); } gLocationUpdate(); socket.emit('player moved', localPlayer, "down"); } if (input.enter == true && gameFocus === true && (gameTime.getTime() - enterChatTime.getTime()) > 1000) { $('#msgField').focus(); console.log("entering chat"); gameFocus = false; }; } // Update all players based on the latest global location gPlayerUpdate(); if (loggedIn === true) { for (i = 0; i < players.length; i++) { if (players[i].moving === true) { playersAnimation[i].Update(); playersAnimation[i].position.x = players[i].rect.x; playersAnimation[i].position.y = players[i].rect.y; } else { playersAnimation[i].SetColumn(1); } } // Update player animations if (localPlayer.moving === true) { localPlayerAni.Update(); localPlayerAni.position.x = localPlayer.rect.x; localPlayerAni.position.y = localPlayer.rect.y; } else { localPlayerAni.SetColumn(1); } } // Store the latest gameTime gameTime = new Date(); // Stop the player animation if the player isn't moving for(i = 0; i < players.length; i++) { players[i].moving = false; } } function draw() { if (loggedIn === true) { ctx.clearRect(0, 0, canvas.height,canvas.width); ctx.fillStyle = "#AAA"; ctx.fillRect(0, 0, canvas.width, canvas.height) // Render Background Sprites testBgSprite.Draw(ctx); // Render the players for(i=0; i<players.length; i++) { ctx.fillStyle = "#000"; ctx.font = "12px Arial"; ctx.fillText(players[i].name, players[i].rect.x - 5, players[i].rect.y - 5); //players[i].rect.Draw(ctx); playersAnimation[i].Draw(ctx); } localPlayerAni.Draw(ctx); // Render the player list box ctx.fillStyle = "#222" ctx.fillRect(580, 0, 120, 500); ctx.fillStyle = "#FFF"; ctx.font = "12px Arial"; ctx.fillText("Connected Players", 590, 15); ctx.fillText("-------------------------", 590, 30); for(i = 0; i < players.length; i++) { ctx.fillText(players[i].name, 590, 47 + (i * 15)); } // Render message pane ctx.fillStyle = "#222" ctx.fillRect(0, 500, 700, 150); // Render the message boxs ctx.fillStyle = "#FFF"; ctx.font = "12px Arial"; for (i = 0; i < messages.length; i++) { messages.reverse(); if (i < 10) { ctx.fillText(messages[i], 5, 640 - (14 * i)); } messages.reverse(); } // Render FPS ctx.fillText("FPS: " + fps, 650, 638); } } animate();
/* * grunt-template4js * https://github.com/albertshaw/grunt-template4js * * Copyright (c) 2014 Xiao Long * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var path = require('path'); var template4js = require('../lib/template4js')({ templateSettings : { strip : false } }); grunt.registerMultiTask('template4js', 'Use template in js files.', function() { var me = this; template4js.compileModules(me.data.options.modules); this.files.forEach(function(f) { grunt.file.write(path.join(f.dest), template4js.compilePath(f.orig.src[0])()); }); }); };
require('dotenv').config(); const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const { env: { NODE_ENV, HOST_NAME, FACEBOOK_APP_ID } } = process; const isDevMode = NODE_ENV === 'development'; exports.webpack = webpack; const config = { devtool: 'inline-source-map', entry: path.resolve(__dirname, 'client/index.jsx'), module: { rules: [ { exclude: [/node_modules/, /dist/, /server/], include: path.join(__dirname, 'client'), test: /\.(js|jsx)$/, use: [ 'babel-loader' ] }, { test: /\.s*css$/, use: ['style-loader', 'css-loader', 'sass-loader'] }, { test: /\.(jpg|png|svg|gif|ico)$/, use: 'url-loader' } ] }, node: { dns: 'empty', fs: 'empty', net: 'empty' }, output: { filename: 'bundle.js', path: path.resolve(__dirname, 'dist/client'), publicPath: '/' }, plugins: [ new webpack.DefinePlugin({ API_URL: JSON.stringify(`${HOST_NAME}/api/v1/`), HOST_NAME: JSON.stringify(`${HOST_NAME}`), FACEBOOK_APP_ID: JSON.stringify(FACEBOOK_APP_ID) }), new HtmlWebpackPlugin(), ], resolve: { extensions: ['.js', '.jsx'] } }; if (isDevMode) { config.entry = [ config.entry, 'webpack-hot-middleware/client?reload=true' ] config.plugins.push(new webpack.HotModuleReplacementPlugin()); } module.exports = config;
var crypto = require('crypto'); var through = require('through'); var pipeline = require('stream-combiner'); var concatStream = require('concat-stream'); var checkSyntax = require('syntax-error'); var parents = require('parents'); var mdeps = require('module-deps'); var browserPack = require('browser-pack'); var depSorter = require('deps-sort'); var browserResolve = require('browser-resolve'); var browserBuiltins = require('browser-builtins'); var insertGlobals = require('insert-module-globals'); var umd = require('umd'); var path = require('path'); var inherits = require('inherits'); var EventEmitter = require('events').EventEmitter; var fs = require('fs'); var emptyModulePath = path.join(__dirname, '_empty.js'); module.exports = function (opts) { if (opts === undefined) opts = {}; if (typeof opts === 'string') opts = { entries: [ opts ] }; if (Array.isArray(opts)) opts = { entries: opts }; var b = new Browserify(opts); [].concat(opts.entries).filter(Boolean).forEach(b.add.bind(b)); return b; }; function hash(what) { return crypto.createHash('md5').update(what).digest('base64').slice(0, 6); } inherits(Browserify, EventEmitter); function Browserify (opts) { var self = this; self.files = []; self.exports = {}; self._pending = 0; self._entries = []; self._ignore = {}; self._external = {}; self._expose = {}; self._mapped = {}; self._transforms = []; self._extensions = ['.js'].concat(opts.extensions).filter(Boolean); self._noParse =[]; self._pkgcache = {}; self._exposeAll = opts.exposeAll; var noParse = [].concat(opts.noParse).filter(Boolean); noParse.forEach(this.noParse.bind(this)); } Browserify.prototype.noParse = function(file) { var self = this; var cwd = process.cwd(); var top = { id: cwd, filename: cwd + '/_fake.js', paths: [] }; self._noParse.push(file, path.resolve(file)); self._pending ++; self._resolve(file, top, function (err, r) { if (r) self._noParse.push(r); if (--self._pending === 0) self.emit('_ready'); }); }; Browserify.prototype.add = function (file) { this.require(file, { entry: true }); return this; }; Browserify.prototype.require = function (id, opts) { var self = this; if (opts === undefined) opts = { expose: id }; self._pending ++; var basedir = opts.basedir || process.cwd(); var fromfile = basedir + '/_fake.js'; var params = { filename: fromfile, modules: browserBuiltins, packageFilter: packageFilter, extensions: self._extensions }; browserResolve(id, params, function (err, file) { if ((err || !file) && !opts.external) { if (err) return self.emit('error', err); if (!file) return self.emit('error', new Error( 'module ' + JSON.stringify(id) + ' not found in require()' )); } if (opts.expose) { self.exports[file] = hash(file); if (typeof opts.expose === 'string') { self._expose[file] = opts.expose; self._mapped[opts.expose] = file; } } if (opts.external) { if (file) self._external[file] = true; else self._external[id] = true; } else { self.files.push(file); } if (opts.entry) self._entries.push(file); if (--self._pending === 0) self.emit('_ready'); }); return self; }; // DEPRECATED Browserify.prototype.expose = function (name, file) { this.exports[file] = name; this.files.push(file); }; Browserify.prototype.external = function (id, opts) { var self = this; if (isBrowserify(id)) { self._pending++; function captureDeps() { var d = mdeps(id.files); d.pipe(through(write, end)); function write (row) { self.external(row.id) } function end () { if (--self._pending === 0) self.emit('_ready'); } } if (id._pending === 0) return captureDeps(); return id.once('_ready', captureDeps); } opts = opts || {}; opts.external = true; if (!opts.parse) { this.noParse(id); if (opts.expose) this.noParse(opts.expose); } return this.require(id, opts); }; Browserify.prototype.ignore = function (file) { this._ignore[file] = true; return this; }; Browserify.prototype.bundle = function (opts, cb) { var self = this; if (typeof opts === 'function') { cb = opts; opts = {}; } if (!opts) opts = {}; if (opts.insertGlobals === undefined) opts.insertGlobals = false; if (opts.detectGlobals === undefined) opts.detectGlobals = true; if (opts.ignoreMissing === undefined) opts.ignoreMissing = false; if (opts.standalone === undefined) opts.standalone = false; opts.resolve = self._resolve.bind(self); opts.transform = self._transforms; opts.noParse = self._noParse; opts.transformKey = [ 'browserify', 'transform' ]; var parentFilter = opts.packageFilter; opts.packageFilter = function (pkg) { if (parentFilter) pkg = parentFilter(pkg); return packageFilter(pkg); }; if (self._pending) { var tr = through(); self.on('_ready', function () { var b = self.bundle(opts, cb); if (!cb) b.on('error', tr.emit.bind(tr, 'error')); b.pipe(tr); }); return tr; } if (opts.standalone && self._entries.length !== 1) { process.nextTick(function () { p.emit('error', 'standalone only works with a single entry point'); }); } var prevCache = opts.cache && copy(opts.cache); var d = (opts.deps || self.deps.bind(self))(opts); var g = opts.detectGlobals || opts.insertGlobals ? insertGlobals(self.files, { resolve: self._resolve.bind(self), always: opts.insertGlobals, vars: opts.insertGlobalVars }) : through() ; var p = self.pack(opts.debug, opts.standalone); if (cb) { p.on('error', cb); p.pipe(concatStream(function (src) { cb(null, src) })); } g.on('dep', function (dep) { self.emit('dep', dep) }); d.on('error', p.emit.bind(p, 'error')); g.on('error', p.emit.bind(p, 'error')); d.pipe(through(function (dep) { if (self._noParse.indexOf(dep.id) >= 0 || (prevCache && prevCache[dep.id])) { p.write(dep); } else this.queue(dep) })).pipe(g).pipe(p); return p; }; Browserify.prototype.transform = function (t) { if (typeof t === 'string' && /^\./.test(t)) { t = path.resolve(t); } this._transforms.push(t); return this; }; Browserify.prototype.deps = function (opts) { var self = this; if (self._pending) { var tr = through(); self.on('_ready', function () { self.deps(opts).pipe(tr); }); return tr; } opts.modules = browserBuiltins; opts.extensions = self._extensions; var d = mdeps(self.files, opts); var tr = d.pipe(through(write)); d.on('error', tr.emit.bind(tr, 'error')); return tr; function write (row) { self.emit('dep', row); if (row.id === emptyModulePath) { row.source = ''; } row.deps = Object.keys(row.deps).reduce(function (acc, key) { if (!self._external[key] && !self._external[row.id]) { acc[key] = row.deps[key]; } return acc; }, {}); if (self._expose[row.id]) { this.queue({ id: row.id, exposed: self._expose[row.id], deps: {}, source: 'module.exports=require(\'' + hash(row.id) + '\');' }); } if (self.exports[row.id]) row.exposed = self.exports[row.id]; if (self._exposeAll) { row.exposed = hash(row.id); } // skip adding this file if it is external if (self._external[row.id]) { return; } if (/\.json$/.test(row.id)) { row.source = 'module.exports=' + row.source; } var ix = self._entries.indexOf(row.id); row.entry = ix >= 0; if (ix >= 0) row.order = ix; this.queue(row); } }; Browserify.prototype.pack = function (debug, standalone) { var self = this; var packer = browserPack({ raw: true }); var mainModule; var hashes = {}, depList = {}, depHash = {}; var input = through(function (row_) { var row = copy(row_); if (debug) { row.sourceRoot = 'file://localhost'; row.sourceFile = row.id; } var dup = hashes[row.hash]; if (dup && sameDeps(depList[dup._id], row.deps)) { row.source = 'module.exports=require(' + JSON.stringify(dup.id) + ')' ; } else if (dup) { row.source = 'arguments[4][' + JSON.stringify(dup.id) + '][0].apply(exports,arguments)' ; } else hashes[row.hash] = { _id: row.id, id: getId(row) }; if (/^#!/.test(row.source)) row.source = '//' + row.source; var err = checkSyntax(row.source, row.id); if (err) return this.emit('error', err); row.id = getId(row); if (row.entry) mainModule = mainModule || row.id; var deps = {}; Object.keys(row.deps || {}).forEach(function (key) { var file = row.deps[key]; var index = row.indexDeps && row.indexDeps[key]; if (self._exposeAll) { index = hash(file); } deps[key] = getId({ id: file, index: index }); }); row.deps = deps; this.queue(row); }); function getId (row) { if (row.exposed) { return row.exposed; } else if (self._external[row.id] || self.exports[row.id]) { return hash(row.id); } else if (self._expose[row.id]) { return row.id; } else if (row.index === undefined) { return row.id; } else return row.index; } var first = true; var hasExports = Object.keys(self.exports).length; var output = through(write, end); var sort = depSorter({ index: true }); return pipeline(through(hasher), sort, input, packer, output); function write (buf) { if (first) writePrelude.call(this); first = false; this.queue(buf); } function end () { if (first) writePrelude.call(this); if (standalone) { this.queue('\n(' + mainModule + ')' + umd.postlude(standalone)); } this.queue('\n;'); this.queue(null); } function writePrelude () { if (!first) return; if (standalone) { return this.queue(umd.prelude(standalone) + 'return '); } if (!hasExports) return this.queue(';'); this.queue('require='); } function hasher (row) { row.hash = hash(row.source); depList[row.id] = row.deps; depHash[row.id] = row.hash; this.queue(row); } function sameDeps (a, b) { var keys = Object.keys(a); if (keys.length !== Object.keys(b).length) return false; for (var i = 0; i < keys.length; i++) { var k = keys[i], ka = a[k], kb = b[k]; var ha = depHash[ka]; var hb = depHash[kb]; var da = depList[ka]; var db = depList[kb]; if (ka === kb) continue; if (ha !== hb || !sameDeps(da, db)) return false; } return true; } }; var packageFilter = function (info) { if (typeof info.browserify === 'string' && !info.browser) { info.browser = info.browserify; delete info.browserify; } return info; }; Browserify.prototype._resolve = function (id, parent, cb) { if (this._ignore[id]) return cb(null, emptyModulePath); var self = this; var result = function (file, pkg, x) { if (self._pending === 0) { self.emit('file', file, id, parent); } if (pkg) { cb(null, file, pkg, x); self.emit('package', file, pkg); } else findPackage(path.dirname(file), function (err, pkgfile, pkg) { if (err) return cb(err) if (pkg && typeof pkg === 'object') { var pkg_ = pkg; pkg = {}; if (typeof pkg_.browserify === 'string' && !pkg_.browser) { pkg.browser = pkg_.browserify; } if (typeof pkg_.browserify === 'object') { pkg.browserify = pkg_.browserify; } } cb(null, file, pkg, x); self.emit('package', file, pkg); }) }; if (self._mapped[id]) return result(self._mapped[id]); parent.modules = browserBuiltins; parent.extensions = self._extensions; if (self._external[id]) return cb(null, emptyModulePath); return browserResolve(id, parent, function(err, file, pkg) { if (err) return cb(err); if (!file && (self._external[id] || self._external[file])) { return cb(null, emptyModulePath); } else if (!file) { return cb(new Error('module ' + JSON.stringify(id) + ' not found from ' + JSON.stringify(parent.filename) )); } if (self._ignore[file]) return cb(null, emptyModulePath); if (self._external[file]) return result(file, pkg, true); result(file, pkg); }); function findPackage (basedir, cb) { var dirs = parents(basedir); (function next () { var dir = dirs.shift(); if (dir === 'node_modules' || dir === undefined) { return cb(null, null, null); } var pkgfile = path.join(dir, 'package.json'); if (self._pkgcache[pkgfile]) { cb(null, pkgfile, self._pkgcache[pkgfile]); } else readPackage(pkgfile, function (err, pkg) { self._pkgcache[pkgfile] = pkg; if (err) return next() else cb(null, pkgfile, pkg) }); })(); } function readPackage (pkgfile, cb) { fs.readFile(pkgfile, function (err, src) { if (err) return cb(err); try { var pkg = JSON.parse(src) } catch (e) {} cb(null, pkg); }); } }; function copy (obj) { return Object.keys(obj).reduce(function (acc, key) { acc[key] = obj[key]; return acc; }, {}); } function isBrowserify (x) { return x && typeof x === 'object' && typeof x.bundle === 'function'; }
import test from 'ava' import * as notificationActions from './notificationActions' test('deliverMessage action returns the expected action', assert => { const inbox = { message: 'I am a dummy mesage', type: 'message' } const action = notificationActions.deliverMessage(inbox) const expectedAction = { type: notificationActions.DELIVER_MESSAGE, payload: {...inbox} } assert.deepEqual(action, expectedAction) }) test('sendMessage action returns the expected action', assert => { const message = 'I am a dummy mesage' const action = notificationActions.sendMessage(message) const expectedAction = { type: notificationActions.SEND_MESSAGE, payload: { type: 'positive', message: message } } assert.deepEqual(action, expectedAction) }) test('removeAction action returns the expected action', assert => { const action = notificationActions.removeMessage() const expectedAction = { type: notificationActions.REMOVE_MESSAGE, payload: {} } assert.deepEqual(action, expectedAction) })
/* * Copyright (C) 2014 United States Government as represented by the Administrator of the * National Aeronautics and Space Administration. All Rights Reserved. */ /** * @exports WmsLayerCapabilities * @version $Id: WmsLayerCapabilities.js 3055 2015-04-29 21:39:51Z tgaskins $ */ define([ '../../error/ArgumentError', '../../util/Logger' ], function (ArgumentError, Logger) { "use strict"; /** * Constructs an WMS Layer instance from an XML DOM. * @alias WmsLayerCapabilities * @constructor * @classdesc Represents a WMS layer description from a WMS Capabilities document. This object holds all the * fields specified in the associated WMS Capabilities document. * @param {{}} layerElement A WMS Layer element describing the layer. * @param {{}} parentNode An object indicating the new layer object's parent object. * @throws {ArgumentError} If the specified layer element is null or undefined. */ var WmsLayerCapabilities = function (layerElement, parentNode) { if (!layerElement) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "WmsLayerCapabilities", "constructor", "Layer element is null or undefined.")); } /** * The parent object, as specified to the constructor of this object. * @type {{}} * @readonly */ this.parent = parentNode; /** * The layers that are children of this layer. * @type {WmsLayerCapabilities[]} * @readonly */ this.layers; /** * The name of this layer description. * @type {String} * @readonly */ this.name; /** * The title of this layer. * @type {String} * @readonly */ this.title; /** * The abstract of this layer. * @type {String} * @readonly */ this.abstract; /** * The list of keywords associated with this layer description. * @type {String[]} * @readonly */ this.keywordList; /** * The identifiers associated with this layer description. Each identifier has the following properties: * authority, content. * @type {Object[]} */ this.identifiers; /** * The metadata URLs associated with this layer description. Each object in the returned array has the * following properties: type, format, url. * @type {Object[]} * @readonly */ this.metadataUrls; /** * The data URLs associated with this layer description. Each object in the returned array has the * following properties: format, url. * @type {Object[]} * @readonly */ this.dataUrls; /** * The feature list URLs associated with this layer description. Each object in the returned array has the * following properties: format, url. * @type {Object[]} * @readonly */ this.featureListUrls; this.assembleLayer(layerElement); }; Object.defineProperties(WmsLayerCapabilities.prototype, { /** * The WMS capability section containing this layer description. * @type {{}} * @readonly * @memberof WmsLayerCapabilities.prototype */ capability: { get: function () { var o = this; while (o && (o instanceof WmsLayerCapabilities)) { o = o.parent; } return o; } }, /** * The WMS queryable attribute. * @type {Boolean} * @readonly * @memberof WmsLayerCapabilities.prototype */ queryable: { get: function () { return WmsLayerCapabilities.replace(this, "_queryable"); } }, /** * The WMS cascaded attribute. * @type {Boolean} * @readonly * @memberof WmsLayerCapabilities.prototype */ cascaded: { get: function () { return WmsLayerCapabilities.replace(this, "_cascaded"); } }, /** * The WMS opaque attribute. * @type {Boolean} * @readonly * @memberof WmsLayerCapabilities.prototype */ opaque: { get: function () { return WmsLayerCapabilities.replace(this, "_opaque"); } }, /** * The WMS noSubsets attribute. * @type {Boolean} * @readonly * @memberof WmsLayerCapabilities.prototype */ noSubsets: { get: function () { return WmsLayerCapabilities.replace(this, "_noSubsets"); } }, /** * The WMS fixedWidth attribute. * @type {Number} * @readonly * @memberof WmsLayerCapabilities.prototype */ fixedWidth: { get: function () { return WmsLayerCapabilities.replace(this, "_fixedWidth"); } }, /** * The WMS fixedHeight attribute. * @type {Number} * @readonly * @memberof WmsLayerCapabilities.prototype */ fixedHeight: { get: function () { return WmsLayerCapabilities.replace(this, "_fixedHeight"); } }, /** * The list of styles associated with this layer description, accumulated from this layer and its parent * layers. Each object returned may have the following properties: name {String}, title {String}, * abstract {String}, legendUrls {Object[]}, styleSheetUrl, styleUrl. Legend urls may have the following * properties: width, height, format, url. Style sheet urls and style urls have the following properties: * format, url. * @type {Object[]} * @readonly * @memberof WmsLayerCapabilities.prototype */ styles: { get: function () { return WmsLayerCapabilities.accumulate(this, "_styles", []); } }, /** * The list of coordinate system descriptions associated with this layer, accumulated from this layer * and its parent layers. WMS servers implementing WMS version 1.3.0 and above have this field. * @type {String[]} * @readonly * @memberof WmsLayerCapabilities.prototype */ crses: { get: function () { return WmsLayerCapabilities.accumulate(this, "_crses", []); } }, /** * The list of coordinate system descriptions associated with this layer, accumulated from this layer * and its parent layers. WMS servers implementing WMS version 1.1.1 and below have this field. * @type {String[]} * @readonly * @memberof WmsLayerCapabilities.prototype */ srses: { get: function () { return WmsLayerCapabilities.accumulate(this, "_srses", []); } }, /** * This layer description's geographic bounding box. WMS servers implementing WMS 1.3.0 and above have * this field. The returned object has properties for each of the WMS-specified fields. For example, * "westBoundingLongitude". * @type {{}} * @readonly * @memberof WmsLayerCapabilities.prototype */ geographicBoundingBox: { get: function () { return WmsLayerCapabilities.replace(this, "_geographicBoundingBox"); } }, /** * This layer description's geographic bounding box. WMS servers implementing WMS 1.1.1 and below have * this field. The returned object has properties for each of the WMS-specified fields. For example, * "maxx". * @type {{}} * @readonly * @memberof WmsLayerCapabilities.prototype */ latLonBoundingBox: { // WMS 1.1.1 get: function () { return WmsLayerCapabilities.replace(this, "_latLonBoundingBox"); } }, /** * The bounding boxes associated with this layer description. The returned object has properties for each * of the defined attributes. For example, "minx". * @type {{}} * @readonly * @memberof WmsLayerCapabilities.prototype */ boundingBoxes: { get: function () { return WmsLayerCapabilities.replace(this, "_boundingBoxes"); } }, /** * The list of dimensions associated with this layer description, accumulated from this layer and its * parent layers. WMS servers implementing WMS version 1.3.0 and above provide this field. * @type {String[]} * @readonly * @memberof WmsLayerCapabilities.prototype */ dimensions: { get: function () { var accumulatedDimensions = [], layer = this; // Accumulate only dimensions with unique names with descendants overriding ancestors. while (layer && (layer instanceof WmsLayerCapabilities)) { if (layer._dimensions && layer._dimensions.length > 0) { layer._dimensions.forEach(function (ancestorDimension) { var name = ancestorDimension.name; var include = true; accumulatedDimensions.forEach(function (descendantDimension) { if (descendantDimension.name === name) { include = false; } }); if (include) { accumulatedDimensions.push(ancestorDimension); } }); } layer = layer.parent; } return accumulatedDimensions.length > 0 ? accumulatedDimensions : undefined; } }, /** * The list of extents associated with this layer description, accumulated from this layer and its * parent layers. WMS servers implementing WMS version 1.3.0 and above provide this field. * @type {String[]} * @readonly * @memberof WmsLayerCapabilities.prototype */ extents: { get: function () { var accumulatedDimensions = [], layer = this; // Accumulate only extents with unique names with descendants overriding ancestors. while (layer && (layer instanceof WmsLayerCapabilities)) { if (layer._extents && layer._extents.length > 0) { layer._extents.forEach(function (ancestorDimension) { var name = ancestorDimension.name; var include = true; accumulatedDimensions.forEach(function (descendantDimension) { if (descendantDimension.name === name) { include = false; } }); if (include) { accumulatedDimensions.push(ancestorDimension); } }); } layer = layer.parent; } return accumulatedDimensions.length > 0 ? accumulatedDimensions : undefined; } }, /** * The attribution element associated with this layer description. The returned object has the following * properties: title {String}, url {String}, logoUrl {{format, url}}. * @type {{}} * @readonly * @memberof WmsLayerCapabilities.prototype */ attribution: { get: function () { return WmsLayerCapabilities.replace(this, "_attribution"); } }, /** * The authority URLs associated with this layer description, accumulated from this layer and its parent * layers. The returned objects have the following properties: name {String}, url {String}. * @type {Object[]} * @readonly * @memberof WmsLayerCapabilities.prototype */ authorityUrls: { get: function () { return WmsLayerCapabilities.accumulate(this, "_authorityUrls", []); } }, /** * The minimum-scale-denominator associated with this layer description. * WMS servers implementing WMS version 1.3.0 and above provide this field. * @type {Number} * @readonly * @memberof WmsLayerCapabilities.prototype */ minScaleDenominator: { get: function () { return WmsLayerCapabilities.replace(this, "_minScaleDenominator"); } }, /** * The maximum-scale-denominator associated with this layer description. * WMS servers implementing WMS version 1.3.0 and above provide this field. * @type {Number} * @readonly * @memberof WmsLayerCapabilities.prototype */ maxScaleDenominator: { get: function () { return WmsLayerCapabilities.replace(this, "_maxScaleDenominator"); } }, /** * The scale hint associated with this layer description. * WMS servers implementing WMS version 1.1.1 and below provide this field. * @type {Number} * @readonly * @memberof WmsLayerCapabilities.prototype */ scaleHint: { get: function () { return WmsLayerCapabilities.replace(this, "_scaleHint"); } } }); WmsLayerCapabilities.prototype.style = function(name) { if (!name) { throw new ArgumentError( Logger.logMessage(Logger.LEVEL_SEVERE, "WmsLayerCapabilities", "style", "Style name is null or undefined.")); } var styles = this.styles; if (!styles) { return null; } for (var i = 0, len = styles.length, style; i < len; i++) { style = styles[i]; if (style.name === name) { return style; } } } WmsLayerCapabilities.accumulate = function (layer, propertyName, accumulation) { // Accumulate all of the named properties in the specified layer and its ancestors. while (layer && (layer instanceof WmsLayerCapabilities)) { var property = layer[propertyName]; if (property) { for (var i = 0; i < property.length; i++) { accumulation.push(property[i]); } } layer = layer.parent; } return accumulation.length > 0 ? accumulation : null; }; WmsLayerCapabilities.replace = function (layer, propertyName) { // Find the first property instance encountered from the specified layer upwards through its ancestors. while (layer && (layer instanceof WmsLayerCapabilities)) { var property = layer[propertyName]; if (property) { return property; } else { layer = layer.parent; } } }; WmsLayerCapabilities.prototype.assembleLayer = function (layerElement) { var elements, attrValue, c, e; attrValue = layerElement.getAttribute("queryable"); if (attrValue) { this._queryable = attrValue === "1" || attrValue === "true" } attrValue = layerElement.getAttribute("opaque"); if (attrValue) { this._opaque = attrValue === "1" || attrValue === "true" } attrValue = layerElement.getAttribute("noSubsets"); if (attrValue) { this._noSubsets = attrValue === "1" || attrValue === "true" } attrValue = layerElement.getAttribute("cascaded"); if (attrValue) { this._cascaded = parseInt("10"); } attrValue = layerElement.getAttribute("fixedWidth"); if (attrValue) { this._fixedWidth = parseInt("10"); } attrValue = layerElement.getAttribute("fixedHeight"); if (attrValue) { this._fixedHeight = parseInt("10"); } var children = layerElement.children || layerElement.childNodes; for (c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "Layer") { if (!this.layers) { this.layers = []; } this.layers.push(new WmsLayerCapabilities(childElement, this)); } else if (childElement.localName === "Name") { this.name = childElement.textContent; } else if (childElement.localName === "Title") { this.title = childElement.textContent; } else if (childElement.localName === "Abstract") { this.abstract = childElement.textContent; } else if (childElement.localName === "KeywordList") { this.keywordList = this.keywordList || []; var children2 = childElement.children || childElement.childNodes; for (var c2 = 0; c2 < children2.length; c2++) { var child2 = children2[c2]; if (child2.localName === "Keyword") { this.keywordList.push(child2.textContent); } } } else if (childElement.localName === "Style") { if (!this._styles) { this._styles = []; } this._styles.push(WmsLayerCapabilities.assembleStyle(childElement)) } else if (childElement.localName === "CRS") { if (!this._crses) { this._crses = []; } this._crses.push(childElement.textContent); } else if (childElement.localName === "SRS") { // WMS 1.1.1 if (!this._srses) { this._srses = []; } this._srses.push(childElement.textContent); } else if (childElement.localName === "EX_GeographicBoundingBox") { this._geographicBoundingBox = WmsLayerCapabilities.assembleGeographicBoundingBox(childElement); } else if (childElement.localName === "LatLonBoundingBox") { // WMS 1.1.1 this._geographicBoundingBox = WmsLayerCapabilities.assembleLatLonBoundingBox(childElement); } else if (childElement.localName === "BoundingBox") { if (!this._boundingBoxes) { this._boundingBoxes = []; } this._boundingBoxes.push(WmsLayerCapabilities.assembleBoundingBox(childElement)); } else if (childElement.localName === "Dimension") { if (!this._dimensions) { this._dimensions = []; } this._dimensions.push(WmsLayerCapabilities.assembleDimension(childElement)); } else if (childElement.localName === "Extent") { // WMS 1.1.1 if (!this._extents) { this._extents = []; } this._extents.push(WmsLayerCapabilities.assembleDimension(childElement)); // same schema as 1.3.0 Dimension } else if (childElement.localName === "Attribution") { this._attribution = WmsLayerCapabilities.assembleAttribution(childElement); } else if (childElement.localName === "AuthorityURL") { if (!this._authorityUrls) { this._authorityUrls = []; } this._authorityUrls.push(WmsLayerCapabilities.assembleAuthorityUrl(childElement)); } else if (childElement.localName === "Identifier") { if (!this.identifiers) { this.identifiers = []; } this.identifiers.push(WmsLayerCapabilities.assembleIdentifier(childElement)); } else if (childElement.localName === "MetadataURL") { if (!this.metadataUrls) { this.metadataUrls = []; } this.metadataUrls.push(WmsLayerCapabilities.assembleMetadataUrl(childElement)); } else if (childElement.localName === "DataURL") { if (!this.dataUrls) { this.dataUrls = []; } this.dataUrls.push(WmsLayerCapabilities.assembleUrl(childElement)); } else if (childElement.localName === "FeatureListURL") { if (!this.featureListUrls) { this.featureListUrls = []; } this.featureListUrls.push(WmsLayerCapabilities.assembleUrl(childElement)); } else if (childElement.localName === "MinScaleDenominator") { this._minScaleDenominator = parseFloat(childElement.textContent); } else if (childElement.localName === "MaxScaleDenominator") { this._maxScaleDenominator = parseFloat(childElement.textContent); } else if (childElement.localName === "ScaleHint") { // WMS 1.1.1 this._scaleHint = {}; this._scaleHint.min = WmsLayerCapabilities.getFloatAttribute(childElement, "min"); this._scaleHint.max = WmsLayerCapabilities.getFloatAttribute(childElement, "max"); } } }; WmsLayerCapabilities.assembleStyle = function (styleElement) { var result = {}; var children = styleElement.children || styleElement.childNodes; for (var c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "Name") { result.name = childElement.textContent; } else if (childElement.localName === "Title") { result.title = childElement.textContent; } else if (childElement.localName === "Abstract") { result.abstract = childElement.textContent; } else if (childElement.localName === "LegendURL") { if (!result.legendUrls) { result.legendUrls = []; } result.legendUrls.push(WmsLayerCapabilities.assembleLegendUrl(childElement)); } else if (childElement.localName === "StyleSheetURL") { result.styleSheetUrl = WmsLayerCapabilities.assembleUrl(childElement); } else if (childElement.localName === "StyleURL") { result.styleUrl = WmsLayerCapabilities.assembleUrl(childElement); } } return result; }; WmsLayerCapabilities.assembleGeographicBoundingBox = function (bboxElement) { var result = {}; var children = bboxElement.children || bboxElement.childNodes; for (var c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "westBoundLongitude") { result.westBoundLongitude = parseFloat(childElement.textContent); } else if (childElement.localName === "eastBoundLongitude") { result.eastBoundLongitude = parseFloat(childElement.textContent); } else if (childElement.localName === "southBoundLatitude") { result.southBoundLatitude = parseFloat(childElement.textContent); } else if (childElement.localName === "northBoundLatitude") { result.northBoundLatitude = parseFloat(childElement.textContent); } } return result; }; WmsLayerCapabilities.assembleLatLonBoundingBox = function (bboxElement) { // WMS 1.1.1 var result = {}; result.minx = WmsLayerCapabilities.getFloatAttribute(bboxElement, "minx"); result.miny = WmsLayerCapabilities.getFloatAttribute(bboxElement, "miny"); result.maxx = WmsLayerCapabilities.getFloatAttribute(bboxElement, "maxx"); result.maxy = WmsLayerCapabilities.getFloatAttribute(bboxElement, "maxy"); return result; }; WmsLayerCapabilities.assembleBoundingBox = function (bboxElement) { var result = {}; result.crs = bboxElement.getAttribute("CRS"); result.minx = WmsLayerCapabilities.getFloatAttribute(bboxElement, "minx"); result.miny = WmsLayerCapabilities.getFloatAttribute(bboxElement, "miny"); result.maxx = WmsLayerCapabilities.getFloatAttribute(bboxElement, "maxx"); result.maxy = WmsLayerCapabilities.getFloatAttribute(bboxElement, "maxy"); result.resx = WmsLayerCapabilities.getFloatAttribute(bboxElement, "resx"); result.resy = WmsLayerCapabilities.getFloatAttribute(bboxElement, "resy"); return result; }; WmsLayerCapabilities.assembleDimension = function (dimensionElement) { var result = {}; result.name = dimensionElement.getAttribute("name"); result.units = dimensionElement.getAttribute("units"); result.unitSymbol = dimensionElement.getAttribute("unitSymbol"); result.default = dimensionElement.getAttribute("default"); result.multipleValues = dimensionElement.getAttribute("multipleValues"); if (result.multipleValues) { result.multipleValues = result.multipleValues === "true" || result.multipleValues === "1"; } result.nearestValue = dimensionElement.getAttribute("nearestValue"); if (result.nearestValue) { result.nearestValue = result.nearestValue === "true" || result.nearestValue === "1"; } result.current = dimensionElement.getAttribute("current"); if (result.current) { result.current = result.current === "true" || result.current === "1"; } result.content = dimensionElement.textContent; return result; }; WmsLayerCapabilities.assembleAttribution = function (attributionElement) { var result = {}; var children = attributionElement.children || attributionElement.childNodes; for (var c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "Title") { result.title = childElement.textContent; } else if (childElement.localName === "OnlineResource") { result.url = childElement.getAttribute("xlink:href"); } else if (childElement.localName === "LogoUrul") { result.logoUrl = WmsLayerCapabilities.assembleLogoUrl(childElement); } } return result; }; WmsLayerCapabilities.assembleAuthorityUrl = function (urlElement) { var result = {}; result.name = urlElement.getAttribute("name"); var children = urlElement.children || urlElement.childNodes; for (var c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "OnlineResource") { result.url = childElement.getAttribute("xlink:href"); } } return result; }; WmsLayerCapabilities.assembleIdentifier = function (identifierElement) { var result = {}; result.authority = identifierElement.getAttribute("authority"); result.content = identifierElement.textContent; return result; }; WmsLayerCapabilities.assembleMetadataUrl = function (urlElement) { var result = {}; result.type = urlElement.getAttribute("type"); var children = urlElement.children || urlElement.childNodes; for (var c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "Format") { result.format = childElement.textContent; } else if (childElement.localName === "OnlineResource") { result.url = childElement.getAttribute("xlink:href"); } } return result; }; WmsLayerCapabilities.assembleLegendUrl = function (urlElement) { var result = {}; result.width = WmsLayerCapabilities.getIntegerAttribute(urlElement, "width"); result.height = WmsLayerCapabilities.getIntegerAttribute(urlElement, "height"); var children = urlElement.children || urlElement.childNodes; for (var c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "Format") { result.format = childElement.textContent; } else if (childElement.localName === "OnlineResource") { result.url = childElement.getAttribute("xlink:href"); } } return result; }; WmsLayerCapabilities.assembleLogoUrl = function (urlElement) { var result = {}; result.width = WmsLayerCapabilities.getIntegerAttribute(urlElement, "width"); result.height = WmsLayerCapabilities.getIntegerAttribute(urlElement, "height"); var children = urlElement.children || urlElement.childNodes; for (var c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "Format") { result.format = childElement.textContent; } else if (childElement.localName === "OnlineResource") { result.url = childElement.getAttribute("xlink:href"); } } return result; }; WmsLayerCapabilities.assembleUrl = function (urlElement) { var result = {}; var children = urlElement.children || urlElement.childNodes; for (var c = 0; c < children.length; c++) { var childElement = children[c]; if (childElement.localName === "Format") { result.format = childElement.textContent; } else if (childElement.localName === "OnlineResource") { result.url = childElement.getAttribute("xlink:href"); } } return result; }; WmsLayerCapabilities.getIntegerAttribute = function (element, attrName) { var result = element.getAttribute(attrName); if (result) { result = parseInt(result); } else { result = undefined; } return result; }; WmsLayerCapabilities.getFloatAttribute = function (element, attrName) { var result = element.getAttribute(attrName); if (result) { result = parseFloat(result); } else { result = undefined; } return result; }; return WmsLayerCapabilities; } ) ;
import React from "react" export default { title: "Dashboard/header", } export const exampleStory = () => ( <div style={{ padding: "16px", backgroundColor: "#eeeeee" }}> <h1 style={{ color: "rebeccapurple" }}>Hello from Storybook and Gatsby!</h1> </div> )
module.exports = { up: function(migration, DataTypes) { return migration.createTable('RefreshTokens', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true }, token: { type: DataTypes.UUID, allowNull: false }, expires_in: { type: DataTypes.DATE, allowNull: false }, created_at: { type: DataTypes.DATE }, updated_at: { type: DataTypes.DATE }, user_id: { type: DataTypes.INTEGER, references: { model: 'Users', key: 'id' } } }); }, down: function(migration) { return migration.dropTable('RefreshTokens'); } };
'use strict'; var changelog = require('conventional-changelog'); var parseUrl = require('github-url-from-git'); module.exports = function (pluginConfig, _ref, cb) { var pkg = _ref.pkg; var repository = pkg.repository ? parseUrl(pkg.repository.url) : null; changelog({ version: pkg.version, repository: repository, file: false }, cb); };
'use strict'; var _ = require('lodash'); var moment = require('moment'); var uuid = require('node-uuid'); var jwt = require('jwt-simple'); /** * various utility methods * * @type {Object} */ module.exports = { /** * gathers all params for this request * * @param {Object} req the express request object * @return {Object} all params * @api public */ allParams: function(req){ var params = req.params.all(); _.merge(params, req.headers); return _.merge(params, req.query); }, /** * Counts only the top level of a object * * @param {Object} obj plain object to count * @return {Integer} the number of top level elements * @api public */ countTopLevel: function(obj){ if(typeof obj !== 'object'){ return -1; } var count = 0; for(var key in obj){ if(obj.hasOwnProperty(key)){ count++; } } return count; }, /** * allows us to access an object like an array [0] == {first object} * * @param {Integer} index the position in the object to look * @param {Object} obj the object to access * @return {Object} the value at given position * @api public */ accessObjectLikeArray: function(index, obj){ // if obj is not an object just return it nothing to do if(typeof obj !== 'object'){ return obj; } // if object already is an array return the value at given index if(typeof obj[index] !== 'undefined'){ return obj[index]; } var count = 0; for(var key in obj){ if(count === index){ return obj[key]; } count++; } }, /** * Creates a new JWT token * * @param {Integer} req * @param {Object} res * @param {Object} device the device model * @return {Object} the created jwt token. * @api public */ createJwt: function(req, res, device) { var jsonWebTokens = waterlock.config.deviceJsonWebTokens || {}; var expiryUnit = (jsonWebTokens.expiry && jsonWebTokens.expiry.unit) || 'days'; var expiryLength = (jsonWebTokens.expiry && jsonWebTokens.expiry.length) || 7; var expires = moment().add(expiryLength, expiryUnit).valueOf(); var issued = Date.now(); device = device || req.session.device; var token = jwt.encode({ iss: device.id + '|' + req.remoteAddress, sub: jsonWebTokens.subject, aud: jsonWebTokens.audience, exp: expires, nbf: issued, iat: issued, jti: uuid.v1() }, jsonWebTokens.secret); return { token: token, expires: expires }; } };
/* * Author: @senthil2rajan * plugin: timepicker * website: senthilraj.github.io/Timepicki */ (function($) { $.fn.timepicki = function(options) { var defaults = { format_output: function(tim, mini, meri) { if(settings.show_meridian){ return tim + " : " + mini + " : " + meri; }else{ return tim + " : " + mini; } }, increase_direction: 'down', custom_classes: '', min_hour_value: 1, max_hour_value: 24, step_size_hours: '1', step_size_minutes: '1', overflow_minutes: false, disable_keyboard_mobile: false, reset: false }; var settings = $.extend({}, defaults, options); return this.each(function() { var ele = $(this); var ele_hei = ele.outerHeight(); ele_hei += 10; $(ele).wrap("<div class='time_pick'>"); var ele_par = $(this).parents(".time_pick"); // developer can specify which arrow makes the numbers go up or down var top_arrow_button = (settings.increase_direction === 'down') ? "<div class='prev action-prev'></div>" : "<div class='prev action-next'></div>"; var bottom_arrow_button = (settings.increase_direction === 'down') ? "<div class='next action-next'></div>" : "<div class='next action-prev'></div>"; var new_ele = $( "<div class='timepicker_wrap " + settings.custom_classes + "'>" + "<div class='arrow_top'></div>" + "<div class='time'>" + top_arrow_button + "<div class='ti_tx'><input type='text' class='timepicki-input'" + (settings.disable_keyboard_mobile ? "readonly" : "") + "></div>" + bottom_arrow_button + "</div>" + "<div class='mins'>" + top_arrow_button + "<div class='mi_tx'><input type='text' class='timepicki-input'" + (settings.disable_keyboard_mobile ? "readonly" : "") + "></div>" + bottom_arrow_button + "</div>"); if(settings.show_meridian){ new_ele.append( "<div class='meridian'>" + top_arrow_button + "<div class='mer_tx'><input type='text' class='timepicki-input' readonly></div>" + bottom_arrow_button + "</div>"); } if(settings.reset){ new_ele.append( "<div><a href='#' class='reset_time'>Reset</a></div>"); } ele_par.append(new_ele); var ele_next = $(this).next(".timepicker_wrap"); var ele_next_all_child = ele_next.find("div"); var inputs = ele_par.find('input'); $('.reset_time').on("click", function(event) { ele.val(""); close_timepicki(); }); $(".timepicki-input").keydown( function(keyevent){ var len = $(this).val().length; // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(keyevent.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl+A (keyevent.keyCode == 65 && keyevent.ctrlKey === true) || // Allow: home, end, left, right (keyevent.keyCode >= 35 && keyevent.keyCode <= 39)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((keyevent.shiftKey || (keyevent.keyCode < 48 || keyevent.keyCode > 57)) && (keyevent.keyCode < 96 || keyevent.keyCode > 105) || len==2 ) { keyevent.preventDefault(); } }); // open or close time picker when clicking $(document).on("click", function(event) { if (!$(event.target).is(ele_next) && ele_next.css("display")=="block" && !$(event.target).is($('.reset_time'))) { if (!$(event.target).is(ele)) { set_value(event, !is_element_in_timepicki($(event.target))); } else { var ele_lef = 0; ele_next.css({ "top": ele_hei + "px", "left": ele_lef + "px" }); open_timepicki(); } } }); // open the modal when the user focuses on the input ele.on('focus', open_timepicki); // select all text in input when user focuses on it inputs.on('focus', function() { var input = $(this); if (!input.is(ele)) { input.select(); } }); // allow user to increase and decrease numbers using arrow keys inputs.on('keydown', function(e) { var direction, input = $(this); // UP if (e.which === 38) { if (settings.increase_direction === 'down') { direction = 'prev'; } else { direction = 'next'; } // DOWN } else if (e.which === 40) { if (settings.increase_direction === 'down') { direction = 'next'; } else { direction = 'prev'; } } if (input.closest('.timepicker_wrap .time').length) { change_time(null, direction); } else if (input.closest('.timepicker_wrap .mins').length) { change_mins(null, direction); } else if (input.closest('.timepicker_wrap .meridian').length && settings.show_meridian) { change_meri(null, direction); } }); // close the modal when the time picker loses keyboard focus inputs.on('blur', function() { setTimeout(function() { var focused_element = $(document.activeElement); if (focused_element.is(':input') && !is_element_in_timepicki(focused_element)) { set_value(); close_timepicki(); } }, 0); }); function is_element_in_timepicki(jquery_element) { return $.contains(ele_par[0], jquery_element[0]) || ele_par.is(jquery_element); } function set_value(event, close) { // use input values to set the time var tim = ele_next.find(".ti_tx input").val(); var mini = ele_next.find(".mi_tx input").val(); var meri = ""; if(settings.show_meridian){ meri = ele_next.find(".mer_tx input").val(); } if (tim.length !== 0 && mini.length !== 0 && (!settings.show_meridian || meri.length !== 0)) { // store the value so we can set the initial value // next time the picker is opened ele.attr('data-timepicki-tim', tim); ele.attr('data-timepicki-mini', mini); if(settings.show_meridian){ ele.attr('data-timepicki-meri', meri); // set the formatted value ele.val(settings.format_output(tim, mini, meri)); }else{ ele.val(settings.format_output(tim, mini)); } } if (close) { close_timepicki(); } } function open_timepicki() { set_date(settings.start_time); ele_next.fadeIn(); // focus on the first input and select its contents var first_input = ele_next.find('input:visible').first(); first_input.focus(); // if the user presses shift+tab while on the first input, // they mean to exit the time picker and go to the previous field var first_input_exit_handler = function(e) { if (e.which === 9 && e.shiftKey) { first_input.off('keydown', first_input_exit_handler); var all_form_elements = $(':input:visible:not(.timepicki-input)'); var index_of_timepicki_input = all_form_elements.index(ele); var previous_form_element = all_form_elements.get(index_of_timepicki_input-1); previous_form_element.focus(); } }; first_input.on('keydown', first_input_exit_handler); } function close_timepicki() { ele_next.fadeOut(); } function set_date(start_time) { var d, ti, mi, mer; // if a value was already picked we will remember that value if (ele.is('[data-timepicki-tim]')) { ti = Number(ele.attr('data-timepicki-tim')); mi = Number(ele.attr('data-timepicki-mini')); if(settings.show_meridian){ mer = ele.attr('data-timepicki-meri'); } // developer can specify a custom starting value } else if (typeof start_time === 'object') { ti = Number(start_time[0]); mi = Number(start_time[1]); if(settings.show_meridian){ mer = start_time[2]; } // default is we will use the current time } else { d = new Date(); ti = d.getHours(); mi = d.getMinutes(); mer = "AM"; if (12 < ti && settings.show_meridian) { ti -= 12; mer = "PM"; } } if (ti < 10) { ele_next.find(".ti_tx input").val("0" + ti); } else { ele_next.find(".ti_tx input").val(ti); } if (mi < 10) { ele_next.find(".mi_tx input").val("0" + mi); } else { ele_next.find(".mi_tx input").val(mi); } if(settings.show_meridian){ if (mer < 10) { ele_next.find(".mer_tx input").val("0" + mer); } else { ele_next.find(".mer_tx input").val(mer); } } } function change_time(cur_ele, direction) { var cur_cli = "time"; var cur_time = Number(ele_next.find("." + cur_cli + " .ti_tx input").val()); var ele_st = Number(settings.min_hour_value); var ele_en = Number(settings.max_hour_value); var step_size = Number(settings.step_size_hours); if ((cur_ele && cur_ele.hasClass('action-next')) || direction === 'next') { if (cur_time + step_size > ele_en) { var min_value = ele_st; if (min_value < 10) { min_value = '0' + min_value; } else { min_value = String(min_value); } ele_next.find("." + cur_cli + " .ti_tx input").val(min_value); } else { cur_time = cur_time + step_size; if (cur_time < 10) { cur_time = "0" + cur_time; } ele_next.find("." + cur_cli + " .ti_tx input").val(cur_time); } } else if ((cur_ele && cur_ele.hasClass('action-prev')) || direction === 'prev') { if (cur_time - step_size <= 0) { var max_value = ele_en; if (max_value < 10) { max_value = '0' + max_value; } else { max_value = String(max_value); } ele_next.find("." + cur_cli + " .ti_tx input").val(max_value); } else { cur_time = cur_time - step_size; if (cur_time < 10) { cur_time = "0" + cur_time; } ele_next.find("." + cur_cli + " .ti_tx input").val(cur_time); } } } function change_mins(cur_ele, direction) { var cur_cli = "mins"; var cur_mins = Number(ele_next.find("." + cur_cli + " .mi_tx input").val()); var ele_st = 0; var ele_en = 59; var step_size = Number(settings.step_size_minutes); if ((cur_ele && cur_ele.hasClass('action-next')) || direction === 'next') { if (cur_mins + step_size > ele_en) { ele_next.find("." + cur_cli + " .mi_tx input").val("00"); if(settings.overflow_minutes){ change_time(null, 'next'); } } else { cur_mins = cur_mins + step_size; if (cur_mins < 10) { ele_next.find("." + cur_cli + " .mi_tx input").val("0" + cur_mins); } else { ele_next.find("." + cur_cli + " .mi_tx input").val(cur_mins); } } } else if ((cur_ele && cur_ele.hasClass('action-prev')) || direction === 'prev') { if (cur_mins - step_size <= -1) { ele_next.find("." + cur_cli + " .mi_tx input").val(ele_en + 1 - step_size); if(settings.overflow_minutes){ change_time(null, 'prev'); } } else { cur_mins = cur_mins - step_size; if (cur_mins < 10) { ele_next.find("." + cur_cli + " .mi_tx input").val("0" + cur_mins); } else { ele_next.find("." + cur_cli + " .mi_tx input").val(cur_mins); } } } } function change_meri(cur_ele, direction) { var cur_cli = "meridian"; var ele_st = 0; var ele_en = 1; var cur_mer = null; cur_mer = ele_next.find("." + cur_cli + " .mer_tx input").val(); if ((cur_ele && cur_ele.hasClass('action-next')) || direction === 'next') { if (cur_mer == "AM") { ele_next.find("." + cur_cli + " .mer_tx input").val("PM"); } else { ele_next.find("." + cur_cli + " .mer_tx input").val("AM"); } } else if ((cur_ele && cur_ele.hasClass('action-prev')) || direction === 'prev') { if (cur_mer == "AM") { ele_next.find("." + cur_cli + " .mer_tx input").val("PM"); } else { ele_next.find("." + cur_cli + " .mer_tx input").val("AM"); } } } // handle clicking on the arrow icons var cur_next = ele_next.find(".action-next"); var cur_prev = ele_next.find(".action-prev"); $(cur_prev).add(cur_next).on("click", function() { var cur_ele = $(this); if (cur_ele.parent().attr("class") == "time") { change_time(cur_ele); } else if (cur_ele.parent().attr("class") == "mins") { change_mins(cur_ele); } else { if(settings.show_meridian){ change_meri(cur_ele); } } }); }); }; }(jQuery));
import React from 'react'; import configureStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import { shallow, mount } from 'enzyme'; import sinon from 'sinon'; import GoogleSignup from '../components/GoogleSignup'; const middlewares = [thunk]; const mockStore = configureStore(middlewares); const FakeGoogleLogin = React.createClass({ render: () => <div />, }); GoogleSignup.__Rewire__('GoogleLogin', FakeGoogleLogin); describe('GoogleSignup', () => { const store = mockStore({}); it('should have one(1) FakeGoogleLogin component', () => { const wrapper = mount(<GoogleSignup store={store} />); expect(wrapper.find(FakeGoogleLogin).length).toEqual(1); }); it('should call componentWillReceiveProps once', () => { const push = jest.fn(); const history = { push }; const nextProps = { currentState: { GoogleSignup: { success: false } } }; sinon.spy(GoogleSignup.prototype, 'componentWillReceiveProps'); const wrapper = mount(<GoogleSignup store={store} history={history} />); const instance = wrapper.instance(); instance.componentWillReceiveProps(nextProps); expect(GoogleSignup.prototype.componentWillReceiveProps.calledOnce).toEqual(true); }); });
import React from 'react' import TableRow from './TableRow' const Table = (props) => { return( <div className='game-container'> { [...new Array(props.rows)].map((val, i) => { if (typeof props.matrix[i] !== "undefined") { return <TableRow cols={props.cols} row={props.matrix[i]} key={i} /> } return ""; }) } </div> ) } export default Table
/* http://keith-wood.name/svg.html SVG for jQuery v1.4.2. Written by Keith Wood (kbwood{at}iinet.com.au) August 2007. Dual licensed under the GPL (http://dev.jquery.com/browser/trunk/jquery/GPL-LICENSE.txt) and MIT (http://dev.jquery.com/browser/trunk/jquery/MIT-LICENSE.txt) licenses. Please attribute the author if you use it. */ (function($) { // Hide scope, no $ conflict /* SVG manager. Use the singleton instance of this class, $.svg, to interact with the SVG functionality. */ function SVGManager() { this._settings = []; // Settings to be remembered per SVG object this._extensions = []; // List of SVG extensions added to SVGWrapper // for each entry [0] is extension name, [1] is extension class (function) // the function takes one parameter - the SVGWrapper instance this.regional = []; // Localisations, indexed by language, '' for default (English) this.regional[''] = {errorLoadingText: 'Error loading', notSupportedText: 'This browser does not support SVG'}; this.local = this.regional['']; // Current localisation this._uuid = new Date().getTime(); this._renesis = detectActiveX('RenesisX.RenesisCtrl'); } /* Determine whether a given ActiveX control is available. @param classId (string) the ID for the ActiveX control @return (boolean) true if found, false if not */ function detectActiveX(classId) { try { return !!(window.ActiveXObject && new ActiveXObject(classId)); } catch (e) { return false; } } var PROP_NAME = 'svgwrapper'; $.extend(SVGManager.prototype, { /* Class name added to elements to indicate already configured with SVG. */ markerClassName: 'hasSVG', /* SVG namespace. */ svgNS: 'http://www.w3.org/2000/svg', /* XLink namespace. */ xlinkNS: 'http://www.w3.org/1999/xlink', /* SVG wrapper class. */ _wrapperClass: SVGWrapper, /* Camel-case versions of attribute names containing dashes or are reserved words. */ _attrNames: {class_: 'class', in_: 'in', alignmentBaseline: 'alignment-baseline', baselineShift: 'baseline-shift', clipPath: 'clip-path', clipRule: 'clip-rule', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorRendering: 'color-rendering', dominantBaseline: 'dominant-baseline', enableBackground: 'enable-background', fillOpacity: 'fill-opacity', fillRule: 'fill-rule', floodColor: 'flood-color', floodOpacity: 'flood-opacity', fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', imageRendering: 'image-rendering', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', strokeDashArray: 'stroke-dasharray', strokeDashOffset: 'stroke-dashoffset', strokeLineCap: 'stroke-linecap', strokeLineJoin: 'stroke-linejoin', strokeMiterLimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', vertAdvY: 'vert-adv-y', vertOriginY: 'vert-origin-y', wordSpacing: 'word-spacing', writingMode: 'writing-mode'}, /* Add the SVG object to its container. */ _attachSVG: function(container, settings) { if ($(container).hasClass(this.markerClassName)) { return; } if (typeof settings == 'string') { settings = {loadURL: settings}; } else if (typeof settings == 'function') { settings = {onLoad: settings}; } $(container).addClass(this.markerClassName); try { var svg = document.createElementNS(this.svgNS, 'svg'); svg.setAttribute('version', '1.1'); svg.setAttribute('width', container.clientWidth); svg.setAttribute('height', container.clientHeight); container.appendChild(svg); this._afterLoad(container, svg, settings); } catch (e) { if ($.browser.msie) { if (!container.id) { container.id = 'svg' + (this._uuid++); } this._settings[container.id] = settings; container.innerHTML = '<embed type="image/svg+xml" width="100%"' + 'height="100%" src="' + (settings.initPath || '') + 'blank.svg"/>'; } else { container.innerHTML = '<p class="svg_error">' + this.local.notSupportedText + '</p>'; } } }, /* SVG callback after loading - register SVG root. */ _registerSVG: function() { for (var i = 0; i < document.embeds.length; i++) { // Check all var container = document.embeds[i].parentNode; if (!$(container).hasClass($.svg.markerClassName) || // Not SVG $.data(container, PROP_NAME)) { // Already done continue; } var svg = null; try { svg = document.embeds[i].getSVGDocument(); } catch(e) { setTimeout($.svg._registerSVG, 250); // Renesis takes longer to load return; } svg = (svg ? svg.documentElement : null); if (svg) { $.svg._afterLoad(container, svg); } } }, /* Post-processing once loaded. */ _afterLoad: function(container, svg, settings) { var settings = settings || this._settings[container.id]; this._settings[container.id] = null; var wrapper = new this._wrapperClass(svg, container); $.data(container, PROP_NAME, wrapper); try { if (settings.settings) { // Additional settings wrapper.configure(settings.settings); } if (settings.onLoad && !settings.loadURL) { // Onload callback settings.onLoad.apply(container, [wrapper]); } } catch (e) { alert(e); } }, /* Return the SVG wrapper created for a given container. @param container (string) selector for the container or (element) the container for the SVG object or jQuery collection - first entry is the container @return (SVGWrapper) the corresponding SVG wrapper element, or null if not attached */ _getSVG: function(container) { container = (typeof container == 'string' ? $(container)[0] : (container.jquery ? container[0] : container)); return $.data(container, PROP_NAME); }, /* Remove the SVG functionality from a div. @param container (element) the container for the SVG object */ _destroySVG: function(container) { var $container = $(container); if (!$container.hasClass(this.markerClassName)) { return; } $container.removeClass(this.markerClassName).empty(); $.removeData(container, PROP_NAME); }, /* Extend the SVGWrapper object with an embedded class. The constructor function must take a single parameter that is a reference to the owning SVG root object. This allows the extension to access the basic SVG functionality. @param name (string) the name of the SVGWrapper attribute to access the new class @param extClass (function) the extension class constructor */ addExtension: function(name, extClass) { this._extensions.push([name, extClass]); } }); /* The main SVG interface, which encapsulates the SVG element. Obtain a reference from $().svg('get') */ function SVGWrapper(svg, container) { this._svg = svg; // The SVG root node this._container = container; // The containing div for (var i = 0; i < $.svg._extensions.length; i++) { var extension = $.svg._extensions[i]; this[extension[0]] = new extension[1](this); } } $.extend(SVGWrapper.prototype, { /* Retrieve the width of the SVG object. */ _width: function() { return this._container.clientWidth; }, /* Retrieve the height of the SVG object. */ _height: function() { return this._container.clientHeight; }, /* Retrieve the root SVG element. @return the top-level SVG element */ root: function() { return this._svg; }, /* Configure the SVG root. @param settings (object) additional settings for the root @param clear (boolean) true to remove existing attributes first, false to add to what is already there (optional) @return (SVGWrapper) this root */ configure: function(settings, clear) { if (clear) { for (var i = this._svg.attributes.length - 1; i >= 0; i--) { var attr = this._svg.attributes.item(i); if (!(attr.nodeName == 'onload' || attr.nodeName == 'version' || attr.nodeName.substring(0, 5) == 'xmlns')) { this._svg.attributes.removeNamedItem(attr.nodeName); } } } for (var attrName in settings) { this._svg.setAttribute(attrName, settings[attrName]); } return this; }, /* Locate a specific element in the SVG document. @param id (string) the element's identifier @return (element) the element reference, or null if not found */ getElementById: function(id) { return this._svg.ownerDocument.getElementById(id); }, /* Change the attributes for a SVG node. @param element (SVG element) the node to change @param settings (object) the new settings @return (SVGWrapper) this root */ change: function(element, settings) { if (element) { for (var name in settings) { if (settings[name] == null) { element.removeAttribute(name); } else { element.setAttribute(name, settings[name]); } } } return this; }, /* Check for parent being absent and adjust arguments accordingly. */ _args: function(values, names, optSettings) { names.splice(0, 0, 'parent'); names.splice(names.length, 0, 'settings'); var args = {}; var offset = 0; if (values[0] != null && (typeof values[0] != 'object' || !values[0].nodeName)) { args['parent'] = null; offset = 1; } for (var i = 0; i < values.length; i++) { args[names[i + offset]] = values[i]; } if (optSettings) { $.each(optSettings, function(i, value) { if (typeof args[value] == 'object') { args.settings = args[value]; args[value] = null; } }); } return args; }, /* Add a title. @param parent (element) the parent node for the new title (optional) @param text (string) the text of the title @param settings (object) additional settings for the title (optional) @return (element) the new title node */ title: function(parent, text, settings) { var args = this._args(arguments, ['text']); var node = this._makeNode(args.parent, 'title', args.settings || {}); node.appendChild(this._svg.ownerDocument.createTextNode(args.text)); return node; }, /* Add a description. @param parent (element) the parent node for the new description (optional) @param text (string) the text of the description @param settings (object) additional settings for the description (optional) @return (element) the new description node */ describe: function(parent, text, settings) { var args = this._args(arguments, ['text']); var node = this._makeNode(args.parent, 'desc', args.settings || {}); node.appendChild(this._svg.ownerDocument.createTextNode(args.text)); return node; }, /* Add a definitions node. @param parent (element) the parent node for the new definitions (optional) @param id (string) the ID of this definitions (optional) @param settings (object) additional settings for the definitions (optional) @return (element) the new definitions node */ defs: function(parent, id, settings) { var args = this._args(arguments, ['id'], ['id']); return this._makeNode(args.parent, 'defs', $.extend( (args.id ? {id: args.id} : {}), args.settings || {})); }, /* Add a symbol definition. @param parent (element) the parent node for the new symbol (optional) @param id (string) the ID of this symbol @param x1 (number) the left coordinate for this symbol @param y1 (number) the top coordinate for this symbol @param x2 (number) the right coordinate for this symbol @param y2 (number) the bottom coordinate for this symbol @param settings (object) additional settings for the symbol (optional) @return (element) the new symbol node */ symbol: function(parent, id, x1, y1, x2, y2, settings) { var args = this._args(arguments, ['id', 'x1', 'y1', 'x2', 'y2']); return this._makeNode(args.parent, 'symbol', $.extend( {id: args.id, viewBox: args.x1 + ' ' + args.y1 + ' ' + args.x2 + ' ' + args.y2}, args.settings || {})); }, /* Add a marker definition. @param parent (element) the parent node for the new marker (optional) @param id (string) the ID of this marker @param refX (number) the x-coordinate for the reference point @param refY (number) the y-coordinate for the reference point @param mWidth (number) the marker viewport width @param mHeight (number) the marker viewport height @param orient (string or int) 'auto' or angle (degrees) (optional) @param settings (object) additional settings for the marker (optional) @return (element) the new marker node */ marker: function(parent, id, refX, refY, mWidth, mHeight, orient, settings) { var args = this._args(arguments, ['id', 'refX', 'refY', 'mWidth', 'mHeight', 'orient'], ['orient']); return this._makeNode(args.parent, 'marker', $.extend( {id: args.id, refX: args.refX, refY: args.refY, markerWidth: args.mWidth, markerHeight: args.mHeight, orient: args.orient || 'auto'}, args.settings || {})); }, /* Add a style node. @param parent (element) the parent node for the new node (optional) @param styles (string) the CSS styles @param settings (object) additional settings for the node (optional) @return (element) the new style node */ style: function(parent, styles, settings) { var args = this._args(arguments, ['styles']); var node = this._makeNode(args.parent, 'style', $.extend( {type: 'text/css'}, args.settings || {})); node.appendChild(this._svg.ownerDocument.createTextNode(args.styles)); if ($.browser.opera) { $('head').append('<style type="text/css">' + args.styles + '</style>'); } return node; }, /* Add a script node. @param parent (element) the parent node for the new node (optional) @param script (string) the JavaScript code @param type (string) the MIME type for the code (optional, default 'text/javascript') @param settings (object) additional settings for the node (optional) @return (element) the new script node */ script: function(parent, script, type, settings) { var args = this._args(arguments, ['script', 'type'], ['type']); var node = this._makeNode(args.parent, 'script', $.extend( {type: args.type || 'text/javascript'}, args.settings || {})); node.appendChild(this._svg.ownerDocument.createTextNode(this._escapeXML(args.script))); if (!$.browser.mozilla) { $.globalEval(args.script); } return node; }, /* Add a linear gradient definition. Specify all of x1, y1, x2, y2 or none of them. @param parent (element) the parent node for the new gradient (optional) @param id (string) the ID for this gradient @param stops (string[][]) the gradient stops, each entry is [0] is offset (0.0-1.0 or 0%-100%), [1] is colour, [2] is opacity (optional) @param x1 (number) the x-coordinate of the gradient start (optional) @param y1 (number) the y-coordinate of the gradient start (optional) @param x2 (number) the x-coordinate of the gradient end (optional) @param y2 (number) the y-coordinate of the gradient end (optional) @param settings (object) additional settings for the gradient (optional) @return (element) the new gradient node */ linearGradient: function(parent, id, stops, x1, y1, x2, y2, settings) { var args = this._args(arguments, ['id', 'stops', 'x1', 'y1', 'x2', 'y2'], ['x1']); var sets = $.extend({id: args.id}, (args.x1 != null ? {x1: args.x1, y1: args.y1, x2: args.x2, y2: args.y2} : {})); return this._gradient(args.parent, 'linearGradient', $.extend(sets, args.settings || {}), args.stops); }, /* Add a radial gradient definition. Specify all of cx, cy, r, fx, fy or none of them. @param parent (element) the parent node for the new gradient (optional) @param id (string) the ID for this gradient @param stops (string[][]) the gradient stops, each entry [0] is offset, [1] is colour, [2] is opacity (optional) @param cx (number) the x-coordinate of the largest circle centre (optional) @param cy (number) the y-coordinate of the largest circle centre (optional) @param r (number) the radius of the largest circle (optional) @param fx (number) the x-coordinate of the gradient focus (optional) @param fy (number) the y-coordinate of the gradient focus (optional) @param settings (object) additional settings for the gradient (optional) @return (element) the new gradient node */ radialGradient: function(parent, id, stops, cx, cy, r, fx, fy, settings) { var args = this._args(arguments, ['id', 'stops', 'cx', 'cy', 'r', 'fx', 'fy'], ['cx']); var sets = $.extend({id: args.id}, (args.cx != null ? {cx: args.cx, cy: args.cy, r: args.r, fx: args.fx, fy: args.fy} : {})); return this._gradient(args.parent, 'radialGradient', $.extend(sets, args.settings || {}), args.stops); }, /* Add a gradient node. */ _gradient: function(parent, name, settings, stops) { var node = this._makeNode(parent, name, settings); for (var i = 0; i < stops.length; i++) { var stop = stops[i]; this._makeNode(node, 'stop', $.extend( {offset: stop[0], stopColor: stop[1]}, (stop[2] != null ? {stopOpacity: stop[2]} : {}))); } return node; }, /* Add a pattern definition. Specify all of vx, vy, xwidth, vheight or none of them. @param parent (element) the parent node for the new pattern (optional) @param id (string) the ID for this pattern @param x (number) the x-coordinate for the left edge of the pattern @param y (number) the y-coordinate for the top edge of the pattern @param width (number) the width of the pattern @param height (number) the height of the pattern @param vx (number) the minimum x-coordinate for view box (optional) @param vy (number) the minimum y-coordinate for the view box (optional) @param vwidth (number) the width of the view box (optional) @param vheight (number) the height of the view box (optional) @param settings (object) additional settings for the pattern (optional) @return (element) the new pattern node */ pattern: function(parent, id, x, y, width, height, vx, vy, vwidth, vheight, settings) { var args = this._args(arguments, ['id', 'x', 'y', 'width', 'height', 'vx', 'vy', 'vwidth', 'vheight'], ['vx']); var sets = $.extend({id: args.id, x: args.x, y: args.y, width: args.width, height: args.height}, (args.vx != null ? {viewBox: args.vx + ' ' + args.vy + ' ' + args.vwidth + ' ' + args.vheight} : {})); return this._makeNode(args.parent, 'pattern', $.extend(sets, args.settings || {})); }, /* Add a mask definition. @param parent (element) the parent node for the new mask (optional) @param id (string) the ID for this mask @param x (number) the x-coordinate for the left edge of the mask @param y (number) the y-coordinate for the top edge of the mask @param width (number) the width of the mask @param height (number) the height of the mask @param settings (object) additional settings for the mask (optional) @return (element) the new mask node */ mask: function(parent, id, x, y, width, height, settings) { var args = this._args(arguments, ['id', 'x', 'y', 'width', 'height']); return this._makeNode(args.parent, 'mask', $.extend( {id: args.id, x: args.x, y: args.y, width: args.width, height: args.height}, args.settings || {})); }, /* Create a new path object. @return (SVGPath) a new path object */ createPath: function() { return new SVGPath(); }, /* Create a new text object. @return (SVGText) a new text object */ createText: function() { return new SVGText(); }, /* Add an embedded SVG element. Specify all of vx, vy, vwidth, vheight or none of them. @param parent (element) the parent node for the new node (optional) @param x (number) the x-coordinate for the left edge of the node @param y (number) the y-coordinate for the top edge of the node @param width (number) the width of the node @param height (number) the height of the node @param vx (number) the minimum x-coordinate for view box (optional) @param vy (number) the minimum y-coordinate for the view box (optional) @param vwidth (number) the width of the view box (optional) @param vheight (number) the height of the view box (optional) @param settings (object) additional settings for the node (optional) @return (element) the new node */ svg: function(parent, x, y, width, height, vx, vy, vwidth, vheight, settings) { var args = this._args(arguments, ['x', 'y', 'width', 'height', 'vx', 'vy', 'vwidth', 'vheight'], ['vx']); var sets = $.extend({x: args.x, y: args.y, width: args.width, height: args.height}, (args.vx != null ? {viewBox: args.vx + ' ' + args.vy + ' ' + args.vwidth + ' ' + args.vheight} : {})); return this._makeNode(args.parent, 'svg', $.extend(sets, args.settings || {})); }, /* Create a group. @param parent (element) the parent node for the new group (optional) @param id (string) the ID of this group (optional) @param settings (object) additional settings for the group (optional) @return (element) the new group node */ group: function(parent, id, settings) { var args = this._args(arguments, ['id'], ['id']); return this._makeNode(args.parent, 'g', $.extend({id: args.id}, args.settings || {})); }, /* Add a usage reference. Specify all of x, y, width, height or none of them. @param parent (element) the parent node for the new node (optional) @param x (number) the x-coordinate for the left edge of the node (optional) @param y (number) the y-coordinate for the top edge of the node (optional) @param width (number) the width of the node (optional) @param height (number) the height of the node (optional) @param ref (string) the ID of the definition node @param settings (object) additional settings for the node (optional) @return (element) the new node */ use: function(parent, x, y, width, height, ref, settings) { var args = this._args(arguments, ['x', 'y', 'width', 'height', 'ref']); if (typeof args.x == 'string') { args.ref = args.x; args.settings = args.y; args.x = args.y = args.width = args.height = null; } var node = this._makeNode(args.parent, 'use', $.extend( {x: args.x, y: args.y, width: args.width, height: args.height}, args.settings || {})); node.setAttributeNS($.svg.xlinkNS, 'href', args.ref); return node; }, /* Add a link, which applies to all child elements. @param parent (element) the parent node for the new link (optional) @param ref (string) the target URL @param settings (object) additional settings for the link (optional) @return (element) the new link node */ link: function(parent, ref, settings) { var args = this._args(arguments, ['ref']); var node = this._makeNode(args.parent, 'a', args.settings); node.setAttributeNS($.svg.xlinkNS, 'href', args.ref); return node; }, /* Add an image. @param parent (element) the parent node for the new image (optional) @param x (number) the x-coordinate for the left edge of the image @param y (number) the y-coordinate for the top edge of the image @param width (number) the width of the image @param height (number) the height of the image @param ref (string) the path to the image @param settings (object) additional settings for the image (optional) @return (element) the new image node */ image: function(parent, x, y, width, height, ref, settings) { var args = this._args(arguments, ['x', 'y', 'width', 'height', 'ref']); var node = this._makeNode(args.parent, 'image', $.extend( {x: args.x, y: args.y, width: args.width, height: args.height}, args.settings || {})); node.setAttributeNS($.svg.xlinkNS, 'href', args.ref); return node; }, /* Draw a path. @param parent (element) the parent node for the new shape (optional) @param path (string or SVGPath) the path to draw @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ path: function(parent, path, settings) { var args = this._args(arguments, ['path']); return this._makeNode(args.parent, 'path', $.extend( {d: (args.path.path ? args.path.path() : args.path)}, args.settings || {})); }, /* Draw a rectangle. Specify both of rx and ry or neither. @param parent (element) the parent node for the new shape (optional) @param x (number) the x-coordinate for the left edge of the rectangle @param y (number) the y-coordinate for the top edge of the rectangle @param width (number) the width of the rectangle @param height (number) the height of the rectangle @param rx (number) the x-radius of the ellipse for the rounded corners (optional) @param ry (number) the y-radius of the ellipse for the rounded corners (optional) @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ rect: function(parent, x, y, width, height, rx, ry, settings) { var args = this._args(arguments, ['x', 'y', 'width', 'height', 'rx', 'ry'], ['rx']); return this._makeNode(args.parent, 'rect', $.extend( {x: args.x, y: args.y, width: args.width, height: args.height}, (args.rx ? {rx: args.rx, ry: args.ry} : {}), args.settings || {})); }, /* Draw a circle. @param parent (element) the parent node for the new shape (optional) @param cx (number) the x-coordinate for the centre of the circle @param cy (number) the y-coordinate for the centre of the circle @param r (number) the radius of the circle @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ circle: function(parent, cx, cy, r, settings) { var args = this._args(arguments, ['cx', 'cy', 'r']); return this._makeNode(args.parent, 'circle', $.extend( {cx: args.cx, cy: args.cy, r: args.r}, args.settings || {})); }, /* Draw an ellipse. @param parent (element) the parent node for the new shape (optional) @param cx (number) the x-coordinate for the centre of the ellipse @param cy (number) the y-coordinate for the centre of the ellipse @param rx (number) the x-radius of the ellipse @param ry (number) the y-radius of the ellipse @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ ellipse: function(parent, cx, cy, rx, ry, settings) { var args = this._args(arguments, ['cx', 'cy', 'rx', 'ry']); return this._makeNode(args.parent, 'ellipse', $.extend( {cx: args.cx, cy: args.cy, rx: args.rx, ry: args.ry}, args.settings || {})); }, /* Draw a line. @param parent (element) the parent node for the new shape (optional) @param x1 (number) the x-coordinate for the start of the line @param y1 (number) the y-coordinate for the start of the line @param x2 (number) the x-coordinate for the end of the line @param y2 (number) the y-coordinate for the end of the line @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ line: function(parent, x1, y1, x2, y2, settings) { var args = this._args(arguments, ['x1', 'y1', 'x2', 'y2']); return this._makeNode(args.parent, 'line', $.extend( {x1: args.x1, y1: args.y1, x2: args.x2, y2: args.y2}, args.settings || {})); }, /* Draw a polygonal line. @param parent (element) the parent node for the new shape (optional) @param points (number[][]) the x-/y-coordinates for the points on the line @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ polyline: function(parent, points, settings) { var args = this._args(arguments, ['points']); return this._poly(args.parent, 'polyline', args.points, args.settings); }, /* Draw a polygonal shape. @param parent (element) the parent node for the new shape (optional) @param points (number[][]) the x-/y-coordinates for the points on the shape @param settings (object) additional settings for the shape (optional) @return (element) the new shape node */ polygon: function(parent, points, settings) { var args = this._args(arguments, ['points']); return this._poly(args.parent, 'polygon', args.points, args.settings); }, /* Draw a polygonal line or shape. */ _poly: function(parent, name, points, settings) { var ps = ''; for (var i = 0; i < points.length; i++) { ps += points[i].join() + ' '; } return this._makeNode(parent, name, $.extend( {points: $.trim(ps)}, settings || {})); }, /* Draw text. Specify both of x and y or neither of them. @param parent (element) the parent node for the text (optional) @param x (number or number[]) the x-coordinate(s) for the text (optional) @param y (number or number[]) the y-coordinate(s) for the text (optional) @param value (string) the text content or (SVGText) text with spans and references @param settings (object) additional settings for the text (optional) @return (element) the new text node */ text: function(parent, x, y, value, settings) { var args = this._args(arguments, ['x', 'y', 'value']); if (typeof args.x == 'string' && arguments.length < 4) { args.value = args.x; args.settings = args.y; args.x = args.y = null; } return this._text(args.parent, 'text', args.value, $.extend( {x: (args.x && isArray(args.x) ? args.x.join(' ') : args.x), y: (args.y && isArray(args.y) ? args.y.join(' ') : args.y)}, args.settings || {})); }, /* Draw text along a path. @param parent (element) the parent node for the text (optional) @param path (string) the ID of the path @param value (string) the text content or (SVGText) text with spans and references @param settings (object) additional settings for the text (optional) @return (element) the new text node */ textpath: function(parent, path, value, settings) { var args = this._args(arguments, ['path', 'value']); var node = this._text(args.parent, 'textPath', args.value, args.settings || {}); node.setAttributeNS($.svg.xlinkNS, 'href', args.path); return node; }, /* Draw text. */ _text: function(parent, name, value, settings) { var node = this._makeNode(parent, name, settings); if (typeof value == 'string') { node.appendChild(node.ownerDocument.createTextNode(value)); } else { for (var i = 0; i < value._parts.length; i++) { var part = value._parts[i]; if (part[0] == 'tspan') { var child = this._makeNode(node, part[0], part[2]); child.appendChild(node.ownerDocument.createTextNode(part[1])); node.appendChild(child); } else if (part[0] == 'tref') { var child = this._makeNode(node, part[0], part[2]); child.setAttributeNS($.svg.xlinkNS, 'href', part[1]); node.appendChild(child); } else if (part[0] == 'textpath') { var set = $.extend({}, part[2]); set.href = null; var child = this._makeNode(node, part[0], set); child.setAttributeNS($.svg.xlinkNS, 'href', part[2].href); child.appendChild(node.ownerDocument.createTextNode(part[1])); node.appendChild(child); } else { // straight text node.appendChild(node.ownerDocument.createTextNode(part[1])); } } } return node; }, /* Add a custom SVG element. @param parent (element) the parent node for the new element (optional) @param name (string) the name of the element @param settings (object) additional settings for the element (optional) @return (element) the new title node */ other: function(parent, name, settings) { var args = this._args(arguments, ['name']); return this._makeNode(args.parent, args.name, args.settings || {}); }, /* Create a shape node with the given settings. */ _makeNode: function(parent, name, settings) { parent = parent || this._svg; var node = this._svg.ownerDocument.createElementNS($.svg.svgNS, name); for (var name in settings) { var value = settings[name]; if (value != null && value != null && (typeof value != 'string' || value != '')) { node.setAttribute($.svg._attrNames[name] || name, value); } } parent.appendChild(node); return node; }, /* Add an existing SVG node to the diagram. @param parent (element) the parent node for the new node (optional) @param node (element) the new node to add or (string) the jQuery selector for the node or (jQuery collection) set of nodes to add @return (SVGWrapper) this wrapper */ add: function(parent, node) { var args = this._args(arguments, ['node']); var svg = this; args.parent = args.parent || this._svg; try { if ($.svg._renesis) { throw 'Force traversal'; } args.parent.appendChild(args.node.cloneNode(true)); } catch (e) { args.node = (args.node.jquery ? args.node : $(args.node)); args.node.each(function() { var child = svg._cloneAsSVG(this); if (child) { args.parent.appendChild(child); } }); } return this; }, /* SVG nodes must belong to the SVG namespace, so clone and ensure this is so. */ _cloneAsSVG: function(node) { var newNode = null; if (node.nodeType == 1) { // element newNode = this._svg.ownerDocument.createElementNS( $.svg.svgNS, this._checkName(node.nodeName)); for (var i = 0; i < node.attributes.length; i++) { var attr = node.attributes.item(i); if (attr.nodeName != 'xmlns' && attr.nodeValue) { if (attr.prefix == 'xlink') { newNode.setAttributeNS($.svg.xlinkNS, attr.localName, attr.nodeValue); } else { newNode.setAttribute(this._checkName(attr.nodeName), attr.nodeValue); } } } for (var i = 0; i < node.childNodes.length; i++) { var child = this._cloneAsSVG(node.childNodes[i]); if (child) { newNode.appendChild(child); } } } else if (node.nodeType == 3) { // text if ($.trim(node.nodeValue)) { newNode = this._svg.ownerDocument.createTextNode(node.nodeValue); } } else if (node.nodeType == 4) { // CDATA if ($.trim(node.nodeValue)) { try { newNode = this._svg.ownerDocument.createCDATASection(node.nodeValue); } catch (e) { newNode = this._svg.ownerDocument.createTextNode( node.nodeValue.replace(/&/g, '&amp;'). replace(/</g, '&lt;').replace(/>/g, '&gt;')); } } } return newNode; }, /* Node names must be lower case and without SVG namespace prefix. */ _checkName: function(name) { name = (name.substring(0, 1) >= 'A' && name.substring(0, 1) <= 'Z' ? name.toLowerCase() : name); return (name.substring(0, 4) == 'svg:' ? name.substring(4) : name); }, /* Load an external SVG document. @param url (string) the location of the SVG document or the actual SVG content @param settings (boolean) see addTo below or (function) see onLoad below or (object) additional settings for the load with attributes below: addTo (boolean) true to add to what's already there, or false to clear the canvas first changeSize (boolean) true to allow the canvas size to change, or false to retain the original onLoad (function) callback after the document has loaded, 'this' is the container, receives SVG object and optional error message as a parameter @return (SVGWrapper) this root */ load: function(url, settings) { settings = (typeof settings == 'boolean'? {addTo: settings} : (typeof settings == 'function'? {onLoad: settings} : settings || {})); if (!settings.addTo) { this.clear(false); } var size = [this._svg.getAttribute('width'), this._svg.getAttribute('height')]; var wrapper = this; // Report a problem with the load var reportError = function(message) { message = $.svg.local.errorLoadingText + ': ' + message; if (settings.onLoad) { settings.onLoad.apply(wrapper._container, [wrapper, message]); } else { wrapper.text(null, 10, 20, message); } }; // Create a DOM from SVG content var loadXML4IE = function(data) { var xml = new ActiveXObject('Microsoft.XMLDOM'); xml.validateOnParse = false; xml.resolveExternals = false; xml.async = false; xml.loadXML(data); if (xml.parseError.errorCode != 0) { reportError(xml.parseError.reason); return null; } return xml; }; // Load the SVG DOM var loadSVG = function(data) { if (!data) { return; } if (data.documentElement.nodeName != 'svg') { var errors = data.getElementsByTagName('parsererror'); var messages = (errors.length ? errors[0].getElementsByTagName('div') : []); // Safari reportError(!errors.length ? '???' : (messages.length ? messages[0] : errors[0]).firstChild.nodeValue); return; } var attrs = {}; for (var i = 0; i < data.documentElement.attributes.length; i++) { var attr = data.documentElement.attributes.item(i); if (!(attr.nodeName == 'version' || attr.nodeName.substring(0, 5) == 'xmlns')) { attrs[attr.nodeName] = attr.nodeValue; } } wrapper.configure(attrs, true); var nodes = data.documentElement.childNodes; for (var i = 0; i < nodes.length; i++) { try { if ($.svg._renesis) { throw 'Force traversal'; } wrapper._svg.appendChild(nodes[i].cloneNode(true)); } catch (e) { wrapper.add(null, nodes[i]); } } if (!settings.changeSize) { wrapper.configure({width: size[0], height: size[1]}); } if (settings.onLoad) { settings.onLoad.apply(wrapper._container, [wrapper]); } }; if (url.match('<svg')) { // Inline SVG loadSVG($.browser.msie ? loadXML4IE(url) : new DOMParser().parseFromString(url, 'text/xml')); } else { // Remote SVG $.ajax({url: url, dataType: ($.browser.msie ? 'text' : 'xml'), success: function(xml) { loadSVG($.browser.msie ? loadXML4IE(xml) : xml); }, error: function(http, message, exc) { reportError(message + (exc ? ' ' + exc.message : '')); }}); } return this; }, loadMapToElement: function(parent ,url, settings) { settings = (typeof settings == 'boolean'? {addTo: settings} : (typeof settings == 'function'? {onLoad: settings} : settings || {})); if (!settings.addTo) { this.clear(false); } var size = [this._svg.getAttribute('width'), this._svg.getAttribute('height')]; var wrapper = this; // Report a problem with the load var reportError = function(message) { message = $.svg.local.errorLoadingText + ': ' + message; if (settings.onLoad) { settings.onLoad.apply(wrapper._container, [wrapper, message]); } else { wrapper.text(null, 10, 20, message); } }; // Create a DOM from SVG content var loadXML4IE = function(data) { var xml = new ActiveXObject('Microsoft.XMLDOM'); xml.validateOnParse = false; xml.resolveExternals = false; xml.async = false; xml.loadXML(data); if (xml.parseError.errorCode != 0) { reportError(xml.parseError.reason); return null; } return xml; }; // Load the SVG DOM var loadSVG = function(data) { if (!data) { return; } if (data.documentElement.nodeName != 'svg') { var errors = data.getElementsByTagName('parsererror'); var messages = (errors.length ? errors[0].getElementsByTagName('div') : []); // Safari reportError(!errors.length ? '???' : (messages.length ? messages[0] : errors[0]).firstChild.nodeValue); return; } var attrs = {}; for (var i = 0; i < data.documentElement.attributes.length; i++) { var attr = data.documentElement.attributes.item(i); if (!(attr.nodeName == 'version' || attr.nodeName.substring(0, 5) == 'xmlns')) { attrs[attr.nodeName] = attr.nodeValue; } } wrapper.change(parent, attrs); var nodes = data.documentElement.childNodes; for (var i = 0; i < nodes.length; i++) { try { if ($.svg._renesis) { //判断是否是IE throw 'Force traversal'; } //firefox下添加子节点 parent.appendChild(nodes[i].cloneNode(true)); } catch (e) { //IE下添加到子节点 wrapper.add(parent, nodes[i]); } } if (!settings.changeSize) { wrapper.configure({width: size[0], height: size[1]}); } if (settings.onLoad) { settings.onLoad.apply(wrapper._container, [wrapper]); } }; if (url.match('<svg')) { // Inline SVG loadSVG($.browser.msie ? loadXML4IE(url) : new DOMParser().parseFromString(url, 'text/xml')); } else { // Remote SVG $.ajax({url: url, dataType: ($.browser.msie ? 'text' : 'xml'), success: function(xml) { loadSVG($.browser.msie ? loadXML4IE(xml) : xml); }, error: function(http, message, exc) { reportError(message + (exc ? ' ' + exc.message : '')); }}); } return this; }, /* Delete a specified node. @param node (element) the drawing node to remove @return (SVGWrapper) this root */ remove: function(node) { node.parentNode.removeChild(node); return this; }, /* Delete everything in the current document. @param attrsToo (boolean) true to clear any root attributes as well, false to leave them (optional) @return (SVGWrapper) this root */ clear: function(attrsToo) { if (attrsToo) { this.configure({}, true); } while (this._svg.firstChild) { this._svg.removeChild(this._svg.firstChild); } return this; }, /* Serialise the current diagram into an SVG text document. @param node (SVG element) the starting node (optional) @return (string) the SVG as text */ toSVG: function(node) { node = node || this._svg; return (typeof XMLSerializer == 'undefined' ? this._toSVG(node) : new XMLSerializer().serializeToString(node)); }, /* Serialise one node in the SVG hierarchy. */ _toSVG: function(node) { var svgDoc = ''; if (!node) { return svgDoc; } if (node.nodeType == 3) { // Text svgDoc = node.nodeValue; } else if (node.nodeType == 4) { // CDATA svgDoc = '<![CDATA[' + node.nodeValue + ']]>'; } else { // Element svgDoc = '<' + node.nodeName; if (node.attributes) { //对node.attributes.length进行了缓存,提高js速度 for (var i = 0, attrlength = node.attributes.length; i < attrlength; i++) { var attr = node.attributes.item(i); if (!($.trim(attr.nodeValue) == '' || attr.nodeValue.match(/^\[object/) || attr.nodeValue.match(/^function/))) { svgDoc += ' ' + (attr.namespaceURI == $.svg.xlinkNS ? 'xlink:' : '') + attr.nodeName + '="' + attr.nodeValue + '"'; } } } if (node.firstChild) { svgDoc += '>'; var child = node.firstChild; while (child) { svgDoc += this._toSVG(child); child = child.nextSibling; } svgDoc += '</' + node.nodeName + '>'; } else { svgDoc += '/>'; } } return svgDoc; }, /* Escape reserved characters in XML. */ _escapeXML: function(text) { text = text.replace(/&/g, '&amp;'); text = text.replace(/</g, '&lt;'); text = text.replace(/>/g, '&gt;'); return text; } }); /* Helper to generate an SVG path. Obtain an instance from the SVGWrapper object. String calls together to generate the path and use its value: var path = root.createPath(); root.path(null, path.move(100, 100).line(300, 100).line(200, 300).close(), {fill: 'red'}); or root.path(null, path.move(100, 100).line([[300, 100], [200, 300]]).close(), {fill: 'red'}); */ function SVGPath() { this._path = ''; } $.extend(SVGPath.prototype, { /* Prepare to create a new path. @return (SVGPath) this path */ reset: function() { this._path = ''; return this; }, /* Move the pointer to a position. @param x (number) x-coordinate to move to or (number[][]) x-/y-coordinates to move to @param y (number) y-coordinate to move to (omitted if x is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ move: function(x, y, relative) { relative = (isArray(x) ? y : relative); return this._coords((relative ? 'm' : 'M'), x, y); }, /* Draw a line to a position. @param x (number) x-coordinate to move to or (number[][]) x-/y-coordinates to move to @param y (number) y-coordinate to move to (omitted if x is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ line: function(x, y, relative) { relative = (isArray(x) ? y : relative); return this._coords((relative ? 'l' : 'L'), x, y); }, /* Draw a horizontal line to a position. @param x (number) x-coordinate to draw to or (number[]) x-coordinates to draw to @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ horiz: function(x, relative) { this._path += (relative ? 'h' : 'H') + (isArray(x) ? x.join(' ') : x); return this; }, /* Draw a vertical line to a position.f @param y (number) y-coordinate to draw to or (number[]) y-coordinates to draw to @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ vert: function(y, relative) { this._path += (relative ? 'v' : 'V') + (isArray(y) ? y.join(' ') : y); return this; }, /* Draw a cubic B閦ier curve. @param x1 (number) x-coordinate of beginning control point or (number[][]) x-/y-coordinates of control and end points to draw to @param y1 (number) y-coordinate of beginning control point (omitted if x1 is array) @param x2 (number) x-coordinate of ending control point (omitted if x1 is array) @param y2 (number) y-coordinate of ending control point (omitted if x1 is array) @param x (number) x-coordinate of curve end (omitted if x1 is array) @param y (number) y-coordinate of curve end (omitted if x1 is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ curveC: function(x1, y1, x2, y2, x, y, relative) { relative = (isArray(x1) ? y1 : relative); return this._coords((relative ? 'c' : 'C'), x1, y1, x2, y2, x, y); }, /* Continue a cubic B閦ier curve. Starting control point is the reflection of the previous end control point. @param x2 (number) x-coordinate of ending control point or (number[][]) x-/y-coordinates of control and end points to draw to @param y2 (number) y-coordinate of ending control point (omitted if x2 is array) @param x (number) x-coordinate of curve end (omitted if x2 is array) @param y (number) y-coordinate of curve end (omitted if x2 is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ smoothC: function(x2, y2, x, y, relative) { relative = (isArray(x2) ? y2 : relative); return this._coords((relative ? 's' : 'S'), x2, y2, x, y); }, /* Draw a quadratic B閦ier curve. @param x1 (number) x-coordinate of control point or (number[][]) x-/y-coordinates of control and end points to draw to @param y1 (number) y-coordinate of control point (omitted if x1 is array) @param x (number) x-coordinate of curve end (omitted if x1 is array) @param y (number) y-coordinate of curve end (omitted if x1 is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ curveQ: function(x1, y1, x, y, relative) { relative = (isArray(x1) ? y1 : relative); return this._coords((relative ? 'q' : 'Q'), x1, y1, x, y); }, /* Continue a quadratic B閦ier curve. Control point is the reflection of the previous control point. @param x (number) x-coordinate of curve end or (number[][]) x-/y-coordinates of points to draw to @param y (number) y-coordinate of curve end (omitted if x is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ smoothQ: function(x, y, relative) { relative = (isArray(x) ? y : relative); return this._coords((relative ? 't' : 'T'), x, y); }, /* Generate a path command with (a list of) coordinates. */ _coords: function(cmd, x1, y1, x2, y2, x3, y3) { if (isArray(x1)) { for (var i = 0; i < x1.length; i++) { var cs = x1[i]; this._path += (i == 0 ? cmd : ' ') + cs[0] + ',' + cs[1] + (cs.length < 4 ? '' : ' ' + cs[2] + ',' + cs[3] + (cs.length < 6 ? '': ' ' + cs[4] + ',' + cs[5])); } } else { this._path += cmd + x1 + ',' + y1 + (x2 == null ? '' : ' ' + x2 + ',' + y2 + (x3 == null ? '' : ' ' + x3 + ',' + y3)); } return this; }, /* Draw an arc to a position. @param rx (number) x-radius of arc or (number/boolean[][]) x-/y-coordinates and flags for points to draw to @param ry (number) y-radius of arc (omitted if rx is array) @param xRotate (number) x-axis rotation (degrees, clockwise) (omitted if rx is array) @param large (boolean) true to draw the large part of the arc, false to draw the small part (omitted if rx is array) @param clockwise (boolean) true to draw the clockwise arc, false to draw the anti-clockwise arc (omitted if rx is array) @param x (number) x-coordinate of arc end (omitted if rx is array) @param y (number) y-coordinate of arc end (omitted if rx is array) @param relative (boolean) true for coordinates relative to the current point, false for coordinates being absolute @return (SVGPath) this path */ arc: function(rx, ry, xRotate, large, clockwise, x, y, relative) { relative = (isArray(rx) ? ry : relative); this._path += (relative ? 'a' : 'A'); if (isArray(rx)) { for (var i = 0; i < rx.length; i++) { var cs = rx[i]; this._path += (i == 0 ? '' : ' ') + cs[0] + ',' + cs[1] + ' ' + cs[2] + ' ' + (cs[3] ? '1' : '0') + ',' + (cs[4] ? '1' : '0') + ' ' + cs[5] + ',' + cs[6]; } } else { this._path += rx + ',' + ry + ' ' + xRotate + ' ' + (large ? '1' : '0') + ',' + (clockwise ? '1' : '0') + ' ' + x + ',' + y; } return this; }, /* Close the current path. @return (SVGPath) this path */ close: function() { this._path += 'z'; return this; }, /* Return the string rendering of the specified path. @return (string) stringified path */ path: function() { return this._path; } }); SVGPath.prototype.moveTo = SVGPath.prototype.move; SVGPath.prototype.lineTo = SVGPath.prototype.line; SVGPath.prototype.horizTo = SVGPath.prototype.horiz; SVGPath.prototype.vertTo = SVGPath.prototype.vert; SVGPath.prototype.curveCTo = SVGPath.prototype.curveC; SVGPath.prototype.smoothCTo = SVGPath.prototype.smoothC; SVGPath.prototype.curveQTo = SVGPath.prototype.curveQ; SVGPath.prototype.smoothQTo = SVGPath.prototype.smoothQ; SVGPath.prototype.arcTo = SVGPath.prototype.arc; /* Helper to generate an SVG text object. Obtain an instance from the SVGWrapper object. String calls together to generate the text and use its value: var text = root.createText(); root.text(null, x, y, text.string('This is '). span('red', {fill: 'red'}).string('!'), {fill: 'blue'}); */ function SVGText() { this._parts = []; // The components of the text object } $.extend(SVGText.prototype, { /* Prepare to create a new text object. @return (SVGText) this text */ reset: function() { this._parts = []; return this; }, /* Add a straight string value. @param value (string) the actual text @return (SVGText) this text object */ string: function(value) { this._parts[this._parts.length] = ['text', value]; return this; }, /* Add a separate text span that has its own settings. @param value (string) the actual text @param settings (object) the settings for this text @return (SVGText) this text object */ span: function(value, settings) { this._parts[this._parts.length] = ['tspan', value, settings]; return this; }, /* Add a reference to a previously defined text string. @param id (string) the ID of the actual text @param settings (object) the settings for this text @return (SVGText) this text object */ ref: function(id, settings) { this._parts[this._parts.length] = ['tref', id, settings]; return this; }, /* Add text drawn along a path. @param id (string) the ID of the path @param value (string) the actual text @param settings (object) the settings for this text @return (SVGText) this text object */ path: function(id, value, settings) { this._parts[this._parts.length] = ['textpath', value, $.extend({href: id}, settings || {})]; return this; } }); /* Attach the SVG functionality to a jQuery selection. @param command (string) the command to run (optional, default 'attach') @param options (object) the new settings to use for these SVG instances @return jQuery (object) for chaining further calls */ $.fn.svg = function(options) { var otherArgs = Array.prototype.slice.call(arguments, 1); if (typeof options == 'string' && options == 'get') { // alert("otherArgs:"+otherArgs.toString()); return $.svg['_' + options + 'SVG'].apply($.svg, [this[0]].concat(otherArgs)); } return this.each(function() { if (typeof options == 'string') { $.svg['_' + options + 'SVG'].apply($.svg, [this].concat(otherArgs)); } else { $.svg._attachSVG(this, options || {}); } }); }; /* Determine whether an object is an array. */ function isArray(a) { return (a && a.constructor == Array); } // Singleton primary SVG interface $.svg = new SVGManager(); })(jQuery);
'use strict'; var _map = require('lodash/map'); var _filter = require('lodash/filter'); var _bind = require('lodash/bind'); var _each = require('lodash/each'); var _difference = require('lodash/difference'); var _findIndex = require('lodash/findIndex'); var _isUndefined = require('lodash/isUndefined'); var _find = require('lodash/find'); var _first = require('lodash/first'); var _clone = require('lodash/clone'); var upgradesImport = require('../upgrades'); var keyedUpgrades = upgradesImport.keyed; var pilots = require('../pilots'); var uniquePilots = pilots.unique; var events = require('../../controllers/events'); var arrayUtils = require('../../utils/array-utils'); var upgradesModel = function (build, upgradeIdList, equippedIdList, pilotIds, equippedAbilityIds) { this.build = build; // Upgrades in order of purchase this.purchased = this.upgradesFromIds(upgradeIdList); this.purchasedAbilities = this.abilitiesFromIds(pilotIds); this.equippedUpgrades = this.upgradesFromIds(equippedIdList); this.equippedAbilities = this.abilitiesFromIds(equippedAbilityIds); this.refreshUpgradesState(); }; upgradesModel.prototype.upgradesFromIds = function (upgradeIdList) { return _map(upgradeIdList, upgradesImport.getById); }; upgradesModel.prototype.abilitiesFromIds = function (abilityIdList) { return _map(abilityIdList, pilots.getById); }; upgradesModel.prototype.refreshUpgradesState = function () { this.all = this.purchased.concat(this.build.currentShip.startingUpgrades); // Validate and equip upgrades to slots var validatedEquippedUpgrades = this.validateUpgrades(this.equippedUpgrades); var validatedEquippedAbilities = this.validateAbilities(this.equippedAbilities); var equipped = this.equipUpgradesToSlots(validatedEquippedUpgrades, validatedEquippedAbilities); this.equippedUpgrades = equipped.equippedUpgrades; this.equippedAbilities = equipped.equippedAbilities; // Can only call getDisabled() once equipped is set, as it needs to look at slots potentially added by equipping this.disabled = this.getDisabledUpgrades(); this.disabledAbilities = this.getDisabledAbilities(); this.unequipped = this.getUnequippedUpgrades(); this.unequippedAbilities = this.getUnequippedAbilities(); }; upgradesModel.prototype.validateUpgrades = function (upgradesList) { // Make sure equipped list only contains upgrades we have purchased or started with var filteredUpgrades = arrayUtils.intersectionSingle(upgradesList, this.all); // Make sure equipped list only contains upgrade types allowed on ship filteredUpgrades = _filter(filteredUpgrades, _bind(this.upgradeAllowedOnShip, this)); return filteredUpgrades; }; upgradesModel.prototype.validateAbilities = function (pilotsList) { // Make sure equipped list only contains upgrades we have purchased var filteredUpgrades = arrayUtils.intersectionSingle(pilotsList, this.purchasedAbilities); // Make sure equipped list only contains abilities allowed in the build filteredUpgrades = _filter(filteredUpgrades, _bind(this.abilityAllowedInBuild, this)); return filteredUpgrades; }; upgradesModel.prototype.getDisabledUpgrades = function () { var thisModel = this; var slotsAllowedInBuild = this.build.upgradeSlots.allUsableSlotTypes(); var disabledUpgrades = []; _each(this.purchased, function (upgrade) { var allowedOnShip = thisModel.upgradeAllowedOnShip(upgrade); var allowedInSlots = (slotsAllowedInBuild.indexOf(upgrade.slot) > -1); if (!allowedOnShip || !allowedInSlots) { disabledUpgrades.push(upgrade); } }); return disabledUpgrades; }; upgradesModel.prototype.getDisabledAbilities = function () { var thisModel = this; var slotsAllowedInBuild = this.build.upgradeSlots.allUsableSlotTypes(); var disabledUpgrades = []; // Abilities only go in Elite slots var allowedInSlots = (slotsAllowedInBuild.indexOf('Elite') > -1); _each(this.purchasedAbilities, function (pilot) { var allowedOnShip = thisModel.abilityAllowedInBuild(pilot); if (!allowedOnShip || !allowedInSlots) { disabledUpgrades.push(pilot); } }); return disabledUpgrades; }; upgradesModel.prototype.getUnequippedUpgrades = function () { // Remove *All* copies of any upgrades which should be disabled var notDisabled = _difference(this.purchased, this.disabled); // Remove one copy of each item which is equipped var unequipped = arrayUtils.differenceSingle(notDisabled, this.equippedUpgrades); return unequipped; }; upgradesModel.prototype.getUnequippedAbilities = function () { // Remove *All* copies of any abiltiies which should be disabled var notDisabled = _difference(this.purchasedAbilities, this.disabledAbilities); // Remove one copy of each item which is equipped var unequipped = arrayUtils.differenceSingle(notDisabled, this.equippedAbilities); return unequipped; }; upgradesModel.prototype.buyCard = function (upgradeId) { var upgrade = upgradesImport.getById(upgradeId); this.purchased.push(upgrade); this.refreshUpgradesState(); events.trigger('model.build.upgrades.add', this.build); }; upgradesModel.prototype.buyPilotAbility = function (pilotId) { var pilot = pilots.getById(pilotId); this.purchasedAbilities.push(pilot); this.refreshUpgradesState(); events.trigger('model.build.pilotAbilities.add', this.build); }; upgradesModel.prototype.loseCard = function (upgradeId) { // remove the first version of this upgrade we find in the purchased list var foundIndex = _findIndex(this.purchased, function (item) { return item.id === upgradeId; }); if (!_isUndefined(foundIndex)) { // remove found upgrade from purchased list this.purchased.splice(foundIndex, 1); } this.refreshUpgradesState(); events.trigger('model.build.upgrades.lose', this.build); }; upgradesModel.prototype.loseAbility = function (pilotId) { var foundIndex = _findIndex(this.purchasedAbilities, function (item) { return item.id === pilotId; }); if (!_isUndefined(foundIndex)) { this.purchasedAbilities.splice(foundIndex, 1); } this.refreshUpgradesState(); events.trigger('model.build.pilotAbilities.lose', this.build); }; upgradesModel.prototype.equip = function (upgradeId) { var upgrade = upgradesImport.getById(upgradeId); this.equippedUpgrades.push(upgrade); this.refreshUpgradesState(); events.trigger('model.build.equippedUpgrades.update', this.build); }; upgradesModel.prototype.equipAbility = function (pilotId) { var pilot = pilots.getById(pilotId); this.equippedAbilities.push(pilot); this.refreshUpgradesState(); events.trigger('model.build.equippedUpgrades.update', this.build); }; upgradesModel.prototype.unequipUpgrade = function (upgradeId) { // find the first instance of this upgrade in the equipped list. // We only look for the first time it appears, as there may be several of the same card equipped var removeIndex = _findIndex(this.equippedUpgrades, function (upgrade) { return upgrade.id === upgradeId; }); // Now remove found index from equipped list if (removeIndex > -1) { this.equippedUpgrades.splice(removeIndex, 1); this.refreshUpgradesState(); events.trigger('model.build.equippedUpgrades.update', this.build); } }; upgradesModel.prototype.unequipAbility = function (pilotId) { // find the first instance of this upgrade in the equipped list. // We only look for the first time it appears, as there may be several of the same card equipped var removeIndex = _findIndex(this.equippedAbilities, function (pilot) { return pilot.id === pilotId; }); // Now remove found index from equipped list if (removeIndex > -1) { this.equippedAbilities.splice(removeIndex, 1); this.refreshUpgradesState(); events.trigger('model.build.equippedUpgrades.update', this.build); } }; // Return array of upgrades of specific type which are legal to purchased for current build // (e.g. restricted by chassis, size, already a starting upgrade, already purchased etc.) upgradesModel.prototype.getAvailableToBuy = function (upgradeType) { var upgradesOfType = keyedUpgrades[upgradeType]; var allowedUpgrades = _filter(upgradesOfType, _bind(this.upgradeAllowedOnShip, this)); allowedUpgrades = _filter(allowedUpgrades, _bind(this.upgradeAllowedInBuild, this)); return allowedUpgrades; }; upgradesModel.prototype.getAbilitiesAvailableToBuy = function () { var allAbilities = uniquePilots; var allowedPilots = _difference(allAbilities, this.purchasedAbilities); var sortedPilots = pilots.sortList(allowedPilots); return sortedPilots; }; upgradesModel.prototype.upgradeAllowedOnShip = function (upgrade) { // Remove any upgrades for different ships if (upgrade.ship && upgrade.ship.indexOf(this.build.currentShip.shipData.name) < 0) { return false; } // Remove any upgrades for different ship sizes if (upgrade.size && upgrade.size.indexOf(this.build.currentShip.shipData.size) < 0) { return false; } return true; }; upgradesModel.prototype.abilityAllowedInBuild = function (pilot) { // Remove pilots whose PS is higher than build if (pilot.skill > this.build.pilotSkill) { return false; } return true; }; upgradesModel.prototype.upgradeAllowedInBuild = function (upgrade) { // Don't show anything which is a starting upgrade for the ship if (this.build.currentShip.startingUpgrades) { var found = _find(this.build.currentShip.startingUpgrades, function (startingUpgrade) { return startingUpgrade.xws === upgrade.xws; }); if (found) { return false; } } // Remove any upgrades the build already has var upgradeExists = _find(this.all, function (existingUpgrade) { // Check xws instead of ID so we remove both sides of dual cards return existingUpgrade.xws === upgrade.xws; }); if (upgradeExists) { var upgradeIsAllowed = false; // filter out any upgrades the player already has // except // * secondary weapons & bombs if (upgrade.slot === 'Bomb' || upgrade.slot === 'Torpedo' || upgrade.slot === 'Cannon' || upgrade.slot === 'Turret' || upgrade.slot === 'Missile') { upgradeIsAllowed = true; // * hull upgrade and shield upgrade } else if (upgrade.xws === 'hullupgrade' || upgrade.xws === 'shieldupgrade') { upgradeIsAllowed = true; } if (!upgradeIsAllowed) { return false; } } return true; }; upgradesModel.prototype.abilityAlreadyInBuild = function (abilityPilot) { // Remove any abilities the build already has var abilityExists = _find(this.purchasedAbilities, function (existingAbility) { return existingAbility.id === abilityPilot.id; }); if (abilityExists) { return true; } return false; }; upgradesModel.prototype.canEquipUpgrade = function (upgradeId) { var upgradeSlots = this.build.upgradeSlots; var upgrade = upgradesImport.getById(upgradeId); var canEquip = false; _each(upgradeSlots.enabled, function (upgradeSlot) { if (upgradeSlot.type === upgrade.slot) { // this slot is the right type for the upgrade if (!upgradeSlot.equipped) { // This slot is free canEquip = true; } } }); return canEquip; }; upgradesModel.prototype.canEquipAbilties = function () { var upgradeSlots = this.build.upgradeSlots; var canEquip = false; _each(upgradeSlots.enabled, function (upgradeSlot) { if (upgradeSlot.type === 'Elite') { // this slot is the right type for the upgrade if (!upgradeSlot.equipped) { // This slot is free canEquip = true; } } }); return canEquip; }; upgradesModel.prototype.equipUpgradesToSlots = function (upgradesToEquip, abilitiesToEquip) { var thisModel = this; var remainingUpgradesToEquip = _clone(upgradesToEquip); var remainingAbilitiesToEquip = _clone(abilitiesToEquip); var equippedUpgrades = []; var equippedAbilities = []; var upgradeSlots = this.build.upgradeSlots; // Reset additonal slots as we are about to repopulate through equipping upgradeSlots.resetAdditionalSlots(); var newSlotIndices = []; _each(upgradeSlots.free, function (upgradeSlot) { var matchingUpgrade = thisModel.matchFreeSlot(upgradeSlot, remainingUpgradesToEquip); var slotsAddedIndices = thisModel.equipSlot(upgradeSlot, matchingUpgrade, equippedUpgrades, equippedAbilities, remainingUpgradesToEquip, remainingAbilitiesToEquip); // If we added any new slots as part of equipping this upgrade, add them to the list newSlotIndices = newSlotIndices.concat(slotsAddedIndices); }); _each(upgradeSlots.enabled, function (upgradeSlot) { var matchingUpgrade = thisModel.matchSlot(upgradeSlot, remainingUpgradesToEquip, remainingAbilitiesToEquip); var slotsAddedIndices = thisModel.equipSlot(upgradeSlot, matchingUpgrade, equippedUpgrades, equippedAbilities, remainingUpgradesToEquip, remainingAbilitiesToEquip); // If we added any new slots as part of equipping this upgrade, add them to the list newSlotIndices = newSlotIndices.concat(slotsAddedIndices); }); // If we added any slots via upgrades, equip to them now while (newSlotIndices.length > 0) { // get the first item index from the array var itemIndex = newSlotIndices.shift(); // try to equip to the additional slot at that index var matchingUpgrade = this.matchSlot(this.build.upgradeSlots.slotsFromUpgrades[itemIndex], remainingUpgradesToEquip, remainingAbilitiesToEquip); var slotsAddedIndices = this.equipSlot(this.build.upgradeSlots.slotsFromUpgrades[itemIndex], matchingUpgrade, equippedUpgrades, equippedAbilities, remainingUpgradesToEquip, remainingAbilitiesToEquip); // If we added yet more slots as part of equipping this upgrade, add them to the list newSlotIndices = newSlotIndices.concat(slotsAddedIndices); } return { equippedUpgrades: equippedUpgrades, equippedAbilities: equippedAbilities }; }; upgradesModel.prototype.matchFreeSlot = function (upgradeSlot, remainingUpgradesToEquip) { // Is there an equipped upgrade for this slot? var matchingUpgrade = _find(remainingUpgradesToEquip, function (upgrade) { return upgrade.id === upgradeSlot.upgrade.id; }); return matchingUpgrade; }; upgradesModel.prototype.matchSlot = function (upgradeSlot, remainingUpgradesToEquip, remainingAbilitiesToEquip) { // Is there an equipped upgrade for this slot? var matchingUpgrade = _find(remainingUpgradesToEquip, function (upgrade) { return upgrade.slot === upgradeSlot.type; }); if (!matchingUpgrade && upgradeSlot.type === 'Elite') { // We didn't find a match, and this is elite, so also check for matching abilities matchingUpgrade = _first(remainingAbilitiesToEquip); } return matchingUpgrade; }; upgradesModel.prototype.equipSlot = function (upgradeSlot, upgradeToEquip, equippedUpgrades, equippedAbilities, remainingUpgradesToEquip, remainingAbilitiesToEquip) { var addedSlotsIndices = []; // clear existing upgrade from slot delete upgradeSlot.equipped; if (upgradeToEquip) { if (this.upgradeisAbility(upgradeToEquip)) { // remove this upgrade from the list available to match slots arrayUtils.removeFirstMatchingValue(remainingAbilitiesToEquip, upgradeToEquip); equippedAbilities.push(upgradeToEquip); } else { // remove this upgrade from the list available to match slots arrayUtils.removeFirstMatchingValue(remainingUpgradesToEquip, upgradeToEquip); equippedUpgrades.push(upgradeToEquip); // Add any extra slots granted by the upgrade addedSlotsIndices = this.addUpgradeGrantsSlot(upgradeToEquip); } upgradeSlot.equipped = upgradeToEquip; } // If we added additional slots via a grant on this upgrade, let the caller know return addedSlotsIndices; }; upgradesModel.prototype.addUpgradeGrantsSlot = function (upgrade) { var thisModel = this; var addedSlotIndices = []; _each(upgrade.grants, function (grant) { if (grant.type === 'slot') { var addedSlotIndex = thisModel.build.upgradeSlots.addAdditionalSlot(grant.name); addedSlotIndices.push(addedSlotIndex); } }); return addedSlotIndices; }; // Return boolean whether upgrade is an ability. Can be used to differentiate between equipped upgrades // which are card and which are pilot abilities upgradesModel.prototype.upgradeisAbility = function (upgrade) { if (upgrade.skill) { // only pilot cards have skill property, not upgrade cards return true; } return false; }; module.exports = upgradesModel;
/** * Copyright (c) 2015-present, yhtml5.com, Inc. * All rights reserved. */ 'use strict'; const downLoad = ({ name = 'download', url = '' }) => { if (process.env.NODE_ENV !== 'production') { if (Object.prototype.toString.call(url) !== '[object String]' && !url) { console.error('The function downLoad url should be a not empty string'); return } } let a = document.createElement('a'); a.href = encodeURI(url); a.download = name; a.id = name; a.style.display = 'none'; // a.click() document.body.appendChild(a); document.getElementById(name).click(); document.body.removeChild(document.getElementById(name)); a = null; }; module.exports = downLoad;
// @flow export default [ { title: 'Front End Engineer', unit: 'Appier', location: 'Taipei, Taiwan', duration: '2017 - Present', description: 'Aixon Team', }, { title: 'F2E&RGBA Meetup', unit: 'Co-organizer', location: 'Taipei, Taiwan', duration: '2016 - Present', description: 'f2e.tw Community', }, { title: 'Front End Developer', unit: 'iCHEF Co., Ltd.', location: 'Taipei, Taiwan', duration: '2016 - 2017', description: 'Cloud Team', }, { title: 'Front End Engineer', unit: 'Galaxy Software Services', location: 'Taipei, Taiwan', duration: '2014 - 2016', description: 'Front End Developer & Web Designer', }, { title: 'Bachelor of Computer Science', unit: 'National Cheng Kung University', location: 'Tainan, Taiwan', duration: '2010 - 2014', description: 'Major in web development', }, ];
/* * timeselector * https://github.com/nicolaszhao/timeselector * * Copyright (c) 2014 Nicolas Zhao * Licensed under the MIT license. */ (function($) { var Timeselector = function() { this._$div = null; this._inst = null; this._showing = false; this.uuid = new Date().getTime(); this.initialized = false; }; Timeselector.prototype = { constructor: Timeselector, _generateHtml: function() { return '<div id="timeselector-div" class="timeselector">' + '<div class="timeselector-item timeselector-hour" data-type="hour">' + '<a class="timeselector-button timeselector-up">+</a>' + '<span class="timeselector-value"></span>' + '<a class="timeselector-button timeselector-down">-</a>' + '</div>' + '<div class="timeselector-separator">:</div>' + '<div class="timeselector-item timeselector-minute" data-type="minute">' + '<a class="timeselector-button timeselector-up">+</a>' + '<span class="timeselector-value"></span>' + '<a class="timeselector-button timeselector-down">-</a>' + '</div>' + '</div>'; }, _setTime: function(inst, step) { var date = inst.date; if (step) { date.setTime(+date + (1000 * 60 * step)); } inst.input.val(this._format(date, inst.options.hours12)); inst.lastValue = inst.input.val(); }, _setTimeFromField: function(inst) { if (inst.input.val() === inst.lastValue) { return; } inst.lastValue = inst.input.val(); var date = new Date(), matches, hour; matches = this._match(inst.lastValue); if (matches) { hour = parseInt(matches[0], 10); if (matches[2]) { if (matches[2].toLowerCase() === 'am' && hour === 12) { hour = 0; } else if (matches[2].toLowerCase() === 'pm' && hour > 0 && hour < 12) { hour = hour + 12; } } date.setHours(hour); date.setMinutes(parseInt(matches[1], 10)); } inst.date = date; }, _match: function(time) { var rtime = /^((?:1[012]|0[1-9])|(?:[01][0-9]|2[0-3])):([0-5][0-9])(?:\s(am|pm))?$/i, matches = rtime.exec(time); if (matches) { matches.splice(0, 1); } return matches; }, _update: function(inst) { var time = this._format(inst.date, inst.options.hours12); time = this._match(time); this._$div.find('.timeselector-value').each(function(i) { $(this).text(time[i]); }); }, _format: function(date, hours12) { var hour = date.getHours(), minute = date.getMinutes(), leadZero = function(num) { return (num < 10 ? '0' : '') + num; }; if (hours12) { if (hour === 0) { hour = 12; } else if (hour > 12) { hour = hour - 12; } return leadZero(hour) + ':' + leadZero(minute) + ' ' + (date.getHours() < 12 ? 'AM' : 'PM'); } return leadZero(hour) + ':' + leadZero(minute); }, _getInst: function(target) { return $(target).data('timeselector'); }, _selectTime: function(inst, type, steps, delay) { delay = delay || 500; var that = this; clearTimeout(this._timer); this._timer = setTimeout(function() { that._selectTime(inst, type, steps, 50); }, delay); this._setTime(inst, type === 'hour' ? steps * 60 : steps * inst.options.step); this._update(inst); }, _stop: function() { clearTimeout(this._timer); }, _doKeyDown: function(event) { var inst = this._getInst(event.target); switch (event.which) { case 27: this._hide(); break; case 38: this._selectTime(inst, 'minute', 1); break; case 40: this._selectTime(inst, 'minute', -1); break; case 33: this._selectTime(inst, 'hour', 1); break; case 34: this._selectTime(inst, 'hour', -1); break; } }, _doKeyUp: function(event) { var inst = this._getInst(event.target); if (inst.input.val() !== inst.lastValue && this._showing) { this._setTimeFromField(inst); this._update(inst); } this._stop(); }, _show: function(input) { input = input.target || input; if (this._lastInput === input) { return; } var $input = $(input), inst = this._getInst(input), isFixed = false, pos; if (this._inst && this._inst !== inst) { this._inst.div.stop(true, true); } this._lastInput = input; this._setTimeFromField(inst); this._update(inst); $input.parents().each(function() { isFixed = $(this).css('position') === 'fixed'; return !isFixed; }); pos = $input.offset(); pos.top += input.offsetHeight; pos.left -= isFixed ? $(document).scrollLeft() : 0; pos.top -= isFixed ? $(document).scrollTop() : 0; inst.div.css({ position: (isFixed ? 'fixed' : 'absolute'), display: 'none', top: pos.top, left: pos.left, zIndex: this._zIndex(input) + 1 }); inst.div.fadeIn('fast'); this._showing = true; this._inst = inst; }, _hide: function() { var inst = this._inst; if (!inst || !this._showing) { return; } inst.div.fadeOut('fast'); this._lastInput = null; this._showing = false; }, _checkExternalClick: function(event) { if (!this._inst) { return; } var $target = $(event.target), inst = this._getInst($target[0]); if ((!inst && !$target.closest('.timeselector').length && this._showing) || (inst && this._inst !== inst)) { this._hide(); } }, _zIndex: function(elem) { elem = $(elem); var position, value; while (elem.length && elem[ 0 ] !== document) { position = elem.css('position'); if (position === 'absolute' || position === 'relative' || position === 'fixed') { value = parseInt(elem.css('zIndex'), 10); if (!isNaN(value) && value !== 0) { return value; } } elem = elem.parent(); } return 0; }, _attach: function(target, options) { var inst; if (this._getInst(target)) { return; } if (!target.id) { this.uuid += 1; target.id = 'timeselector-input-' + this.uuid; } inst = { id: target.id, input: $(target), div: this._$div, options: $.extend({}, options) }; this._setTimeFromField(inst); if (this._match(target.value)) { this._setTime(inst); } $(target).data('timeselector', inst) .attr('autocomplete', 'off') .on('keydown.timeselector', $.proxy(this._doKeyDown, this)) .on('keyup.timeselector', $.proxy(this._doKeyUp, this)) .on('focus.timeselector', $.proxy(this._show, this)) .on('blur.timeselector', $.proxy(this._stop, this)); }, _create: function() { var that = this; this._$div = $(this._generateHtml()).appendTo('body').hide() .on('mousedown.timeselector', '.timeselector-button', function(event) { var $button = $(this); if (that._inst.input[0] !== document.activeElement) { that._inst.input.focus(); } $button.addClass('timeselector-state-active'); that._selectTime(that._inst, $button.parent('.timeselector-item').data('type'), $button.hasClass('timeselector-up') ? 1 : -1); event.preventDefault(); }) .on('mouseup.timeselector', '.timeselector-button', function() { $(this).removeClass('timeselector-state-active'); that._stop(); }) .on('mouseenter.timeselector', '.timeselector-button', function() { var $button = $(this); if ($button.hasClass('timeselector-state-active')) { that._selectTime(that._inst, $button.parent('.timeselector-item').data('type'), $button.hasClass('timeselector-up') ? 1 : -1); } }) .on('mouseleave.timeselector', '.timeselector-button', $.proxy(this._stop, this)) .on('click.timeselector', '.timeselector-value', function() { that._setTime(that._inst); that._hide(); }); $(document).on('mousedown.timeselector', $.proxy(this._checkExternalClick, this)); }, option: function(target, options) { var inst = this._getInst(target); if (inst) { if (this._inst === inst) { this._hide(); } $.extend(inst.options, options); this._setTime(inst); this._update(inst); } }, refresh: function(target) { var inst = this._getInst(target); if (inst) { this._setTimeFromField(inst); this._update(inst); if (this._match(target.value)) { this._setTime(inst); } } } }; $.fn.timeselector = function(options) { var args = Array.prototype.slice.call(arguments, 1); if (!$.fn.timeselector.timer.initialized) { $.fn.timeselector.timer._create(); $.fn.timeselector.timer.initialized = true; } if (typeof options === 'string') { this.each(function() { var method = $.fn.timeselector.timer[options]; if (typeof method === 'function' && options.charAt(0) !== '_') { method.apply($.fn.timeselector.timer, [this].concat(args)); } }); } else { options = $.extend({}, $.fn.timeselector.defaults, options); this.each(function() { $.fn.timeselector.timer._attach(this, options); }); } return this; }; $.fn.timeselector.defaults = { hours12: true, step: 1 }; $.fn.timeselector.timer = new Timeselector(); }(jQuery));