code
stringlengths
2
1.05M
var Cards = require('../Cards'); var getWinner = function(state) { var winners = state.players.filter(function(player) { return player.hole_cards != undefined && player.amount_won != undefined; }); if (winners.length == 0) { // Not last round return undefined; } return { hand: winners[0].hole_cards, handScore: Cards.getHandScore(winners[0].hole_cards), flop: state.community_cards, player: winners[0] }; }; var getWinnerScore = function(states) { return states .map(function(state) { return getWinner(state); }) .filter(function(result) { return result != undefined; }) .map(function(result) { return { bot: result.player.name, handScore: result.handScore }; }); }; module.exports = { getWinnerScore: getWinnerScore };
function mergeRoute(original, template) { const result = { ...original }; for (const key in template) { const templateValue = template[key]; if (typeof templateValue == 'function') { const originalValue = original[key]; if (originalValue) { result[key] = (...args) => { templateValue(originalValue, ...args); }; } else { result[key] = templateValue; } } } return result; } export function processTabs(tabData) { return tabData.map(tab => tab.getTabData()); } export function processRoutes(childRoutes, templateRoute, store) { return childRoutes.map(config => mergeRoute(config.getRoute(store), templateRoute)); } // WEBPACK FOOTER // // ./src/client/common/config/config-processor.js
require('babel-register'); require('./global'); const getenv = require('getenv'); const env = require('../config/expose'); global.CONFIG = getenv.multi(env).default; require('../src/utils/seeder.runner') .default('./src/seeds/');
app.controller('ProgramsController', function($scope, programs) { $scope.chart = { data: { series: [], labels: [] }, options: { distributeSeries: true, horizontalBars: true, height: '400px', axisY: { offset: 140 }, chartPadding: { top: 0, right: 0, bottom: 4, left: 0 }, plugins:[ Chartist.plugins.tooltip({ appendToBody: true, anchorToPoint: true, currency: 'Anzahl der teilnehmenden Schulen: ', transformTooltipTextFnc: function(value) { return parseInt(value, 10).toFixed(0) + ' '; } }) ] } }; programs.get(function(err, data) { data.sort(function(a, b) { return a.amount - b.amount; }); $scope.chart.data.series = data.map(function(d) { return d.amount; }); $scope.chart.data.labels = data.map(function(d) { return d.name; }); }); });
import svgMarkup from './PhoneIcon.svg'; import React from 'react'; import Icon from '../private/Icon/Icon'; export default function PhoneIcon(props) { return <Icon markup={svgMarkup} {...props} />; } PhoneIcon.displayName = 'PhoneIcon';
const Joi = require('joi'); module.exports = { VerifyMember: { email: Joi.string().email().required(), password: Joi.string().required() }, CreateMember: { name: Joi.string().required(), email: Joi.string().email().required(), password: Joi.string().required() }, UpdateProfile: { email: Joi.string().email().required(), name: Joi.string().required(), phone: Joi.string(), country: Joi.string(), address: Joi.string(), city: Joi.string(), state: Joi.string(), zip_code: Joi.string() }, SendPasswordResetEmail: { email: Joi.string().email().required() } };
require('proof')(1, async okay => { await require('./harness')(okay, 'idbcursor_update_objectstore4') await harness(async function () { var db, t = async_test() var open_rq = createdb(t); open_rq.onupgradeneeded = function(e) { db = e.target.result; var objStore = db.createObjectStore("test"); objStore.add("data", "key"); }; open_rq.onsuccess = t.step_func(function(e) { var txn = db.transaction("test", "readwrite"), cursor_rq = txn.objectStore("test") .openCursor(); cursor_rq.onsuccess = t.step_func(function(e) { var cursor = e.target.result; cursor.value = "new data!"; cursor.update(cursor.value).onsuccess = t.step_func(function(e) { assert_equals(e.target.result, "key"); t.done(); }); }); }); }) })
require('file?name=fontawesome-webfont.eot!font-awesome/fonts/fontawesome-webfont.eot'); require('file?name=fontawesome-webfont.svg!font-awesome/fonts/fontawesome-webfont.svg'); require('file?name=fontawesome-webfont.ttf!font-awesome/fonts/fontawesome-webfont.ttf'); require('file?name=fontawesome-webfont.woff!font-awesome/fonts/fontawesome-webfont.woff'); require('file?name=fontawesome-webfont.woff2!font-awesome/fonts/fontawesome-webfont.woff2'); require('file?name=addon.xml!./addon.xml'); require('!style!css!sass!./scss/main.scss'); require('./js/ripple'); var $ = require('jquery'); $('body').append(require('jade!./template/index.jade')()); $('body').css({'background-image': `url(${require("url!./img/splash.jpg")})`}); var Remote = require('./js/remote'); var remote = new Remote($('i.fa'));
/** * The MIT License (MIT) * * Copyright (c) 2016 DeNA Co., Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ /// <reference path="base.js"/> /// <reference path="object.js"/> /// <reference path="region.js"/> /** * A class representing a bounding box. * @extends {createjs.Object} * @implements {createjs.Region} * @constructor */ createjs.BoundingBox = function() { createjs.Object.call(this); }; createjs.inherits('BoundingBox', createjs.BoundingBox, createjs.Object); /** * Returns a clone of the specified box. * @param {createjs.BoundingBox} box * @return {createjs.BoundingBox} */ createjs.BoundingBox.clone = function(box) { /// <param type="createjs.BoundingBox" name="box"/> /// <returns type="createjs.BoundingBox"/> var clone = new createjs.BoundingBox(); clone.minX = box.minX; clone.minY = box.minY; clone.maxX = box.maxX; clone.maxY = box.maxY; return clone; }; /** * The left position of this bounding box. * @type {number} */ createjs.BoundingBox.prototype.minX = 10000; /** * The top position of this bounding box. * @type {number} */ createjs.BoundingBox.prototype.minY = 10000; /** * The right position of this bounding box. * @type {number} */ createjs.BoundingBox.prototype.maxX = -10000; /** * The bottom position of this bounding box. * @type {number} */ createjs.BoundingBox.prototype.maxY = -10000; /** * Resets all properties of this object to the initial state. * @const */ createjs.BoundingBox.prototype.reset = function() { this.minX = 10000; this.minY = 10000; this.maxX = -10000; this.maxY = -10000; }; /** * Returns the x position of this bounding box. * @return {number} * @const */ createjs.BoundingBox.prototype.getLeft = function() { /// <returns type="number"/> return this.minX; }; /** * Returns the y position of this bounding box. * @return {number} * @const */ createjs.BoundingBox.prototype.getTop = function() { /// <returns type="number"/> return this.minY; }; /** * Returns the width of this bounding box. * @return {number} * @const */ createjs.BoundingBox.prototype.getWidth = function() { /// <returns type="number"/> return this.maxX - this.minX; }; /** * Returns the height of this bounding box. * @return {number} * @const */ createjs.BoundingBox.prototype.getHeight = function() { /// <returns type="number"/> return this.maxY - this.minY; }; /** * Returns whether this box is an empty one. * @param {createjs.BoundingBox} box * @return {boolean} * @const */ createjs.BoundingBox.prototype.isEqual = function(box) { /// <param type="createjs.BoundingBox" name="box"/> /// <returns type="boolean"/> return this.minX == box.minX && this.maxX == box.maxX && this.minY == box.minY && this.maxY == box.maxY; }; /** * Updates this bounding box. * @param {number} x * @param {number} y * @const */ createjs.BoundingBox.prototype.update = function(x, y) { /// <param type="number" name="x"/> /// <param type="number" name="y"/> this.minX = createjs.min(x, this.minX); this.minY = createjs.min(y, this.minY); this.maxX = createjs.max(x, this.maxX); this.maxY = createjs.max(y, this.maxY); }; /** * Inflates this bounding box. * @param {createjs.BoundingBox} box * @const */ createjs.BoundingBox.prototype.inflate = function(box) { /// <param type="createjs.BoundingBox" name="box"/> this.minX = createjs.min(box.minX, this.minX); this.minY = createjs.min(box.minY, this.minY); this.maxX = createjs.max(box.maxX, this.maxX); this.maxY = createjs.max(box.maxY, this.maxY); }; /** * Adds the specified margin to this box. * @param {number} margin * @const */ createjs.BoundingBox.prototype.addMargin = function(margin) { /// <param type="number" name="margin"/> this.minX -= margin; this.minY -= margin; this.maxX += margin; this.maxY += margin; this.maxX = this.minX + createjs.truncate(this.maxX - this.minX); this.maxY = this.minY + createjs.truncate(this.maxY - this.minY); }; /** * Returns whether this box contains the specified one. * @param {createjs.BoundingBox} box * @return {boolean} * @const */ createjs.BoundingBox.prototype.containBox = function(box) { /// <param type="createjs.BoundingBox" name="box"/> /// <returns type="boolean"/> createjs.assert(!this.isEmpty() && !box.isEmpty()); return this.minX <= box.minX && box.maxX <= this.maxX && this.minY <= box.minY && box.maxY <= this.maxY; }; /** * Returns whether this box has intersection with the specified one. * @param {createjs.BoundingBox} box * @return {boolean} * @const */ createjs.BoundingBox.prototype.hasIntersection = function(box) { /// <param type="createjs.BoundingBox" name="box"/> /// <returns type="boolean"/> // Two convexes have intersection only when there are not any lines in between // them separated by a gap as noted by the hyperplane-separation theorem. // Especially for two rectangles, their separation axises become an X-axis and // a Y-axis. So, these rectangles have intersection when there are not any // gaps in their projections both to the X-axis and to the Y-axis. var maxMinX = createjs.max(this.minX, box.minX); var minMaxX = createjs.min(this.maxX, box.maxX); var maxMinY = createjs.max(this.minY, box.minY); var minMaxY = createjs.min(this.maxY, box.maxY); return maxMinX < minMaxX && maxMinY < minMaxY; }; /** * Returns whether this box has intersections with the specified rectangle * (0,0)-(width,height). This method is used by a renderer to determine if it * needs to redraw its objects. * @param {number} width * @param {number} height * @return {boolean} * @const */ createjs.BoundingBox.prototype.isDirty = function(width, height) { /// <param type="number" name="width"/> /// <param type="number" name="height"/> /// <returns type="boolean"/> if (this.isEmpty() || this.maxX <= 0 || width <= this.minX || this.maxY <= 0 || height <= this.minY) { return false; } return true; }; /** * Returns whether this box is a subset of the specified rectangle * (0,0)-(width,height). This method is used by a renderer to calculate its * clipping rectangle. * @param {number} width * @param {number} height * @return {boolean} * @const */ createjs.BoundingBox.prototype.needClip = function(width, height) { /// <param type="number" name="width"/> /// <param type="number" name="height"/> /// <returns type="boolean"/> if (this.minX <= 0 && width <= this.maxX && this.maxY <= 0 && height <= this.maxY) { return false; } // Snap this bounding box to a pixel boundary. this.minX = (this.minX <= 0) ? 0 : createjs.floor(this.minX); this.minY = (this.minY <= 0) ? 0 : createjs.floor(this.minY); this.maxX = createjs.ceil(this.maxX); this.maxY = createjs.ceil(this.maxY); return true; }; /** @override */ createjs.BoundingBox.prototype.isEmpty = function() { /// <returns type="boolean"/> return this.maxX <= this.minX; }; /** @override */ createjs.BoundingBox.prototype.contain = function(x, y) { /// <param type="number" name="x"/> /// <param type="number" name="y"/> /// <returns type="boolean"/> return this.minX <= x && x <= this.maxX && this.minY <= y && y <= this.maxY; };
import fetch from 'isomorphic-fetch'; import handleResponse from '../utils/fetchHandler'; import API_BASE from '../utils/APIBase'; export const LOAD_USER_REQUEST = 'LOAD_USER_REQUEST'; export const LOAD_USER_SUCCESS = 'LOAD_USER_SUCCESS'; export const LOAD_USER_FAILURE = 'LOAD_USER_FAILURE'; async function get(username) { return fetch(`${API_BASE}/api/v1/user/${username}`, { headers: { Accept: 'application/json', }, }) .then(handleResponse); } export function loadUser(username) { return async dispatch => { if (!username || typeof username !== 'string') { throw new Error('Invalid username'); } try { dispatch({ type: LOAD_USER_REQUEST }); const res = await get(username); dispatch({ type: LOAD_USER_SUCCESS, user: res, }); } catch (err) { dispatch({ type: LOAD_USER_FAILURE, error: err.message }); } }; }
import React from 'react'; import { shallow, mount } from 'enzyme'; import Nav from '../lib/Nav'; describe('Nav', () => { const clickNavFn = jest.fn(); const wrapper = shallow(<Nav sevenClicked = { clickNavFn } tenClicked = { clickNavFn } cityClicked = { clickNavFn }/>) const mountWrap = mount(<Nav sevenClicked = { clickNavFn } tenClicked = { clickNavFn } cityClicked = { clickNavFn }/>) it('should exist', () => { expect(wrapper).toBeDefined() }) it('should have 3 buttons', () => { expect(wrapper.find('button').length).toEqual(3) }) it('should have a function for the sevenClicked property', () => { expect(mountWrap.props().sevenClicked).toEqual(clickNavFn) }) it('should have a function for the tenClicked property', () => { expect(mountWrap.props().tenClicked).toEqual(clickNavFn) }) it('should have a function for the cityClicked property', () => { expect(mountWrap.props().cityClicked).toEqual(clickNavFn) }) it.skip('should run a function when a tab button is clicked', () => { const navButton = wrapper.find('button') navButton.simulate('click') expect(clickNavFn).toHaveBeenCalled() expect(clickNavFn).toHaveBeenCalledTimes(1) navButton.simulate('click') expect(clickNavFn).toHaveBeenCalledTimes(2) }) })
var pjson = require("./package.json"); var config = require("./config/general"); var socket_config = require("./config/general"); var log = require("winston") var cluster = require('cluster'); var http = require('http'); var numCPUs = require('os').cpus().length; var Server = require("./scripts/server"); var Socket = require("./scripts/socket"); var Cluster = function(cluster) { var exports = { master: cluster.isMaster }; function start(cb) { cb = cb || function(){}; if (cluster.isMaster) { log.info((pjson.name || "web cluster") + " > starting infrastructure..."); var workerManager = require("./worker"); workerManager.startAll(); for (var i = 0; i < numCPUs; i++) cluster.fork() exports.cpus = numCPUs; cluster.on('exit', function(worker, code, signal) { console.log('server ' + worker.process.pid + ' died'); }); cb(); } else if (cluster.isWorker) { var socket = null; var server = new Server(function(server, app){ server.listen(app.get('port'), function(){ socket = new Socket(server); log.info('server listening on port ' + app.get('port')); }); }); } }; exports.start = start; function init() { if(!config[config.state]) throw new Error("No configuration state available"); var state = config[config.state]; numCPUs = state.cluster? state.cluster.max || numCPUs : numCPUs; return exports; } return init(); } var cluster = new Cluster(cluster); cluster.start(function(){ log.info("starting cluster with " + cluster.cpus + " forks.\n") });
import toString from './toString'; /** Used to generate unique IDs. */ var idCounter = 0; /** * Generates a unique ID. If `prefix` is given the ID is appended to it. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {string} [prefix=''] The value to prefix the ID with. * @returns {string} Returns the unique ID. * @example * * _.uniqueId('contact_'); * // => 'contact_104' * * _.uniqueId(); * // => '105' */ function uniqueId(prefix) { var id = ++idCounter; return toString(prefix) + id; } export default uniqueId;
/* @flow */ import Extractor from './Extractor'; export default (content: string, options: ?DoctrineOptions): Array<CommentObject> => { const extractor = new Extractor(options); return extractor.extract(content); };
/* */ var combine = require("./index"); var Benchmark = require("benchmark"); var fs = require("fs"); var point = require("turf-point"); var linestring = require("turf-linestring"); var polygon = require("turf-polygon"); var featurecollection = require("turf-featurecollection"); var pt1 = point(50, 51); var pt2 = point(100, 101); var l1 = linestring([[102.0, -10.0], [130.0, 4.0]]); var l2 = linestring([[40.0, -20.0], [150.0, 18.0]]); var p1 = polygon([[[20.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0]]]); var p2 = polygon([[[30.0, 0.0], [102.0, 0.0], [103.0, 1.0]]]); var suite = new Benchmark.Suite('turf-combine'); suite.add('turf-combine#point', function() { combine(featurecollection([pt1, pt2])); }).add('turf-combine#line', function() { combine(featurecollection([l1, l2])); }).add('turf-combine#polygon', function() { combine(featurecollection([p1, p2])); }).on('cycle', function(event) { console.log(String(event.target)); }).on('complete', function() {}).run();
var ReportGraphSingleStudent = React.createClass({displayName: "ReportGraphSingleStudent", selectStudent: function( msg, data ){ console.log( msg, data ); this.setState({currentStudent: data}); }, componentWillMount: function() { console.log("ReportGraphSingleStudent componentWillMount"); var token = PubSub.subscribe( 'SELECT_STUDENT', this.selectStudent ); }, render: function() { console.log("ReportGraphSingleStudent: Render : "); console.log(this.props.currentStudent); return ( React.createElement("div", {className: "graph-container"}, React.createElement("div", {className: "graph-title"}, "Performance Details for ", this.props.currentStudent.firstName, " ", this.props.currentStudent.lastInitial), React.createElement("span", null, " October 01, 2014 - November 01, 2014"), React.createElement("div", {className: "graph"}, React.createElement("div", {className: "graph-options"} ) ) ) ) } }); var ReportSingleStudent = React.createClass({displayName: "ReportSingleStudent", handleClick: function(student) { console.log("Clicked"); PubSub.publish( 'SELECT_STUDENT', student ); }, render: function() { console.log(this.props.student); return ( React.createElement("div", {className: "item"}, React.createElement("div", {className: "evaluation-student", onClick: this.handleClick.bind(this, this.props.student)}, React.createElement("div", {className: "imageWrapper"}), React.createElement("span", {className: "student-link"}, this.props.student.firstName, " ", this.props.student.lastInitial) ) ) ) } }); var ReportStudentList = React.createClass({displayName: "ReportStudentList", render: function() { console.log(this.props.allStudents); var studentListHtml = []; this.props.allStudents.forEach(function(oneStudent) { studentListHtml.push(React.createElement(ReportSingleStudent, {student: oneStudent, key: oneStudent.id})) }); return ( React.createElement("div", {id: "students-in-class", className: "row"}, React.createElement("div", {id: "arrowL", className: "col-xs-1"}), React.createElement("div", {id: "student-list-container", className: "col-xs-10"}, React.createElement("div", {className: "list"}, studentListHtml ) ), React.createElement("div", {id: "arrowR", className: "col-xs-1"}) ) ); } }); var ReportUI = React.createClass({displayName: "ReportUI", render: function() { console.log(this.props.allStudents); return ( React.createElement("div", {id: "pageContent"}, React.createElement("div", {id: "top-evaluation-bar"}, React.createElement("div", {id: "top-student-navigation"}, React.createElement("div", {className: "container"}, React.createElement(ReportStudentList, {allStudents: this.props.allStudents}) ) ) ), React.createElement("div", {id: "report-container", className: "container"}, React.createElement("div", {className: "row"}, React.createElement("div", {className: "col-md-7"}, React.createElement(ReportGraphSingleStudent, {currentStudent: this.props.currentStudent}) ), React.createElement("div", {className: "col-md-5"}, React.createElement("div", {standards: true, "current-standard": "currentStandard", "available-standards": "availableStandards"}), React.createElement("div", {"standards-exposures": true}) ) ) ), React.createElement("div", {"differentiation-resources": true, "list-of-differentiation-assets": "differentiationResources[currentStandard]"}) ) ); } }); student1 = { id:'5TDT7S1MC4Q2RDNBZSXHWOEEK8', firstName: 'Student', lastInitial: '1' }; student2 = { id:'3312BBCPETOREGHBGX2DZGYW58', firstName: 'Student', lastInitial: '2' }; student3 = { id:'6YDT7S1MC4Q2RDNBFRSDWOSWK8', firstName: 'Student', lastInitial: '3' }; student4 = { id:'38DT7S1MC4Q2RDNBFRSDWOSWK8', firstName: 'Student', lastInitial: '4' }; var allStudents = [student1, student2, student3, student4]; var currentStudent = student1; availableStandards = ["1.NBT.4", "1.NBT.5", "1.NBT.6"]; currentStandard = "1.NBT.4"; differentiationResources = {}; differentiationResources["1.NBT.4"] = ["1nbt4 - 1", "1nbt4 - 2", "1nbt4 - 3", "1nbt4 - 4"]; differentiationResources["1.NBT.5"] = ["1nbt5 - 1", "1nbt5 - 2"]; differentiationResources["1.NBT.6"] = ["1nbt6 - 1", "1nbt6 - 2", "1nbt6 - 3"]; React.render(React.createElement(ReportUI, {allStudents: allStudents, currentStudent: currentStudent}), document.getElementById("pageContent123"));
// OAuth2 template module.exports = function(idValue, secretValue) { // github - http://developer.github.com/ var config = {}; config.enabled=true; config.type='oauth-2.0'; config.authorizationUrl = 'https://github.com/login/oauth/authorize'; config.accessTokenUrl = 'https://github.com/login/oauth/access_token'; config.baseUrl = 'https://api.github.com'; config.defaultLoadUrl = '/user'; config.userIdPath = 'login'; config.clientId = idValue; config.clientSecret = secretValue; return config; };
import { escapeKey, unescapeKey } from 'shared/keypaths'; import { addToArray, removeFromArray } from 'utils/array'; import { isArray, isObject, isFunction } from 'utils/is'; import bind from 'utils/bind'; import { create, keys as objectKeys } from 'utils/object'; const shuffleTasks = { early: [], mark: [] }; const registerQueue = { early: [], mark: [] }; export const noVirtual = { virtual: false }; export default class ModelBase { constructor(parent) { this.deps = []; this.children = []; this.childByKey = {}; this.links = []; this.bindings = []; if (parent) { this.parent = parent; this.root = parent.root; } } addShuffleTask(task, stage = 'early') { shuffleTasks[stage].push(task); } addShuffleRegister(item, stage = 'early') { registerQueue[stage].push({ model: this, item }); } downstreamChanged() {} findMatches(keys) { const len = keys.length; let existingMatches = [this]; let matches; let i; for (i = 0; i < len; i += 1) { const key = keys[i]; if (key === '*') { matches = []; existingMatches.forEach(model => { matches.push.apply(matches, model.getValueChildren(model.get())); }); } else { matches = existingMatches.map(model => model.joinKey(key)); } existingMatches = matches; } return matches; } getKeypath(ractive) { if (ractive !== this.ractive && this._link) return this._link.target.getKeypath(ractive); if (!this.keypath) { const parent = this.parent && this.parent.getKeypath(ractive); this.keypath = parent ? `${this.parent.getKeypath(ractive)}.${escapeKey(this.key)}` : escapeKey(this.key); } return this.keypath; } getValueChildren(value) { let children; if (isArray(value)) { children = []; if ('length' in this && this.length !== value.length) { children.push(this.joinKey('length')); } value.forEach((m, i) => { children.push(this.joinKey(i)); }); } else if (isObject(value) || isFunction(value)) { children = objectKeys(value).map(key => this.joinKey(key)); } else if (value != null) { children = []; } const computed = this.computed; if (computed) { children.push.apply(children, objectKeys(computed).map(k => this.joinKey(k))); } return children; } getVirtual(shouldCapture) { const value = this.get(shouldCapture, { virtual: false }); if (isObject(value)) { const result = isArray(value) ? [] : create(null); let keys = objectKeys(value); let i = keys.length; while (i--) { const child = this.childByKey[keys[i]]; if (!child) result[keys[i]] = value[keys[i]]; else if (child._link) result[keys[i]] = child._link.getVirtual(); else result[keys[i]] = child.getVirtual(); } i = this.children.length; while (i--) { const child = this.children[i]; if (!(child.key in result) && child._link) { result[child.key] = child._link.getVirtual(); } } if (this.computed) { keys = objectKeys(this.computed); i = keys.length; while (i--) { result[keys[i]] = this.computed[keys[i]].get(); } } return result; } else return value; } has(key) { if (this._link) return this._link.has(key); const value = this.get(false, noVirtual); if (!value) return false; key = unescapeKey(key); if ((isFunction(value) || isObject(value)) && key in value) return true; let computed = this.computed; if (computed && key in this.computed) return true; computed = this.root.ractive && this.root.ractive.computed; if (computed) { objectKeys(computed).forEach(k => { if (computed[k].pattern && computed[k].pattern.test(this.getKeypath())) return true; }); } return false; } joinAll(keys, opts) { let model = this; for (let i = 0; i < keys.length; i += 1) { if ( opts && opts.lastLink === false && i + 1 === keys.length && model.childByKey[keys[i]] && model.childByKey[keys[i]]._link ) return model.childByKey[keys[i]]; model = model.joinKey(keys[i], opts); } return model; } notifyUpstream(startPath) { let parent = this.parent; const path = startPath || [this.key]; while (parent) { if (parent.patterns) parent.patterns.forEach(o => o.notify(path.slice())); path.unshift(parent.key); parent.links.forEach(l => l.notifiedUpstream(path, this.root)); parent.deps.forEach(d => d.handleChange(path)); parent.downstreamChanged(startPath); parent = parent.parent; } } rebind(next, previous, safe) { if (this._link) { this._link.rebind(next, previous, false); } // tell the deps to move to the new target let i = this.deps.length; while (i--) { if (this.deps[i].rebind) this.deps[i].rebind(next, previous, safe); } i = this.links.length; while (i--) { const link = this.links[i]; // only relink the root of the link tree if (link.owner && link.owner._link) link.relinking(next, safe); } i = this.children.length; while (i--) { const child = this.children[i]; child.rebind(next ? next.joinKey(child.key) : undefined, child, safe); } i = this.bindings.length; while (i--) { this.bindings[i].rebind(next, previous, safe); } } reference() { 'refs' in this ? this.refs++ : (this.refs = 1); } register(dep) { this.deps.push(dep); } registerLink(link) { addToArray(this.links, link); } registerPatternObserver(observer) { (this.patterns || (this.patterns = [])).push(observer); this.register(observer); } registerTwowayBinding(binding) { this.bindings.push(binding); } unreference() { if ('refs' in this) this.refs--; } unregister(dep) { removeFromArray(this.deps, dep); } unregisterLink(link) { removeFromArray(this.links, link); } unregisterPatternObserver(observer) { removeFromArray(this.patterns, observer); this.unregister(observer); } unregisterTwowayBinding(binding) { removeFromArray(this.bindings, binding); } updateFromBindings(cascade) { let i = this.bindings.length; while (i--) { const value = this.bindings[i].getValue(); if (value !== this.value) this.set(value); } // check for one-way bindings if there are no two-ways if (!this.bindings.length) { const oneway = findBoundValue(this.deps); if (oneway && oneway.value !== this.value) this.set(oneway.value); } if (cascade) { this.children.forEach(updateFromBindings); this.links.forEach(updateFromBindings); if (this._link) this._link.updateFromBindings(cascade); } } } // TODO: this may be better handled by overriding `get` on models with a parent that isRoot export function maybeBind(model, value, shouldBind) { if (shouldBind && isFunction(value) && model.parent && model.parent.isRoot) { if (!model.boundValue) { model.boundValue = bind(value._r_unbound || value, model.parent.ractive); } return model.boundValue; } return value; } function updateFromBindings(model) { model.updateFromBindings(true); } export function findBoundValue(list) { let i = list.length; while (i--) { if (list[i].bound) { const owner = list[i].owner; if (owner) { const value = owner.name === 'checked' ? owner.node.checked : owner.node.value; return { value }; } } } } export function fireShuffleTasks(stage) { if (!stage) { fireShuffleTasks('early'); fireShuffleTasks('mark'); } else { const tasks = shuffleTasks[stage]; shuffleTasks[stage] = []; let i = tasks.length; while (i--) tasks[i](); const register = registerQueue[stage]; registerQueue[stage] = []; i = register.length; while (i--) register[i].model.register(register[i].item); } } export function shuffle(model, newIndices, link, unsafe) { model.shuffling = true; let i = newIndices.length; while (i--) { const idx = newIndices[i]; // nothing is actually changing, so move in the index and roll on if (i === idx) { continue; } // rebind the children on i to idx if (i in model.childByKey) model.childByKey[i].rebind( !~idx ? undefined : model.joinKey(idx), model.childByKey[i], !unsafe ); } const upstream = model.source().length !== model.source().value.length; model.links.forEach(l => l.shuffle(newIndices)); if (!link) fireShuffleTasks('early'); i = model.deps.length; while (i--) { if (model.deps[i].shuffle) model.deps[i].shuffle(newIndices); } model[link ? 'marked' : 'mark'](); if (!link) fireShuffleTasks('mark'); if (upstream) model.notifyUpstream(); model.shuffling = false; }
'use strict'; const assert = require('assert'); const mm = require('egg-mock'); const request = require('supertest'); const sleep = require('mz-modules/sleep'); const fs = require('fs'); const path = require('path'); const Application = require('../../lib/application'); const utils = require('../utils'); describe('test/lib/application.test.js', () => { let app; afterEach(mm.restore); describe('create application', () => { it('should throw options.baseDir required', () => { assert.throws(() => { new Application({ baseDir: 1, }); }, /options.baseDir required, and must be a string/); }); it('should throw options.baseDir not exist', () => { assert.throws(() => { new Application({ baseDir: 'not-exist', }); }, /Directory not-exist not exists/); }); it('should throw options.baseDir is not a directory', () => { assert.throws(() => { new Application({ baseDir: __filename, }); }, /is not a directory/); }); }); describe('app start timeout', function() { afterEach(() => app.close()); it('should emit `startTimeout` event', function(done) { app = utils.app('apps/app-start-timeout'); app.once('startTimeout', done); }); }); describe('app.keys', () => { it('should throw when config.keys missing on non-local and non-unittest env', function* () { mm.env('test'); app = utils.app('apps/keys-missing'); yield app.ready(); mm(app.config, 'keys', null); try { app.keys; throw new Error('should not run this'); } catch (err) { assert(err.message === 'Please set config.keys first'); } // make sure app close yield app.close(); }); it('should throw when config.keys missing on unittest env', function* () { mm.env('unittest'); app = utils.app('apps/keys-missing'); yield app.ready(); mm(app.config, 'keys', null); try { app.keys; throw new Error('should not run this'); } catch (err) { assert(err.message === 'Please set config.keys first'); } // make sure app close yield app.close(); }); it('should throw when config.keys missing on local env', function* () { mm.env('local'); app = utils.app('apps/keys-missing'); yield app.ready(); mm(app.config, 'keys', null); try { app.keys; throw new Error('should not run this'); } catch (err) { assert(err.message === 'Please set config.keys first'); } // make sure app close yield app.close(); }); it('should use exists keys', function* () { mm.env('unittest'); app = utils.app('apps/keys-exists'); yield app.ready(); assert(app.keys); assert(app.keys); assert(app.config.keys === 'my keys'); yield app.close(); }); }); describe('handle uncaughtException', () => { let app; before(() => { app = utils.cluster('apps/app-throw'); return app.ready(); }); after(() => app.close()); it('should handle uncaughtException and log it', function* () { yield request(app.callback()) .get('/throw') .expect('foo') .expect(200); yield sleep(1100); const logfile = path.join(utils.getFilepath('apps/app-throw'), 'logs/app-throw/common-error.log'); const body = fs.readFileSync(logfile, 'utf8'); assert(body.includes('ReferenceError: a is not defined (uncaughtException throw')); }); }); describe('warn confused configurations', () => { it('should warn if confused configurations exist', function* () { const app = utils.app('apps/confused-configuration'); yield app.ready(); const logs = fs.readFileSync(utils.getFilepath('apps/confused-configuration/logs/confused-configuration/confused-configuration-web.log'), 'utf8'); assert(logs.match(/Unexpected config key `bodyparser` exists, Please use `bodyParser` instead\./)); assert(logs.match(/Unexpected config key `notFound` exists, Please use `notfound` instead\./)); assert(logs.match(/Unexpected config key `sitefile` exists, Please use `siteFile` instead\./)); assert(logs.match(/Unexpected config key `middlewares` exists, Please use `middleware` instead\./)); assert(logs.match(/Unexpected config key `httpClient` exists, Please use `httpclient` instead\./)); }); }); describe('test on apps/demo', () => { let app; before(() => { app = utils.app('apps/demo'); return app.ready(); }); after(() => app.close()); describe('application.deprecate', () => { it('should get deprecate with namespace egg', function* () { const deprecate = app.deprecate; assert(deprecate._namespace === 'egg'); assert(deprecate === app.deprecate); }); }); describe('curl()', () => { it('should curl success', function* () { const localServer = yield utils.startLocalServer(); const res = yield app.curl(`${localServer}/foo/app`); assert(res.status === 200); }); }); describe('env', () => { it('should return app.config.env', function* () { assert(app.env === app.config.env); }); }); describe('proxy', () => { it('should delegate app.config.proxy', function* () { assert(app.proxy === app.config.proxy); }); }); describe('inspect && toJSON', () => { it('should override koa method', function() { const inspectResult = app.inspect(); const jsonResult = app.toJSON(); assert.deepEqual(inspectResult, jsonResult); assert(inspectResult.env === app.config.env); }); }); describe('class style controller', () => { it('should work with class style controller', () => { return request(app.callback()) .get('/class-controller') .expect('this is bar!') .expect(200); }); }); }); });
'use strict'; angular .module('playlistApp') .controller('PlaylistCtrl', PlaylistCtrl); angular .module('playlistApp') .controller('PlaylistListCtrl', PlaylistListCtrl); function PlaylistCtrl (Playlist, YoutubePlayerService, Queue, $routeParams, $scope, $log) { $scope.playlist = Playlist.query({ id: $routeParams.playlistId }); $scope.playSong = function() { Queue.setQueue([this.song.name, this.song.yt_id]); }; $scope.playAll = function() { var i, _i, _len, _ref; Queue.clearQueue(); _ref = $scope.playlist.songs; for (_i = 0, _len = _ref.length; _i < _len; _i++) { i = _ref[_i]; Queue.addToEndQueue([i.name, i.yt_id]); } $scope.queue = Queue.getQueue(); }; $scope.playShuffled = function() { $scope.playAll(); Queue.shuffleQueue(); $scope.queue = Queue.getQueue(); }; }; function PlaylistListCtrl (PlaylistList, $scope) { // Uses the controller as syntax. var vm = this; vm.playlists = PlaylistList.query(); //$scope.playlists = PlaylistList.query(); };
'use strict'; /** * Module dependencies */ var fiteHubPolicy = require('../policies/fiteHub.server.policy'), fiteHub = require('../controllers/fiteHub.server.controller'); module.exports = function (app) { // FiteHub collection routes app.route('/api/fiteHub').all(fiteHubPolicy.isAllowed) .get(fiteHub.list) .post(fiteHub.create); // Single fiter routes app.route('/api/fiteHub/:fiterId').all(fiteHubPolicy.isAllowed) .get(fiteHub.read) .put(fiteHub.update) .delete(fiteHub.delete); // Finish by binding the fiter middleware app.param('fiterId', fiteHub.fiterByID); };
/* Copyright 2013-2014 appPlant UG Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var LocalNotification = function () { this._defaults = { message: '', title: '', autoCancel: false, badge: 0, id: '0', json: '', repeat: '' }; }; LocalNotification.prototype = { /** * Gibt alle Standardeinstellungen an. * * @return {Object} */ getDefaults: function () { return this._defaults; }, /** * Überschreibt die Standardeinstellungen. * * @param {Object} defaults */ setDefaults: function (newDefaults) { var defaults = this.getDefaults(); for (var key in defaults) { if (newDefaults[key] !== undefined) { defaults[key] = newDefaults[key]; } } }, /** * @private * Merged die Eigenschaften mit den Standardwerten. * * @param {Object} options * @retrun {Object} */ mergeWithDefaults: function (options) { var defaults = this.getDefaults(); for (var key in defaults) { if (options[key] === undefined) { options[key] = defaults[key]; } } return options; }, /** * @private */ applyPlatformSpecificOptions: function () { var defaults = this._defaults; switch (device.platform) { case 'Android': defaults.icon = 'icon'; defaults.smallIcon = null; defaults.ongoing = false; defaults.sound = 'TYPE_NOTIFICATION'; break; case 'iOS': defaults.sound = ''; break; case 'WinCE': case 'Win32NT': defaults.smallImage = null; defaults.image = null; defaults.wideImage = null; }; }, /** * Fügt einen neuen Eintrag zur Registry hinzu. * * @param {Object} options * @return {Number} Die ID der Notification */ add: function (options) { var options = this.mergeWithDefaults(options), callbackFn = null; if (options.id) { options.id = options.id.toString(); } if (options.date === undefined) { options.date = new Date(); } if (typeof options.date == 'object') { options.date = Math.round(options.date.getTime()/1000); } if (['WinCE', 'Win32NT'].indexOf(device.platform)) { callbackFn = function (cmd) { eval(cmd); }; } cordova.exec(callbackFn, null, 'LocalNotification', 'add', [options]); return options.id; }, /** * Entfernt die angegebene Notification. * * @param {String} id */ cancel: function (id) { cordova.exec(null, null, 'LocalNotification', 'cancel', [id.toString()]); }, /** * Entfernt alle registrierten Notifications. */ cancelAll: function () { cordova.exec(null, null, 'LocalNotification', 'cancelAll', []); }, /** * @async * * Retrieves a list with all currently pending notifications. * * @param {Function} callback */ getScheduledIds: function (callback) { cordova.exec(callback, null, 'LocalNotification', 'getScheduledIds', []); }, /** * @async * * Checks wether a notification with an ID is scheduled. * * @param {String} id * @param {Function} callback */ isScheduled: function (id, callback) { cordova.exec(callback, null, 'LocalNotification', 'isScheduled', [id.toString()]); }, /** * Occurs when a notification was added. * * @param {String} id The ID of the notification * @param {String} state Either "foreground" or "background" * @param {String} json A custom (JSON) string */ onadd: function (id, state, json) {}, /** * Occurs when the notification is triggered. * * @param {String} id The ID of the notification * @param {String} state Either "foreground" or "background" * @param {String} json A custom (JSON) string */ ontrigger: function (id, state, json) {}, /** * Fires after the notification was clicked. * * @param {String} id The ID of the notification * @param {String} state Either "foreground" or "background" * @param {String} json A custom (JSON) string */ onclick: function (id, state, json) {}, /** * Fires if the notification was canceled. * * @param {String} id The ID of the notification * @param {String} state Either "foreground" or "background" * @param {String} json A custom (JSON) string */ oncancel: function (id, state, json) {} }; var plugin = new LocalNotification(); document.addEventListener('deviceready', function () { plugin.applyPlatformSpecificOptions(); }, false); module.exports = plugin;
import MediaStates from './app/MediaStates' import SoundPlayer from './app/SoundPlayer' import SoundRecorder from './app/SoundRecorder' export default { MediaStates, SoundPlayer, SoundRecorder }
'use strict'; const events = require('events'); const util = require('util'); const _ = require('lodash'); const UrlMapper = require('../../url-mapper'); const ObjectGroup = require('../object-group'); const consoleTracker = module.exports = new events.EventEmitter(); consoleTracker.buffer = []; function addToConsoleGroup(object) { return ObjectGroup.add('console', object); } function _wrap(agent, level, type, original) { if (original && '__original' in original) { return original; } function writeLog() { const text = util.format.apply(null, arguments); const trace = UrlMapper.makeStackTrace(writeLog); let url; let column; let line; if (trace.length > 0 && trace[0].url) { url = trace[0].url; line = trace[0].lineNumber; column = trace[0].columnNumber; } const message = { source: 'javascript', level: level, text: text, type: type, url: url, line: line, column: column, parameters: _.map(arguments, addToConsoleGroup), stackTrace: trace, }; consoleTracker.buffer.push(message); consoleTracker.emit('message', message); if (typeof original === 'function') { return original.apply(console, arguments); } } writeLog.__original = original; return writeLog; } function _unwrap(obj, field) { const current = obj[field]; if (typeof current === 'function' && typeof current.__original === 'function') { obj[field] = current.__original; } } consoleTracker.clearMessages = function clearMessages() { consoleTracker.buffer = []; }; consoleTracker.enable = function enable() { /* eslint no-console: 0 */ console.dir = _wrap(this, 'log', 'dir', console.dir); console.dirxml = _wrap(this, 'log', 'dirxml', console.dirxml); console.error = _wrap(this, 'error', 'log', console.error); console.info = _wrap(this, 'info', 'log', console.info); console.log = _wrap(this, 'log', 'log', console.log); console.table = _wrap(this, 'log', 'table', console.table); console.trace = _wrap(this, 'log', 'trace', console.trace); console.warn = _wrap(this, 'warning', 'log', console.warn); }; consoleTracker.disable = function disable() { _unwrap(console, 'dir'); _unwrap(console, 'dirxml'); _unwrap(console, 'error'); _unwrap(console, 'info'); _unwrap(console, 'log'); _unwrap(console, 'table'); _unwrap(console, 'trace'); _unwrap(console, 'warn'); };
/*! * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. */ // Too much stuff can go wrong with during call cleanup, so it's really helpful // to log what it's doing /* eslint-disable no-console */ import {Call} from '@ciscospark/plugin-phone'; import sinon from '@ciscospark/test-helper-sinon'; import {maxWaitForPromise} from '@ciscospark/test-helper-mocha'; beforeEach(() => { sinon.spy(Call, 'make'); }); afterEach('end all calls', function () { if (!Call.make.restore) { return Promise.resolve(); } return Promise.resolve() .then(() => { console.log('ending all calls started by this test'); this.timeout(30000); const promises = Call.make.returnValues && Call.make.returnValues.map((c) => { console.log(`ending call ${c.internalCallId}`); if (c.spark.canAuthorize && c.spark.internal.device.url) { // We need to stop listening to events, otherwise this function gets // weird, unexplained errors on nextTick. c.off(); return maxWaitForPromise(2000, c.hangup()) .then(() => console.log(`ended call ${c.internalCallId}`)) .catch((reason) => console.warn(reason.toString())); } console.log(`can't end call ${c.internalCallId}, so attempting to brick it`); return maxWaitForPromise(2000, c.cleanup()); }); Call.make.restore(); return maxWaitForPromise(15000, Promise.all(promises)) .then(() => console.log('done ending calls')) .catch((reason) => console.warn(reason.stack || reason.toString())); }) .catch((err) => { console.warn('something went wrong in the phone plugin afterEach hook'); console.warn(err); }); });
/*jslint node: true */ /*global angular */ 'use strict'; angular.module('ct.clientCommon') .constant('RESOURCE_CONST', (function () { var model = ['path', 'type', 'storage', 'factory'], // related to ModelProp schemaModel = ['schema', 'schemaId', 'resource'].concat(model), // related to Schema & ModelProp basicStore = ['objId', 'flags', 'storage', 'next'], stdArgs = schemaModel.concat(basicStore, ['subObj', 'customArgs']), processRead = 0x01, // process argument during read processStore = 0x02, // process argument during store toProcess = function (processArg, toCheck) { var process = true; if (processArg && toCheck) { process = ((processArg & toCheck) !== 0); } return process; }; return { STORE_LIST: 'list', STORE_OBJ: 'obj', PROCESS_READ: processRead, PROCESS_STORE: processStore, PROCESS_READ_STORE: (processRead | processStore), PROCESS_FOR_READ: function (toCheck) { return toProcess(processRead, toCheck); }, PROCESS_FOR_STORE: function (toCheck) { return toProcess(processStore, toCheck); }, MODEL_ARGS: model, SCHEMA_MODEL_ARGS: schemaModel, BASIC_STORE_ARGS: basicStore, STD_ARGS: stdArgs, QUERY_OR: '$or', // performs a logical OR operation on an array of two or more <expressions> and selects the documents that satisfy at least one of the <expressions> QUERY_AND: '$and', // performs a logical AND operation on an array of two or more expressions (e.g. <expression1>, <expression2>, etc.) and selects the documents that satisfy all the expressions QUERY_NOT: '$not', // performs a logical NOT operation on the specified <operator-expression> and selects the documents that do not match the <operator-expression> QUERY_NOR: '$nor', // performs a logical NOR operation on an array of one or more query expression and selects the documents that fail all the query expressions QUERY_OR_JOIN: '|', // multi field OR QUERY_AND_JOIN: '+', // multi field AND QUERY_COMMA_JOIN: ',', // multi field comma join QUERY_NE: '!', // inverse i.e. not equal QUERY_EQ: '=', // equal QUERY_GT: '>', // greater than QUERY_LT: '<', // less than QUERY_GTE: '>=', // greater than or equal QUERY_LTE: '<=', // less than or equal QUERY_BLANK: '~', // blank QUERY_NBLANK: '!~' // not blank }; }())) .factory('resourceFactory', resourceFactory); /* Manually Identify Dependencies https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y091 */ resourceFactory.$inject = ['$resource', '$filter', '$injector', 'baseURL', 'storeFactory', 'miscUtilFactory', 'pagerFactory', 'compareFactory', 'standardFactoryFactory', 'resourceListFactory', 'queryFactory', 'consoleService', 'SCHEMA_CONST', 'RESOURCE_CONST']; function resourceFactory ($resource, $filter, $injector, baseURL, storeFactory, miscUtilFactory, pagerFactory, compareFactory, standardFactoryFactory, resourceListFactory, queryFactory, consoleService, SCHEMA_CONST, RESOURCE_CONST) { // Bindable Members Up Top, https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md#style-y033 var factory = { NAME: 'resourceFactory', createResources: createResources, getStoreResource: getStoreResource, storeServerRsp: storeServerRsp, storeSubDoc: storeSubDoc, standardiseArgs: standardiseArgs, getStandardArgsObject: getStandardArgsObject, checkArgs: checkArgs, arrayiseArguments: arrayiseArguments, findInStandardArgs: findInStandardArgs, findAllInStandardArgs: findAllInStandardArgs, addResourcesToArgs: addResourcesToArgs, standardiseModelArgs: standardiseModelArgs, getObjectInfo: getObjectInfo, removeSchemaPathTypeArgs: removeSchemaPathTypeArgs, copyBasicStorageArgs: copyBasicStorageArgs, removeBasicStorageArgs: removeBasicStorageArgs, getServerRsp: getServerRsp, extendFactory: extendFactory }, modelArgsMap = {}, StandardArgsInfo = [ // arg info for getStandardArgsObject() { name: 'factory', test: angular.isString, dflt: undefined }, { name: 'resource', test: angular.isString, dflt: undefined }, { name: 'subObj', test: angular.isArray, dflt: undefined }, { name: 'schema', test: angular.isObject, dflt: {} }, { name: 'flags', test: angular.isNumber, dflt: storeFactory.NOFLAG }, { name: 'next', test: angular.isFunction, dflt: undefined }, { name: 'customArgs', test: angular.isObject, dflt: {} } ], con; // console logger if (consoleService.isEnabled(factory.NAME)) { con = consoleService.getLogger(factory.NAME); } // add additional methods to factory extendFactory(factory, standardFactoryFactory); extendFactory(factory, resourceListFactory); extendFactory(factory, queryFactory); RESOURCE_CONST.MODEL_ARGS.forEach(function (prop) { switch (prop) { case 'path': modelArgsMap[prop] = 'getModelName'; // Schema object function to get value break; case 'type': modelArgsMap[prop] = 'getType'; // Schema object function to get value break; case 'storage': modelArgsMap[prop] = 'getStorageType'; // Schema object function to get value break; case 'factory': modelArgsMap[prop] = 'getModelFactory'; // Schema object function to get value break; } }); // need the return here so that object prototype functions are added return factory; // need to return factory as end so that object prototype functions are added /* function implementation -------------------------- */ /** * Extend a factory with poprerties from another factory * @param {object} dst Factory to extend * @param {object} src Factory to get poprerties from * @param {Array} addlist List of properties to add to dst * @param {Array} exlist List of properties to not add to dst * @returns {object} Destination factory */ function extendFactory (dst, src, addlist, exlist) { if (addlist) { addlist = addlist.slice(); } else { addlist = Object.getOwnPropertyNames(src); } if (exlist) { exlist = exlist.slice(); } else { exlist = []; } exlist.push('NAME'); // never copy name // remove excluded entries from add list exlist.forEach(function (prop) { var idx = addlist.findIndex(function (element) { return (element === prop); }); if (idx >= 0) { addlist.splice(idx, 1); } }); // copy add list entries addlist.forEach(function (prop) { if (miscUtilFactory.hasProperty(src, prop)) { dst[prop] = src[prop]; } }); return dst; } /** * Create resources * @param {object} options Options specifying ids & types * @param {object} resources Object to add the new resources to * @returns {object} Object updateed with the new resources */ function createResources (options, resources) { var srcId, result, args = standardiseArgs(options); if (!resources) { resources = {}; } args.objId.forEach(function (id) { switch (args.storage) { case RESOURCE_CONST.STORE_OBJ: if (!srcId) { result = args.factory.newObj(id, storeFactory.CREATE_INIT); } else { result = args.factory.duplicateObj(id, srcId, storeFactory.OVERWRITE); } break; case RESOURCE_CONST.STORE_LIST: if (!srcId) { result = args.factory.newList(id, { title: id, flags: storeFactory.CREATE_INIT, resource: args.resource }); } else { result = args.factory.duplicateList(id, srcId, storeFactory.OVERWRITE); } break; default: result = undefined; } if (result) { resources[id] = result; } if (!srcId) { srcId = id; } }); if (args.subObj) { args.subObj.forEach(function (subObj) { createResources(subObj, resources); }); } return resources; } /** * Get a store object * @param {object} options process arguments object with following properties: * @param {string} objId id of object to get * @param {number} flags storefactory flags * @return {object} ResourceList or object */ function getStoreResource (options) { var result, args = standardiseArgs(options); if (args.storage === RESOURCE_CONST.STORE_LIST) { result = args.factory.getList(args.objId, args.flags); } else if (args.storage === RESOURCE_CONST.STORE_OBJ) { result = args.factory.getObj(args.objId, args.flags); } return result; } /** * Store a response from the server * @param {object} response Server response * @param {object} args process arguments object with following properties: * @param {string|Array} objId id/array of ids of object to save response data to * @param {string} storage save as list or object flag; STORE_LIST, STORE_OBJ, default depends on response * @param {string} path path within response object to object to store * @param {string} type object type, @see SCHEMA_CONST.FIELD_TYPES * @param {object} schema Schema to use to retrieve object path & type * @param {number} schemaId Schema id to use to retrieve object path & type * @param {number} flags storefactory flags * @param {object|string} factory factory (or factory name) to handle saving of objects/lists * @param {function} next function to call after processing * @param {Object|array} subObj additional set(s) of arguments for sub objects * @return {object} ResourceList or object */ function storeServerRsp (response, args) { if (!RESOURCE_CONST.PROCESS_FOR_STORE(args.processArg)) { // arg only processed during read, so ignore return undefined; } // else process for store var stdArgs = standardiseArgs(args, args.parent), factory = stdArgs.factory, idArray = stdArgs.objId, resp, asList, i, toSave = getObjectInfo(response, stdArgs).object; // store sub objects first if (args.subObj) { miscUtilFactory.toArray(args.subObj).forEach(function (subObj) { storeSubDoc(response, subObj, stdArgs); }); } resp = toSave; // default result is raw object if (idArray.length) { if (stdArgs.storage === RESOURCE_CONST.STORE_LIST) { asList = true; } else if (stdArgs.storage === RESOURCE_CONST.STORE_OBJ) { asList = false; } else { asList = Array.isArray(toSave); } if (asList) { // process a query response if (toSave) { resp = factory.setList(idArray[0], toSave, stdArgs.flags); } else { resp = factory.initList(idArray[0], stdArgs.flags); } } else { // process a get response if (toSave) { resp = factory.setObj(idArray[0], toSave, stdArgs.flags); } else { resp = factory.initObj(idArray[0], stdArgs.flags); } } if (con) { con.debug('storeServerRsp: ' + idArray[0]); } // if multiple objId's secondary ids are set to copies for (i = 1; i < idArray.length; ++i) { if (asList) { factory.duplicateList(idArray[i], idArray[0], storeFactory.EXISTING, { list: true // just duplicate list }); } else { factory.duplicateObj(idArray[i], idArray[0], storeFactory.OVERWRITE); } } } if (stdArgs.next) { stdArgs.next(resp); } return resp; } /** * Get the object to save based on the provided path * @param {object} response Response object * @param {string} path Path to required object * @return {object} object to save */ function getObjectInfo (response, args) { var paths = [], object = response, parent, property; if (args.path) { paths.push(args.path); } for (parent = args.parent; parent && parent.path; parent = parent.parent) { paths.unshift(parent.path); } // drill down to get item to save paths.forEach(function (path) { if (object) { parent = object; property = path; object = parent[property]; } }); return { object: object, // object to save parent: parent, // parent object property: property }; // parent object property } /** * Process a populated sub document, by copying the data to a new factory object and * transforming the original to ObjectIds. * @param {object} response Server response * @param {object} args process arguments object, @see storeServerRsp() for details * @param {object} parent Object's parent */ function storeSubDoc(response, args, parent) { if (!RESOURCE_CONST.PROCESS_FOR_STORE(args.processArg)) { // arg only processed during read, so ignore return undefined; } // else process for store var stdArgs = standardiseArgs(args, parent), resp, list, toSaveInfo = getObjectInfo(response, stdArgs), toSave = toSaveInfo.object; // store subdoc, resp is ResourceList or object resp = storeServerRsp(response, stdArgs); // update response with expected response type i.e. ObjectIds if (resp) { if (SCHEMA_CONST.FIELD_TYPES.IS_OBJECTID(stdArgs.type)) { // field is objectId, so was saved as object toSaveInfo.parent[toSaveInfo.property] = resp._id; } else if (SCHEMA_CONST.FIELD_TYPES.IS_OBJECTID_ARRAY(stdArgs.type)) { // field is an array of objectId if (Array.isArray(toSave)) { if (resp.isResourceList) { list = resp.list; // its a ResourceList } else { list = resp; // should be an raw array } for (var i = 0; i < toSave.length; ++i) { toSave[i] = list[i]._id; } } } } return resp; } /** * Standardise a server response argument object * @param {object} args process arguments object, @see storeServerRsp() for details * @param {object} parent Object's parent * @return {object} arguments object */ function standardiseArgs (args, parent) { var stdArgs = angular.copy(args); if (stdArgs.objId) { stdArgs.objId = miscUtilFactory.toArray(stdArgs.objId); } else { stdArgs.objId = []; } stdArgs.flags = (args.flags ? args.flags : storeFactory.NOFLAG); stdArgs.parent = parent; copySchemaModelArgs( standardiseModelArgs(copySchemaModelArgs(args), false /*no copy*/), stdArgs); if (typeof args.factory === 'string') { // get factory instance from injector stdArgs.factory = $injector.get(args.factory); } if (stdArgs.subObj) { if (Array.isArray(stdArgs.subObj)) { for (var i = 0; i < stdArgs.subObj.length; ++i) { stdArgs.subObj[i] = standardiseArgs(stdArgs.subObj[i], stdArgs); } } else { stdArgs.subObj = [standardiseArgs(stdArgs.subObj, stdArgs)]; } } return stdArgs; } /** * Return a standard args object * @param {string|array} objId Id(s) to use for storage * @param {string} factory Factory name * @param {string} resource Name of factory resource to access resources on server * @param {array} subObj Sub-objects * @param {object} schema Schema object * @param {number} flags storeFactory flags * @param {function} next Function to call following completion * @param {object} customArgs Custom properties * @returns {object} Standard args object * * NOTE 1: make sure to update StandardArgsInfo on any change to function prototype. * 2: the objIdargument must be passed */ function getStandardArgsObject(objId, factory, resource, subObj, schema, flags, next, customArgs) { var args = intCheckStandardArgsObjectArgs(arrayiseArguments(arguments, 1)); // exclude objId return { objId: objId, factory: args.factory, resource: args.resource, schema: args.schema.schema, schemaId: args.schema.schemaId, //type/path/storage/factory: can be retrieved using schema & schemaId subObj: args.subObj, flags: args.flags, next: args.next, customArgs: args.customArgs }; } /** * Check arguemnts for getRspOptionsObject() making sure args are correctly positioned * @param {object} funcArguments Argument object for original function * @return {object} checked argument object */ function intCheckStandardArgsObjectArgs(funcArguments) { return checkArgs(StandardArgsInfo, funcArguments); } /** * Check arguments for correct positioning in function call * @param {Array} argsInfo Array of argument info objects: * { name: <arg name>, test: <predicate validity test>, * dflt: <default value> } * @param {object|Array} funcArguments Argument object for original function or an array of arguments * @return {object} checked argument object */ function checkArgs(argsInfo, funcArguments) { var args = (Array.isArray(funcArguments) ? funcArguments.slice() : arrayiseArguments(funcArguments)), arg, checked = {}; for (var i = 0, ll = argsInfo.length; i < ll; ++i) { arg = argsInfo[i]; if (!arg.test(args[i])) { if (args.length < ll) { // num of args < expected args.splice(i, 0, arg.dflt); // insert argument default value } else { if (args[i] !== undefined) { // right shift arguments for (var j = args.length - 1; j > i; --j) { args[j] = args[j - 1]; } } args[i] = arg.dflt; // set argument to default value } } checked[arg.name] = args[i]; } return checked; } /** * * Convert a function arguments object to an array * @param {object} funcArguments Argument object for original function * @param {number} start Argument indexto start from * @return {Array} argument array */ function arrayiseArguments(funcArguments, start) { var array; if (start === undefined) { start = 0; } if (start >= funcArguments.length) { array = []; } else if (funcArguments.length === 1) { array = [funcArguments[0]]; } else { array = Array.prototype.slice.call(funcArguments, start); } return array; } /** * Find an arg object within a StandardArgs object * @param {object} stdArgs StandardArgs object to traverse * @param {function} callback Function to test arg objects * @return {object} arguments object */ function findInStandardArgs (stdArgs, callback) { var arg; if (callback(stdArgs)) { arg = stdArgs; } if (!arg && stdArgs.subObj) { for (var i = 0; !arg && (i < stdArgs.subObj.length); ++i) { arg = findInStandardArgs(stdArgs.subObj[i], callback); } } return arg; } /** * Find all arg objects within a StandardArgs object * @param {object} stdArgs StandardArgs object to traverse * @param {function} callback Function to test arg objects * @param {Array} args Array to add matching arg objects to * @return {Array} Array of matching arg objects */ function findAllInStandardArgs (stdArgs, callback, args) { if (!args) { args = []; } if (callback(stdArgs)) { args.push(stdArgs); } if (stdArgs.subObj) { stdArgs.subObj.forEach(function (sub) { findAllInStandardArgs(sub, callback, args); }); } return args; } /** * Add resources required by Schema object * @param {object} args Args object to add to * @return {object} arguments object */ function addResourcesToArgs (args) { if (!args.injector) { /* need to pass run stage injector to Schema object as since it is created during the config stage it only has access to the config stage injector (only providers and constants accessible) */ args.injector = $injector; } if (!args.findInStandardArgs) { args.findInStandardArgs = findInStandardArgs; } return args; } /** * Standardise a server response argument object * @param {object} args process arguments object with following properties: * @see storeServerRsp() * @return {object} arguments object */ function standardiseModelArgs (args, makeCopy) { makeCopy = ((makeCopy === undefined) ? true : makeCopy); var stdArgs = args; if (makeCopy) { stdArgs = copySchemaModelArgs(args); } if (stdArgs.schema && (typeof stdArgs.schemaId === 'number') && (stdArgs.schemaId >= 0)) { // if not explicitly set retrieve using schema & schemaId RESOURCE_CONST.MODEL_ARGS.forEach(function (prop) { if (!stdArgs[prop]) { stdArgs[prop] = stdArgs.schema[modelArgsMap[prop]](stdArgs.schemaId); } }); //- if (!stdArgs.path) { //- // path not explicitly provided, retrieve from schema & schemaId //- stdArgs.path = stdArgs.schema.getModelName(stdArgs.schemaId); //- } //- if (!stdArgs.type) { //- // path not explicitly provided, retrieve from schema & schemaId //- stdArgs.type = stdArgs.schema.getType(stdArgs.schemaId); } return stdArgs; } /** * Copy the standard Schema/ModelProp arguments * @param {Array} list list of properties to copy * @param {object} args process arguments object to copy from * @param {object} to process arguments object to copy to * @return {object} arguments object */ function copyArgs (list, args, to) { if (!to) { to = {}; } return miscUtilFactory.copyProperties(args, to, list); } /** * Copy the standard Schema/ModelProp arguments * @param {object} args process arguments object to copy from * @param {object} to process arguments object to copy to * @return {object} arguments object */ function copySchemaModelArgs (args, to) { return copyArgs(RESOURCE_CONST.SCHEMA_MODEL_ARGS, args, to); } /** * Remove the standard Schema/ModelProp arguments * @param {object} args process arguments object to remove from * @return {object} arguments object */ function removeSchemaPathTypeArgs (args) { return miscUtilFactory.removeProperties(args, RESOURCE_CONST.SCHEMA_MODEL_ARGS); } /** * Copy the basic storage arguments * @param {object} args process arguments object to copy from * @param {object} to process arguments object to copy to * @return {object} arguments object */ function copyBasicStorageArgs (args, to) { return copyArgs(RESOURCE_CONST.BASIC_STORE_ARGS, args, to); } /** * Remove the standard Schema/ModelProp arguments * @param {object} args process arguments object to remove from * @return {object} arguments object */ function removeBasicStorageArgs (args) { return miscUtilFactory.removeProperties(args, RESOURCE_CONST.BASIC_STORE_ARGS); } /** * Get a stored response from the server * @param {object} args process arguments object with following properties: * @see storeServerRsp() * @return {object} ResourceList or object */ function getServerRsp (args) { var stdArgs = standardiseArgs(args), factory = stdArgs.factory, idArray = stdArgs.objId, resp = [], asList = true, asObj = true, read; if (stdArgs.storage === RESOURCE_CONST.STORE_LIST) { asObj = false; } else if (stdArgs.storage === RESOURCE_CONST.STORE_OBJ) { asList = false; } // else no type specified so try both if (asList) { idArray.forEach(function (id) { read = factory.getList(id, stdArgs.flags); if (read) { resp.push(read); } }); } if (asObj) { idArray.forEach(function (id) { read = factory.getObj(id, stdArgs.flags); if (read) { resp.push(read); } }); } if (stdArgs.next) { stdArgs.next(resp); } return resp; } }
import { LitElement, html, css } from 'lit-element' import { repeat } from 'lit-html/directives/repeat.js' import { store } from '../../reduxStore.js' import { connect } from 'pwa-helpers/connect-mixin.js' import './timeline-animation.js' import { getAnimation, getAnimations, getLive } from '../../selectors/index.js' import { SCENE_TYPE_STATIC } from '../../constants/timeline.js' import { setSceneOnTimeline } from '../../actions/index.js' import '@material/mwc-icon/mwc-icon.js' /* * Handle a scene in a timeline */ class TimelineScene extends connect(store)(LitElement) { static get properties() { return { timelineScene: { type: Object }, progress: { type: Number }, // All animations that exist in luminave, not only the ones assigned to the scene animations: { type: Array }, live: { type: Boolean } } } _stateChanged(state) { // @TODO: timeline-manager should update all it's children when the animations in the state are changing if (!Object.is(this.animations, getAnimations(state))) { this.animations = getAnimations(state) this.requestUpdate() } this.live = getLive(state) } animationEnded(e) { // @TODO: Do not reset the scene if one of it's animations is done // every anmation has to have it's own progress and type if (this.timelineScene.type === SCENE_TYPE_STATIC) { const scene = { sceneId: this.timelineScene.sceneId, timelineSceneId: this.timelineScene.timelineSceneId, started: new Date().getTime() } store.dispatch(setSceneOnTimeline(scene)) } } /* * Check if there is no animation assigned to the scene to inform the user that * they should add an animation in order to see something */ noAnimationInScene(animations) { if (animations === undefined || animations.length === 0) { return html`<mwc-icon title="No animation is assigned to this Scene">error</mwc-icon>` } return html`` } static get styles() { return css` mwc-icon { color: var(--default-warning-color); } ` } render() { const { timelineScene, progress, live } = this return html` <style> h3 { font-size: 1em; font-weight: normal; margin: 0; } </style> <div> <h3>${timelineScene.scene.name}</h3> ${this.noAnimationInScene(timelineScene.scene.animations)} ${repeat(timelineScene.scene.animations, animationId => html` <div> <timeline-animation .animation="${getAnimation(store.getState(), { animationId })}" .fixtureIds=${timelineScene.scene.fixtures} .started=${timelineScene.started} .sceneName=${timelineScene.scene.name} .showMeta=${!live} progress=${progress} @animation-ended=${e => this.animationEnded(e)} > </timeline-animation> </div> `)} </div> ` } } customElements.define('timeline-scene', TimelineScene)
/* @property id {String} The id by which you'll reference this expression. @property caption {String} The alt text that will appear for this image. Primarily used for accessability. @property src {String} The path to the image, relative to the `public` directory. Example: { id: 'steven--jumping', caption: 'Steven Universe jumping', src: 'images/expressions/steven--jumping.png' } */ export default [{ id: 'bitsy-neutral', caption: 'Bitsy', src: 'theater/characters/bitsy/neutral.png' }, { id: 'bitsy-happy', caption: 'Bitsy happy', src: 'theater/characters/bitsy/happy.png' }, { id: 'bitsy-laughing', caption: 'Bitsy laughing', src: 'theater/characters/bitsy/laughing.png' }, { id: 'bitsy-bored', caption: 'Bitsy bored', src: 'theater/characters/bitsy/bored.png' }, { id: 'bitsy-angry', caption: 'Bitsy angry', src: 'theater/characters/bitsy/angry.png' }, { id: 'bitsy-sad', caption: 'Bitsy sad', src: 'theater/characters/bitsy/sad.png' }, { id: 'bitsy-blush', caption: 'Bitsy blush', src: 'theater/characters/bitsy/blush.png' }, { id: 'bitsy-embarrassed', caption: 'Bitsy embarrassed', src: 'theater/characters/bitsy/embarrassed.png' }, { id: 'bitsy-panic', caption: 'Bitsy panic', src: 'theater/characters/bitsy/panic.png' }, { id: 'bitsy-surprised', caption: 'Bitsy surprised', src: 'theater/characters/bitsy/surprised.png' }, { id: 'emma-neutral', caption: 'Emma', src: 'theater/characters/emma/neutral.png' }, { id: 'emma-happy', caption: 'Emma happy', src: 'theater/characters/emma/happy.png' }, { id: 'emma-laughing', caption: 'Emma laughing', src: 'theater/characters/emma/laughing.png' }, { id: 'emma-bored', caption: 'Emma bored', src: 'theater/characters/emma/bored.png' }, { id: 'emma-angry', caption: 'Emma angry', src: 'theater/characters/emma/angry.png' }, { id: 'emma-sad', caption: 'Emma sad', src: 'theater/characters/emma/sad.png' }, { id: 'emma-embarrassed', caption: 'Emma embarrassed', src: 'theater/characters/emma/embarrassed.png' }, { id: 'emma-panic', caption: 'Emma panic', src: 'theater/characters/emma/panic.png' }, { id: 'emma-surprised', caption: 'Emma surprised', src: 'theater/characters/emma/surprised.png' }];
'use strict'; import Settings from 'settings'; var settings = new Settings(); window.settings = settings; // TODO: automatically save settings to localStorage settings.observe('*', (prop, oldVal, newVal) => console.log(prop, oldVal, newVal)); export default settings;
/** @module ember-data */ import Ember from 'ember'; import Model from 'ember-data/model'; import { assert, warn, runInDebug } from "ember-data/-private/debug"; import _normalizeLink from "ember-data/-private/system/normalize-link"; import normalizeModelName from "ember-data/-private/system/normalize-model-name"; import { InvalidError } from 'ember-data/adapters/errors'; import { promiseArray, promiseObject } from "ember-data/-private/system/promise-proxies"; import { _bind, _guard, _objectIsAlive } from "ember-data/-private/system/store/common"; import { normalizeResponseHelper } from "ember-data/-private/system/store/serializer-response"; import { serializerForAdapter } from "ember-data/-private/system/store/serializers"; import { _find, _findMany, _findHasMany, _findBelongsTo, _findAll, _query as _query3, _queryRecord } from "ember-data/-private/system/store/finders"; import { getOwner } from 'ember-data/-private/utils'; import coerceId from "ember-data/-private/system/coerce-id"; import RecordArrayManager from "ember-data/-private/system/record-array-manager"; import ContainerInstanceCache from 'ember-data/-private/system/store/container-instance-cache'; import InternalModel from "ember-data/-private/system/model/internal-model"; import EmptyObject from "ember-data/-private/system/empty-object"; import isEnabled from 'ember-data/-private/features'; var badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number'; export { badIdFormatAssertion }; var Backburner = Ember._Backburner; var Map = Ember.Map; //Get the materialized model from the internalModel/promise that returns //an internal model and return it in a promiseObject. Useful for returning //from find methods function promiseRecord(internalModel, label) { var toReturn = internalModel.then(function (model) { return model.getRecord(); }); return promiseObject(toReturn, label); } var get = Ember.get; var set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var isPresent = Ember.isPresent; var Promise = Ember.RSVP.Promise; var copy = Ember.copy; var Store; var Service = Ember.Service; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +internalModel+ means a record internalModel object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a DS.Model. /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```app/services/store.js import DS from 'ember-data'; export default DS.Store.extend({ }); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `findRecord()` method: ```javascript store.findRecord('person', 123).then(function (person) { }); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below: [createRecord](#method_createRecord) is used for creating new records on the client side. This will return a new record in the `created.uncommitted` state. In order to persist this record to the backend you will need to call `record.save()`. [push](#method_push) is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the `loaded.saved` state. The primary use-case for `store#push` is to notify Ember Data about record updates (full or partial) that happen outside of the normal adapter methods (for example [SSE](http://dev.w3.org/html5/eventsource/) or [Web Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). [pushPayload](#method_pushPayload) is a convenience wrapper for `store#push` that will deserialize payloads if the Serializer implements a `pushPayload` method. Note: When creating a new record using any of the above methods Ember Data will update `DS.RecordArray`s such as those returned by `store#peekAll()`, `store#findAll()` or `store#filter()`. This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values. @class Store @namespace DS @extends Ember.Service */ Store = Service.extend({ /** @method init @private */ init: function init() { this._super.apply(this, arguments); this._backburner = new Backburner(['normalizeRelationships', 'syncRelationships', 'finished']); // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = RecordArrayManager.create({ store: this }); this._pendingSave = []; this._instanceCache = new ContainerInstanceCache(getOwner(this)); //Used to keep track of all the find requests that need to be coalesced this._pendingFetch = Map.create(); }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `app/adapters/custom.js` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.JSONAPIAdapter @type {(DS.Adapter|String)} */ adapter: '-json-api', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function serialize(record, options) { var snapshot = record._internalModel.createSnapshot(); return snapshot.serialize(options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @return DS.Adapter */ defaultAdapter: Ember.computed('adapter', function () { var adapter = get(this, 'adapter'); assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name', typeof adapter === 'string'); adapter = this.retrieveManagedInstance('adapter', adapter); return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of a `Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` To create a new instance of a `Post` that has a relationship with a `User` record: ```js var user = this.store.peekRecord('user', 1); store.createRecord('post', { title: "Rails is omakase", user: user }); ``` @method createRecord @param {String} modelName @param {Object} inputProperties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function createRecord(modelName, inputProperties) { assert("You need to pass a model name to the store's createRecord method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var properties = copy(inputProperties) || new EmptyObject(); // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(modelName, properties); } // Coerce ID to a string properties.id = coerceId(properties.id); var internalModel = this.buildInternalModel(typeClass, properties.id); var record = internalModel.getRecord(); // Move the record out of its initial `empty` state into // the `loaded` state. internalModel.loadedData(); // Set the properties specified on the record. record.setProperties(properties); internalModel.eachRelationship(function (key, descriptor) { internalModel._relationships.get(key).setHasData(true); }); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} modelName @param {Object} properties from the new record @return {String} if the adapter can generate one, an ID */ _generateId: function _generateId(modelName, properties) { var adapter = this.adapterFor(modelName); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this, modelName, properties); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function deleteRecord(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.findRecord('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function unloadRecord(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** @method find @param {String} modelName @param {String|Integer} id @param {Object} options @return {Promise} promise @private */ find: function find(modelName, id, options) { // The default `model` hook in Ember.Route calls `find(modelName, id)`, // that's why we have to keep this method around even though `findRecord` is // the public way to get a record by modelName and id. if (arguments.length === 1) { assert('Using store.find(type) has been removed. Use store.findAll(type) to retrieve all records for a given type.'); } if (Ember.typeOf(id) === 'object') { assert('Calling store.find() with a query object is no longer supported. Use store.query() instead.'); } if (options) { assert('Calling store.find(type, id, { preload: preload }) is no longer supported. Use store.findRecord(type, id, { preload: preload }) instead.'); } assert("You need to pass the model name and id to the store's find method", arguments.length === 2); assert("You cannot pass `" + Ember.inspect(id) + "` as id to the store's find method", Ember.typeOf(id) === 'string' || Ember.typeOf(id) === 'number'); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); return this.findRecord(modelName, id); }, /** This method returns a record for a given type and id combination. The `findRecord` method will always resolve its promise with the same object for a given type and `id`. The `findRecord` method will always return a **promise** that will be resolved with the record. Example ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id); } }); ``` If the record is not yet available, the store will ask the adapter's `find` method to find the necessary data. If the record is already present in the store, it depends on the reload behavior _when_ the returned promise resolves. ### Reloading The reload behavior is configured either via the passed `options` hash or the result of the adapter's `shouldReloadRecord`. If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if the requested record is already in the store: ```js store.push({ data: { id: 1, type: 'post', revision: 1 } }); // adapter#findRecord resolves with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] store.findRecord('post', 1, { reload: true }).then(function(post) { post.get("revision"); // 2 }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with the cached version in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`, then a background reload is started, which updates the records' data, once it is available: ```js // app/adapters/post.js import ApplicationAdapter from "./application"; export default ApplicationAdapter.extend({ shouldReloadRecord(store, snapshot) { return false; }, shouldBackgroundReloadRecord(store, snapshot) { return true; } }); // ... store.push({ data: { id: 1, type: 'post', revision: 1 } }); var blogPost = store.findRecord('post', 1).then(function(post) { post.get('revision'); // 1 }); // later, once adapter#findRecord resolved with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] blogPost.get('revision'); // 2 ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findRecord`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findRecord('post', params.post_id, { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findRecord: function(store, type, id, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekRecord](#method_peekRecord) to get the cached version of a record. @since 1.13.0 @method findRecord @param {String} modelName @param {(String|Integer)} id @param {Object} options @return {Promise} promise */ findRecord: function findRecord(modelName, id, options) { assert("You need to pass a model name to the store's findRecord method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); assert(badIdFormatAssertion, typeof id === 'string' && id.length > 0 || typeof id === 'number' && !isNaN(id)); var internalModel = this._internalModelForId(modelName, id); options = options || {}; if (!this.hasRecordForId(modelName, id)) { return this._findByInternalModel(internalModel, options); } var fetchedInternalModel = this._findRecord(internalModel, options); return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); }, _findRecord: function _findRecord(internalModel, options) { // Refetch if the reload option is passed if (options.reload) { return this.scheduleFetch(internalModel, options); } var snapshot = internalModel.createSnapshot(options); var typeClass = internalModel.type; var adapter = this.adapterFor(typeClass.modelName); // Refetch the record if the adapter thinks the record is stale if (adapter.shouldReloadRecord(this, snapshot)) { return this.scheduleFetch(internalModel, options); } if (options.backgroundReload === false) { return Promise.resolve(internalModel); } // Trigger the background refetch if backgroundReload option is passed if (options.backgroundReload || adapter.shouldBackgroundReloadRecord(this, snapshot)) { this.scheduleFetch(internalModel, options); } // Return the cached record return Promise.resolve(internalModel); }, _findByInternalModel: function _findByInternalModel(internalModel, options) { options = options || {}; if (options.preload) { internalModel._preloadData(options.preload); } var fetchedInternalModel = this._findEmptyInternalModel(internalModel, options); return promiseRecord(fetchedInternalModel, "DS: Store#findRecord " + internalModel.typeKey + " with id: " + get(internalModel, 'id')); }, _findEmptyInternalModel: function _findEmptyInternalModel(internalModel, options) { if (internalModel.isEmpty()) { return this.scheduleFetch(internalModel, options); } //TODO double check about reloading if (internalModel.isLoading()) { return internalModel._loadingPromise; } return Promise.resolve(internalModel); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} modelName @param {Array} ids @return {Promise} promise */ findByIds: function findByIds(modelName, ids) { assert("You need to pass a model name to the store's findByIds method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var promises = new Array(ids.length); for (var i = 0; i < ids.length; i++) { promises[i] = this.findRecord(modelName, ids[i]); } return promiseArray(Ember.RSVP.all(promises).then(Ember.A, null, "DS: Store#findByIds of " + modelName + " complete")); }, /** This method is called by `findRecord` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {InternalModel} internalModel model @return {Promise} promise */ // TODO rename this to have an underscore fetchRecord: function fetchRecord(internalModel, options) { var typeClass = internalModel.type; var id = internalModel.id; var adapter = this.adapterFor(typeClass.modelName); assert("You tried to find a record but you have no adapter (for " + typeClass + ")", adapter); assert("You tried to find a record but your adapter (for " + typeClass + ") does not implement 'findRecord'", typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'); var promise = _find(adapter, this, typeClass, id, internalModel, options); return promise; }, scheduleFetchMany: function scheduleFetchMany(records) { var internalModels = new Array(records.length); var fetches = new Array(records.length); for (var i = 0; i < records.length; i++) { internalModels[i] = records[i]._internalModel; } for (var i = 0; i < internalModels.length; i++) { fetches[i] = this.scheduleFetch(internalModels[i]); } return Ember.RSVP.Promise.all(fetches); }, scheduleFetch: function scheduleFetch(internalModel, options) { var typeClass = internalModel.type; if (internalModel._loadingPromise) { return internalModel._loadingPromise; } var resolver = Ember.RSVP.defer('Fetching ' + typeClass + 'with id: ' + internalModel.id); var pendingFetchItem = { record: internalModel, resolver: resolver, options: options }; var promise = resolver.promise; internalModel.loadingData(promise); if (!this._pendingFetch.get(typeClass)) { this._pendingFetch.set(typeClass, [pendingFetchItem]); } else { this._pendingFetch.get(typeClass).push(pendingFetchItem); } Ember.run.scheduleOnce('afterRender', this, this.flushAllPendingFetches); return promise; }, flushAllPendingFetches: function flushAllPendingFetches() { if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch = Map.create(); }, _flushPendingFetchForType: function _flushPendingFetchForType(pendingFetchItems, typeClass) { var store = this; var adapter = store.adapterFor(typeClass.modelName); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var records = Ember.A(pendingFetchItems).mapBy('record'); function _fetchRecord(recordResolverPair) { recordResolverPair.resolver.resolve(store.fetchRecord(recordResolverPair.record, recordResolverPair.options)); // TODO adapter options } function resolveFoundRecords(records) { records.forEach(function (record) { var pair = Ember.A(pendingFetchItems).findBy('record', record); if (pair) { var resolver = pair.resolver; resolver.resolve(record); } }); return records; } function makeMissingRecordsRejector(requestedRecords) { return function rejectMissingRecords(resolvedRecords) { resolvedRecords = Ember.A(resolvedRecords); var missingRecords = requestedRecords.reject(function (record) { return resolvedRecords.contains(record); }); if (missingRecords.length) { warn('Ember Data expected to find records with the following ids in the adapter response but they were missing: ' + Ember.inspect(Ember.A(missingRecords).mapBy('id')), false, { id: 'ds.store.missing-records-from-adapter' }); } rejectRecords(missingRecords); }; } function makeRecordsRejector(records) { return function (error) { rejectRecords(records, error); }; } function rejectRecords(records, error) { records.forEach(function (record) { var pair = Ember.A(pendingFetchItems).findBy('record', record); if (pair) { var resolver = pair.resolver; resolver.reject(error); } }); } if (pendingFetchItems.length === 1) { _fetchRecord(pendingFetchItems[0]); } else if (shouldCoalesce) { // TODO: Improve records => snapshots => records => snapshots // // We want to provide records to all store methods and snapshots to all // adapter methods. To make sure we're doing that we're providing an array // of snapshots to adapter.groupRecordsForFindMany(), which in turn will // return grouped snapshots instead of grouped records. // // But since the _findMany() finder is a store method we need to get the // records from the grouped snapshots even though the _findMany() finder // will once again convert the records to snapshots for adapter.findMany() var snapshots = Ember.A(records).invoke('createSnapshot'); var groups = adapter.groupRecordsForFindMany(this, snapshots); groups.forEach(function (groupOfSnapshots) { var groupOfRecords = Ember.A(groupOfSnapshots).mapBy('_internalModel'); var requestedRecords = Ember.A(groupOfRecords); var ids = requestedRecords.mapBy('id'); if (ids.length > 1) { _findMany(adapter, store, typeClass, ids, requestedRecords).then(resolveFoundRecords).then(makeMissingRecordsRejector(requestedRecords)).then(null, makeRecordsRejector(requestedRecords)); } else if (ids.length === 1) { var pair = Ember.A(pendingFetchItems).findBy('record', groupOfRecords[0]); _fetchRecord(pair); } else { assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false); } }); } else { pendingFetchItems.forEach(_fetchRecord); } }, /** Get the reference for the specified record. Example ```javascript var userRef = store.getReference('user', 1); // check if the user is loaded var isLoaded = userRef.value() !== null; // get the record of the reference (null if not yet available) var user = userRef.value(); // get the identifier of the reference if (userRef.remoteType() === "id") { var id = userRef.id(); } // load user (via store.find) userRef.load().then(...) // or trigger a reload userRef.reload().then(...) // provide data for reference userRef.push({ id: 1, username: "@user" }).then(function(user) { userRef.value() === user; }); ``` @method getReference @param {String} type @param {String|Integer} id @since 2.5.0 @return {RecordReference} */ getReference: function getReference(type, id) { return this._internalModelForId(type, id).recordReference; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it is available in the store, otherwise it will return `null`. A record is available if it has been fetched earlier, or pushed manually into the store. _Note: This is an synchronous method and does not return a promise._ ```js var post = store.peekRecord('post', 1); post.get('id'); // 1 ``` @since 1.13.0 @method peekRecord @param {String} modelName @param {String|Integer} id @return {DS.Model|null} record */ peekRecord: function peekRecord(modelName, id) { assert("You need to pass a model name to the store's peekRecord method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); if (this.hasRecordForId(modelName, id)) { return this._internalModelForId(modelName, id).getRecord(); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} internalModel @return {Promise} promise */ reloadRecord: function reloadRecord(internalModel) { var modelName = internalModel.type.modelName; var adapter = this.adapterFor(modelName); var id = internalModel.id; assert("You cannot reload a record without an ID", id); assert("You tried to reload a record but you have no adapter (for " + modelName + ")", adapter); assert("You tried to reload a record but your adapter does not implement `findRecord`", typeof adapter.findRecord === 'function' || typeof adapter.find === 'function'); return this.scheduleFetch(internalModel); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {(String|DS.Model)} modelName @param {(String|Integer)} inputId @return {Boolean} */ hasRecordForId: function hasRecordForId(modelName, inputId) { assert("You need to pass a model name to the store's hasRecordForId method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var id = coerceId(inputId); var internalModel = this.typeMapFor(typeClass).idToRecord[id]; return !!internalModel && internalModel.isLoaded(); }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String} modelName @param {(String|Integer)} id @return {DS.Model} record */ recordForId: function recordForId(modelName, id) { assert("You need to pass a model name to the store's recordForId method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); return this._internalModelForId(modelName, id).getRecord(); }, _internalModelForId: function _internalModelForId(typeName, inputId) { var typeClass = this.modelFor(typeName); var id = coerceId(inputId); var idToRecord = this.typeMapFor(typeClass).idToRecord; var record = idToRecord[id]; if (!record || !idToRecord[id]) { record = this.buildInternalModel(typeClass, id); } return record; }, /** @method findMany @private @param {Array} internalModels @return {Promise} promise */ findMany: function findMany(internalModels) { var finds = new Array(internalModels.length); for (var i = 0; i < internalModels.length; i++) { finds[i] = this._findByInternalModel(internalModels[i]); } return Promise.all(finds); }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {(Relationship)} relationship @return {Promise} promise */ findHasMany: function findHasMany(owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.type + ")", adapter); assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", typeof adapter.findHasMany === 'function'); return _findHasMany(adapter, this, owner, link, relationship); }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function findBelongsTo(owner, link, relationship) { var adapter = this.adapterFor(owner.type.modelName); assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.type + ")", adapter); assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", typeof adapter.findBelongsTo === 'function'); return _findBelongsTo(adapter, this, owner, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. --- If you do something like this: ```javascript store.query('person', { page: 1 }); ``` The call made to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?page=1" Processing by Api::V1::PersonsController#index as HTML Parameters: { "page"=>"1" } ``` --- If you do something like this: ```javascript store.query('person', { ids: [1, 2, 3] }); ``` The call to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3" Processing by Api::V1::PersonsController#index as HTML Parameters: { "ids" => ["1", "2", "3"] } ``` This method returns a promise, which is resolved with a `RecordArray` once the server returns. @since 1.13.0 @method query @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ query: function query(modelName, _query2) { return this._query(modelName, _query2); }, _query: function _query(modelName, query, array) { assert("You need to pass a model name to the store's query method", isPresent(modelName)); assert("You need to pass a query hash to the store's query method", query); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); array = array || this.recordArrayManager.createAdapterPopulatedRecordArray(typeClass, query); var adapter = this.adapterFor(modelName); assert("You tried to load a query but you have no adapter (for " + typeClass + ")", adapter); assert("You tried to load a query but your adapter does not implement `query`", typeof adapter.query === 'function'); return promiseArray(_query3(adapter, this, typeClass, query, array)); }, /** This method makes a request for one record, where the `id` is not known beforehand (if the `id` is known, use `findRecord` instead). This method can be used when it is certain that the server will return a single object for the primary data. Let's assume our API provides an endpoint for the currently logged in user via: ``` // GET /api/current_user { user: { id: 1234, username: 'admin' } } ``` Since the specific `id` of the `user` is not known beforehand, we can use `queryRecord` to get the user: ```javascript store.queryRecord('user', {}).then(function(user) { let username = user.get('username'); console.log(`Currently logged in as ${username}`); }); ``` The request is made through the adapters' `queryRecord`: ```javascript // app/adapters/user.js import DS from "ember-data"; export default DS.Adapter.extend({ queryRecord(modelName, query) { return Ember.$.getJSON("/api/current_user"); } }); ``` Note: the primary use case for `store.queryRecord` is when a single record is queried and the `id` is not known beforehand. In all other cases `store.query` and using the first item of the array is likely the preferred way: ``` // GET /users?username=unique { data: [{ id: 1234, type: 'user', attributes: { username: "unique" } }] } ``` ```javascript store.query('user', { username: 'unique' }).then(function(users) { return users.get('firstObject'); }).then(function(user) { let id = user.get('id'); }); ``` This method returns a promise, which resolves with the found record. If the adapter returns no data for the primary data of the payload, then `queryRecord` resolves with `null`: ``` // GET /users?username=unique { data: null } ``` ```javascript store.queryRecord('user', { username: 'unique' }).then(function(user) { console.log(user); // null }); ``` @since 1.13.0 @method queryRecord @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise which resolves with the found record or `null` */ queryRecord: function queryRecord(modelName, query) { assert("You need to pass a model name to the store's queryRecord method", isPresent(modelName)); assert("You need to pass a query hash to the store's queryRecord method", query); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var adapter = this.adapterFor(modelName); assert("You tried to make a query but you have no adapter (for " + typeClass + ")", adapter); assert("You tried to make a query but your adapter does not implement `queryRecord`", typeof adapter.queryRecord === 'function'); return promiseObject(_queryRecord(adapter, this, typeClass, query)); }, /** `findAll` asks the adapter's `findAll` method to find the records for the given type, and returns a promise which will resolve with all records of this type present in the store, even if the adapter only returns a subset of them. ```app/routes/authors.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('author'); } }); ``` _When_ the returned promise resolves depends on the reload behavior, configured via the passed `options` hash and the result of the adapter's `shouldReloadAll` method. ### Reloading If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if there are already records in the store: ```js store.push({ data: { id: 'first', type: 'author' } }); // adapter#findAll resolves with // [ // { // id: 'second', // type: 'author' // } // ] store.findAll('author', { reload: true }).then(function(authors) { authors.getEach("id"); // ['first', 'second'] }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with all the records currently loaded in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`, then a background reload is started. Once this resolves, the array with which the promise resolves, is updated automatically so it contains all the records in the store: ```js // app/adapters/application.js export default DS.Adapter.extend({ shouldReloadAll(store, snapshotsArray) { return false; }, shouldBackgroundReloadAll(store, snapshotsArray) { return true; } }); // ... store.push({ data: { id: 'first', type: 'author' } }); var allAuthors; store.findAll('author').then(function(authors) { authors.getEach('id'); // ['first'] allAuthors = authors; }); // later, once adapter#findAll resolved with // [ // { // id: 'second', // type: 'author' // } // ] allAuthors.getEach('id'); // ['first', 'second'] ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findAll`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model: function() { return this.store.findAll('post', { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the `snapshotRecordArray` ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.findAll('post', { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findAll: function(store, type, sinceToken, snapshotRecordArray) { if (snapshotRecordArray.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekAll](#method_peekAll) to get an array of current records in the store, without waiting until a reload is finished. See [query](#method_query) to only get a subset of records from the server. @since 1.13.0 @method findAll @param {String} modelName @param {Object} options @return {Promise} promise */ findAll: function findAll(modelName, options) { assert("You need to pass a model name to the store's findAll method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); return this._fetchAll(typeClass, this.peekAll(modelName), options); }, /** @method _fetchAll @private @param {DS.Model} typeClass @param {DS.RecordArray} array @return {Promise} promise */ _fetchAll: function _fetchAll(typeClass, array, options) { options = options || {}; var adapter = this.adapterFor(typeClass.modelName); var sinceToken = this.typeMapFor(typeClass).metadata.since; assert("You tried to load all records but you have no adapter (for " + typeClass + ")", adapter); assert("You tried to load all records but your adapter does not implement `findAll`", typeof adapter.findAll === 'function'); set(array, 'isUpdating', true); if (options.reload) { return promiseArray(_findAll(adapter, this, typeClass, sinceToken, options)); } var snapshotArray = array.createSnapshot(options); if (adapter.shouldReloadAll(this, snapshotArray)) { return promiseArray(_findAll(adapter, this, typeClass, sinceToken, options)); } if (options.backgroundReload === false) { return promiseArray(Promise.resolve(array)); } if (options.backgroundReload || adapter.shouldBackgroundReloadAll(this, snapshotArray)) { _findAll(adapter, this, typeClass, sinceToken, options); } return promiseArray(Promise.resolve(array)); }, /** @method didUpdateAll @param {DS.Model} typeClass @private */ didUpdateAll: function didUpdateAll(typeClass) { var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); set(liveRecordArray, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type in the store. Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use [store.findAll](#method_findAll). Also note that multiple calls to `peekAll` for a given type will always return the same `RecordArray`. Example ```javascript var localPosts = store.peekAll('post'); ``` @since 1.13.0 @method peekAll @param {String} modelName @return {DS.RecordArray} */ peekAll: function peekAll(modelName) { assert("You need to pass a model name to the store's peekAll method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var typeClass = this.modelFor(modelName); var liveRecordArray = this.recordArrayManager.liveRecordArrayFor(typeClass); this.recordArrayManager.populateLiveRecordArray(liveRecordArray, typeClass); return liveRecordArray; }, /** This method unloads all records in the store. Optionally you can pass a type which unload all records for a given type. ```javascript store.unloadAll(); store.unloadAll('post'); ``` @method unloadAll @param {String=} modelName */ unloadAll: function unloadAll(modelName) { assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), !modelName || typeof modelName === 'string'); if (arguments.length === 0) { var typeMaps = this.typeMaps; var keys = Object.keys(typeMaps); var types = new Array(keys.length); for (var i = 0; i < keys.length; i++) { types[i] = typeMaps[keys[i]]['type'].modelName; } types.forEach(this.unloadAll, this); } else { var typeClass = this.modelFor(modelName); var typeMap = this.typeMapFor(typeClass); var records = typeMap.records.slice(); var record = undefined; for (var i = 0; i < records.length; i++) { record = records[i]; record.unloadRecord(); record.destroy(); // maybe within unloadRecord } typeMap.metadata = new EmptyObject(); } }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The filter function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. Example ```javascript store.filter('post', function(post) { return post.get('unread'); }); ``` The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query, which is the equivalent of calling [query](#method_query) with that same query, to fetch additional records from the server. The results returned by the server could then appear in the filter if they match the filter function. The query itself is not used to filter records, it's only sent to your server for you to be able to do server-side filtering. The filter function will be applied on the returned results regardless. Example ```javascript store.filter('post', { unread: true }, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @private @param {String} modelName @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} @deprecated */ filter: function filter(modelName, query, _filter) { assert("You need to pass a model name to the store's filter method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); if (!Ember.ENV.ENABLE_DS_FILTER) { assert('The filter API has been moved to a plugin. To enable store.filter using an environment flag, or to use an alternative, you can visit the ember-data-filter addon page. https://github.com/ember-data/ember-data-filter', false); } var promise; var length = arguments.length; var array; var hasQuery = length === 3; // allow an optional server query if (hasQuery) { promise = this.query(modelName, query); } else if (arguments.length === 2) { _filter = query; } modelName = this.modelFor(modelName); if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(modelName, _filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(modelName, _filter); } promise = promise || Promise.resolve(array); return promiseArray(promise.then(function () { return array; }, null, 'DS: Store#filter of ' + modelName)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a findRecord() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded('post', 1); // false store.findRecord('post', 1).then(function() { store.recordIsLoaded('post', 1); // true }); ``` @method recordIsLoaded @param {String} modelName @param {string} id @return {boolean} */ recordIsLoaded: function recordIsLoaded(modelName, id) { assert("You need to pass a model name to the store's recordIsLoaded method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); return this.hasRecordForId(modelName, id); }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {InternalModel} internalModel */ dataWasUpdated: function dataWasUpdated(type, internalModel) { this.recordArrayManager.recordDidChange(internalModel); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {InternalModel} internalModel @param {Resolver} resolver @param {Object} options */ scheduleSave: function scheduleSave(internalModel, resolver, options) { var snapshot = internalModel.createSnapshot(options); internalModel.flushChangedAttributes(); internalModel.adapterWillCommit(); this._pendingSave.push({ snapshot: snapshot, resolver: resolver }); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function flushPendingSave() { var _this = this; var pending = this._pendingSave.slice(); this._pendingSave = []; pending.forEach(function (pendingItem) { var snapshot = pendingItem.snapshot; var resolver = pendingItem.resolver; var record = snapshot._internalModel; var adapter = _this.adapterFor(record.type.modelName); var operation; if (get(record, 'currentState.stateName') === 'root.deleted.saved') { return resolver.resolve(); } else if (record.isNew()) { operation = 'createRecord'; } else if (record.isDeleted()) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, _this, operation, snapshot)); }); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {InternalModel} internalModel the in-flight internal model @param {Object} data optional data (see above) */ didSaveRecord: function didSaveRecord(internalModel, dataArg) { var data; if (dataArg) { data = dataArg.data; } if (data) { // normalize relationship IDs into records this._backburner.schedule('normalizeRelationships', this, '_setupRelationships', internalModel, data); this.updateId(internalModel, data); } //We first make sure the primary data has been updated //TODO try to move notification to the user to the end of the runloop internalModel.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {InternalModel} internalModel @param {Object} errors */ recordWasInvalid: function recordWasInvalid(internalModel, errors) { internalModel.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {InternalModel} internalModel @param {Error} error */ recordWasError: function recordWasError(internalModel, error) { internalModel.adapterDidError(error); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {InternalModel} internalModel @param {Object} data */ updateId: function updateId(internalModel, data) { var oldId = internalModel.id; var id = coerceId(data.id); assert("An adapter cannot assign a new id to a record that already has an id. " + internalModel + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(internalModel.type).idToRecord[id] = internalModel; internalModel.setId(id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param {DS.Model} typeClass @return {Object} typeMap */ typeMapFor: function typeMapFor(typeClass) { var typeMaps = get(this, 'typeMaps'); var guid = Ember.guidFor(typeClass); var typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: new EmptyObject(), records: [], metadata: new EmptyObject(), type: typeClass }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {(String|DS.Model)} type @param {Object} data */ _load: function _load(data) { var internalModel = this._internalModelForId(data.type, data.id); internalModel.setupData(data); this.recordArrayManager.recordDidChange(internalModel); return internalModel; }, /* In case someone defined a relationship to a mixin, for example: ``` var Comment = DS.Model.extend({ owner: belongsTo('commentable'. { polymorphic: true}) }); var Commentable = Ember.Mixin.create({ comments: hasMany('comment') }); ``` we want to look up a Commentable class which has all the necessary relationship metadata. Thus, we look up the mixin and create a mock DS.Model, so we can access the relationship CPs of the mixin (`comments`) in this case */ _modelForMixin: function _modelForMixin(modelName) { var normalizedModelName = normalizeModelName(modelName); // container.registry = 2.1 // container._registry = 1.11 - 2.0 // container = < 1.11 var owner = getOwner(this); var mixin = owner._lookupFactory('mixin:' + normalizedModelName); if (mixin) { //Cache the class as a model owner.register('model:' + normalizedModelName, Model.extend(mixin)); } var factory = this.modelFactoryFor(normalizedModelName); if (factory) { factory.__isMixin = true; factory.__mixin = mixin; } return factory; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String} modelName @return {DS.Model} */ modelFor: function modelFor(modelName) { assert("You need to pass a model name to the store's modelFor method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var factory = this.modelFactoryFor(modelName); if (!factory) { //Support looking up mixins as base types for polymorphic relationships factory = this._modelForMixin(modelName); } if (!factory) { throw new Ember.Error("No model was found for '" + modelName + "'"); } factory.modelName = factory.modelName || normalizeModelName(modelName); return factory; }, modelFactoryFor: function modelFactoryFor(modelName) { assert("You need to pass a model name to the store's modelFactoryFor method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var normalizedKey = normalizeModelName(modelName); var owner = getOwner(this); return owner._lookupFactory('model:' + normalizedKey); }, /** Push some data for a given type into the store. This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments: - record's `type` should always be in singular, dasherized form - members (properties) should be camelCased [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level): ```js store.push({ data: { // primary data for single record of type `Person` id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } } }); ``` [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7) `data` property can also hold an array (of records): ```js store.push({ data: [ // an array of records { id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } }, { id: '2', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' } } ] }); ``` [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355) There are some typical properties for `JSONAPI` payload: * `id` - mandatory, unique record's key * `type` - mandatory string which matches `model`'s dasherized name in singular form * `attributes` - object which holds data for record attributes - `DS.attr`'s declared in model * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`): - [`links`](http://jsonapi.org/format/#document-links) - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship For this model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { data: [ { id: '2', type: 'person' }, { id: '3', type: 'person' }, { id: '4', type: 'person' } ] } } } } ``` [Demo.](http://ember-twiddle.com/343e1735e034091f5bde) To represent the children relationship as a URL: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { links: { related: '/people/1/children' } } } } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's [normalize](#method_normalize) method is a convenience helper for converting a json payload into the form Ember Data expects. ```js store.push(store.normalize('person', data)); ``` This method can be used both to push in brand new records, as well as to update existing records. @method push @param {Object} data @return {DS.Model|Array} the record(s) that was created or updated. */ push: function push(data) { var included = data.included; var i, length; if (included) { for (i = 0, length = included.length; i < length; i++) { this._pushInternalModel(included[i]); } } if (Array.isArray(data.data)) { length = data.data.length; var internalModels = new Array(length); for (i = 0; i < length; i++) { internalModels[i] = this._pushInternalModel(data.data[i]).getRecord(); } return internalModels; } if (data.data === null) { return null; } assert('Expected an object in the \'data\' property in a call to \'push\' for ' + data.type + ', but was ' + Ember.typeOf(data.data), Ember.typeOf(data.data) === 'object'); var internalModel = this._pushInternalModel(data.data); return internalModel.getRecord(); }, _hasModelFor: function _hasModelFor(type) { return !!getOwner(this)._lookupFactory('model:' + type); }, _pushInternalModel: function _pushInternalModel(data) { var _this2 = this; var modelName = data.type; assert('You must include an \'id\' for ' + modelName + ' in an object passed to \'push\'', data.id !== null && data.id !== undefined && data.id !== ''); assert('You tried to push data with a type \'' + modelName + '\' but no model could be found with that name.', this._hasModelFor(modelName)); runInDebug(function () { // If Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload // contains unknown attributes or relationships, log a warning. if (Ember.ENV.DS_WARN_ON_UNKNOWN_KEYS) { (function () { var type = _this2.modelFor(modelName); // Check unknown attributes var unknownAttributes = Object.keys(data.attributes || {}).filter(function (key) { return !get(type, 'fields').has(key); }); var unknownAttributesMessage = 'The payload for \'' + type.modelName + '\' contains these unknown attributes: ' + unknownAttributes + '. Make sure they\'ve been defined in your model.'; warn(unknownAttributesMessage, unknownAttributes.length === 0, { id: 'ds.store.unknown-keys-in-payload' }); // Check unknown relationships var unknownRelationships = Object.keys(data.relationships || {}).filter(function (key) { return !get(type, 'fields').has(key); }); var unknownRelationshipsMessage = 'The payload for \'' + type.modelName + '\' contains these unknown relationships: ' + unknownRelationships + '. Make sure they\'ve been defined in your model.'; warn(unknownRelationshipsMessage, unknownRelationships.length === 0, { id: 'ds.store.unknown-keys-in-payload' }); })(); } }); // Actually load the record into the store. var internalModel = this._load(data); this._backburner.join(function () { _this2._backburner.schedule('normalizeRelationships', _this2, '_setupRelationships', internalModel, data); }); return internalModel; }, _setupRelationships: function _setupRelationships(record, data) { // This will convert relationships specified as IDs into DS.Model instances // (possibly unloaded) and also create the data structures used to track // relationships. setupRelationships(this, record, data); }, /** Push some raw data into the store. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```js var pushData = { posts: [ { id: 1, post_title: "Great post", comment_ids: [2] } ], comments: [ { id: 2, comment_body: "Insightful comment" } ] } store.pushPayload(pushData); ``` By default, the data will be deserialized using a default serializer (the application serializer if it exists). Alternatively, `pushPayload` will accept a model type which will determine which serializer will process the payload. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer; ``` ```js store.pushPayload('comment', pushData); // Will use the application serializer store.pushPayload('post', pushData); // Will use the post serializer ``` @method pushPayload @param {String} modelName Optionally, a model type used to determine which serializer will be used @param {Object} inputPayload */ pushPayload: function pushPayload(modelName, inputPayload) { var _this3 = this; var serializer; var payload; if (!inputPayload) { payload = modelName; serializer = defaultSerializer(this); assert("You cannot use `store#pushPayload` without a modelName unless your default serializer defines `pushPayload`", typeof serializer.pushPayload === 'function'); } else { payload = inputPayload; assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); serializer = this.serializerFor(modelName); } if (false) { return this._adapterRun(function () { return serializer.pushPayload(_this3, payload); }); } else { this._adapterRun(function () { return serializer.pushPayload(_this3, payload); }); } }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { var modelName = message.model; var data = message.data; store.push(store.normalize(modelName, data)); }); ``` @method normalize @param {String} modelName The name of the model type for this payload @param {Object} payload @return {Object} The normalized payload */ normalize: function normalize(modelName, payload) { assert("You need to pass a model name to the store's normalize method", isPresent(modelName)); assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var serializer = this.serializerFor(modelName); var model = this.modelFor(modelName); return serializer.normalize(model, payload); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {DS.Model} type @param {String} id @param {Object} data @return {InternalModel} internal model */ buildInternalModel: function buildInternalModel(type, id, data) { var typeMap = this.typeMapFor(type); var idToRecord = typeMap.idToRecord; assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); assert('\'' + Ember.inspect(type) + '\' does not appear to be an ember-data model', typeof type._create === 'function'); // lookupFactory should really return an object that creates // instances with the injections applied var internalModel = new InternalModel(type, id, this, null, data); // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = internalModel; } typeMap.records.push(internalModel); return internalModel; }, //Called by the state machine to notify the store that the record is ready to be interacted with recordWasLoaded: function recordWasLoaded(record) { this.recordArrayManager.recordWasLoaded(record); }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method _dematerializeRecord @private @param {InternalModel} internalModel */ _dematerializeRecord: function _dematerializeRecord(internalModel) { var type = internalModel.type; var typeMap = this.typeMapFor(type); var id = internalModel.id; internalModel.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = typeMap.records.indexOf(internalModel); typeMap.records.splice(loc, 1); }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns an instance of the adapter for a given type. For example, `adapterFor('person')` will return an instance of `App.PersonAdapter`. If no `App.PersonAdapter` is found, this method will look for an `App.ApplicationAdapter` (the default adapter for your entire application). If no `App.ApplicationAdapter` is found, it will return the value of the `defaultAdapter`. @method adapterFor @public @param {String} modelName @return DS.Adapter */ adapterFor: function adapterFor(modelName) { assert("You need to pass a model name to the store's adapterFor method", isPresent(modelName)); assert('Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); return this.lookupAdapter(modelName); }, _adapterRun: function _adapterRun(fn) { return this._backburner.run(fn); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). if no `App.ApplicationSerializer` is found, it will attempt to get the `defaultSerializer` from the `PersonAdapter` (`adapterFor('person')`). If a serializer cannot be found on the adapter, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @public @param {String} modelName the record to serialize @return {DS.Serializer} */ serializerFor: function serializerFor(modelName) { assert("You need to pass a model name to the store's serializerFor method", isPresent(modelName)); assert('Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ' + Ember.inspect(modelName), typeof modelName === 'string'); var fallbacks = ['application', this.adapterFor(modelName).get('defaultSerializer'), '-default']; var serializer = this.lookupSerializer(modelName, fallbacks); return serializer; }, /** Retrieve a particular instance from the container cache. If not found, creates it and placing it in the cache. Enabled a store to manage local instances of adapters and serializers. @method retrieveManagedInstance @private @param {String} modelName the object modelName @param {String} name the object name @param {Array} fallbacks the fallback objects to lookup if the lookup for modelName or 'application' fails @return {Ember.Object} */ retrieveManagedInstance: function retrieveManagedInstance(type, modelName, fallbacks) { var normalizedModelName = normalizeModelName(modelName); var instance = this._instanceCache.get(type, normalizedModelName, fallbacks); set(instance, 'store', this); return instance; }, lookupAdapter: function lookupAdapter(name) { return this.retrieveManagedInstance('adapter', name, this.get('_adapterFallbacks')); }, _adapterFallbacks: Ember.computed('adapter', function () { var adapter = this.get('adapter'); return ['application', adapter, '-json-api']; }), lookupSerializer: function lookupSerializer(name, fallbacks) { return this.retrieveManagedInstance('serializer', name, fallbacks); }, willDestroy: function willDestroy() { this._super.apply(this, arguments); this.recordArrayManager.destroy(); this.unloadAll(); } }); function deserializeRecordId(store, key, relationship, id) { if (isNone(id)) { return; } assert('A ' + relationship.parentType + ' record was pushed into the store with the value of ' + key + ' being ' + Ember.inspect(id) + ', but ' + key + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !Array.isArray(id)); //TODO:Better asserts return store._internalModelForId(id.type, id.id); } function deserializeRecordIds(store, key, relationship, ids) { if (isNone(ids)) { return; } assert('A ' + relationship.parentType + ' record was pushed into the store with the value of ' + key + ' being \'' + Ember.inspect(ids) + '\', but ' + key + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', Array.isArray(ids)); var _ids = new Array(ids.length); for (var i = 0; i < ids.length; i++) { _ids[i] = deserializeRecordId(store, key, relationship, ids[i]); } return _ids; } // Delegation to the adapter and promise management function defaultSerializer(store) { return store.serializerFor('application'); } function _commit(adapter, store, operation, snapshot) { var internalModel = snapshot._internalModel; var modelName = snapshot.modelName; var typeClass = store.modelFor(modelName); var promise = adapter[operation](store, typeClass, snapshot); var serializer = serializerForAdapter(store, adapter, modelName); var label = 'DS: Extract and notify about ' + operation + ' completion of ' + internalModel; assert('Your adapter\'s \'' + operation + '\' method must return a value, but it returned \'undefined\'', promise !== undefined); promise = Promise.resolve(promise, label); promise = _guard(promise, _bind(_objectIsAlive, store)); promise = _guard(promise, _bind(_objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { store._adapterRun(function () { var payload, data; if (adapterPayload) { payload = normalizeResponseHelper(serializer, store, typeClass, adapterPayload, snapshot.id, operation); if (payload.included) { store.push({ data: payload.included }); } data = payload.data; } store.didSaveRecord(internalModel, { data: data }); }); return internalModel; }, function (error) { if (error instanceof InvalidError) { var errors = serializer.extractErrors(store, typeClass, error, snapshot.id); store.recordWasInvalid(internalModel, errors); } else { store.recordWasError(internalModel, error); } throw error; }, label); } function setupRelationships(store, record, data) { if (!data.relationships) { return; } record.type.eachRelationship(function (key, descriptor) { var kind = descriptor.kind; if (!data.relationships[key]) { return; } var relationship; if (data.relationships[key].links && data.relationships[key].links.related) { var relatedLink = _normalizeLink(data.relationships[key].links.related); if (relatedLink && relatedLink.href) { relationship = record._relationships.get(key); relationship.updateLink(relatedLink.href); } } if (data.relationships[key].meta) { relationship = record._relationships.get(key); relationship.updateMeta(data.relationships[key].meta); } // If the data contains a relationship that is specified as an ID (or IDs), // normalizeRelationship will convert them into DS.Model instances // (possibly unloaded) before we push the payload into the store. normalizeRelationship(store, key, descriptor, data.relationships[key]); var value = data.relationships[key].data; if (value !== undefined) { if (kind === 'belongsTo') { relationship = record._relationships.get(key); relationship.setCanonicalRecord(value); } else if (kind === 'hasMany') { relationship = record._relationships.get(key); relationship.updateRecordsFromAdapter(value); } } }); } function normalizeRelationship(store, key, relationship, jsonPayload) { var data = jsonPayload.data; if (data) { var kind = relationship.kind; if (kind === 'belongsTo') { jsonPayload.data = deserializeRecordId(store, key, relationship, data); } else if (kind === 'hasMany') { jsonPayload.data = deserializeRecordIds(store, key, relationship, data); } } } export { Store }; export default Store;
'use strict'; var info = require('../'); var should = require('should'); describe('browser-info', function() { it('should return info', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.68 Safari/537.36', }; should(info().name).equal('Chrome'); should(info().version).equal('42'); should(info().fullVersion).equal('42.0.2311.68'); should(info().os).equal('Linux'); done(); }); it('should detect Android', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.23 Mobile Safari/537.36' }; should(info().os).equal('Android'); should(info().name).equal('Chrome'); should(info().version).equal('48'); should(info().fullVersion).equal('48.0.2564.23'); done(); }); it('should detect iOS', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1' }; should(info().os).equal('iOS'); should(info().name).equal('Safari'); should(info().version).equal('9'); should(info().fullVersion).equal('9.0'); done(); }); it('should detect Edge', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/13' }; should(info().os).equal('Windows'); should(info().name).equal('Edge'); should(info().version).equal('13'); should(info().fullVersion).equal('13'); done(); }); it('should detect IE mobile', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (compatible; MSIE 9.0; Windows Phone OS 7.5; Trident/5.0; IEMobile/9.0)' }; should(info().os).equal('Windows Phone'); should(info().name).equal('IEMobile'); should(info().version).equal('9'); should(info().fullVersion).equal('9.0'); done(); }); it('should detect Opera', function(done) { global.navigator = { userAgent: 'Opera/9.80 (X11; Linux i686; Ubuntu/14.10) Presto/2.12.388 Version/12.16' }; should(info().name).equal('Opera'); should(info().os).equal('Linux'); should(info().version).equal('12'); should(info().fullVersion).equal('12.16'); done(); }); it('should detect Firefox', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0' }; should(info().name).equal('Firefox'); should(info().os).equal('Linux'); should(info().version).equal('57'); should(info().fullVersion).equal('57.0'); done(); }); it('should detect Waterfox', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x86; rv:40.0) Gecko/20100101 Firefox/40.0.2 Waterfox/40.0.2' }; should(info().name).equal('Waterfox'); should(info().os).equal('Windows'); should(info().version).equal('40'); should(info().fullVersion).equal('40.0.2'); done(); }); it('should detect OperaCoast', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_1_1 like Mac OS X) AppleWebKit/602.2.14 (KHTML, like Gecko) Coast/5.04.110603 Mobile/14B100 Safari/7534.48.3' }; should(info().os).equal('iOS'); should(info().name).equal('OperaCoast'); should(info().version).equal('5'); should(info().fullVersion).equal('5.04.110603'); done(); }); it('should detect IE', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko' }; should(info().name).equal('IE'); should(info().os).equal('Windows'); should(info().version).equal('11'); should(info().fullVersion).equal('11.0'); done(); }); it('should detect edge cases', function(done) { global.navigator = { userAgent: 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.116 Safari/537.36 Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10' }; should(info().name).equal('Chrome'); should(info().os).equal('Windows'); should(info().version).equal('34'); should(info().fullVersion).equal('34.0.1847.116'); done(); }); it('should detect IE from argument', function(done) { var userAgent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko' should(info(userAgent).name).equal('IE'); should(info(userAgent).os).equal('Windows'); should(info(userAgent).version).equal('11'); should(info(userAgent).fullVersion).equal('11.0'); done(); }); });
'use strict'; var mongoose = require('mongoose-bird')(), Schema = mongoose.Schema; var CurrenttaskSchema = new Schema({ name: String, totalSeconds:Number, date: Date, started: Boolean, userId: Schema.Types.ObjectId, workStream: Schema.Types.ObjectId }); module.exports = mongoose.model('Currenttask', CurrenttaskSchema);
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 18H7V6h10v12z" /> , 'StayCurrentPortraitRounded');
/* eslint no-param-reassign: 0 */ import expressJwt from 'express-jwt'; import jwt from 'jsonwebtoken'; import crypto from 'crypto'; import config from '../../config'; import { getUserFromRefreshToken, register, saveRefreshToken } from '../db/user-repository'; const defaultTokenTime = 1800; // authorizes, decrypts, and assigns jwt params to req.user const authUserFromAccessToken = expressJwt({ secret: config.secret, }); const getRefreshToken = async (req, res, next) => { if (req.body.persist) { const refreshToken = `${req.user.id}.${crypto.randomBytes(40).toString('hex')}`; await saveRefreshToken(req.user.id, refreshToken); req.token.refreshToken = refreshToken; } return next(); }; const getAccessToken = (req, res, next) => { if (!req.user && !req.user.id) { next(new Error('User not set, cannot create jwt, please login again')); } else { req.token = req.token || {}; req.token.accessToken = jwt.sign( { id: req.user.id, username: req.user.username }, config.secret, { expiresIn: config.tokenTime || defaultTokenTime }); next(); } }; const validateRefreshToken = async (req, res, next) => { const { refreshToken } = req.body; console.log(req.body); try { const user = await getUserFromRefreshToken(refreshToken); if (!user) { next(new Error('loaded a blank user?? would this ever happen?')); } req.user = user; return next(); } catch (err) { return next(err); } }; const registerUser = async (req, res, next) => { const { username, password } = req.body; try { const user = await register({ username, password }); res.status(201).json({ username: user.username, registered: true, }); } catch (err) { res.status(201).json({ error: 'Could not create username', }); } }; export { getAccessToken, getRefreshToken, authUserFromAccessToken, validateRefreshToken, registerUser, };
const logger = require('winston'); const app = require('./app'); const port = app.get('port'); const server = app.listen(port); process.on('unhandledRejection', (reason, p) => logger.error('Unhandled Rejection at: Promise ', p, reason) ); server.on('listening', () => logger.info( 'Feathers application started on http://%s:%d', app.get('host'), port ) );
define(['joga', 'text!Inspector.html'], function (joga, html) { function Inspector() { this.inspectee = joga.objectProperty(window); this.element = joga.elementProperty(html); } Inspector.prototype.properties = function () { var properties = []; for (var prop in this.inspectee()) { properties.push(document.createTextNode(prop)); } return properties; }; return Inspector; });
/// <reference path="../../../src/bobril.d.ts"/> var GameOfLifeApp; (function (GameOfLifeApp) { var HeaderLevel; (function (HeaderLevel) { HeaderLevel[HeaderLevel["H1"] = 0] = "H1"; HeaderLevel[HeaderLevel["H2"] = 1] = "H2"; HeaderLevel[HeaderLevel["H3"] = 2] = "H3"; })(HeaderLevel = GameOfLifeApp.HeaderLevel || (GameOfLifeApp.HeaderLevel = {})); var Header = (function () { function Header() { } Header.getTag = function (level) { switch (level) { case HeaderLevel.H1: return "h1"; case HeaderLevel.H2: return "h2"; case HeaderLevel.H3: return "h3"; } }; Header.render = function (ctx, me) { me.tag = this.getTag(ctx.data.level); me.children = ctx.data.content; }; return Header; }()); GameOfLifeApp.Header = Header; })(GameOfLifeApp || (GameOfLifeApp = {}));
{ if (node instanceof HTMLShadowElement) return; if (node instanceof HTMLContentElement) { var content = node; this.updateDependentAttributes(content.getAttribute("select")); var anyDistributed = false; for (var i = 0; i < pool.length; i++) { var node = pool[i]; if (!node) continue; if (matches(node, content)) { destributeNodeInto(node, content); pool[i] = undefined; anyDistributed = true; } } if (!anyDistributed) { for (var child = content.firstChild; child; child = child.nextSibling) { destributeNodeInto(child, content); } } return; } for (var child = node.firstChild; child; child = child.nextSibling) { this.poolDistribution(child, pool); } }
/** * Created by gt60 on 13-11-12. */ var ZorderTouchMenu = cc.Menu.extend({ ctor:function (){ cc.Menu.prototype.ctor.call(this); this.initWithItems(); }, _itemForTouch:function (touch) { var touchLocation = touch.getLocation(); var itemChildren = this.children, locItemChild; if (itemChildren && itemChildren.length > 0) { for (var i = itemChildren.length - 1; i >= 0; i--) { locItemChild = itemChildren[i]; if (locItemChild.isVisible() && locItemChild.isEnabled()) { var local = locItemChild.convertToNodeSpace(touchLocation); var r = locItemChild.rect(); r.x = 0; r.y = 0; if (cc.rectContainsPoint(r, local)) return locItemChild; } } } return null; } }); var MouseOverMenu = ZorderTouchMenu.extend({ _mouseOverItem:null, _mouseListener:null, ctor:function () { ZorderTouchMenu.prototype.ctor.call(this); this._mouseListener = cc.EventListener.create({ event: cc.EventListener.MOUSE, onMouseMove: this.onMouseMove }); if ('mouse' in cc.sys.capabilities && !this._mouseListener._isRegistered()) { cc.eventManager.addListener(this._mouseListener, this); } }, onMouseMove:function (event) { var target = event.getCurrentTarget(); var currentItem = target._itemForOver(event.getLocation()); if (currentItem != target._mouseOverItem) { if (target._mouseOverItem) { target._mouseOverItem.unselected(); } target._mouseOverItem = currentItem; if (target._mouseOverItem) { target._mouseOverItem.selected(event.getLocation()); } } }, _itemForOver:function (touchLocation) { var itemChildren = this.children, locItemChild; if (itemChildren && itemChildren.length > 0) { for (var i = itemChildren.length - 1; i >= 0; i--) { locItemChild = itemChildren[i]; if (locItemChild && locItemChild.isVisible()) { var local = locItemChild.convertToNodeSpace(touchLocation); var r = locItemChild.rect(); r.x = 0; r.y = 0; if (cc.rectContainsPoint(r, local)) return locItemChild; } } } return null; } }); var CardMenu = MouseOverMenu.extend({ _downCallBack:null, _movedCallback:null, _targetLayer:null, ctor:function (callback1, callback2, targrt) { MouseOverMenu.prototype.ctor.call(this); this._downCallBack = callback1; this._movedCallback = callback2; this._targetLayer = targrt; }, _onTouchBegan:function (touch, event) { var target = event.getCurrentTarget(); target._selectedItem = target._itemForTouch(touch); if (target._selectedItem) { target._selectedItem.unselected(); target._selectedItem.activate(); return true; } return false; }, _onTouchMoved:function (touch, event) { var target = event.getCurrentTarget(); target._state = cc.MENU_STATE_TRACKING_TOUCH; event._currentTarget = target._targetLayer; target._movedCallback([touch], event); }, _onTouchEnded:function (touch, event) { var target = event.getCurrentTarget(); if (target._state == cc.MENU_STATE_TRACKING_TOUCH) { target._state = cc.MENU_STATE_WAITING; event._currentTarget = target._targetLayer; target._downCallBack([touch], event); } } }); var CARD_TAG = 100; var SelectDialog = cc.Sprite.extend({ _maxNum:8, _list:[], _callback:null, _targetLayer:null, _menu:null, _finishBtn:null, ctor:function (list, callback, target, max) { this._super(res.PlantSelect); this._list = list; this._callback = callback; this._targetLayer = target; this._maxNum = max || this._maxNum; this._menu = new MouseOverMenu(); this._menu.setPosition(cc.p(-100, 0)); this.addChild(this._menu); var title = cc.LabelTTF.create("请选择您的植物,最大数量:" + this._maxNum, "宋体", 20); title.setColor(cc.color.YELLOW); title.setPosition(cc.p(230, 535)); this.addChild(title); for (var i in this._list) { var plant = this._list[i]; var card = new CardSprite(plant); var row = i % 5; var col = parseInt(i / 5, 10); card.initWithCallback(this.onCardSelect, this); card.setColor(cc.color.WHITE); card.setScale(0.85); card.setPosition(cc.p(155 + row * 89, 490 + col * -55)); this._menu.addChild(card, 1, CARD_TAG + i); } cc.MenuItemFont.setFontName("宋体"); cc.MenuItemFont.setFontSize(25); var reset = cc.MenuItemFont.create("重选", this.onReset, this); reset.setColor(cc.color.YELLOW); reset.setPosition(cc.p(-300, -250)); this._finishBtn = cc.MenuItemFont.create("完成", this.onFinish, this); this._finishBtn.setColor(cc.color.YELLOW); this._finishBtn.setPosition(cc.p(-150, -250)); this._finishBtn.setEnabled(false); var menu = cc.Menu.create(reset, this._finishBtn); this.addChild(menu); }, onCardSelect:function (sender) { var cards = PZ.CONTAINER.CARDS; if (sender.getState() == PZ.CARD_STATE.SELECTED) { sender.setState(0); sender.setColor(cc.color.WHITE); this.removeCard(sender._plantType); } else if (cards.length < this._maxNum) { sender.setState(PZ.CARD_STATE.SELECTED); sender.setColor(cc.color.GRAY); this.addCard(sender._plantType); } }, addCard:function (cardType) { this._finishBtn.setEnabled(true); var cards = PZ.CONTAINER.CARDS; var len = cards.length; cards.push(cardType); var card = new CardSprite(cardType); card.setPosition(card.rect().width / 2, cc.visibleRect.height - card.rect().height * (0.5 + len)); this._menu.addChild(card, 1, len); }, removeCard:function (cardType) { var cards = PZ.CONTAINER.CARDS; var id; for (var i = 0; i < cards.length; ++i) { if (cardType == cards[i]) { id = i; break; } } this._menu.removeChildByTag(id); for (var i = id + 1; i < cards.length; ++i) { var nextCard = this._menu.getChildByTag(i); nextCard.setTag(i - 1); nextCard.setPosition(cc.pAdd(nextCard.getPosition(), cc.p(0, nextCard.rect().height))); } cards.splice(id, 1); if (cards.length <= 0) { this._finishBtn.setEnabled(false); } }, onReset:function () { for (var i in PZ.CONTAINER.CARDS) { this._menu.removeChildByTag(i); } PZ.CONTAINER.CARDS = []; for (var i in this._list) { var card = this._menu.getChildByTag(CARD_TAG + i); card.setState(0); card.setColor(cc.color.WHITE); } }, onFinish:function () { this.removeFromParent(true); this._callback.call(this._targetLayer, this); } }); var OptionMenu = cc.Menu.extend({ _menuOfParent:null, _OptionBtn:null, ctor:function (menu) { cc.Menu.prototype.ctor.call(this); this.initWithItems(null, null); if (menu) { this._menuOfParent = menu; } var OptionsMenuback = cc.MenuItemImage.create(res.OptionsMenuback); OptionsMenuback.setEnabled(false); this.addChild(OptionsMenuback); var btnNormal = cc.Sprite.create(res.OptionsBackButton, cc.rect(0, 0, 360, 100)); var label = cc.LabelTTF.create("回 到 游 戏", "微软雅黑", 35); label.setPosition(cc.p(180, 55)); btnNormal.addChild(label); var btnSelected = cc.Sprite.create(res.OptionsBackButton, cc.rect(0, 100, 360, 100)); var label2 = cc.LabelTTF.create("回 到 游 戏", "微软雅黑", 35); label2.setPosition(cc.p(180, 53)); btnSelected.addChild(label2); this._OptionBtn = cc.MenuItemSprite.create( btnNormal, btnSelected, function (sender) { if (this._menuOfParent) { var blank = this._menuOfParent.getChildByTag(BLANK_ZORDER); blank.removeFromParent(true); } cc.director.resume(); this.removeFromParent(true); }, this); this._OptionBtn.setPosition(cc.p(0, -190)); this.addChild(this._OptionBtn); }, onEnter:function () { cc.Menu.prototype.onEnter.call(this); if (this._menuOfParent) { var blank = new BlankItem(); this._menuOfParent.addChild(blank, BLANK_ZORDER, BLANK_ZORDER); } cc.director.pause(); }, onExit:function () { cc.Menu.prototype.onExit.call(this); cc.director.resume(); } }); var MusicOption = OptionMenu.extend({ ctor:function (menu) { OptionMenu.prototype.ctor.call(this, menu); cc.MenuItemFont.setFontName("幼圆"); cc.MenuItemFont.setFontSize(20); var bgmLabel = cc.MenuItemFont.create("背景音乐"); bgmLabel.setDisabledColor(cc.color.WHITE); bgmLabel.setEnabled(false); bgmLabel.setPosition(cc.p(-50, 70)); var effecfLabel = cc.MenuItemFont.create("音 效"); effecfLabel.setDisabledColor(cc.color.WHITE); effecfLabel.setEnabled(false); effecfLabel.setPosition(cc.p(-50, 20)); var bgmOption = cc.MenuItemToggle.create( cc.MenuItemImage.create(res.checkBox_empty), cc.MenuItemImage.create(res.checkBox_selected), this.onBGMOption, this ); bgmOption.setSelectedIndex(PZ.MUSIC ? 1 : 0); bgmOption.setScale(1.2); bgmOption.setPosition(cc.p(50, 70)); var effectOption = cc.MenuItemToggle.create( cc.MenuItemImage.create(res.checkBox_empty), cc.MenuItemImage.create(res.checkBox_selected), this.onEffectOption, this ); effectOption.setSelectedIndex(PZ.EFFECT_SOUND ? 1 : 0); effectOption.setScale(1.2); effectOption.setPosition(cc.p(50, 20)); this.addChild(bgmLabel); this.addChild(bgmOption); this.addChild(effecfLabel); this.addChild(effectOption); }, onBGMOption:function (sender) { PZ.MUSIC = sender.getSelectedIndex() == 1; }, onEffectOption:function (sender) { PZ.EFFECT_SOUND = sender.getSelectedIndex() == 1; } }); var GameOption = MusicOption.extend({ _layer:null, _oldState:null, ctor:function (menu, layer) { MusicOption.prototype.ctor.call(this, menu); this._layer = layer; this._oldState = layer._state; cc.MenuItemFont.setFontName("幼圆"); cc.MenuItemFont.setFontSize(20); var restart = cc.MenuItemFont.create( "重新开始", function () { cc.director.resume(); cc.director.runScene(cc.TransitionFade.create(0.5, layer.constructor.scene())); }, layer ); restart.setPosition(cc.p(0, -30)); var back = cc.MenuItemFont.create( "返回菜单", function () { cc.director.resume(); cc.director.runScene(cc.TransitionFade.create(1, WelcomeLayer.scene())); }, layer ); back.setPosition(cc.p(0, -70)); this.addChild(restart); this.addChild(back); }, onEnter:function () { this._super(); this._layer._state = PZ.GAME_STATE.PAUSING; }, onExit:function () { this._super(); this._layer._state = this._oldState; } }); var SelectMenu = OptionMenu.extend({ ctor:function (menu) { OptionMenu.prototype.ctor.call(this, menu); cc.MenuItemFont.setFontName("幼圆"); cc.MenuItemFont.setFontSize(20); var stage1 = cc.MenuItemFont.create("第一关", this.onStageSelect); stage1.stage = GameStage.Stage1_1; stage1.setPosition(cc.p(-50, 90)); var stage2 = cc.MenuItemFont.create("第二关", this.onStageSelect); stage2.stage = GameStage.Stage1_2; stage2.setPosition(cc.p(50, 90)); var stage3 = cc.MenuItemFont.create("第三关", this.onStageSelect); stage3.stage = GameStage.Stage1_3; stage3.setPosition(cc.p(-50, 60)); var stage4 = cc.MenuItemFont.create("第四关", this.onStageSelect); stage4.stage = GameStage.Stage1_4; stage4.setPosition(cc.p(50, 60)); var stage5 = cc.MenuItemFont.create("第五关", this.onStageSelect); stage5.stage = GameStage.Stage1_5; stage5.setPosition(cc.p(-50, 30)); var stage6 = cc.MenuItemFont.create("第六关", this.onStageSelect); stage6.stage = GameStage.Stage1_6; stage6.setPosition(cc.p(50, 30)); var stage7 = cc.MenuItemFont.create("第七关", this.onStageSelect); stage7.stage = GameStage.Stage1_7; stage7.setPosition(cc.p(-50, 0)); var stage8 = cc.MenuItemFont.create("第八关", this.onStageSelect); stage8.stage = GameStage.Stage1_8; stage8.setPosition(cc.p(50, 0)); var stage9 = cc.MenuItemFont.create("第九关", this.onStageSelect); stage9.stage = GameStage.Stage1_9; stage9.setPosition(cc.p(-50, -30)); var stage10 = cc.MenuItemFont.create("第十关", this.onStageSelect); stage10.stage = GameStage.Stage1_10; stage10.setPosition(cc.p(50, -30)); var test = cc.MenuItemFont.create("测试关", this.onStageSelect); test.stage = GameStage.Test; test.setPosition(cc.p(0, -60)); this.addChild(stage1); this.addChild(stage2); this.addChild(stage3); this.addChild(stage4); this.addChild(stage5); this.addChild(stage6); this.addChild(stage7); this.addChild(stage8); this.addChild(stage9); this.addChild(stage10); this.addChild(test); }, onStageSelect:function (label) { cc.director.resume(); cc.director.runScene(cc.TransitionFade.create(1, GameLayer.scene(label.stage))); } });
import * as actionTypes from "../actionTypes"; const serverDataInitialState = {}; export default function (state = serverDataInitialState, action) { switch (action.type) { case actionTypes.serverData.SET: return action.data; case actionTypes.serverData.UPDATE: { let { server, data } = action; if (data) { let current = state[server] || {}; return { ...state, [server]: { ...current, ...data } }; } } } return state; }
define(function (require) { const ko = require("knockout"), site = require("engine/common/framework"); var EditViewModelBase = function (dirtyProperties) { this.errors = ko.validation.group(dirtyProperties, { deep: true, live: true }); this._dirtyFlag = new ko.DirtyFlag(dirtyProperties); }; EditViewModelBase.prototype = { isChanged: function () { return this._dirtyFlag().isDirty(); }, isValidated: function () { return this.errors().length === 0; }, canSave: function () { return this.isChanged() & this.isValidated(); }, resetChanged: function () { this._dirtyFlag().reset(); }, toDto: function () { var dto = site.clone(this); delete dto.resetChanged; delete dto.isChanged; delete dto.isValidated; delete dto.canSave; delete dto.errors; delete dto._dirtyFlag; delete dto.errorsList; delete dto.toDto; delete dto.__moduleId__; delete dto.constructor; return ko.toJS(dto); } } return EditViewModelBase; });
var OfflinePlugin = require(__ROOT__); var path = require('path'); var deepExtend = require('deep-extend'); var DefinePlugin = require('webpack/lib/DefinePlugin'); var compare = require('./compare'); var webpackMajorVersion = require('webpack/package.json').version.split('.')[0]; module.exports = function(OfflinePluginOptions, testFlags) { testFlags = testFlags || {}; if (testFlags.minimumWebpackMajorVersion && parseInt(webpackMajorVersion, 10) < testFlags.minimumWebpackMajorVersion) { throw new Error('unsupported webpack version'); } delete testFlags.minimumWebpackMajorVersion; var testDir = process.cwd(); var outputPath = path.join(testDir, '__output'); OfflinePluginOptions.__tests = deepExtend({ swMetadataOnly: true, ignoreRuntime: true, noVersionDump: true, appCacheEnabled: true, pluginVersion: '999.999.999' }, testFlags); var config = { bail: true, entry: { main: 'main.js' }, output: { path: outputPath, filename: '[name].js', }, plugins: [ new OfflinePlugin(OfflinePluginOptions), new DefinePlugin({ RUNTIME_PATH: JSON.stringify(path.join(__ROOT__, 'runtime')) }), ], resolve: { modules: [ path.join(testDir), 'node_modules' ], extensions: ['.js'] } }; if (webpackMajorVersion === '4') { config.mode = 'none'; config.resolve.extensions.push('.wasm'); } return config; };
import React, { PureComponent } from 'react'; export default class States extends PureComponent { props: { states: any[], selected: string, id: string, noLabel: boolean, onChange: (e: SyntheticEvent) => void, }; render() { const { states, onChange, id, selected, noLabel } = this.props; return ( <fieldset> {noLabel ? null : <label htmlFor={id}>State/Province</label>} <select id={id} onChange={onChange} value={selected}> {states.map((x, i) => ( <option key={i} value={x.value}>{x.text}</option> ))} </select> </fieldset> ); } }
import React from "react"; import { shallow } from "enzyme"; import renderer from "react-test-renderer"; import { spy } from "sinon"; import AddButton from "../../app/components/AddButton"; describe("Add Button component", () => { it("should be defined", () => { expect(AddButton).toBeDefined(); }); it("Should match snapshot", () => { const tree = renderer.create(<AddButton add={jest.fn()} />).toJSON(); expect(tree).toMatchSnapshot(); }); it("Should render a button", () => { const button = shallow(<AddButton add={jest.fn()} />).find("button"); expect(button).toHaveLength(1); }); it("Should call add when clicked", () => { const toggleAdd = spy(); const component = shallow(<AddButton add={toggleAdd} />); component.find("button").simulate("click"); expect(toggleAdd.called).toBe(true); }); });
var ursa = require('ursa'); var toPEM = require('ssh-key-to-pem'); var inherits = require('inherits'); var BlockStream = require('block-stream'); var combine = require('stream-combiner2'); var through = require('through2'); var defined = require('defined'); exports.encrypt = function (pub, opts) { if (!opts) opts = {}; if (typeof pub !== 'string') pub = String(pub); if (/^ssh-\w+/.test(pub)) pub = toPEM(pub); var pubkey = ursa.createPublicKey(pub); var bufsize = pubkey.getModulus().length; var blocks = new BlockStream(bufsize - 42, { nopad: true }); var limit = defined(opts.limit, 100); var len = 0; var enc = through(function (buf, e, next) { len += buf.length; if (len > limit) { var err = new Error( 'Encryption limit (' + opts.limit + ' bytes) reached.\n' + 'It is not advisable to encrypt over (n/8-11) bytes with' + 'asymmetric crypto for an `n` byte key.\n' + 'Instead, encrypt a key data with asymmetric crypto for a ' + 'symmetric encryption cipher.\n' + 'See also: http://stackoverflow.com/questions/5583379' ); err.type = 'LIMIT'; return this.emit('error', err); } this.push(pubkey.encrypt(buf)); next(); }); if (opts.encoding === 'buffer' || opts.encoding === undefined) { return combine(blocks, enc); } return combine(blocks, enc, through({ encoding: opts.encoding })); }; exports.decrypt = function (priv, opts) { if (!opts) opts = {}; if (typeof priv !== 'string') priv = String(priv); if (/^ssh-\w+/.test(priv)) priv = toPEM(priv); var privkey = ursa.createPrivateKey(priv); var bufsize = privkey.getModulus().length; var blocks = new BlockStream(bufsize, { nopad: true }); var decrypt = through(function (buf, e, next) { var ciphertext try { ciphertext = privkey.decrypt(buf) } catch (err) { return this.emit('error', err) } this.push(ciphertext); next(); }); if (opts.encoding === 'buffer' || opts.encoding === undefined) { return combine(blocks, decrypt); } var b64decode = through(function (buf, e, next) { this.push(Buffer(buf.toString(), opts.encoding)); }); return combine(b64decode, blocks, decrypt); };
// @flow import * as npm from '../npm'; import Project from '../../Project'; import * as processes from '../processes'; import fixtures from 'fixturez'; import containDeep from 'jest-expect-contain-deep'; const f = fixtures(__dirname); jest.mock('../logger'); jest.mock('../processes'); let REAL_ENV = process.env; const unsafeProcesses: any & typeof processes = processes; describe('npm', () => { describe('publish', () => { let cwd; let result; beforeEach(async () => { cwd = f.find('simple-project'); }); afterEach(async () => { process.env = REAL_ENV; }); test('returns published true when npm publish <package> is successesful', async () => { unsafeProcesses.spawn.mockImplementation(() => Promise.resolve()); result = await npm.publish('simple-project', { cwd }); expect(result).toEqual({ published: true }); }); test('returns published false when npm publish <package> is unsuccessesful', async () => { unsafeProcesses.spawn.mockImplementation(() => Promise.reject()); result = await npm.publish('simple-project', { cwd }); expect(result).toEqual({ published: false }); }); test('Overrides the npm_config_registry env variable correctly', async () => { process.env = { npm_config_registry: 'https://registry.yarnpkg.com' }; unsafeProcesses.spawn.mockImplementation(() => Promise.resolve()); result = await npm.publish('simple-project', { cwd }); expect(unsafeProcesses.spawn).toHaveBeenCalledWith( 'npm', ['publish'], containDeep({ cwd, env: {} }) ); }); }); test('info()'); test('addTag()'); test('removeTag()'); });
import deepFreeze from 'deep-freeze'; import { narozeniSortMethod, prijmeniJmenoNarozeniSortMethod, reverseSortDirType, sortForColumn, SortDirTypes, } from './sort'; const narozeniSortMethodDescending = (a, b) => narozeniSortMethod(a, b, true); const data = [ { prijmeni: 'Balabák', jmeno: 'Roman', narozeni: { rok: 1956 }, obec: 'Ostrava 2', email: '', datum: new Date('2017-06-09T00:00:00.000Z'), kategorie: { pohlavi: 'muž', typ: 'půlmaraton', vek: { min: 60, max: 150 }, }, startCislo: 17, kod: '10728864', zaplaceno: 250, predepsano: 200, dokonceno: undefined, cas: undefined, }, { prijmeni: 'Kyselová', jmeno: 'Slavěna', narozeni: { den: 13, mesic: 8, rok: 2001 }, obec: 'Aš', email: 'sks@por.cz', datum: new Date('2018-06-09T00:00:00.000Z'), kategorie: { typ: 'půlmaraton', pohlavi: 'žena', vek: { min: 40, max: 49 }, }, zaplaceno: 0, predepsano: 200, dokonceno: false, cas: undefined, }, { prijmeni: 'Sukdoláková', jmeno: 'Martina', narozeni: { rok: 1963, mesic: 12, den: 7 }, pohlavi: 'žena', obec: 'Zlín', email: '', datum: new Date('2016-06-11T00:00:00.000Z'), kategorie: { typ: 'maraton', pohlavi: 'žena', vek: { min: 50, max: 59 }, }, zaplaceno: 0, dokonceno: true, cas: 'PT3H07M56.12S', }, { prijmeni: 'Zralá', jmeno: 'Hana', narozeni: { den: 25, mesic: 7, rok: 1999 }, obec: 'Bučovice', email: 'zrala.kl@s.cz', datum: new Date('2018-06-09T00:00:00.000Z'), kategorie: { typ: 'půlmaraton', pohlavi: 'žena', vek: { min: 18, max: 39 }, }, startCislo: 10, kod: 'abc023skd204mvs345', zaplaceno: 100, predepsano: 200, dokonceno: true, cas: 'PT1H23M32.56S', }, ]; deepFreeze(data); it('reverseSortDirType - default', () => { expect(reverseSortDirType(undefined)).toEqual('asc'); }); it('reverseSortDirType - asc->desc', () => { expect(reverseSortDirType(SortDirTypes.ASC)).toEqual('desc'); }); it('reverseSortDirType - desc->asc', () => { expect(reverseSortDirType(SortDirTypes.DESC)).toEqual('asc'); }); it('narozeniSort(desc=false) - nulls', () => { const narozeni = [null, { rok: 1978, mesic: 8, den: 7 }, null]; expect(narozeni.sort(narozeniSortMethod)).toEqual([{ rok: 1978, mesic: 8, den: 7 }, null, null]); }); it('narozeniSort(desc=false) - jen roky', () => { const narozeni = [{ rok: 1978 }, { rok: 1956 }, { rok: 2001 }]; expect(narozeni.sort(narozeniSortMethod)).toEqual([{ rok: 1956 }, { rok: 1978 }, { rok: 2001 }]); }); it('narozeniSort(desc=false) - roky, dny, měsíce', () => { const narozeni = [ { rok: 1978, mesic: 4, den: 7 }, { rok: 1956, mesic: 2, den: 25 }, { rok: 2001, mesic: 4, den: 13 }, { rok: 1956, mesic: 1, den: 26 }, { rok: 2001, mesic: 4, den: 12 }, { rok: 1956, mesic: 2, den: 25 }, ]; expect(narozeni.sort(narozeniSortMethod)).toEqual([ { rok: 1956, mesic: 1, den: 26 }, { rok: 1956, mesic: 2, den: 25 }, { rok: 1956, mesic: 2, den: 25 }, { rok: 1978, mesic: 4, den: 7 }, { rok: 2001, mesic: 4, den: 12 }, { rok: 2001, mesic: 4, den: 13 }, ]); }); it('narozeniSort(desc=false) - prázdný měsíc a den', () => { const narozeni = [ { rok: 1978, mesic: 8, den: 7 }, { rok: 1978 }, { rok: 1978, mesic: 8, den: 6 }, ]; expect(narozeni.sort(narozeniSortMethod)).toEqual([ { rok: 1978, mesic: 8, den: 6 }, { rok: 1978, mesic: 8, den: 7 }, { rok: 1978 }, ]); }); it('narozeniSort(desc=true) - nulls', () => { const narozeni = [null, { rok: 1978, mesic: 8, den: 7 }, null]; expect(narozeni.sort(narozeniSortMethodDescending)).toEqual([ null, null, { rok: 1978, mesic: 8, den: 7 }, ]); }); it('narozeniSort(desc=true) - jen roky', () => { const narozeni = [{ rok: 1978 }, { rok: 1956 }, { rok: 2001 }]; expect(narozeni.sort(narozeniSortMethodDescending)).toEqual([ { rok: 1956 }, { rok: 1978 }, { rok: 2001 }, ]); }); it('narozeniSort(desc=true) - roky, dny, měsíce', () => { const narozeni = [ { rok: 1978, mesic: 4, den: 7 }, { rok: 1956, mesic: 2, den: 25 }, { rok: 2001, mesic: 4, den: 13 }, { rok: 1956, mesic: 1, den: 26 }, { rok: 2001, mesic: 4, den: 12 }, { rok: 1956, mesic: 2, den: 25 }, ]; expect(narozeni.sort(narozeniSortMethodDescending)).toEqual([ { rok: 1956, mesic: 1, den: 26 }, { rok: 1956, mesic: 2, den: 25 }, { rok: 1956, mesic: 2, den: 25 }, { rok: 1978, mesic: 4, den: 7 }, { rok: 2001, mesic: 4, den: 12 }, { rok: 2001, mesic: 4, den: 13 }, ]); }); it('narozeniSort(desc=true) - prázdný měsíc a den', () => { const narozeni = [ { rok: 1978, mesic: 8, den: 7, id: 1 }, { rok: 1978, id: 2 }, { rok: 1978, mesic: 10, id: 3 }, { rok: 1978, mesic: 10, id: 4 }, { rok: 1978, mesic: 8, den: 6, id: 5 }, { rok: 1978, mesic: 8, den: 5, id: 6 }, { rok: 1978, mesic: 9, id: 7 }, { rok: 1978, mesic: 10, id: 8 }, ]; expect(narozeni.sort(narozeniSortMethodDescending)).toEqual([ { rok: 1978, id: 2 }, { rok: 1978, mesic: 8, den: 5, id: 6 }, { rok: 1978, mesic: 8, den: 6, id: 5 }, { rok: 1978, mesic: 8, den: 7, id: 1 }, { rok: 1978, mesic: 9, id: 7 }, { rok: 1978, mesic: 10, id: 3 }, { rok: 1978, mesic: 10, id: 4 }, { rok: 1978, mesic: 10, id: 8 }, ]); }); it('narozeniSort(desc=true) - prázdný den', () => { const narozeni = [{ rok: 1978, mesic: 8 }, { rok: 1978 }, { rok: 1978, mesic: 8, den: 6 }]; expect(narozeni.sort(narozeniSortMethodDescending)).toEqual([ { rok: 1978 }, { rok: 1978, mesic: 8 }, { rok: 1978, mesic: 8, den: 6 }, ]); }); it('prijmeniJmenoNarozeniSortMethod - podle jména', () => { const ucastnici = [ { prijmeni: 'Bubáková', jmeno: 'Milena', narozeni: { rok: 1978, mesic: 8, den: 7 } }, { prijmeni: 'Bubáková', jmeno: 'Alena', narozeni: { rok: 1999, mesic: 1, den: 23 } }, ]; expect(ucastnici.sort(prijmeniJmenoNarozeniSortMethod)).toEqual([ { prijmeni: 'Bubáková', jmeno: 'Alena', narozeni: { rok: 1999, mesic: 1, den: 23 } }, { prijmeni: 'Bubáková', jmeno: 'Milena', narozeni: { rok: 1978, mesic: 8, den: 7 } }, ]); }); it('prijmeniJmenoNarozeniSortMethod - podle narození', () => { const ucastnici = [ { prijmeni: 'Bubáková', jmeno: 'Milena', narozeni: { rok: 1999, mesic: 8, den: 7 } }, { prijmeni: 'Bubáková', jmeno: 'Milena', narozeni: { rok: 1968, mesic: 1, den: 23 } }, ]; expect(ucastnici.sort(prijmeniJmenoNarozeniSortMethod)).toEqual([ { prijmeni: 'Bubáková', jmeno: 'Milena', narozeni: { rok: 1968, mesic: 1, den: 23 } }, { prijmeni: 'Bubáková', jmeno: 'Milena', narozeni: { rok: 1999, mesic: 8, den: 7 } }, ]); }); it('sortForColumn - prijmeni ASC', () => { expect(sortForColumn({ data, sortColumn: 'prijmeni', sortDir: SortDirTypes.ASC })).toEqual([ data[0], data[1], data[2], data[3], ]); }); it('sortForColumn - prijmeni DESC', () => { expect(sortForColumn({ data, sortColumn: 'prijmeni', sortDir: SortDirTypes.DESC })).toEqual([ data[3], data[2], data[1], data[0], ]); }); it('sortForColumn - jmeno ASC', () => { expect(sortForColumn({ data, sortColumn: 'jmeno', sortDir: SortDirTypes.ASC })).toEqual([ data[3], data[2], data[0], data[1], ]); }); it('sortForColumn - jmeno DESC', () => { expect(sortForColumn({ data, sortColumn: 'jmeno', sortDir: SortDirTypes.DESC })).toEqual([ data[1], data[0], data[2], data[3], ]); }); it('sortForColumn - obec ASC', () => { expect(sortForColumn({ data, sortColumn: 'obec', sortDir: SortDirTypes.ASC })).toEqual([ data[1], data[3], data[0], data[2], ]); }); it('sortForColumn - email DESC', () => { expect(sortForColumn({ data, sortColumn: 'email', sortDir: SortDirTypes.DESC })).toEqual([ data[3], data[1], data[2], data[0], ]); }); it('sortForColumn - datum ASC', () => { expect(sortForColumn({ data, sortColumn: 'datum', sortDir: SortDirTypes.ASC })).toEqual([ data[2], data[0], data[1], data[3], ]); }); it('sortForColumn - datum DESC', () => { expect(sortForColumn({ data, sortColumn: 'datum', sortDir: SortDirTypes.DESC })).toEqual([ data[3], data[1], data[0], data[2], ]); }); it('sortForColumn - kategorie ASC', () => { expect(sortForColumn({ data, sortColumn: 'kategorie', sortDir: SortDirTypes.ASC })).toEqual([ data[2], data[0], data[3], data[1], ]); }); it('sortForColumn - kategorie DESC', () => { expect(sortForColumn({ data, sortColumn: 'kategorie', sortDir: SortDirTypes.DESC })).toEqual([ data[1], data[3], data[0], data[2], ]); }); it('sortForColumn - startCislo ASC', () => { expect(sortForColumn({ data, sortColumn: 'startCislo', sortDir: SortDirTypes.ASC })).toEqual([ data[3], data[0], data[1], data[2], ]); }); it('sortForColumn - startCislo DESC', () => { expect(sortForColumn({ data, sortColumn: 'startCislo', sortDir: SortDirTypes.DESC })).toEqual([ data[0], data[3], data[2], data[1], ]); }); it('sortForColumn - zaplaceno ASC', () => { expect(sortForColumn({ data, sortColumn: 'zaplaceno', sortDir: SortDirTypes.ASC })).toEqual([ data[1], data[2], data[3], data[0], ]); }); it('sortForColumn - zaplaceno DESC', () => { expect(sortForColumn({ data, sortColumn: 'zaplaceno', sortDir: SortDirTypes.DESC })).toEqual([ data[0], data[3], data[2], data[1], ]); }); it('sortForColumn - dokonceno ASC', () => { expect(sortForColumn({ data, sortColumn: 'dokonceno', sortDir: SortDirTypes.ASC })).toEqual([ data[2], data[3], data[1], data[0], ]); }); it('sortForColumn - dokonceno DESC', () => { expect(sortForColumn({ data, sortColumn: 'dokonceno', sortDir: SortDirTypes.DESC })).toEqual([ data[0], data[1], data[3], data[2], ]); }); it('sortForColumn - cas ASC', () => { expect(sortForColumn({ data, sortColumn: 'cas', sortDir: SortDirTypes.ASC })).toEqual([ data[3], data[2], data[0], data[1], ]); }); it('sortForColumn - cas DESC', () => { expect(sortForColumn({ data, sortColumn: 'cas', sortDir: SortDirTypes.DESC })).toEqual([ data[2], data[3], data[1], data[0], ]); });
import { on } from './event'; import promiseFn from './promise'; import { query } from './selector'; import { getCssVar } from './style'; export function bind(fn, context) { return function (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(context, arguments) : fn.call(context, a) : fn.call(context); }; } var hasOwnProperty = Object.prototype.hasOwnProperty; export function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } export const Promise = 'Promise' in window ? window.Promise : promiseFn; export class Deferred { constructor() { this.promise = new Promise((resolve, reject) => { this.reject = reject; this.resolve = resolve; }); } } const classifyRe = /(?:^|[-_\/])(\w)/g; export function classify(str) { return str.replace(classifyRe, (_, c) => c ? c.toUpperCase() : ''); } const hyphenateRe = /([a-z\d])([A-Z])/g; export function hyphenate(str) { return str .replace(hyphenateRe, '$1-$2') .toLowerCase(); } const camelizeRE = /-(\w)/g; export function camelize(str) { return str.replace(camelizeRE, toUpper); } function toUpper(_, c) { return c ? c.toUpperCase() : ''; } export function ucfirst(str) { return str.length ? toUpper(null, str.charAt(0)) + str.slice(1) : ''; } var strPrototype = String.prototype; var startsWithFn = strPrototype.startsWith || function (search) { return this.lastIndexOf(search, 0) === 0; }; export function startsWith(str, search) { return startsWithFn.call(str, search); } var endsWithFn = strPrototype.endsWith || function (search) { return this.substr(-search.length) === search; }; export function endsWith(str, search) { return endsWithFn.call(str, search); } var includesFn = function (search) { return ~this.indexOf(search); }; var includesStr = strPrototype.includes || includesFn; var includesArray = Array.prototype.includes || includesFn; export function includes(obj, search) { return obj && (isString(obj) ? includesStr : includesArray).call(obj, search); } export const isArray = Array.isArray; export function isFunction(obj) { return typeof obj === 'function'; } export function isObject(obj) { return obj !== null && typeof obj === 'object'; } export function isPlainObject(obj) { return isObject(obj) && Object.getPrototypeOf(obj) === Object.prototype; } export function isWindow(obj) { return isObject(obj) && obj === obj.window; } export function isDocument(obj) { return isObject(obj) && obj.nodeType === 9; } export function isBoolean(value) { return typeof value === 'boolean'; } export function isString(value) { return typeof value === 'string'; } export function isNumber(value) { return typeof value === 'number'; } export function isNumeric(value) { return isNumber(value) || isString(value) && !isNaN(value - parseFloat(value)); } export function isUndefined(value) { return value === void 0; } export function toBoolean(value) { return isBoolean(value) ? value : value === 'true' || value === '1' || value === '' ? true : value === 'false' || value === '0' ? false : value; } export function toNumber(value) { var number = Number(value); return !isNaN(number) ? number : false; } export function toFloat(value) { return parseFloat(value) || 0; } export function toList(value) { return isArray(value) ? value : isString(value) ? value.split(/,(?![^(]*\))/).map(value => isNumeric(value) ? toNumber(value) : toBoolean(value.trim())) : [value]; } var vars = {}; export function toMedia(value) { if (isString(value)) { if (value[0] === '@') { var name = `media-${value.substr(1)}`; value = vars[name] || (vars[name] = toFloat(getCssVar(name))); } else if (isNaN(value)) { return value; } } return value && !isNaN(value) ? `(min-width: ${value}px)` : false; } export function coerce(type, value, context) { if (type === Boolean) { return toBoolean(value); } else if (type === Number) { return toNumber(value); } else if (type === 'query') { return query(value, context); } else if (type === 'list') { return toList(value); } else if (type === 'media') { return toMedia(value); } return type ? type(value) : value; } export function toMs(time) { return !time ? 0 : endsWith(time, 'ms') ? toFloat(time) : toFloat(time) * 1000; } export function swap(value, a, b) { return value.replace(new RegExp(`${a}|${b}`, 'mg'), function (match) { return match === a ? b : a; }); } export const assign = Object.assign || function (target, ...args) { target = Object(target); for (var i = 0; i < args.length; i++) { var source = args[i]; if (source !== null) { for (var key in source) { if (hasOwn(source, key)) { target[key] = source[key]; } } } } return target; }; export function each(obj, cb) { for (var key in obj) { if (cb.call(obj[key], obj[key], key) === false) { break; } } } export function clamp(number, min = 0, max = 1) { return Math.min(Math.max(number, min), max); } export function noop() {} export function intersectRect(r1, r2) { return r1.left <= r2.right && r2.left <= r1.right && r1.top <= r2.bottom && r2.top <= r1.bottom; } export function pointInRect(point, rect) { return intersectRect({top: point.y, bottom: point.y, left: point.x, right: point.x}, rect); } export function ajax(url, options) { return new Promise((resolve, reject) => { var env = assign({ data: null, method: 'GET', headers: {}, xhr: new XMLHttpRequest(), beforeSend: noop, responseType: '' }, options); var xhr = env.xhr; env.beforeSend(env); for (var prop in env) { if (prop in xhr) { try { xhr[prop] = env[prop]; } catch (e) {} } } xhr.open(env.method.toUpperCase(), url); for (var header in env.headers) { xhr.setRequestHeader(header, env.headers[header]); } on(xhr, 'load', () => { if (xhr.status === 0 || xhr.status >= 200 && xhr.status < 300 || xhr.status === 304) { resolve(xhr); } else { reject(assign(Error(xhr.statusText), { xhr, status: xhr.status })); } }); on(xhr, 'error', () => reject(assign(Error('Network Error'), {xhr}))); on(xhr, 'timeout', () => reject(assign(Error('Network Timeout'), {xhr}))); xhr.send(env.data); }); }
'use strict'; var _react = require('react'); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultMessage = '\nGatsby is currently using the default _template. You can override it by\ncreating a React component at "/pages/_template.js".\n\nYou can see what this default template does by visiting:\nhttps://github.com/gatsbyjs/gatsby/blob/master/lib/isomorphic/pages/_template.js\n'; /* weak */ console.info(defaultMessage); function template(props) { return _react2.default.createElement( 'div', null, props.children ); } template.propTypes = { children: _react.PropTypes.node }; template.defaultProps = { children: null }; module.exports = template;
var app = require('express')(); var http = require('http').Server(app); var io = require('socket.io')(http); app.get('/', function(req, res){ res.sendFile(__dirname + '/Chat'); // res.send('<h1>Hello world</h1>'); }); // http.listen(3000, funcion(){ io.listen(3000, function(){ console.log('listening on *:3000'); }); io.on('connection', function(socket){ // connect // inherit from tutorial console.log('A user connected.'); // disconnect // inherit from tutorial socket.on('disconnect', function(){ console.log('user disconnected'); }); // ping all user when new user connected // inherit from tutorial socket.on('room', function(room) { socket.join(room); console.log("someone joined " + room); // TODO: remove testing line var message = 'Lets welcome a new buddy to ' + room; io.sockets.in(room).emit('chat message', message); console.log("emited message: " + message); }); /** ======================================== * Real Work * ======================================== */ // message socket.on('thread', function(data){ var r = data['room']; var d = data['html']; io.sockets.in(r).emit('thread', d); }); // vote socket.on('vote', function(data){ io.emit('vote', data); }); // hand socket.on('hand', function(data){ io.emit('hand', data); }); // respond socket.on('respond', function(data){ io.emit('respond', data); }); // delegate respond socket.on('delegate respond', function(data){ var r = data['room']; var d = { "user": data['user'], "message": data['message'] }; io.sockets.in(r).emit('delegate respond', data); }); // depreciated socket.on('live vote', function(data){ io.emit('live vote', data); }); // poll start socket.on('poll start', function(data){ var r = data['room']; var d = data['data']; io.sockets.in(r).emit('poll start', d); }); // poll vote socket.on('poll vote', function(data){ var r = data['room']; var d = data['data']; console.log("poll vote in " + r); io.sockets.in(r).emit('poll vote', d); }); // message socket.on('system broadcasting', function(msg){ io.emit('system broadcasting', msg); }); /* // send a message to everyone except for certain socket socket.broadcast.emit('hi'); */ });
'use strict'; const expect = require('chai').expect; const coMocha = require('co-mocha'); const VError = require('verror'); const Tree = require('../lib/tree'); const SrcCollection = require('../lib/src-collection'); const Logger = require('shark-logger'); const path = require('path'); const cofse = require('co-fs-extra'); describe('Initialization',function(){ before(function() { this.logger = Logger({ name: 'SharkTreeLogger' }); }); it('should parse {"dest/path": "src/path"}', function *() { var dest = path.join(__dirname, './fixtures/dest-a.txt'); var src = path.join(__dirname, './fixtures/1.txt'); var files = {}; files[dest] = src; var tree = yield Tree(files, this.logger); expect(tree.getSrcCollectionByDest(dest).getFileByIndex(0).getSrc()).equal(src); }); it('should parse {"dest/path": ["src/path/1", "src/path/2"]}', function *() { var dest = path.join(__dirname, './fixtures/dest-a.txt'); var src1 = path.join(__dirname, './fixtures/1.txt'); var src2 = path.join(__dirname, './fixtures/2.txt'); var files = {}; files[dest] = [src1, src2]; var tree = yield Tree(files, this.logger); expect(tree.getSrcCollectionByDest(dest).getFileByIndex(0).getSrc()).equal(src1); expect(tree.getSrcCollectionByDest(dest).getFileByIndex(1).getSrc()).equal(src2); }); it('should parse {"dest/path": {files: ["src/path/1", "src/path/2"], options: {test: "ipsum"}}}}', function *() { var dest = path.join(__dirname, './fixtures/dest-a.txt'); var src1 = path.join(__dirname, './fixtures/1.txt'); var src2 = path.join(__dirname, './fixtures/2.txt'); var files = {}; files[dest] = { files: [src1, src2], options: { test: 'ipsum' } }; var tree = yield Tree(files, this.logger); expect(tree.getSrcCollectionByDest(dest).getFileByIndex(0).getSrc()).equal(src1); expect(tree.getSrcCollectionByDest(dest).getFileByIndex(1).getSrc()).equal(src2); expect(tree.getSrcCollectionByDest(dest).getOptions()).eql({test: 'ipsum'}); }); it('should exclude invalid path/2 {"dest/path": ["src/path/valid/1", "src/path/invalid/2"]}', function *() { var dest = path.join(__dirname, './fixtures/dest-a.txt'); var src1 = path.join(__dirname, './fixtures/1.txt'); var src2 = path.join(__dirname, './fixtures/2222-invalid.txt'); var files = {}; files[dest] = [src1, src2]; var tree = yield Tree(files, this.logger); expect(tree.getSrcCollectionByDest(dest).getFileByIndex(0).getSrc()).equal(src1); expect(tree.getSrcCollectionByDest(dest).getCount()).equal(1); }); it('should createTree from dest', function *() { var dest1 = path.join(__dirname, './fixtures/dest-a.txt'); var dest2 = path.join(__dirname, './fixtures/dest-b.txt'); var src1 = path.join(__dirname, './fixtures/1.txt'); var src2 = path.join(__dirname, './fixtures/2.txt'); var files = {}; files[dest1] = [src1, src2]; files[dest2] = [src2]; var tree = yield Tree(files, this.logger); var newTree = yield tree.createTreeFromDest(dest1); expect(newTree.hasDest(dest1)).to.be.true; expect(newTree.hasDest(dest2)).to.be.false; }); });
'use strict'; var tempresultModule = angular.module('tempresult'); tempresultModule.controller ('tempresultController', ['$scope', '$http', '$location', 'Authentication', 'Tempresult', 'ngTableParams', '$modal', '$log', 'ConvertArray', function($scope, $http, $location, Authentication, Tempresult, ngTableParams, $modal, $log, ConvertArray) { var tags = "Negativo,Inflamacion leve, Celula superficiales X, Flora mixta"; $scope.currentPage = 1; $scope.pageSize = 10; $scope.q = ""; $scope.users = []; $scope.totalUsers = 0; $scope.usersPerPage = 25; // this should match however many results your API puts on one page getResultsPage(1, $scope.q); $scope.pagination = { current: 1 }; $scope.pageChanged = function(newPage, filter) { getResultsPage(newPage, filter); }; function getResultsPage(pageNumber, filterLetter) { $http.get('api/template', { params: { page: pageNumber, count: 4, filter: filterLetter } }) .then(function(result) { $scope.users = result.data.results; $scope.totalUsers = result.data.total console.log(result); }); } //Open the middleware to open a single cliente modal. this.modelRemove = function (size, selectedcliente) { $scope.patient = selectedcliente; var modalInstance = $modal.open({ templateUrl: 'tempresult/views/patient-delete.template.html', controller: //'modalDelete', function ($scope, $modalInstance, patient) { $scope.patient = patient; $scope.ok = function () { //console.log($scope.cliente); // $scope.doSearch(); $modalInstance.close($scope.patient); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }, size: size, resolve: { patient: function () { return selectedcliente; } } }); modalInstance.result.then(function (selectedcliente) { $scope.selected = selectedcliente; //console.log($scope.selected); }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; //Open the middleware to open a single pais modal. this.modelUpdate = function (size, selectedTemplate) { var modalInstance = $modal.open({ templateUrl: 'tempresult/views/edit-tempresult.client.view.html', controller: function ($scope, $modalInstance, patient) { $scope.selectedTemplate = selectedTemplate; $scope.ok = function () { $modalInstance.close($scope.selectedTemplate); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }, size: size, resolve: { patient: function () { return selectedTemplate; } } }); modalInstance.result.then(function (selectedItem) { $scope.selected = selectedItem; }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; this.modelCreate = function (size) { var modalInstance = $modal.open({ templateUrl: 'tempresult/views/create-tempresult.client.view.html', controller: function ($scope, $modalInstance) { $scope.ok = function () { $modalInstance.close($scope.patient); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; }, size: size }); modalInstance.result.then(function (selectedItem) { }, function () { $log.info('Modal dismissed at: ' + new Date()); }); }; this.doSearch = function () { $scope.tableParams.reload(); }; } ]); tempresultModule.controller ('tempresultCreateController', ['$scope', '$http', '$routeParams', 'Tempresult', function($scope, $http, $routeParams, Tempresult) { this.create = function(){ var template = new Tempresult({ reportname : $scope.reportname, tipomuestra : $scope.proType, resultado: $scope.resultado, tecnica: $scope.tecnica, diagnostico : $scope.diagnostico, nota: $scope.nota }); template.$save(function(response){ console.log(response); }, function(errorResponse) { // En otro caso, presentar al usuario el mensaje de error $scope.error = errorResponse.data.message console.log($scope.error); }); }; } ]); tempresultModule.controller ('tempresultUpdateController', ['$scope', '$http', '$routeParams', 'Authentication', 'Tempresult', function($scope, $http, $routeParams, Authentication, Tempresult) { this.update = function(template){ var template = new Tempresult({ _id: $scope.selectedTemplate._id, reportname: $scope.selectedTemplate.reportname, tipomuestra: $scope.selectedTemplate.tipomuestra, resultado: $scope.selectedTemplate.resultado, tecnica: $scope.selectedTemplate.tecnica, nota: $scope.selectedTemplate.nota, diagnostico: $scope.selectedTemplate.diagnostico }); console.log(template); template.$update(function(){ }, function(err){ console.log('There was error'); }); }; } ]); tempresultModule.controller('tempresultDeleteController', ['$scope', 'Authentication', 'tempresult', 'Notify', '$mdToast', '$animate', function($scope, Authentication, tempresult, Notify, $mdToast, $animate) { $scope.authentication = Authentication; // Update existing Pai this.delete = function(patient) { //console.log ('passed'); var patient = new tempresult({ _id: $scope.patient._id }); console.log($scope.patient); patient.$remove(function(){ Notify.sendMsg('newPis', {'id': 'nada'}); }, function(errorResponse) { $scope.error = errorResponse.data.message; }); }; this.showSimpleToast = function() { $mdToast.show( $mdToast.simple() .content('Paciente Eliminado!!') .position('bottom right') .hideDelay(3000) ); }; } ]); tempresultModule.directive('templateList', ['tempresult', 'Notify', function(Cliente, Notify){ return { restrict: 'E', transclude: true, templateUrl: 'tempresult/views/tempresult-list.template.html', link: function(scope, element, attr){ // when a new procedimiento is added update the cliente List.. Notify.getMsg('newPis', function(event, data){ scope.pacientsCtrl.doSearch(); }); } }; }]);
import Ember from 'ember'; import zfWidget from 'ember-cli-foundation-6-sass/mixins/zf-widget'; export default Ember.Component.extend(zfWidget, { /** @member tag type */ tagName: 'ul', /** @member Class names */ classNames: ['vertical', 'menu'], /** @member Attribute bindings */ attributeBindings: ['data-drilldown'], /** @member Makes the data attribute binding appear */ 'data-drilldown': ' ', /** @member Foundation type */ 'zfType': 'Drilldown', /** @member Foundation specific options */ 'zfOptions': ['backButton', 'wrapper', 'closeOnClick'] });
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; const invariant = require('fbjs/lib/invariant'); export type ViewToken = {item: any, key: string, index: ?number, isViewable: boolean, section?: any}; export type ViewabilityConfig = {| /** * Minimum amount of time (in milliseconds) that an item must be physically viewable before the * viewability callback will be fired. A high number means that scrolling through content without * stopping will not mark the content as viewable. */ minimumViewTime?: number, /** * Percent of viewport that must be covered for a partially occluded item to count as * "viewable", 0-100. Fully visible items are always considered viewable. A value of 0 means * that a single pixel in the viewport makes the item viewable, and a value of 100 means that * an item must be either entirely visible or cover the entire viewport to count as viewable. */ viewAreaCoveragePercentThreshold?: number, /** * Similar to `viewAreaPercentThreshold`, but considers the percent of the item that is visible, * rather than the fraction of the viewable area it covers. */ itemVisiblePercentThreshold?: number, /** * Nothing is considered viewable until the user scrolls or `recordInteraction` is called after * render. */ waitForInteraction?: boolean, |}; /** * A Utility class for calculating viewable items based on current metrics like scroll position and * layout. * * An item is said to be in a "viewable" state when any of the following * is true for longer than `minimumViewTime` milliseconds (after an interaction if `waitForInteraction` * is true): * * - Occupying >= `viewAreaCoveragePercentThreshold` of the view area XOR fraction of the item * visible in the view area >= `itemVisiblePercentThreshold`. * - Entirely visible on screen */ class ViewabilityHelper { _config: ViewabilityConfig; _hasInteracted: boolean = false; _lastUpdateTime: number = 0; _timers: Set<number> = new Set(); _viewableIndices: Array<number> = []; _viewableItems: Map<string, ViewToken> = new Map(); constructor(config: ViewabilityConfig = {viewAreaCoveragePercentThreshold: 0}) { this._config = config; } /** * Cleanup, e.g. on unmount. Clears any pending timers. */ dispose() { this._timers.forEach(clearTimeout); } /** * Determines which items are viewable based on the current metrics and config. */ computeViewableItems( itemCount: number, scrollOffset: number, viewportHeight: number, getFrameMetrics: (index: number) => ?{length: number, offset: number}, renderRange?: {first: number, last: number}, // Optional optimization to reduce the scan size ): Array<number> { const {itemVisiblePercentThreshold, viewAreaCoveragePercentThreshold} = this._config; const viewAreaMode = viewAreaCoveragePercentThreshold != null; const viewablePercentThreshold = viewAreaMode ? viewAreaCoveragePercentThreshold : itemVisiblePercentThreshold; invariant( viewablePercentThreshold != null && (itemVisiblePercentThreshold != null) !== (viewAreaCoveragePercentThreshold != null), 'Must set exactly one of itemVisiblePercentThreshold or viewAreaCoveragePercentThreshold', ); const viewableIndices = []; if (itemCount === 0) { return viewableIndices; } let firstVisible = -1; const {first, last} = renderRange || {first: 0, last: itemCount - 1}; invariant( last < itemCount, 'Invalid render range ' + JSON.stringify({renderRange, itemCount}) ); for (let idx = first; idx <= last; idx++) { const metrics = getFrameMetrics(idx); if (!metrics) { continue; } const top = metrics.offset - scrollOffset; const bottom = top + metrics.length; if ((top < viewportHeight) && (bottom > 0)) { firstVisible = idx; if (_isViewable( viewAreaMode, viewablePercentThreshold, top, bottom, viewportHeight, metrics.length, )) { viewableIndices.push(idx); } } else if (firstVisible >= 0) { break; } } return viewableIndices; } /** * Figures out which items are viewable and how that has changed from before and calls * `onViewableItemsChanged` as appropriate. */ onUpdate( itemCount: number, scrollOffset: number, viewportHeight: number, getFrameMetrics: (index: number) => ?{length: number, offset: number}, createViewToken: (index: number, isViewable: boolean) => ViewToken, onViewableItemsChanged: ({viewableItems: Array<ViewToken>, changed: Array<ViewToken>}) => void, renderRange?: {first: number, last: number}, // Optional optimization to reduce the scan size ): void { const updateTime = Date.now(); if (this._lastUpdateTime === 0 && itemCount > 0 && getFrameMetrics(0)) { // Only count updates after the first item is rendered and has a frame. this._lastUpdateTime = updateTime; } const updateElapsed = this._lastUpdateTime ? updateTime - this._lastUpdateTime : 0; if (this._config.waitForInteraction && !this._hasInteracted) { return; } let viewableIndices = []; if (itemCount) { viewableIndices = this.computeViewableItems( itemCount, scrollOffset, viewportHeight, getFrameMetrics, renderRange, ); } if (this._viewableIndices.length === viewableIndices.length && this._viewableIndices.every((v, ii) => v === viewableIndices[ii])) { // We might get a lot of scroll events where visibility doesn't change and we don't want to do // extra work in those cases. return; } this._viewableIndices = viewableIndices; this._lastUpdateTime = updateTime; if (this._config.minimumViewTime && updateElapsed < this._config.minimumViewTime) { const handle = setTimeout( () => { this._timers.delete(handle); this._onUpdateSync(viewableIndices, onViewableItemsChanged, createViewToken); }, this._config.minimumViewTime, ); this._timers.add(handle); } else { this._onUpdateSync(viewableIndices, onViewableItemsChanged, createViewToken); } } /** * Records that an interaction has happened even if there has been no scroll. */ recordInteraction() { this._hasInteracted = true; } _onUpdateSync(viewableIndicesToCheck, onViewableItemsChanged, createViewToken) { // Filter out indices that have gone out of view since this call was scheduled. viewableIndicesToCheck = viewableIndicesToCheck.filter( (ii) => this._viewableIndices.includes(ii) ); const prevItems = this._viewableItems; const nextItems = new Map( viewableIndicesToCheck.map(ii => { const viewable = createViewToken(ii, true); return [viewable.key, viewable]; }) ); const changed = []; for (const [key, viewable] of nextItems) { if (!prevItems.has(key)) { changed.push(viewable); } } for (const [key, viewable] of prevItems) { if (!nextItems.has(key)) { changed.push({...viewable, isViewable: false}); } } if (changed.length > 0) { this._viewableItems = nextItems; onViewableItemsChanged({viewableItems: Array.from(nextItems.values()), changed}); } } } function _isViewable( viewAreaMode: boolean, viewablePercentThreshold: number, top: number, bottom: number, viewportHeight: number, itemLength: number, ): bool { if (_isEntirelyVisible(top, bottom, viewportHeight)) { return true; } else { const pixels = _getPixelsVisible(top, bottom, viewportHeight); const percent = 100 * (viewAreaMode ? pixels / viewportHeight : pixels / itemLength); return percent >= viewablePercentThreshold; } } function _getPixelsVisible( top: number, bottom: number, viewportHeight: number ): number { const visibleHeight = Math.min(bottom, viewportHeight) - Math.max(top, 0); return Math.max(0, visibleHeight); } function _isEntirelyVisible( top: number, bottom: number, viewportHeight: number ): bool { return top >= 0 && bottom <= viewportHeight && bottom > top; } module.exports = ViewabilityHelper;
define(['iframeResizer'], function(iFrameResize) { describe('Scroll Page', function() { var iframe var log = LOG beforeEach(function() { loadIFrame('iframe600.html') }) afterEach(function() { tearDown(iframe) }) it('mock incoming message', function(done) { iframe = iFrameResize({ log: log, id: 'scroll1' })[0] window.parentIFrame = { scrollTo: function(x, y) { expect(x).toBe(0) expect(y).toBe(0) done() } } mockMsgFromIFrame(iframe, 'scrollTo') }) it('mock incoming message', function(done) { iframe = iFrameResize({ log: log, id: 'scroll2' })[0] window.parentIFrame = { scrollToOffset: function(x, y) { expect(x).toBe(8) expect(y).toBe(8) done() } } mockMsgFromIFrame(iframe, 'scrollToOffset') }) }) })
import * as Utils from './utils' import * as Evaluators from './evaluators' import * as Nodes from './nodes' import * as Parser from './parser' import ColorScale from './ColorScale' import ValueType from './ValueType' import BlendMode from './BlendMode' Parser.parser.yy = Nodes export function evaluate(expr, options) { options = Object.assign({ evaluator: Evaluators.CoreEvaluator.instance, withAst: false, astWithLocs: false, }, options) let program let value let error try { program = Parser.parse(expr) value = program.evaluate(options.evaluator) } catch (e) { error = e.message || String(e) } return { withAst: options.withAst, astWithLocs: options.astWithLocs, evaluator: options.evaluator.$type, expr, program, result: error != null ? null : value, resultStr: error != null ? null : formatValue(value), astStr: error != null || !options.withAst || !program ? null : JSON.stringify(program.getDto(options.astWithLocs), null, ' '), error: error != null ? error : null, } } function formatValue(value) { if (Utils.isColor(value)) { return Utils.formatColor(value) } else if (typeof value === 'number') { const s = value % 1 === 0 ? String(value) : value.toFixed(4).replace(/0+$/, '') return s } else if (typeof value === 'string') { return value } else if (Array.isArray(value)) { let s = '[' for (let i = 0; i < value.length; i++) { s += formatValue(value[i]) + (i < value.length - 1 ? ', ' : '') } s += ']' return s } else if (value instanceof ColorScale) { return String(value) } else { return JSON.stringify(value, null, ' ') } } export { Nodes, Evaluators, ColorScale, BlendMode, ValueType, Utils, }
'use strict'; import React from 'react' import reactCSS from 'reactcss' import map from 'lodash/map' import throttle from 'lodash/throttle' import markdown from '../helpers/markdown' import { Grid } from '../../../react-basic-layout' import MarkdownTitle from './MarkdownTitle' import Markdown from './Markdown' import Code from './Code' import Sidebar from './Sidebar' class Docs extends React.Component { constructor() { super(); this.state = { sidebarFixed: false, visible: false, files: {}, }; this.changeSelection = this.changeSelection.bind(this); this.attachSidebar = this.attachSidebar.bind(this); this.handleScroll = this.handleScroll.bind(this); this.handleScroll = throttle(this.handleScroll, 200); } componentDidMount() { window.addEventListener('scroll', this.handleScroll, false); } componentWillUnmount() { window.removeEventListener('scroll', this.handleScroll, false); } handleScroll(e) { this.changeSelection(); this.attachSidebar(); } attachSidebar() { var sidebar = this.refs.sidebar; if (sidebar) { var sidebarTop = sidebar.getBoundingClientRect().top; if (sidebarTop <= 0 && this.state.sidebarFixed === false) { this.setState({ sidebarFixed: true }); } if (sidebarTop > 0 && this.state.sidebarFixed === true) { this.setState({ sidebarFixed: false }); } } } changeSelection() { const items = document.getElementsByClassName('file'); const doc = document.documentElement; const top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0); map(items, (item) => { const bottomOfItem = item.offsetTop + item.clientHeight; if (item.offsetTop < top && bottomOfItem > top) { if (this.state.visible !== item.id) { this.setState({ visible: item.id }); } } }); } render() { var markdownFiles = []; for (var fileName in this.props.markdown) { if (this.props.markdown.hasOwnProperty(fileName)) { var file = this.props.markdown[fileName]; if (file) { var args = markdown.getArgs(file); var body = markdown.getBody(file); markdownFiles.push( <div key={ fileName } id={ args.id } className="markdown file"> { args.title && !args.hideTitle && ( <MarkdownTitle isHeadline={ markdown.isSubSection(fileName) ? true : false } title={ args.title } link={ args.id } primaryColor={ this.props.primaryColor } /> ) } <Markdown>{ body }</Markdown> </div> ); } } } return ( <div> <style>{` #intro em{ font-style: normal; position: absolute; margin-top: 25px; color: #FF9800; } .rendered{ color: #607D8B; // blue grey 500 } .rendered .hljs-comment { color: #B0BEC5; // blue grey 200 } .rendered .hljs-keyword{ color: #EF9A9A; // red 200 } .rendered .hljs-string{ color: #689F38; // light green 700 } .rendered .hljs-title{ } .text code{ background: #ddd; padding: 1px 5px 3px; border-radius: 2px; box-shadow: inset 0 0 0 1px rgba(0,0,0,.03); font-size: 85%; vertical-align: bottom; } .markdown.file:last-child { min-height: 100vh; } .markdown a { color: #4A90E2; } .markdown a:visited { color: #49535B; } .markdown p{ margin: 15px 24px 15px 0; } .markdown h1{ font-size: 36px; font-weight: 200; color: rgba(0,0,0,.77); margin: 0; padding-top: 54px; padding-bottom: 5px; line-height: 46px; } .markdown h2{ font-size: 26px; line-height: 32px; font-weight: 200; color: rgba(0,0,0,.57); padding-top: 20px; margin-top: 20px; margin-bottom: 10px; } .markdown h3{ font-weight: normal; font-size: 20px; padding-top: 20px; margin-top: 20px; color: rgba(0,0,0,.67); } `}</style> { this.props.sidebar !== false ? <Grid> <div ref="sidebar"> <Sidebar files={ this.props.markdown } active={ this.state.visible } primaryColor={ this.props.primaryColor } bottom={ this.props.bottom } fixed={ this.state.sidebarFixed } /> </div> <div ref="files"> { markdownFiles } </div> </Grid> : <div ref="files"> { markdownFiles } </div> } </div> ); } } Docs.defaultProps = { primaryColor: '#03A9F4', }; module.exports = Docs;
import RectangleTexture from "openfl/display3D/textures/RectangleTexture"; import Context3DTextureFormat from "openfl/display3D/Context3DTextureFormat"; import Stage3DTest from "./../../display/Stage3DTest"; import * as assert from "assert"; describe ("ES6 | RectangleTexture", function () { it ("uploadFromBitmapData", function () { // TODO: Confirm functionality var context3D = Stage3DTest.__getContext3D (); if (context3D != null) { var rectangleTexture = context3D.createRectangleTexture (1, 1, Context3DTextureFormat.BGRA, false); var exists = rectangleTexture.uploadFromBitmapData; assert.notEqual (exists, null); } }); it ("uploadFromByteArray", function () { // TODO: Confirm functionality var context3D = Stage3DTest.__getContext3D (); if (context3D != null) { var rectangleTexture = context3D.createRectangleTexture (1, 1, Context3DTextureFormat.BGRA, false); var exists = rectangleTexture.uploadFromByteArray; assert.notEqual (exists, null); } }); });
const webpack = require('webpack'); const merge = require('webpack-merge'); const development = require('./dev.config.js'); const production = require('./prod.config.js'); const developmentSSR = require('./dev.ssr.config.js'); const path = require('path'); const TARGET = process.env.npm_lifecycle_event; process.env.BABEL_ENV = TARGET; var devUrl; // Location dist for dev and prod if (!global.ssr && process.env.NODE_ENV === 'development') { devUrl = 'http://localhost:3000/dist/'; } if (global.ssr && process.env.NODE_ENV === 'development') { devUrl = 'http://localhost:3001/dist/'; } if (process.env.NODE_ENV === 'production') { devUrl = '/dist/'; } const common = { output: { path: __dirname + '/../dist/', publicPath: devUrl, filename: '[name].js', chunkFilename: '[name].chunk.js', }, resolve: { extensions: ['', '.jsx', '.js', '.json', '.css'], modulesDirectories: ['node_modules'], // Webpack alias for beautiful import alias: { components: path.join(__dirname, '../app/components/'), containers: path.join(__dirname, '../app/containers/'), 'redux/modules': path.join(__dirname, '../app/redux/modules/'), 'redux/store': path.join(__dirname, '../app/redux/store/'), constants: path.join(__dirname, '../app/constants/'), decorators: path.join(__dirname, '../app/decorators/'), utils: path.join(__dirname, '../app/utils/'), test: path.join(__dirname, '../app/test/'), }, }, module: { loaders: [{ // Loader for fonts (woff) test: /\.woff(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff', }, { // Loader for fonts (woff2) test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-woff2', }, { // Loader for fonts (ttf) test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream', }, { // Loader for fonts (otf) test: /\.otf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/font-otf', }, { // Loader for fonts (eot) test: /\.eot(\?v=\d+\.\d+\.\d+)?$/, loader: 'file', }, { // Loader for images (svg) test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml', }, { // Loader for js test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader', }, { // Loader for images (png) test: /\.png$/, loader: 'file?name=[name].[ext]', }, { // Loader for images (jpg) test: /\.jpg$/, loader: 'file?name=[name].[ext]', }, { // Loader for images (gif) test: /\.gif$/, loader: 'file?name=[name].[ext]', }], }, plugins: [ // Define global constants new webpack.DefinePlugin({ 'process.env': { NODE_ENV: process.env.NODE_ENV === 'development' ? '"development"' : '"production"', }, __DEVELOPMENT__: process.env.NODE_ENV === 'development', __PRODUCTION__: process.env.NODE_ENV === 'production', __CLIENT__: true, }), // Chunks for generate vendor bundle new webpack.optimize.CommonsChunkPlugin({ minChunks: 2, name: 'vendor', }), ], postcss: () => [ require('postcss-partial-import'), require('postcss-nested'), require('postcss-short'), require('autoprefixer')({ browsers: ['> 5%'], remove: false, }), ], }; if (process.env.NODE_ENV === 'development' && !global.ssr) { module.exports = merge(development, common); } if (process.env.NODE_ENV === 'development' && global.ssr) { module.exports = merge(developmentSSR, common); } if (process.env.NODE_ENV === 'production') { module.exports = merge(production, common); }
export default function ( component ) { var ancestor, query; // If there's a live query for this component type, add it ancestor = component.root; while ( ancestor ) { if ( query = ancestor._liveComponentQueries[ '_' + component.name ] ) { query.push( component.instance ); } ancestor = ancestor._parent; } }
var MemoryStream = require('memorystream'); var GlitchedStream = require('glitch').GlitchedStream; var fs = require('fs'); module.exports = function(grunt) { grunt.registerMultiTask('glitch', 'Clean files and folders.', function() { var options = this.options({ enabled : false, deviation: 2, probability: 0.0001, whiteList: [], blackList: [], deviationFunction: null, force : false }); if(!options.enabled) { grunt.log.warn('Glitch task isn\'t explicitly enabled.'); return; } var done = this.async(); var count = 0; var multiDone = function() { count++; if(count === this.filesSrc.length) { done(); } }.bind(this); this.filesSrc.forEach(function(filepath) { var rstream = fs.createReadStream(filepath); rstream.on('end', function() { fs.writeFile(filepath, mstream.toBuffer(), function() { multiDone(); }); }); rstream.on('error', function() { if(options.force) { multiDone(); } else { done(false); } }); var mstream = new MemoryStream(null, { readable : false }); var gstream = new GlitchedStream(options); rstream.pipe(gstream).pipe(mstream); }); }); };
module.exports = function(grunt) { // Add our custom tasks. grunt.loadTasks('../../../tasks'); // Project configuration. grunt.initConfig({ zaproxyStart: { options: { port: 8081 } }, zaproxyStop: { options: { port: 8081 } } }); // Default task. grunt.registerTask('default', ['zaproxyStart', 'zaproxyStop']); };
// Generated by CoffeeScript 1.8.0 (function() { 'use strict'; /* WorkQueueMgr Example -- provider03 For each string in the two expectedItems lists, this app sends it into either 'demo:work-queue-1' or 'demo:work-queue-2' for consumption by worker03. When done with that, it quits. Usage: cd demo/lib node provider01.js clear node provider01.js node provider01.js 10 ... node provider01.js stop Use this app in conjunction with worker03.js. See the worker03 source code for more details. */ var WorkQueueMgr, clear, clearWorkQueues, createWorkQueues, expectedItemsQ1, expectedItemsQ2, initEventHandlers, itemCntQ1, itemCntQ2, mgr, queue1, queue1Name, queue2, queue2Name, sendData, sendStop, shutDown, stop, timesToRepeat; queue1 = null; queue2 = null; queue1Name = 'demo:work-queue-1'; queue2Name = 'demo:work-queue-2'; mgr = null; expectedItemsQ1 = ['item one', 'item two', 'item three']; itemCntQ1 = 0; expectedItemsQ2 = ['item foo', 'item bar', 'item baz']; itemCntQ2 = 0; clear = process.argv[2] === 'clear'; stop = process.argv[2] === 'stop'; timesToRepeat = parseInt(process.argv[2]) || 1; WorkQueueMgr = require('node-redis-queue').WorkQueueMgr; mgr = new WorkQueueMgr(); mgr.connect(function() { console.log('work queue manager ready'); initEventHandlers(); createWorkQueues(); if (stop) { sendStop(); return shutDown(); } else if (clear) { return clearWorkQueues(function() { return shutDown(); }); } else { sendData(); return shutDown(); } }); initEventHandlers = function() { mgr.on('error', function(error) { console.log('>>>' + error); return shutDown(); }); return mgr.on('end', function() { console.log('>>>End Redis connection'); return shutDown(); }); }; createWorkQueues = function() { queue1 = mgr.createQueue(queue1Name); queue2 = mgr.createQueue(queue2Name); }; clearWorkQueues = function(done) { var queuesToClear; queuesToClear = 2; queue1.clear(function() { console.log('Cleared "' + queue1.queueName + '"'); if (!--queuesToClear) { return done(); } }); return queue2.clear(function() { console.log('Cleared "' + queue2.queueName + '"'); if (!--queuesToClear) { return done(); } }); }; sendData = function() { var item, _i, _j, _len, _len1; while (timesToRepeat--) { for (_i = 0, _len = expectedItemsQ1.length; _i < _len; _i++) { item = expectedItemsQ1[_i]; console.log('publishing "' + item + '" to queue "' + queue1.queueName + '"'); queue1.send(item); } for (_j = 0, _len1 = expectedItemsQ2.length; _j < _len1; _j++) { item = expectedItemsQ2[_j]; console.log('publishing "' + item + '" to queue "' + queue2.queueName + '"'); queue2.send(item); } } }; sendStop = function() { console.log('stopping worker03'); queue1.send('***stop***'); return queue2.send('***stop***'); }; shutDown = function() { return mgr.shutdownSoon(); }; }).call(this);
var mutuationMethodModel = new Vue({ el: '#app', data: { items: [ ] } })
/* Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang("a11yhelp", "mk", {title: "Инструкции за пристапност", contents: "Содржина на делот за помош. За да го затворите овој дијалот притиснете ESC.", legend: [ {name: "Општо", items: [ {name: "Мени за едиторот", legend: "Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT-TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button."}, {name: "Дијалот за едиторот", legend: "Inside a dialog, press TAB to navigate to next dialog field, press SHIFT + TAB to move to previous field, press ENTER to submit dialog, press ESC to cancel dialog. For dialogs that have multiple tab pages, press ALT + F10 to navigate to tab-list. Then move to next tab with TAB OR RIGTH ARROW. Move to previous tab with SHIFT + TAB or LEFT ARROW. Press SPACE or ENTER to select the tab page."}, {name: "Editor Context Menu", legend: "Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC."}, {name: "Editor List Box", legend: "Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT + TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box."}, {name: "Editor Element Path Bar", legend: "Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor."} ]}, {name: "Commands", items: [ {name: " Undo command", legend: "Press ${undo}"}, {name: " Redo command", legend: "Press ${redo}"}, {name: " Bold command", legend: "Press ${bold}"}, {name: " Italic command", legend: "Press ${italic}"}, {name: " Underline command", legend: "Press ${underline}"}, {name: " Link command", legend: "Press ${link}"}, {name: " Toolbar Collapse command", legend: "Press ${toolbarCollapse}"}, {name: " Access previous focus space command", legend: "Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."}, {name: " Access next focus space command", legend: "Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces."}, {name: " Accessibility Help", legend: "Press ${a11yHelp}"} ]} ], backspace: "Backspace", tab: "Tab", enter: "Enter", shift: "Shift", ctrl: "Ctrl", alt: "Alt", pause: "Pause", capslock: "Caps Lock", escape: "Escape", pageUp: "Page Up", pageDown: "Page Down", end: "End", home: "Home", leftArrow: "Left Arrow", upArrow: "Up Arrow", rightArrow: "Right Arrow", downArrow: "Down Arrow", insert: "Insert", "delete": "Delete", leftWindowKey: "Left Windows key", rightWindowKey: "Right Windows key", selectKey: "Select key", numpad0: "Numpad 0", numpad1: "Numpad 1", numpad2: "Numpad 2", numpad3: "Numpad 3", numpad4: "Numpad 4", numpad5: "Numpad 5", numpad6: "Numpad 6", numpad7: "Numpad 7", numpad8: "Numpad 8", numpad9: "Numpad 9", multiply: "Multiply", add: "Add", subtract: "Subtract", decimalPoint: "Decimal Point", divide: "Divide", f1: "F1", f2: "F2", f3: "F3", f4: "F4", f5: "F5", f6: "F6", f7: "F7", f8: "F8", f9: "F9", f10: "F10", f11: "F11", f12: "F12", numLock: "Num Lock", scrollLock: "Scroll Lock", semiColon: "Semicolon", equalSign: "Equal Sign", comma: "Comma", dash: "Dash", period: "Period", forwardSlash: "Forward Slash", graveAccent: "Grave Accent", openBracket: "Open Bracket", backSlash: "Backslash", closeBracket: "Close Bracket", singleQuote: "Single Quote"});
import CycleBase, { CycleExecution, CycleSetup, DisposeFunction, } from '@cycle/base'; import KefirAdapter from './adapter'; /** * Takes a `main` function and circularly connects it to the given collection * of driver functions. * * **Example:** * ```js * import {run} from 'cyclejs-kefir'; * const dispose = run(main, drivers); * // ... * dispose(); * ``` * * The `main` function expects a collection of "source" streams (returned from * drivers) as input, and should return a collection of "sink" streams (to be * given to drivers). A "collection of streams" is a JavaScript object where * keys match the driver names registered by the `drivers` object, and values * are the streams. Refer to the documentation of each driver to see more * details on what types of sources it outputs and sinks it receives. * * @param {Function} main a function that takes `sources` as input and outputs * `sinks`. * @param {Object} drivers an object where keys are driver names and values * are driver functions. * @return {Function} a dispose function, used to terminate the execution of the * Cycle.js program, cleaning up resources used. * @function run */ export function run(main,drivers) { return CycleBase(main, drivers, {streamAdapter: KefirAdapter}).run(); } /** * A function that prepares the Cycle application to be executed. Takes a `main` * function and prepares to circularly connects it to the given collection of * driver functions. As an output, `Cycle()` returns an object with three * properties: `sources`, `sinks` and `run`. Only when `run()` is called will * the application actually execute. Refer to the documentation of `run()` for * more details. * * **Example:** * ```js * import Cycle from 'cyclejs-kefir'; * const {sources, sinks, run} = Cycle(main, drivers); * // ... * const dispose = run(); // Executes the application * // ... * dispose(); * ``` * * @param {Function} main a function that takes `sources` as input * and outputs `sinks`. * @param {Object} drivers an object where keys are driver names and values * are driver functions. * @return {Object} an object with three properties: `sources`, `sinks` and * `run`. `sources` is the collection of driver sources, `sinks` is the * collection of driver sinks, these can be used for debugging or testing. `run` * is the function that once called will execute the application. * @function Cycle */ const Cycle = function(main,drivers) { return CycleBase(main, drivers, {streamAdapter: KefirAdapter}); }; Cycle.run = run; export default Cycle;
// @flow import Bugsnag from 'bugsnag-js'; import config from 'config'; Bugsnag.apiKey = config.bugsnagAPIKey; export const reportError = (err: Error) => Bugsnag.notifyException(err); export default { reportError, };
export default () => ({ path: '*', /* Async getComponent is only invoked when route matches */ getComponent (nextState, cb) { /* Webpack - use 'require.ensure' to create a split point and embed an async module loader (jsonp) when bundling */ require.ensure([], (require) => { /* Webpack - use require callback to define dependencies for bundling */ const Score = require('./components/Score').default /* Return getComponent */ cb(null, Score) /* Webpack named bundle */ }, 'Score') } })
'use strict'; const EventEmitter = require('events'); function hasOwnProperty(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } /** * 构造器,传入限流值,设置异步调用最大并发数 * Examples: * ``` * var bagpipe = new Bagpipe(100); * bagpipe.push(fs.readFile, 'path', 'utf-8', function (err, data) { * // TODO * }); * ``` * Events: * - `full`, 当活动异步达到限制值时,后续异步调用将被暂存于队列中。当队列的长度大于限制值的2倍或100的时候时候,触发`full`事件。事件传递队列长度值。 * - `outdated`, 超时后的异步调用异常返回。 * Options: * - `disabled`, 禁用限流,测试时用 * - `refuse`, 拒绝模式,排队超过限制值时,新来的调用将会得到`TooMuchAsyncCallError`异常 * - `timeout`, 设置异步调用的时间上线,保证异步调用能够恒定的结束,不至于花费太长时间 * @param {Number} limit 并发数限制值 * @param {Object} options Options */ class Bagpipe extends EventEmitter { constructor(limit, options = {}) { super(); this.limit = limit; this.active = 0; this.queue = []; this.options = { disabled: false, refuse: false, ratio: 1, timeout: null }; if (typeof options === 'boolean') { options = { disabled: options }; } for (var key in this.options) { if (hasOwnProperty(options, key)) { this.options[key] = options[key]; } } // queue length this.queueLength = Math.round(this.limit * (this.options.ratio || 1)); } /** * 推入方法,参数。最后一个参数为回调函数 * @param {Function} method 异步方法 * @param {Mix} args 参数列表,最后一个参数为回调函数。 */ push(method, ...args) { if (typeof args[args.length - 1] !== 'function') { args.push(function () {}); } var callback = args[args.length - 1]; if (this.options.disabled || this.limit < 1) { method(...args); return this; } // 队列长度也超过限制值时 if (this.queue.length < this.queueLength || !this.options.refuse) { this.queue.push({ method: method, args: args }); } else { var err = new Error('Too much async call in queue'); err.name = 'TooMuchAsyncCallError'; callback(err); } if (this.queue.length > 1) { this.emit('full', this.queue.length); } this.next(); return this; } /*! * 继续执行队列中的后续动作 */ next() { // 没到限制,或者没有排队 if (this.active >= this.limit || !this.queue.length) { return; } const {method, args} = this.queue.shift(); this.active++; const callback = args[args.length - 1]; var timer = null; var called = false; // inject logic args[args.length - 1] = (err, ...rest) => { // anyway, clear the timer if (timer) { clearTimeout(timer); timer = null; } // if timeout, don't execute if (!called) { this._next(); callback(err, ...rest); } else { // pass the outdated error if (err) { this.emit('outdated', err); } } }; var timeout = this.options.timeout; if (timeout) { timer = setTimeout(() => { // set called as true called = true; this._next(); // pass the exception var err = new Error(timeout + 'ms timeout'); err.name = 'BagpipeTimeoutError'; err.data = { name: method.name, method: method.toString(), args: args.slice(0, -1) }; callback(err); }, timeout); } method(...args); } _next() { this.active--; this.next(); } } module.exports = Bagpipe;
// source: lospec.com _palettes = { "2bit-catgirls-rise":"#162c27,#534650,#6f9b8a,#ead7be", "ice-cream-gb":"#7c3f58,#eb6b6f,#f9a875,#fff6d3", "kirokaze-gameboy":"#332c50,#46878f,#94e344,#e2f3e4", "rustic-gb":"#2c2137,#764462,#edb4a1,#a96868", "mist-gb":"#2d1b00,#1e606e,#5ab9a8,#c4f0c2", "hallowpumpkin":"#300030,#602878,#f89020,#f8f088", "en4":"#fbf7f3,#e5b083,#426e5d,#20283d", "fuzzyfour":"#302387,#ff3796,#00faac,#fffdaf", "crimson":"#eff9d6,#ba5044,#7a1c4b,#1b0326", "dirtyboy":"#c4cfa1,#8b956d,#4d533c,#1f1f1f", "ayy4":"#00303b,#ff7777,#ffce96,#f1f2da", "nostalgia":"#d0d058,#a0a840,#708028,#405010", "wish-gb":"#622e4c,#7550e8,#608fcf,#8be5ff", "spacehaze":"#f8e3c4,#cc3495,#6b1fb1,#0b0630", "blue-seni":"#d0f4f8,#70b0c0,#3c3468,#1c0820", "purpledawn":"#eefded,#9a7bbc,#2d757e,#001b2e", "andrade-gameboy":"#202020,#5e6745,#aeba89,#e3eec0", "lightgreen":"#f4fbd0,#68cf68,#1e9178,#05241f", "nymph-gb":"#2c2137,#446176,#3fac95,#a1ef8c", "platinum":"#e0f0e8,#a8c0b0,#507868,#183030", "harshgreens":"#beeb71,#6ab417,#376d03,#172808", "muddysand":"#e6d69c,#b4a56a,#7b7162,#393829", "arq4":"#ffffff,#6772a9,#3a3277,#000000", "grand-dad-4":"#4c1c2d,#d23c4e,#5fb1f5,#eaf5fa", "cherrymelon":"#fcdeea,#ff4d6d,#265935,#012824", "links-awakening-sgb":"#5a3921,#6b8c42,#7bc67b,#ffffb5", "nintendo-super-gameboy":"#331e50,#a63725,#d68e49,#f7e7c6", "nintendo-gameboy-bgb":"#081820,#346856,#88c070,#e0f8d0", "pokemon-sgb":"#181010,#84739c,#f7b58c,#ffefff", "cga-palette-1-high":"#000000,#ff55ff,#55ffff,#ffffff", "kirby-sgb":"#2c2c96,#7733e7,#e78686,#f7bef7", "gb-chocolate":"#ffe4c2,#dca456,#a9604c,#422936", "2-bit-grayscale":"#000000,#676767,#b6b6b6,#ffffff", "grafxkid-gameboy-pocket-gray":"#2b2b26,#706b66,#a89f94,#e0dbcd", "grapefruit":"#65296c,#b76591,#f4b26b,#fff5dd", "cga-palette-2-high":"#000000,#FF5555,#55FFFF,#FFFFFF", "grafxkid-gameboy-pocket-green":"#4c625a,#7b9278,#abc396,#dbf4b4", "nintendo-gameboy-black-zero":"#2e463d,#385d49,#577b46,#7e8416", "didi4":"#dcfecf,#77af68,#3a655a,#210b2e", "cga-palette-0-high":"#000000,#55ff55,#ff5555,#ffff55", "jb4":"#daf3ec,#00bff3,#ed008c,#260016", "pj-gameboy":"#1f1f1f,#4d533c,#8b956d,#c4cfa1", "megaman-v-sgb":"#102533,#42678e,#6f9edf,#cecece", "nintendo-gameboy-arne":"#243137,#3f503f,#768448,#acb56b", "darkboy4":"#e7e8f3,#8c83c3,#634d8f,#120b19", "metroid-ii-sgb":"#2c1700,#047e60,#b62558,#aedf1e", "cga-palette-0-low":"#000000,#00aa00,#aa0000,#aa5500", "sweet-guarana":"#253b46,#18865f,#61d162,#ebe7ad", "gb-easy-greens":"#004333,#0d8833,#a1bc00,#ebdd77", "cga-palette-1-low":"#000000,#aa00aa,#00aaaa,#aaaaaa", "super-mario-land-2-sgb":"#000000,#11c600,#dfa677,#eff7b6", "cga-palette-2-low":"#000000,#aa0000,#00aaaa,#aaaaaa", "arne-4":"#000000,#00519c,#b84b12,#afd84f", "kid-icarus-sgb":"#1e0000,#9e0000,#f78e50,#cef7f7", "infinite-ikea":"#12223c,#104a7d,#45a9ff,#f6d76b,#f6f0f7", "fire-weeds":"#060013,#e2d6fe,#fea631,#e5371b,#630f19", "blessing":"#74569b,#96fbc7,#f7ffae,#ffb3cb,#d8bfd8", "water-lemon":"#02382d,#3ba711,#f8c15a,#fefefe,#fa2e42", "cn-intro-2013":"#0b0b0b,#de27b0,#4d99f4,#e1ed39,#e9e9e2", "ink":"#1f1f29,#413a42,#596070,#96a2b3,#eaf0d8", "stormy-6":"#f8eebf,#edbb70,#a95a3f,#242828,#3a5043,#7f9860", "oil-6":"#fbf5ef,#f2d3ab,#c69fa5,#8b6d9c,#494d7e,#272744", "code-melon":"#b440a3,#ff91ab,#79c220,#f1e899,#2a1a54,#20798b", "cp_rust-5":"#230000,#712f30,#a54932,#e18866,#f0bb9c,#ffe2c6", "boomboom":"#000000,#242423,#ffffff,#be2633,#44891a,#31a2f2,#1b2632", "rabbit":"#d47564,#e8c498,#ecece0,#4fa4a5,#aad395,#3b324a,#5c6182", "supernova-7":"#1a080e,#3d203b,#543246,#773a4d,#a75252,#cf7862,#ffce9c", "slso8":"#0d2b45,#203c56,#544e68,#8d697a,#d08159,#ffaa5e,#ffd4a3,#ffecd6", "funkyfuture-8":"#2b0f54,#ab1f65,#ff4f69,#fff7f8,#ff8142,#ffda45,#3368dc,#49e7ec", "pollen8":"#73464c,#ab5675,#ee6a7c,#ffa7a5,#ffe07e,#ffe7d6,#72dcbb,#34acba", "greyt-bit":"#574368,#8488d3,#cfd3c1,#f8c868,#8ddb34,#69cfef,#d1b3ff,#ff8e65", "petite-8":"#0a0a10,#181b22,#272f3b,#47534e,#7b8046,#c5af63,#efd98d,#f8f4e4", "cave":"#000000,#100029,#361d23,#443f4f,#8f56b3,#c79065,#9ce4c7,#f5f5f5", "petite-8-afterdark":"#070810,#0d0f11,#161c20,#272b29,#4b4a27,#776131,#a07c43,#bb9a67", "cave-rock":"#33337f,#2188cf,#ffffff,#4891aa,#244855,#80350e,#ff9f46,#b6b6aa", "superb-8":"#f6faff,#eeea18,#edc495,#3d9c09,#0891cd,#776b7d,#e62800,#000800", "endesga-8":"#fdfdf8,#d32734,#da7d22,#e6da29,#28c641,#2d93dd,#7b53ad,#1b1c33", "secam":"#000000,#2121ff,#f03c79,#ff50ff,#7fff00,#7fffff,#ffff3f,#ffffff", "nyx8":"#08141e,#0f2a3f,#20394f,#f6d6bd,#c3a38a,#997577,#816271,#4e495f", "rkbv":"#15191a,#8a4c58,#d96275,#e6b8c1,#456b73,#4b97a6,#a5bdc2,#fff5f7", "ammo-8":"#040c06,#112318,#1e3a29,#305d42,#4d8061,#89a257,#bedc7f,#eeffcc", "dawnbringers-8-color":"#000000,#55415f,#646964,#d77355,#508cd7,#64b964,#e6c86e,#dcf5ff", "matriax8c":"#f0f0dc,#fac800,#10c840,#00a0c8,#d24040,#a0694b,#736464,#101820", "fantastic-8":"#dbdbdd,#9c8e8e,#524ba3,#1f1e23,#6a9254,#dcac6c,#e55656,#73493c", "generic-8":"#1c1121,#edece9,#a13b3b,#f37f9a,#ee961a,#2d5365,#40a933,#25a6c5", "westmost-8":"#131315,#4a5381,#b96f5a,#dadada,#343651,#644338,#4c9453,#cab17a", "generic-8-color":"#000000,#cc3500,#5ec809,#1d286f,#00c4ff,#8e8e8e,#ffe052,#ffffff", "armor-8":"#181819,#857d7d,#f6f6f5,#444d8e,#463737,#aa3d33,#e9b370,#4a9042", "3-bit-rgb":"#000000,#ff0000,#00ff00,#0000ff,#00ffff,#ff00ff,#ffff00,#ffffff", "fairy-tales":"#0e30a6,#d20000,#4dd928,#ffe600,#4b3159,#83606f,#708f4d,#adb870", "haretro8":"#ffe6d2,#ffb400,#32b4ff,#0ac832,#cc66cc,#c73b32,#995f3d,#1e2832", "crayolablind":"#8e3179,#ca3435,#ff91a4,#fcd667,#93dfb8,#b5b35c,#02a4d3,#00468c,#ffffff", "rube-goldberg":"#e1e1df,#f3d754,#cbbead,#f0bd8a,#ce6c37,#f03428,#04b0d8,#54a04f,#232722", "firestorm":"#1b2032,#46344a,#f95e3e,#fd4b35,#ec6756,#ff845f,#ffa15f,#fdde85,#ffecb3", "gameboy-pop":"#ff0033,#ff3366,#bd7100,#ffcc00,#76ec08,#33ccff,#2086fd,#57001a,#b2194c", "evening10":"#ce9a93,#b5725d,#68212d,#1b0d1f,#47446d,#6a8da7,#bcd5ca,#ddddc6,#729f7c,#344233", "cataclysm-10":"#f1a37c,#e64a43,#bd1a2a,#760a32,#340a2a,#170e22,#2c242b,#684954,#b1817d,#d5baa2", "pixelwave":"#19002b,#3e1973,#5f0073,#884bff,#7b53ff,#b31fff,#e900ff,#437dff,#8fb1fe,#c6d7ff", "the-desert-level":"#f4faaf,#e3d88f,#ccb690,#74aec6,#ae8d78,#8c7d66,#6d7073,#287051,#635751,#61444a,#3a383c", "night-11":"#183048,#507088,#b0e0d8,#98b880,#fff0b8,#e8b4a0,#9890a8,#705180,#743838,#986858,#d07050", "polar11":"#0a0a0a,#ab2929,#d1691f,#f5ca2f,#f5f1ed,#878c81,#99c24e,#5f9448,#339db5,#2d6296,#2f2b6b", "gzxp":"#000000,#ad9ba8,#f3ead7,#9f253f,#da6252,#aa7c14,#e8ca00,#006a14,#0eaf03,#1f1daf,#4458d6", "mordfikosz-11":"#be783c,#d7af87,#ebebaf,#64af50,#556e6e,#3c3c5f,#96d2f0,#a07da0,#9b4146,#46282d,#14141e", "speedycube-11":"#f2fdff,#85c8e2,#97d374,#93928d,#5e5a93,#222849,#efdd8b,#e5a57e,#ce6d5c,#875d4e,#663358", "finlal-11":"#171419,#530c1e,#223555,#af3451,#3b6688,#238433,#9f8474,#889eb7,#bda0bc,#cbc990,#e4e5f1", "nevercreature-11":"#3a3746,#99d9ea,#c06170,#a98b3d,#446499,#933c2d,#3c6738,#e9fabc,#6194c7,#f88878,#f4d055", "calder-8":"#d50407,#0c25a5,#047937,#e2c906,#eb491d,#005fa8,#08a484,#2143cb,#fdaa1d,#751d6b,#807b73", "evening12":"#1b0d1f,#2c329f,#51a6ee,#aeddca,#f5f5ce,#c75684,#9a212d,#3d152a,#a85639,#e6b543,#729f7c,#344233", "japanese-woodblock":"#2b2821,#624c3c,#d9ac8b,#e3cfb4,#243d5c,#5d7275,#5c8b93,#b1a58d,#b03a48,#d4804d,#e0c872,#3e6958", "nopal-12":"#e2e4df,#c5cfc4,#a8b5ae,#92929c,#ffeced,#fbd4d2,#f1b4b4,#cca3a3,#f1eab6,#e4dba0,#cac18a,#aba47b", "aap-micro12":"#040303,#1c1618,#47416b,#6c8c50,#e3d245,#d88038,#a13d3b,#4e282e,#9a407e,#f0d472,#f9f5ef,#8a8fc4", "the-clumsy-dozen":"#5c0032,#b5081f,#e97325,#f7f131,#eef0e9,#bb90a7,#6b546a,#192116,#3e0080,#28668f,#1abd94,#97e65e", "jungle-level":"#856360,#8d2887,#2b180a,#862a00,#c76735,#e29f51,#c5e369,#c8ede0,#4492ee,#698426,#2e5b3f,#082b0e", "spec12":"#0f0808,#918c89,#d6d9d0,#d9d15d,#db6e3b,#a82d2d,#781c26,#8ed959,#32ba3b,#2f63bd,#30188f,#d9be93", "poke14":"#ffffff,#e8958b,#d45362,#612431,#f5dc8c,#cc8945,#8f3f29,#c0fac2,#5dd48f,#417d53,#6cadeb,#5162c2,#24325e,#1b1221", "warioware-diy":"#000000,#f8d898,#f8a830,#c04800,#f80000,#c868e8,#10c0c8,#2868c0,#089050,#70d038,#f8f858,#787878,#c0c0c0,#f8f8f8", "still-life":"#3f2811,#7a2222,#d13b27,#e07f8a,#5d853a,#68c127,#b3e868,#122615,#513155,#286fb8,#9b8bff,#a8e4d4,#cc8218,#c7b581", "aap-radiantxv":"#070505,#211919,#523a2a,#8a6b3e,#c19c4d,#eadb74,#a0b335,#537c44,#423c56,#596faf,#6bb9b6,#fbfaf9,#b8aab0,#79707e,#945b28", "syz15":"#0e0c19,#9d1f2f,#f28c8c,#b05621,#c9ad23,#d8e1a9,#52b466,#0e4f38,#68062f,#8d5a88,#126f7e,#53269a,#221452,#122f70,#223421", "tui-15":"#1d0d0d,#132242,#173727,#463a31,#784d30,#1042ac,#15709b,#a26d3d,#2ba1c3,#f0b03f,#b2a283,#c5b4d0,#f0c298,#7cdbcf,#e2e7f9", "summer-dream":"#fe9494,#fb6c6c,#c16d4a,#ffd3ad,#f5ad67,#808000,#90cc90,#c3ffc3,#66cdaa,#4682b4,#3d438b,#bebeff,#825acd,#dda0dd,#2f2c4a", "cade15":"#100f0c,#35165c,#4462bc,#4cbaff,#045524,#1c9924,#5c4a6c,#7c8e8d,#381000,#8e0232,#bc4604,#fa7d61,#d4920c,#ffd750,#e2f1d2", "equpix15":"#523c4e,#2a2a3a,#3e5442,#84545c,#38607c,#5c7a56,#101024,#b27e56,#d44e52,#55a894,#80ac40,#ec8a4b,#8bd0ba,#ffcc68,#fff8c0", "oh-hell-pastel-15":"#fc9977,#fcbd90,#fae6aa,#fff7d5,#f7f6a6,#a3d96a,#80d99b,#57cfc9,#51c0db,#70a5d4,#6d74cf,#584478,#8459c9,#be57c2,#de76a5", "kirby-15":"#2a0000,#78014f,#d50e55,#ed673a,#ffc75d,#03760b,#53b810,#c3ffe2,#8f11ba,#356ee2,#47c9ed,#59404b,#927691,#cb9cdc,#e427c6", "15p-dx":"#6e3232,#bb5735,#df9245,#ecd274,#83a816,#277224,#173b47,#046894,#17a1a9,#81dbcd,#fdf9f1,#c7b295,#87715b,#463f3c,#201708", "quick15":"#130f12,#422434,#21405f,#008080,#4ac23d,#5c915b,#6c6970,#8ec19f,#655c3f,#a9784b,#972e22,#f4714a,#fecd23,#efeee2,#699291", "impromptu-15":"#eee0b7,#debb59,#b48d6c,#c0624d,#a34646,#6d4859,#4a3e4f,#39373f,#404269,#4d5d75,#7b9096,#7fb8b5,#8fab62,#6e8a6c,#70755a", "apple-ii":"#000000,#515c16,#843d52,#ea7d27,#514888,#e85def,#f5b7c9,#006752,#00c82c,#919191,#c9d199,#00a6f0,#98dbc9,#c8c1f7,#ffffff", "jewel":"#321e2d,#662431,#b8281c,#d26a12,#f2c53c,#f0e89c,#dfb77f,#bc7b62,#79416b,#566094,#4a8fa9,#4dc1b3,#73e37b,#7482a1,#9cacba", "msx":"#000000,#cacaca,#ffffff,#b75e51,#d96459,#fe877c,#cac15e,#ddce85,#3ca042,#40b64a,#73ce7c,#5955df,#7e75f0,#64daee,#b565b3", "zx-spectrum":"#000000,#0022c7,#002bfb,#d62816,#ff331c,#d433c7,#ff40fc,#00c525,#00f92f,#00c7c9,#00fbfe,#ccc82a,#fffc36,#cacaca,#ffffff", "generic-15":"#222428,#5c596f,#a59ab6,#f4f0f4,#703f30,#d5555f,#ff95cf,#d7772d,#f3c775,#ffd8c3,#186444,#7ca230,#2b51a7,#169ac8,#81d5d7", "magic-15":"#11000b,#2b152b,#383038,#1e415b,#774372,#ba5150,#676a72,#587a44,#a089d6,#d99065,#afb8b6,#8ec5da,#9ccc82,#e8d876,#e3eac5", "softy-15":"#d9f6ea,#f1da04,#22172c,#3ec9ee,#bed3dc,#d0a841,#9cb31a,#0ea84a,#9fb8ae,#bd6666,#657140,#99119c,#156090,#40136d,#5c3411", "axol15":"#670c69,#bc0e58,#dc5c10,#f8f59e,#ecffff,#aed968,#5c88c2,#3f29a3,#3f1b49,#5a341b,#945936,#d0af82,#b5bb97,#5f6b64,#1e4246", "mord15":"#231923,#786973,#f5e6fa,#96d2f0,#6987a5,#3c3c5f,#507855,#9baf78,#e6e19b,#c89b82,#aa5564,#644146,#41234b,#a07da0,#e1afbe", "autum15-yellow":"#550000,#882211,#cc8844,#ddbb99,#ffddbb,#ddcc77,#999944,#555533,#ffffee,#bbddff,#6677aa,#666677,#443344,#223355,#111122", "nevercreature-15":"#181824,#593020,#5071a1,#61b68d,#c67569,#c2a530,#e2ae99,#d2eef6,#24484c,#6d7940,#409d34,#8f7045,#92e77c,#89d2e2,#eeda9d", "autum15":"#666677,#001122,#331111,#550000,#882211,#aa6622,#bb9977,#ffddbb,#ffffee,#555533,#999944,#6677aa,#bbddff,#443344,#112244", "mmtec-vp1":"#000000,#131384,#841313,#bd2e1b,#555555,#138413,#7a70da,#cf7925,#d870da,#aaaaaa,#80d456,#6ad7d8,#e5c587,#efe879,#ffffff", "drz15a":"#141419,#392f47,#664851,#a55d52,#d87272,#f29a80,#ffe35b,#ffffee,#515a8e,#537f3b,#80827e,#85abdd,#a4db72,#ffbffc,#cfeef7", "acid-15":"#170326,#40073d,#8f1e40,#d36036,#808080,#37bea1,#e3da78,#f4f9d2,#1c0d59,#094440,#1c5182,#21973b,#c9829b,#b5d737,#c0f8af", "ridley126-15":"#1b2f50,#324179,#3a7ebb,#39c4d0,#32c879,#67df53,#dfc449,#d5ea63,#4d48a3,#8344a7,#8b2d4c,#b22e2e,#b65d6e,#b2652e,#ce862c", "eggy-15":"#2e403d,#0e0c1b,#4609a1,#495266,#f0f2d0,#ca1e0f,#3c9b87,#c41be3,#9e7e74,#f63468,#2bcff2,#ea9d18,#afd87e,#ddd4cb,#f9d955", "chips-challenge-amiga-atari-st":"#ffffff,#ddddff,#9999dd,#666699,#444466,#000000,#dd6699,#00bb00,#66ffff,#00bbff,#0066ff,#0000bb,#ffdd00,#dd6600,#bb0000,#664400", "rabbit-jump":"#e0e0e0,#e0c040,#e06020,#e00000,#a00000,#000000,#808080,#a0a0a0,#a08040,#008000,#006000,#004000,#2080a0,#006060,#e0a0a0,#c06060", "super-breakout-st":"#efefef,#cfcfcf,#afafaf,#8f8f8f,#000000,#0f0fef,#6fafcf,#6fcfef,#ef6f6f,#cf4f4f,#efaf2f,#cf8f2f,#0fef0f,#0fcf0f,#ef0fef,#cf0fcf", "sierra-adventures-atari-st":"#e0e0e0,#a0a0a0,#404040,#000000,#e0e040,#a06000,#60e0e0,#408080,#e060e0,#800080,#80e040,#008000,#e06040,#800000,#0060e0,#0000a0", "supaplex":"#ffffff,#b0b0b0,#909090,#808080,#707070,#606060,#000000,#804000,#b00000,#e01010,#f09040,#e0e000,#00b060,#008050,#7090e0,#5050d0", "zeitgeist16":"#141019,#3d414a,#5d727b,#a6adb3,#f7f7ef,#e05569,#5b3156,#8f4438,#dd844b,#ecb984,#e6e759,#62c45a,#2f7141,#393b8a,#5080d6,#7bcee0", "sweetie-16":"#1a1c2c,#5d275d,#b13e53,#ef7d57,#ffcd75,#a7f070,#38b764,#257179,#29366f,#3b5dc9,#41a6f6,#73eff7,#f4f4f4,#94b0c2,#566c86,#333c57", "steam-lords":"#213b25,#3a604a,#4f7754,#a19f7c,#77744f,#775c4f,#603b3a,#3b2137,#170e19,#2f213b,#433a60,#4f5277,#65738c,#7c94a1,#a0b9ba,#c0d1cc", "na16":"#8c8fae,#584563,#3e2137,#9a6348,#d79b7d,#f5edba,#c0c741,#647d34,#e4943a,#9d303b,#d26471,#70377f,#7ec4c1,#34859d,#17434b,#1f0e1c", "bubblegum-16":"#16171a,#7f0622,#d62411,#ff8426,#ffd100,#fafdff,#ff80a4,#ff2674,#94216a,#430067,#234975,#68aed4,#bfff3c,#10d275,#007899,#002859", "endesga-16":"#e4a672,#b86f50,#743f39,#3f2832,#9e2835,#e53b44,#fb922b,#ffe762,#63c64d,#327345,#193d3f,#4f6781,#afbfd2,#ffffff,#2ce8f4,#0484d1", "island-joy-16":"#ffffff,#6df7c1,#11adc1,#606c81,#393457,#1e8875,#5bb361,#a1e55a,#f7e476,#f99252,#cb4d68,#6a3771,#c92464,#f48cb6,#f7b69e,#9b9c82", "pico-8":"#000000,#1D2B53,#7E2553,#008751,#AB5236,#5F574F,#C2C3C7,#FFF1E8,#FF004D,#FFA300,#FFEC27,#00E436,#29ADFF,#83769C,#FF77A8,#FFCCAA", "cthulhu-16":"#1d2531,#a5e5c5,#f0fafd,#52a593,#2b6267,#1e303a,#3b4251,#527b92,#7dc1c1,#c7fff3,#b8cbd8,#7e8da1,#8fa990,#e5debb,#cea061,#854731", "taffy-16":"#222533,#6275ba,#a3c0e6,#fafffc,#ffab7b,#ff6c7a,#dc435b,#3f48c2,#448de7,#2bdb72,#a7f547,#ffeb33,#f58931,#db4b3d,#a63d57,#36354d", "europa-16":"#ffffff,#75ceea,#317ad7,#283785,#1a1b35,#2e354e,#4f6678,#a4bcc2,#ecf860,#94d446,#3b7850,#20322e,#512031,#a43e4b,#dc7d5e,#f0cc90", "galaxy-flame":"#699fad,#3a708e,#2b454f,#111215,#151d1a,#1d3230,#314e3f,#4f5d42,#9a9f87,#ede6cb,#f5d893,#e8b26f,#b6834c,#704d2b,#40231e,#151015", "aap-16":"#070708,#332222,#774433,#cc8855,#993311,#dd7711,#ffdd55,#ffff33,#55aa44,#115522,#44eebb,#3388dd,#5544aa,#555577,#aabbbb,#ffffff", "endesga-soft-16":"#fefed7,#dbbc96,#ddac46,#c25940,#683d64,#9c6659,#88434f,#4d2831,#a9aba3,#666869,#51b1ca,#1773b8,#639f5b,#376e49,#323441,#161323", "peachy-pop-16":"#fdffff,#ff8686,#fb4771,#ce186a,#8f0b5f,#53034b,#ad6dea,#9fb9ff,#567feb,#0a547b,#278c7f,#0ce7a7,#acfcad,#ffec6d,#ffa763,#ff4040", "fzt-ethereal-16":"#f3f3f3,#f9c2a4,#b8700e,#5e0d24,#a29eb4,#c259df,#8f27b8,#c1002b,#6c606f,#0047ed,#00a8f3,#ddb411,#004952,#07865c,#00c37d,#051c25", "arq16":"#ffffff,#ffd19d,#aeb5bd,#4d80c9,#e93841,#100820,#511e43,#054494,#f1892d,#823e2c,#ffa9a9,#5ae150,#ffe947,#7d3ebf,#eb6c82,#1e8a4c", "ultima-vi-atari-st":"#f0f0f0,#c0a0a0,#706060,#202020,#000000,#50f050,#00a000,#006000,#5090f0,#0040d0,#101070,#f0d080,#e05000,#d00000,#504020,#d030d0", "enos16":"#fafafa,#d4d4d4,#9d9d9d,#4b4b4b,#f9d381,#eaaf4d,#f9938a,#e75952,#9ad1f9,#58aeee,#8deda7,#44c55b,#c3a7e1,#9569c8,#bab5aa,#948e82", "simplejpc-16":"#050403,#221f31,#543516,#9b6e2d,#e1b047,#f5ee9b,#fefefe,#8be1e0,#7cc264,#678fcb,#316f23,#404a68,#a14d3f,#a568d4,#9a93b7,#ea9182", "jw-64":"#000000,#404040,#8c8c8c,#c8c8c8,#644020,#a82f2f,#b46429,#e0806c,#403fc0,#6496f4,#63d4f0,#e0e040,#b437b4,#54c048,#a0f66e,#ffffff", "ultima-vi-sharp-x68000":"#e1e1e1,#a5a5a5,#4b4b4b,#000000,#e1c3b4,#e1a578,#a55a0f,#a50000,#e11e00,#e14be1,#e1e14b,#4be14b,#00a500,#0000a5,#4b4be1,#4be1e1", "jmp-japanese-machine-palette":"#000000,#191028,#46af45,#a1d685,#453e78,#7664fe,#833129,#9ec2e8,#dc534b,#e18d79,#d6b97b,#e9d8a1,#216c4b,#d365c8,#afaab9,#f5f4eb", "eroge-copper":"#0d080d,#4f2b24,#825b31,#c59154,#f0bd77,#fbdf9b,#fff9e4,#bebbb2,#7bb24e,#74adbb,#4180a0,#32535f,#2a2349,#7d3840,#c16c5b,#e89973", "fantasy-16":"#8e6d34,#513a18,#332710,#14130c,#461820,#a63c1e,#d37b1e,#e7bc4f,#eeeefa,#d9d55b,#757320,#14210f,#040405,#1c1b2f,#435063,#60a18f", "dawnbringer-16":"#140c1c,#442434,#30346d,#4e4a4e,#854c30,#346524,#d04648,#757161,#597dce,#d27d2c,#8595a1,#6daa2c,#d2aa99,#6dc2ca,#dad45e,#deeed6", "commodore64":"#000000,#626262,#898989,#adadad,#ffffff,#9f4e44,#cb7e75,#6d5412,#a1683c,#c9d487,#9ae29b,#5cab5e,#6abfc6,#887ecb,#50459b,#a057a3", "dinoknight-16":"#0f151b,#292732,#535867,#95928f,#f1f1ea,#c58d65,#8d5242,#513d3d,#ecd56d,#ea7730,#cd3d3d,#7c3f8c,#304271,#0083c8,#47a44d,#1f6143", "psygnosia":"#000000,#1b1e29,#362747,#443f41,#52524c,#64647c,#736150,#77785b,#9ea4a7,#cbe8f7,#e08b79,#a2324e,#003308,#084a3c,#546a00,#516cbf", "castpixel-16":"#2d1b2e,#218a91,#3cc2fa,#9af6fd,#4a247c,#574b67,#937ac5,#8ae25d,#8e2b45,#f04156,#f272ce,#d3c0a8,#c5754a,#f2a759,#f7db53,#f9f4ea", "zxarne-5-2":"#000000,#3c351f,#313390,#1559db,#a73211,#d85525,#a15589,#cd7a50,#629a31,#9cd33c,#28a4cb,#65dcd6,#e8bc50,#f1e782,#bfbfbd,#f2f1ed", "color-graphics-adapter":"#000000,#555555,#AAAAAA,#FFFFFF,#0000AA,#5555FF,#00AA00,#55FF55,#00AAAA,#55FFFF,#AA0000,#FF5555,#AA00AA,#FF55FF,#AA5500,#FFFF55", "colodore":"#000000,#4a4a4a,#7b7b7b,#b2b2b2,#ffffff,#813338,#c46c71,#553800,#8e5029,#edf171,#a9ff9f,#56ac4d,#75cec8,#706deb,#2e2c9b,#8e3c97", "copper-tech":"#000000,#262144,#355278,#60748a,#898989,#5aa8b2,#91d9f3,#ffffff,#f4cd72,#bfb588,#c58843,#9e5b47,#5f4351,#dc392d,#6ea92c,#1651dd", "easter-island":"#f6f6bf,#e6d1d1,#868691,#794765,#f5e17a,#edc38d,#cc8d86,#ca657e,#39d4b9,#8dbcd2,#8184ab,#686086,#9dc085,#7ea788,#567864,#051625", "chromatic16":"#000000,#90B0B0,#FFFFFF,#800018,#FF0000,#A05000,#FF8000,#FFC080,#FFFF00,#20AC00,#40FF00,#003070,#3070B0,#00D0FF,#A000E0,#FF60FF", "commodore-vic-20":"#000000,#ffffff,#a8734a,#e9b287,#772d26,#b66862,#85d4dc,#c5ffff,#a85fb4,#e99df5,#559e4a,#92df87,#42348b,#7e70ca,#bdcc71,#ffffb0", "arne-16":"#000000,#493c2b,#be2633,#e06f8b,#9d9d9d,#a46422,#eb8931,#f7e26b,#ffffff,#1b2632,#2f484e,#44891a,#a3ce27,#005784,#31a2f2,#b2dcef", "cgarne":"#000000,#5e606e,#2234d1,#4c81fb,#0c7e45,#6cd947,#44aacc,#7be2f9,#8a3622,#eb8a60,#5c2e78,#e23d69,#aa5c3d,#ffd93f,#b5b5b5,#ffffff", "night-16":"#0f0f1e,#fff8bc,#0c2133,#48586d,#79a0b0,#b0ce9d,#657f49,#3f4536,#b99d6a,#ffdd91,#dd945b,#9a5142,#644b48,#333033,#767088,#c5a3b3", "grunge-shift":"#000000,#242424,#240024,#482400,#6c2424,#b42400,#d8b490,#b49000,#6c6c00,#484800,#00fcd8,#4890fc,#486c90,#244890,#9048b4,#d86cb4", "microsoft-windows":"#000000,#7e7e7e,#bebebe,#ffffff,#7e0000,#fe0000,#047e00,#06ff04,#ffff04,#7e7e00,#00007e,#0000ff,#7e007e,#fe00ff,#047e7e,#06ffff", "cm16":"#e7ebf8,#adb1e0,#b06bb5,#6d2ea4,#aae474,#14ada0,#597acd,#7dc9de,#fff7a7,#ffbe6c,#ff6773,#bb027a,#f8c8af,#a17374,#2e5b86,#0c2a47", "crimso-11":"#ffffe3,#f3d762,#bf9651,#769a55,#cb5e31,#8e393d,#7a4962,#5e4531,#8ec3cf,#867696,#456e51,#3d6286,#353d5a,#232e32,#41292d,#110b11", "a64":"#0b0b0b,#566262,#8d8d85,#a7b5ba,#f0e9cf,#d39f80,#b0703e,#5a4142,#d1d15b,#a7d254,#58a23c,#7ac2e0,#786aff,#3e489d,#8363ad,#c14867", "r-place":"#FFFFFF,#E4E4E4,#888888,#222222,#FFA7D1,#E50000,#E59500,#A06A42,#E5D900,#94E044,#02BE01,#00D3DD,#0083C7,#0000EA,#CF6EE4,#820080", "naji-16":"#101a3a,#3d0e26,#64113d,#482e69,#3f425a,#6a3465,#74434a,#595579,#b73e62,#8d6d9c,#64967c,#c0719f,#c8926c,#dca286,#f2c966,#e6d1d5", "thug-16":"#504050,#a04040,#d06060,#f08080,#ffc0c0,#b0d0e0,#70b0c0,#4080b0,#000030,#102040,#204040,#306050,#409060,#50c060,#50ff90,#f0f0d0", "andrew-kensler-16":"#000000,#ffffff,#c98f4c,#6e4e23,#e80200,#efe305,#6a8927,#195648,#16ed75,#32c1c3,#057fc1,#3f32ae,#baaaff,#ff949d,#e30ec2,#7a243d", "chip16":"#d64b61,#3a2333,#000014,#538cc1,#70c6e5,#063e4c,#637272,#8e3737,#598e33,#7cb649,#565349,#eac879,#c4854e,#6f1a71,#e5e5e5,#d8a2a2", "macintosh-ii":"#ffffff,#ffff00,#ff6500,#dc0000,#ff0097,#360097,#0000ca,#0097ff,#00a800,#006500,#653600,#976536,#b9b9b9,#868686,#454545,#000000", "fun16":"#080008,#5e6660,#2a3443,#5d4632,#44508c,#a6414d,#c86b36,#8375af,#52903c,#db7ebd,#5b99f4,#deac85,#94cc4e,#84dbfc,#f2de70,#fcfffe", "flyguy-16":"#271620,#242d42,#326b3c,#64b450,#eeea44,#f0e9db,#a93630,#3f3025,#533c60,#24495e,#379589,#a4e8df,#eeb691,#db8333,#785136,#566969", "master-16":"#141414,#3b312f,#6e655f,#969590,#ebe8da,#f57d7d,#a11a2c,#4a1628,#612a2a,#c96540,#d4be42,#f0c295,#276647,#66bf3d,#2b3061,#4582cc", "cd-bac":"#000000,#da835c,#7f3710,#c4c466,#f4fb4a,#c7f0dc,#77e28e,#31983f,#37368d,#8e64e3,#d697ff,#f5cee6,#fdf5f9,#ce3f50,#5d0929,#301421", "pavanz-16":"#200037,#ffeedc,#65253f,#333e55,#b42f4b,#845a75,#406b81,#8f693d,#2b7d5f,#888da3,#c78f86,#d89763,#a1b25c,#a2ccc9,#e1cbc7,#efd497", "drazile-16":"#d1a649,#dd7252,#c64b3b,#754653,#9b7269,#bc8dad,#ccb4a1,#cad86c,#abbabc,#6fbc6f,#4f737c,#303a35,#5c3a96,#8a878e,#6f96d6,#e2e2c7", "super17-16":"#240909,#28171a,#371a2e,#342b41,#57333f,#323764,#2a5a51,#334591,#834848,#d73860,#507952,#265ace,#947a6c,#c3b570,#df8ac7,#eaf4b7", "optimum":"#000000,#575757,#a0a0a0,#ffffff,#2a4bd7,#1d6914,#814a19,#8126c0,#9dafff,#81c57a,#e9debb,#ad2323,#29d0d0,#ffee33,#ff9233,#ffcdf3", "risc-os":"#ffffff,#dcdcdc,#b9b9b9,#979797,#767676,#555555,#363636,#000000,#004597,#eded04,#05ca00,#dc0000,#ededb9,#558600,#ffb900,#04b9ff", "thomson-m05":"#000000,#bbbbbb,#ff0000,#dd7777,#eebb00,#ffff00,#dddd77,#00ff00,#77dd77,#00ffff,#bbffff,#ffffff,#ff00ff,#dd77ee,#0000ff,#7777dd", "indecision":"#fff4e0,#8fcccb,#449489,#285763,#2f2b5c,#4b3b9c,#457cd6,#f2b63d,#d46e33,#e34262,#94353d,#57253b,#9c656c,#d1b48c,#b4ba47,#6d8c32,#2c1b2e", "slso-clr17":"#2e2c3b,#3e415f,#55607d,#747d88,#41de95,#2aa4aa,#3b77a6,#249337,#56be44,#c6de78,#f3c220,#c4651c,#b54131,#61407a,#8f3da7,#ea619d,#c1e5ea", "ocaso":"#4b414a,#7e5956,#cf685a,#f3936a,#fada6d,#b9c773,#7eb678,#52a67e,#4c7768,#766d6d,#625760,#cb8177,#fe8e8f,#fff9bb,#bff0f0,#98b8d1,#9299ad", "spaceyeaster":"#201c34,#4f4b58,#cf2a83,#65367d,#7f7b8d,#e14d9d,#7d4898,#363042,#9a1a5f,#4e2b61,#aba2bf,#e56dae,#b685cf,#42192f,#351844,#84c9f5,#4184af", "17pastels":"#373254,#68356f,#5e6b82,#25718c,#11abbe,#69f6bf,#eff0d7,#f8e574,#a3e75c,#6d4442,#a16557,#f98bb7,#c84c66,#f79152,#9b9c82,#1c866d,#59b15e", "sgm-palette2":"#111111,#331133,#442255,#664477,#6655bb,#7788ff,#bbbbff,#ddddff,#ffeeff,#ffee99,#ffcc66,#ff8877,#ff3388,#bb4466,#774455,#aa6666,#dd9988", "17undertones":"#141923,#414168,#3a7fa7,#35e3e3,#8fd970,#5ebb49,#458352,#dcd37b,#fffee5,#ffd035,#cc9245,#a15c3e,#a42f3b,#f45b7a,#c24998,#81588d,#bcb0c2", "aap-majestyxvii":"#f4f3de,#b18961,#6d534f,#31232c,#0f0c0f,#762626,#ad5023,#d49322,#eacf5a,#97ab39,#58782a,#2b4024,#384e96,#2c99cc,#6cdcd5,#763858,#c45471", "17-above-zero":"#89697c,#413849,#0f5671,#4962ab,#4687c8,#89b7e4,#ecfbff,#849ace,#d2c1dd,#41a399,#8ec8ac,#0c1236,#6e5457,#9e8072,#ead6b7,#c895a7,#17845b", "2019-04-22-0xdb-01":"#202040,#404060,#969696,#dcdcc0,#ffffe6,#9c1f2e,#d97a46,#f2bb68,#f7ed7c,#52ca64,#c3d94c,#30999c,#63e2d4,#9db6ff,#4a52c2,#993697,#ff5988", "whimsy17":"#fff2ee,#431b31,#503a79,#742f52,#715e64,#cc5867,#306b8c,#68858a,#ad9087,#e18387,#6eba81,#eea38b,#94c5d1,#ecc5d3,#ffcd97,#8bf3aa,#e9f39a", "jinn17":"#261412,#895545,#777553,#6cb369,#aec375,#7d898f,#b296a5,#a9d7f4,#dbf1ee,#45353f,#4c4c69,#646273,#69759a,#735ec5,#7894c3,#b3a3f7,#5dcbe4", "dw17":"#140415,#671010,#754b37,#877b56,#8b9d53,#77ca73,#0e673f,#293065,#577dac,#f079a3,#b16fb9,#b33c6f,#dd8022,#f8cc01,#fec9af,#f2feff,#add3fe", "12bit":"#ffeeee,#111111,#ddaaaa,#445555,#888899,#99ddff,#77aacc,#557799,#555577,#333355,#558855,#aabb77,#eeddaa,#cc9955,#aa7744,#aa5566,#774455", "17vivid":"#070818,#2d2747,#3c4965,#4a4aa8,#8161c5,#3191e7,#55f6ff,#f7ffe0,#e2be57,#ffdf31,#c86b36,#95274a,#f159a9,#785537,#536f61,#62953c,#aae75d", "sgm-palette1":"#332233,#554422,#775522,#996666,#bb7744,#ee7799,#ee9922,#dddd77,#ddffff,#224455,#555566,#336666,#666677,#6677aa,#558888,#8888cc,#99bbff", "jp17":"#e1f6d2,#25222c,#54b43c,#374f7a,#3c7252,#63e474,#d7e95b,#a0714d,#a3aca6,#828484,#725997,#c694a8,#d1c6aa,#e99d46,#d7503c,#754e3b,#48d8ce", "sy17":"#fdfdf8,#252a8c,#808080,#bbbfdd,#6fa0c0,#3972be,#3e5d58,#4c8f49,#99bf69,#dad573,#c1a2a7,#b370b6,#664096,#020207,#444022,#905f3f,#c68d41", "drz17a":"#f1efdb,#191926,#8f857a,#674c47,#716261,#bd5d5d,#a493ad,#f3a09f,#f3bb55,#fbce9f,#423745,#4e517b,#5e797b,#997161,#c48d6c,#72ab6c,#89c7b4", "juicy-17":"#e1f6d2,#25222c,#54b43c,#374f7a,#3c7252,#63e474,#d7e95b,#a0714d,#a3aca6,#828484,#725997,#c694a8,#d1c6aa,#e99d46,#d7503c,#754e3b,#48d8ce", "clumpy-18":"#701a6a,#b22a79,#e084ac,#ecbcd2,#ece5ff,#b3cbff,#7b82fe,#601abc,#491173,#26181d,#46201b,#564c38,#787f53,#b5c59b,#e7e8b7,#dbc09e,#b88347,#994e2e", "goblin18":"#1b1221,#3a1367,#3e2ea8,#475ec2,#6996bf,#e3e9ea,#c2c2c2,#978b9c,#69566c,#46394c,#104b29,#3f8230,#98bc4d,#dddca7,#bc9e85,#b26d5c,#a43737,#4e1326", "banana-split":"#252422,#666666,#bfbdad,#d36d62,#e29273,#ce6e96,#dbb3b3,#7d4f6d,#ae86b2,#9f4549,#af7662,#4f9dad,#7be1ea,#38663b,#427b63,#2a4b46,#48536f,#59333b,#f6e9ba", "afternoon":"#2a2445,#331b31,#3c2c58,#4e2146,#352c58,#3f2d6a,#4f6185,#731615,#8b1514,#a04a26,#a32535,#a33425,#ba4c29,#ba292b,#8068bd,#8d75ca,#ec547b,#fda69a,#a599e3,#ffe8dc", "20p-dx":"#170d20,#474757,#787876,#b1b9a6,#ebffda,#68293e,#a94400,#d97e00,#ebd000,#523c14,#816031,#bc8b57,#ebcd93,#0e4c58,#046e92,#01a3c3,#55deb7,#177947,#5ab217,#b1e329", "ega-com-extended":"#292929,#52575c,#94999e,#deeedc,#7b2d2f,#d04043,#cb8f21,#e6c439,#6c4b37,#8c6946,#538a6a,#63b465,#2c4267,#38668b,#775780,#f4a66c,#576e54,#82e8e8,#9d446a,#eb7272", "c20":"#fcfcf5,#b9bbbb,#606060,#354353,#27215f,#f8bf87,#f76f2d,#cc4633,#c81530,#60322d,#111117,#770961,#c10d6b,#ec626c,#f4cc2d,#88dd3c,#2daa3d,#3e661a,#0c6f94,#1bb0b8", "hybrid20":"#140f1c,#474757,#6c6c6b,#b5bab1,#f4fee7,#5e322a,#955219,#df6620,#f0ce17,#bc8b57,#ebcd93,#1e5851,#086f93,#01a3c3,#38c7b8,#44ae2a,#9de033,#493049,#f8bf87,#d22c58", "oak21":"#f8873d,#b3495b,#621a8e,#ae39ac,#ee8dff,#fff49f,#b1d36e,#527f55,#18283a,#20434a,#257677,#74f1eb,#5695d9,#3e4c92,#381232,#814a54,#a3775f,#454b4e,#6e7880,#afbcc5,#ffffff", "mortmort":"#0f0e17,#50576b,#8d87a2,#bcb7c5,#ae57a4,#ea71bd,#ff8b9c,#ad3e50,#e1534a,#b8614e,#f29546,#ffce00,#3f7e00,#6ca800,#bdd156,#00a383,#3fc778,#a1ef79,#007dc7,#42cafd,#92f4ff", "graveyard":"#857a68,#a38a79,#beb590,#8a6966,#765b62,#1b1a1f,#302d33,#453c49,#5b4d5e,#756376,#8f7a8d,#a693a0,#8d7f98,#767488,#65686f,#4f554f,#6c6f65,#7b847a,#838798,#9fa8b3,#bdc9ce", "db-iso22":"#0c0816,#4c4138,#70503a,#bc5f4e,#ce9148,#e4da6c,#90c446,#698e34,#4d613c,#26323c,#2c4b73,#3c7373,#558dde,#74baea,#f0faff,#cfb690,#b67c74,#845a78,#555461,#746658,#6b7b89,#939388", "mother-earth":"#eeeec7,#dec26d,#cd9957,#bd6b44,#ac4136,#6c3434,#3e2d2e,#6e4c49,#94725d,#bfa17a,#ddcf95,#96c083,#5fa367,#4a806b,#3e625e,#384d52,#4c547a,#676786,#b1b0bf,#8e8897,#786072,#5a444e", "darchangel-22":"#b4b884,#849a78,#5c7c68,#205e64,#585e5c,#144054,#404068,#142858,#c87c94,#b49ab8,#e4d4dc,#e4d488,#e4b884,#e49a80,#907c68,#885e54,#6c3444,#142230,#5c7c90,#849aac,#b4d4e0,#e8f0dc", "eishiya-22":"#35212e,#562e3c,#a14462,#eb998b,#fddbc8,#42465c,#356d67,#4c9568,#7fb961,#b0d45d,#ffe788,#b20000,#f06152,#7d4444,#9e6c69,#cca69c,#5066a1,#76afda,#abddff,#dcf2ff,#e8743c,#ffc556", "ykb-22":"#cfcfc9,#9c9c97,#28252a,#482e2b,#804a3e,#b89286,#d2b7ae,#d2c2ae,#e7e5d1,#807868,#745b41,#684a45,#4a685d,#53a170,#a5c787,#8da9ae,#477e88,#404859,#ae86b2,#cf9db9,#8a5f67,#a97777", "atprises-22":"#dad6c6,#4f4153,#b06c81,#d1abb8,#d7be80,#cd9736,#b15c23,#86190b,#55312e,#412936,#181718,#4f6275,#7b8e43,#45502a,#3d3030,#784a44,#a38274,#b1aaa0,#99cad0,#1687b6,#13517d,#113350", "jerrypie-22":"#1e2431,#245168,#37969b,#9cc6d9,#dceff8,#c4d7a4,#937946,#794122,#523c20,#9d7dae,#76446e,#29472d,#347750,#40d58e,#72b245,#538947,#cfbe5b,#e06e36,#d2391c,#35291d,#191716,#552e41", "daruda-22":"#dee5d9,#0f0e13,#230a29,#40002d,#56002c,#700d1a,#6d291c,#813221,#923d13,#9f4a14,#b05302,#b96915,#bf8109,#cf9213,#d5a627,#e0bc25,#e8cf50,#e8e36f,#e7e88d,#e7a079,#e8a9a3,#e7b5c6", "super-plum-21":"#000000,#341f34,#4d1f4d,#a63a82,#a64b4b,#15788c,#266eff,#283b73,#ffbca6,#ff5983,#f37c55,#14cc80,#00d5ff,#8cb2ff,#642db3,#ffffff,#ffeecc,#ffc34d,#cbe545,#80ffea,#daeaf2,#6f66cc", "fourlines-22":"#faf9f9,#463b52,#5c575a,#57627a,#617351,#6b9755,#990b2d,#b56172,#878774,#a6a49c,#b4b4b4,#0d0d0d,#121682,#4e40a6,#7160ba,#4c7ed8,#169c78,#ad655f,#e36625,#eb9488,#ffc192,#f8e200", "mpb-24":"#2E2669,#324286,#1F6CC7,#47A9DC,#ACECDF,#F3F3EC,#FFD521,#F27C0D,#BE2A13,#77225C,#81C757,#32954A,#264A4B,#393758,#9E899F,#E3CCC0,#D19C80,#D06B0B,#7D472C,#A76C35,#F67EA2,#F24573", "xaiue-22-3":"#f1efb7,#ded75c,#c7a439,#8c7b26,#7c5a26,#6c472b,#45381d,#2c1e12,#6a673a,#ad8b45,#ded5aa,#a37963,#ccbc8e,#7b6c5c,#49473f,#161212,#2d2f3b,#3e4f80,#76829e,#a9acb7,#a1948f,#5f6679", "tuckie-22":"#f9f7b6,#f9de70,#e2a88e,#dd5d49,#84453b,#5d5b8c,#02566b,#161423,#4fb5ac,#e5f2fc,#a1d2fc,#f2d8a9,#f58b5d,#c96d61,#f87c90,#dd809c,#157bae,#688ed1,#d3ff97,#8ff79d,#0baeba,#312d47", "bogdanr5000-22":"#d48d5d,#f5c15f,#f0ec8d,#5a6699,#547fab,#7bb7c7,#6b928f,#8db697,#adc2a7,#bdd2cc,#e4eaed,#0e0e14,#585870,#2e2c29,#3d4463,#e0c0a6,#937296,#b88499,#cf9786,#9c5c6b,#944038,#b37a6f", "galapogos-22":"#a31f5f,#3c1010,#702500,#ba3200,#ef6a3d,#ee9f84,#95c9bc,#678893,#413f45,#352b2b,#1f0614,#fffaeb,#3a2d1d,#603f3e,#81573b,#b87b34,#ffc83b,#eadf7a,#c7ce6c,#818b31,#284a36,#0c2a23", "drazile-22":"#3f0909,#442038,#7a3123,#684a5d,#ce1c2b,#c16543,#ef6f2f,#efab62,#f7a8c5,#f7d942,#f2fbfc,#050004,#0c1223,#07353f,#38318e,#4e772b,#517cc1,#46af75,#9aa5a5,#8ed834,#4edbe8,#bdeef9", "artifice-machine-22":"#fbfbc4,#eef0f0,#efa88f,#ff8080,#f34b76,#f39f4b,#8f9f60,#64db9f,#afafaf,#58c4e7,#80708f,#f34b4b,#130d0d,#843c3c,#582734,#3c0420,#241e1c,#3c3c04,#103028,#206060,#273458,#301e42", "mordfikosz-22":"#aaaaaa,#151515,#4d302c,#724927,#a46a39,#c58b4a,#e1da6a,#bbc05c,#95a74f,#6a7f42,#415262,#446c9b,#6aa4d5,#afcbe4,#8988a1,#7b629c,#50307b,#21101d,#a1334f,#cd738b,#e1b2bf,#f4f1f3", "xaiue-22-2":"#fcfae4,#877469,#08060b,#372e23,#5b4d21,#9f7e2b,#6bcd63,#b3d6ef,#afb0e9,#4d8cd3,#4b4cb7,#b54537,#e58b37,#e0da2c,#70b03c,#3d7f4f,#2b404b,#1d183e,#6d4369,#b666a6,#ce989b,#f3d7bd", "xaiue-22":"#fcfae4,#877469,#08060b,#372e23,#5b4d21,#9f7e2b,#6bcd63,#b3d6ef,#afb0e9,#4d8cd3,#4b4cb7,#b54537,#e58b37,#e0da2c,#70b03c,#3d7f4f,#2b404b,#1d183e,#6d4369,#b666a6,#ce989b,#f3d7bd", "dpixel-22":"#040406,#4e4a36,#7e7256,#b0a480,#9da4b7,#131a21,#242e56,#2c5090,#6a8ab6,#a2c9dc,#edf0f1,#1b4331,#317d3c,#7db642,#c7e149,#fad43c,#c08b18,#dc5b28,#73230f,#2e1a23,#c8a090,#d6ced6", "irenaart-22":"#030505,#433c47,#706468,#c3ae86,#e4efff,#4de2f4,#2896c6,#11476c,#6440a2,#fe8c8f,#d1080e,#af3703,#731906,#734430,#d08150,#f9c89a,#f6d043,#df971a,#925a0b,#5d6606,#a4a718,#cce761", "d-jinn-22":"#141829,#2e2333,#353040,#373d2d,#6e3535,#a13535,#50568a,#606e3a,#5c6c70,#cf4e75,#4c877f,#cc7054,#00ffff,#bd78cc,#8f9e42,#ccad66,#7bb9e3,#bbcc66,#b0d9d1,#ebe288,#f5f2dc,#0e1224", "electric-crayon-22":"#000000,#554555,#a8a8a8,#ffffff,#a80000,#fe0000,#a85500,#fe7600,#fea876,#a8a800,#ffff04,#04a800,#06ff04,#04a8a8,#06ffff,#0076ff,#0000a8,#0000ff,#7600ff,#a800a8,#fe00ff,#fe0076", "bigpotato-22":"#030003,#f7f5ef,#c1decf,#eccd83,#d6ae87,#abb0c2,#74b1ce,#98af3c,#d89725,#be8867,#70838d,#bb6d3e,#aa6982,#3c7478,#966531,#616d36,#a6451f,#545b57,#73425f,#3a4164,#4a2525,#24162b", "nevercreature-22":"#0e0d28,#1e323e,#403d56,#74491d,#457074,#746d47,#665ba4,#3ba137,#2f938b,#01b0cf,#6b94ff,#880015,#c04110,#fb7760,#b7834f,#a6cd33,#f0b37b,#9e87dc,#99d9ea,#f5ea85,#c0c0c0,#daede9", "crimso-22":"#332230,#274653,#504b79,#be3751,#6d7855,#c8773d,#80ac37,#e8ab93,#5fd37a,#d3daff,#fdfffc,#181018,#443a36,#73473f,#336625,#416ebb,#c76b90,#88959e,#5ebacb,#e7b44a,#eed6af,#e9e66b", "keeling00-22":"#d0e0c6,#282c44,#29add0,#89a0d1,#54e8c9,#933689,#35902b,#3626b4,#2ede4e,#db303e,#367887,#d98489,#8ce13a,#dde04c,#e12ec4,#7b292e,#9538df,#85ad73,#94742e,#374ee6,#db972b,#db8ee0", "tranquil-fantasy-23":"#a52d27,#c96d45,#d1ca80,#a29d6b,#836b3f,#63492c,#413325,#28221f,#3a3b3d,#5f6367,#869598,#acc2c3,#d4eded,#97b58a,#65845c,#3a5941,#223a30,#503b68,#855b69,#dfb9ca,#acdcf1,#7ca8d5,#4c6ead", "dimwiddy-22":"#000000,#fae8e9,#e0cdf2,#e2e15c,#bab7a9,#b9abfa,#eba750,#c3be21,#e47251,#bb66e3,#7189e5,#519a4b,#897f7f,#cb4667,#a64887,#3a6d69,#38662c,#9e1f71,#ab2c29,#183776,#5d203e,#1e1647,#07060d", "vinik24":"#000000,#6f6776,#9a9a97,#c5ccb8,#8b5580,#c38890,#a593a5,#666092,#9a4f50,#c28d75,#7ca1c0,#416aa3,#8d6268,#be955c,#68aca9,#387080,#6e6962,#93a167,#6eaa78,#557064,#9d9f7f,#7e9e99,#5d6872,#433455", "fantasy-24":"#1f240a,#39571c,#a58c27,#efac28,#efd8a1,#ab5c1c,#183f39,#ef692f,#efb775,#a56243,#773421,#724113,#2a1d0d,#392a1c,#684c3c,#927e6a,#276468,#ef3a0c,#45230d,#3c9f9c,#9b1a0a,#36170c,#550f0a,#300f0a", "mail-24":"#17111a,#372538,#7a213a,#e14141,#ffa070,#c44d29,#ffbf36,#fff275,#753939,#cf7957,#ffd1ab,#39855a,#83e04c,#dcff70,#243b61,#3898ff,#6eeeff,#682b82,#bf3fb3,#ff80aa,#3e375c,#7884ab,#b2bcc2,#ffffff", "24p-dx":"#170f07,#484542,#897a6c,#c9b79c,#fcf5e8,#6f241d,#c0460e,#ee8300,#ffc42d,#4c2c35,#8e5340,#cc8c58,#f7c78b,#0d4157,#207949,#66b632,#c9e251,#00719d,#00abc4,#6fddd5,#632c53,#b7466c,#ff7986,#ffbda9", "battery24":"#f8ffba,#332431,#573752,#784465,#8f476a,#a64c6c,#d9577c,#e04646,#e6634c,#e89851,#e8cb58,#e2ed82,#fcffde,#76e856,#3ae056,#c9fa75,#b5f26b,#41c47c,#46b38e,#4c90a1,#497791,#466287,#424a70,#303042", "superfuture25":"#100820,#181e33,#606fab,#b7d9ee,#ffffff,#2c1923,#965039,#db9357,#f8daac,#c0c0c0,#1c332d,#366943,#70c33b,#ffff00,#4d4d4d,#611b32,#d2352f,#ff8000,#e4bb40,#ff0040,#00ffe1,#0080ff,#45107e,#9c09cc,#ff00ff", "today-land-palette-v2":"#141414,#31383d,#5a676c,#94a8aa,#edefef,#5e1632,#ae2432,#e37017,#f4bf42,#452323,#7e423a,#c67742,#f0b784,#1b3845,#21675f,#34b06f,#98e88a,#212363,#264ba4,#1e8fde,#6cd5e4,#441c5c,#8e307f,#e4629a,#f2b4b7", "humers":"#fcf6df,#b3ac9a,#605f49,#343329,#0a0117,#3b1e61,#7c4892,#c4769f,#ffa092,#9b415a,#6b1d16,#431815,#95492a,#d5764b,#f7dd9a,#e1b64f,#94873b,#265315,#8bba70,#1a7c60,#132127,#1b21b3,#187dcf,#3ebab9,#85e4ed", "nt1h":"#ffffff,#acf693,#46c657,#158968,#222f46,#425d69,#65908b,#8fb9ac,#bddfcc,#abd1d2,#8babbf,#566a89,#383a63,#fff18d,#edc660,#de993c,#c25e22,#4b003b,#8a0047,#bc1334,#e43636,#ff9a70,#9cd8fc,#5e96dd,#3953c0,#19157f", "amstrad-cpc":"#040404,#808080,#ffffff,#800000,#ff0000,#ff8080,#ff7f00,#ffff80,#ffff00,#808000,#008000,#01ff00,#80ff00,#80ff80,#01ff80,#008080,#01ffff,#80ffff,#0080ff,#0000ff,#00007f,#7f00ff,#8080ff,#ff80ff,#ff00ff,#ff0080,#800080", "container-28":"#f2ffe8,#ffe742,#fe9e23,#f94b07,#932727,#441717,#5b362e,#b66251,#df9278,#edb794,#a58960,#826740,#064031,#017236,#73ae48,#92e346,#7acca7,#839892,#2f4070,#463352,#251920,#2a2840,#445b56,#616f4f,#bd4283,#651d43,#37053b,#1c040f", "mspaint-xp":"#000000,#808080,#c0c0c0,#ffffff,#800000,#ff0000,#808000,#ffff00,#008000,#00ff00,#008080,#00ffff,#000080,#0000ff,#800080,#ff00ff,#808040,#ffff80,#004040,#00ff80,#0080ff,#80ffff,#004080,#8080ff,#8000ff,#ff0080,#804000,#ff8040", "mspaint-vista":"#000000,#464646,#787878,#b4b4b4,#dcdcdc,#ffffff,#990030,#9c5a3c,#ed1c24,#ffa3b1,#ff7e00,#e5aa7a,#ffc20e,#f5e49c,#fff200,#fff9bd,#a8e61d,#d3f9bc,#22b14c,#9dbb61,#00b7ef,#99d9ea,#4d6df3,#709ad1,#2f3699,#546d8e,#6f3198,#b5a5d5", "star29":"#8e2436,#f1223c,#531f28,#2c121d,#0d1219,#1b1d46,#253169,#2d478d,#366dc0,#5cc4f9,#ffffff,#b3b3e1,#747aa5,#444c6c,#202838,#ba5d2f,#ec812f,#7b392a,#512520,#321615,#6c3296,#d33cf2,#3f2668,#211839,#60a33d,#afef49,#356d32,#22442b,#111f19", "arcade-standard-29":"#f1f0ee,#ff4d4d,#9f1e31,#ffc438,#f06c00,#f1c284,#c97e4f,#973f3f,#57142e,#72cb25,#238531,#0a4b4d,#30c5ad,#2f7e83,#69deff,#33a5ff,#3259e2,#28237b,#c95cd1,#6c349d,#ffaabc,#e55dac,#17191b,#96a5ab,#586c79,#2a3747,#b9a588,#7e6352,#412f2f", "linear-color-palette-basic":"#0e0c0c,#5f2d56,#993970,#dc4a7b,#f78697,#9f294e,#62232f,#8f4029,#c56025,#ee8e2e,#fccba3,#da4e38,#facb3e,#97da3f,#4ba747,#3d734f,#314152,#417089,#49a790,#72d6ce,#5698cc,#5956bd,#473579,#8156aa,#c278d0,#f0b3dd,#fdf7ed,#d3bfa9,#aa8d7a,#775c55,#483b3a", "30-color":"#201923,#ffffff,#fcff5d,#7dfc00,#0ec434,#228c68,#8ad8e8,#235b54,#29bdab,#3998f5,#37294f,#277da7,#3750db,#f22020,#991919,#ffcba5,#e68f66,#c56133,#96341c,#632819,#ffc413,#f47a22,#2f2aa0,#b732cc,#772b9d,#f07cab,#d30b94,#edeff3,#c3a5b4,#946aa2,#5d4c86", "mr-cool-juicy-fruit":"#000000,#281619,#3f151c,#87161d,#a03312,#e3640a,#f39f12,#dea44e,#97a937,#618629,#536d4e,#172921,#14162c,#232943,#34495b,#547394,#65686e,#8c8787,#aba5a5,#a6937a,#6d6954,#7c746f,#6a5854,#544f4e,#3a302c,#534a35,#85543d,#996d4d,#d58869,#f0ba7e,#dfd0b9,#ffffff", "endesga-32":"#be4a2f,#d77643,#ead4aa,#e4a672,#b86f50,#733e39,#3e2731,#a22633,#e43b44,#f77622,#feae34,#fee761,#63c74d,#3e8948,#265c42,#193c3e,#124e89,#0099db,#2ce8f5,#ffffff,#c0cbdc,#8b9bb4,#5a6988,#3a4466,#262b44,#181425,#ff0044,#68386c,#b55088,#f6757a,#e8b796,#c28569", "sheltzy32":"#8cffde,#45b8b3,#839740,#c9ec85,#46c657,#158968,#2c5b6d,#222a5c,#566a89,#8babbf,#cce2e1,#ffdba5,#ccac68,#a36d3e,#683c34,#000000,#38002c,#663b93,#8b72de,#9cd8fc,#5e96dd,#3953c0,#800c53,#c34b91,#ff94b3,#bd1f3f,#ec614a,#ffa468,#fff6ae,#ffda70,#f4b03c,#ffffff", "juice-32":"#330e22,#662435,#994c4c,#cc897c,#ffccb5,#e57239,#b23535,#7f184b,#3d063d,#07000e,#4f1f1b,#874d36,#d89d61,#ffc759,#ffeb8c,#b2d660,#50b247,#257c49,#105448,#0a3947,#121d35,#384766,#6b7a99,#b8c5d8,#fffff2,#91e0cc,#358282,#3e6ab2,#192866,#5b3582,#a5528b,#d37484", "pineapple-32":"#43002a,#890027,#d9243c,#ff6157,#ffb762,#c76e46,#73392e,#34111f,#030710,#273b2d,#458239,#9cb93b,#ffd832,#ff823b,#d1401f,#7c191a,#310c1b,#833f34,#eb9c6e,#ffdaac,#ffffe4,#bfc3c6,#6d8a8d,#293b49,#041528,#033e5e,#1c92a7,#77d6c1,#ffe0dc,#ff88a9,#c03b94,#601761", "resurrect-32":"#ffffff,#fb6b1d,#e83b3b,#831c5d,#c32454,#f04f78,#f68181,#fca790,#e3c896,#ab947a,#966c6c,#625565,#3e3546,#0b5e65,#0b8a8f,#1ebc73,#91db69,#fbff86,#fbb954,#cd683d,#9e4539,#7a3045,#6b3e75,#905ea9,#a884f3,#eaaded,#8fd3ff,#4d9be6,#4d65b4,#484a77,#30e1b9,#8ff8e2", "pico-8-secret-palette":"#000000,#1d2b53,#7e2553,#008751,#ab5236,#5f574f,#c2c3c7,#fff1e8,#ff004d,#ffa300,#ffec27,#00e436,#29adff,#83769c,#ff77a8,#ffccaa,#291814,#111d35,#422136,#125359,#742f29,#49333b,#a28879,#f3ef7d,#be1250,#ff6c24,#a8e72e,#00b543,#065ab5,#754665,#ff6e59,#ff9d81", "cpc-boy":"#000000,#1b1b65,#3535c9,#661e25,#553361,#7f35c9,#bc3535,#c0466e,#df6d9b,#1b651b,#1b6e83,#1e79e5,#795f1b,#808080,#9194df,#c97f35,#e39b8d,#f878f8,#35af35,#35b78f,#35c1d7,#7fc935,#adc8aa,#8de1c7,#e1c643,#e4dd9a,#ffffff,#eeeae0,#acb56b,#768448,#3f503f,#243137", "star32":"#ffffff,#75cefb,#4c6ac8,#282159,#773198,#c54daa,#f78f9f,#e03940,#8e243f,#531f37,#2d1b29,#11151a,#483861,#6a6893,#99a9c7,#cce8eb,#b0ef49,#45a346,#326d55,#224044,#1a212d,#562f35,#863b36,#b96234,#f1bf59,#9e5132,#d9995a,#eed492,#a6e5bf,#52a593,#2a5866,#1d2d3a", "turd32":"#fffed6,#b0dcd2,#7bb2a2,#7b8d78,#e99ced,#ee71ce,#f23c85,#c22346,#c58e25,#b25618,#9c2519,#711919,#f0d839,#f9b351,#7ad679,#2bd234,#779c21,#248d1f,#246200,#2c400d,#1bd2a8,#1f7877,#2b2e0b,#062a0f,#222834,#1a2524,#131c25,#050a19,#2f4848,#263642,#1c396a,#182446", "lxj-32":"#ffffff,#fbffd6,#f4ff75,#f5d868,#f5c356,#f8b242,#f29606,#7cb2d3,#6281c2,#4548ae,#502fbb,#4122a9,#a53636,#882a2a,#782424,#622121,#9156aa,#6a387e,#552766,#431f51,#8d6230,#765734,#7b6a5c,#6b5e51,#544a44,#3f3938,#332f2e,#5e685c,#3a4537,#262e25,#1d221c,#121412", "zughy-32":"#472d3c,#5e3643,#7a444a,#a05b53,#bf7958,#eea160,#f4cca1,#b6d53c,#71aa34,#397b44,#3c5956,#302c2e,#5a5353,#7d7071,#a0938e,#cfc6b8,#dff6f5,#8aebf1,#28ccdf,#3978a8,#394778,#39314b,#564064,#8e478c,#cd6093,#ffaeb6,#f4b41b,#f47e1b,#e6482e,#a93b3b,#827094,#4f546b", "dawnbringer-32":"#000000,#222034,#45283c,#663931,#8f563b,#df7126,#d9a066,#eec39a,#fbf236,#99e550,#6abe30,#37946e,#4b692f,#524b24,#323c39,#3f3f74,#306082,#5b6ee1,#639bff,#5fcde4,#cbdbfc,#ffffff,#9badb7,#847e87,#696a6a,#595652,#76428a,#ac3232,#d95763,#d77bba,#8f974a,#8a6f30", "greenstar32":"#312e2f,#635c5a,#81776b,#c6b5a5,#ffedd4,#96567a,#ca7091,#60434f,#884f5e,#af6567,#bb7979,#c37c6b,#dd997e,#e9b58c,#c68b5b,#8c594a,#5e443f,#e1ad56,#f8cf8e,#efdc76,#cebe55,#9d9f37,#72792b,#515e2e,#45644f,#508657,#bbd18a,#5b546c,#6a7189,#7a949c,#80aba4,#aed7b9", "marshmellow32":"#2b3f41,#3a5356,#57797d,#8ca697,#3f3e20,#555735,#767f45,#a4ab79,#593234,#734141,#8c504d,#b87a66,#c1bcac,#afa491,#907b67,#71554a,#3c3c3c,#544a44,#a1623b,#b68241,#e2b55f,#b2b2b2,#7c7c7c,#4b5053,#3c3a3f,#4e3c5c,#6e4d7e,#8f619a,#20415b,#235b7c,#2d80a6,#5eb3bc", "koni32":"#000000,#0b0a0d,#161524,#222640,#2b4057,#306566,#34a870,#49f25a,#a4ff63,#fff240,#f2a53f,#cc7a47,#f54025,#a63a3a,#995348,#733758,#4d2a49,#46346a,#8c2eb8,#f261da,#ffa8d4,#b3dfff,#70a5fa,#407cff,#1f50cc,#213ea6,#272f66,#414558,#6d7078,#898b8c,#bbbdbf,#ffffff", "ufo-50":"#ffffff,#a48080,#feb854,#e8ea4a,#58f5b1,#64a4a4,#cc68e4,#fe626e,#c8c8c8,#e03c32,#fe7000,#63b31d,#a4f022,#27badb,#fe48de,#d10f4c,#707070,#991515,#ca4a00,#a3a324,#008456,#006ab4,#9600dc,#861650,#000000,#4c0000,#783450,#8a6042,#003d10,#202040,#340058,#4430ba", "andrew-kensler-32":"#d6a090,#fe3b1e,#a12c32,#fa2f7a,#fb9fda,#e61cf7,#992f7c,#47011f,#051155,#4f02ec,#2d69cb,#00a6ee,#6febff,#08a29a,#2a666a,#063619,#000000,#4a4957,#8e7ba4,#b7c0ff,#ffffff,#acbe9c,#827c70,#5a3b1c,#ae6507,#f7aa30,#f4ea5c,#9b9500,#566204,#11963b,#51e113,#08fdcc", "atapki-baby32":"#000000,#424242,#7f7e7f,#bebebe,#ffffff,#ff9c7c,#ff0000,#9d1636,#43142b,#8c3a21,#c96e19,#efb300,#ffff00,#04be00,#0c7a42,#113939,#0000ff,#3776ff,#37bbff,#04ffff,#ffb5ec,#ff00ff,#a018cf,#4e1f7f,#131225,#38466c,#32421b,#5e5e39,#a9e0a6,#f4d1c3,#4f3835,#1d1918", "arne-32":"#000000,#493c2b,#be2633,#e06f8b,#a46422,#eb8931,#f7e26b,#ffffff,#9d9d9d,#2f484e,#1b2632,#44891a,#a3ce27,#005784,#31a2f2,#b2dcef,#342a97,#656d71,#cccccc,#732930,#cb43a7,#524f40,#ad9d33,#ec4700,#fab40b,#115e33,#14807e,#15c2a5,#225af6,#9964f9,#f78ed6,#f4b990", "hybrid32":"#593339,#903d62,#ae6253,#dd9c68,#edce9f,#c2c237,#6aba3b,#3b8f5b,#335a5c,#376129,#979ea8,#c0c7b7,#e4edf5,#38c2d6,#296291,#353456,#613755,#955b8d,#d467a2,#e5df52,#ec6b24,#a83135,#565299,#645964,#2e2a35,#d96f67,#9d5a33,#5095e6,#526626,#101b21,#f21e44,#ffffff", "gnome-32":"#eae8e3,#bab5ab,#807d74,#565248,#c5d2c8,#83a67f,#5d7555,#445632,#e0b6af,#c1665a,#884631,#663822,#ada7c8,#887fa3,#625b81,#494066,#9db8d2,#7590ae,#4b6983,#314e6c,#efe0cd,#e0c39e,#b39169,#826647,#df421e,#990000,#eed680,#d1940c,#46a046,#267726,#ffffff,#000000", "zykro-32":"#000000,#181a1a,#3b494f,#5d6d72,#7a8e95,#99aab0,#bfced3,#ffffff,#7a0724,#8f091d,#a70a0a,#ca1818,#de4c35,#c74c20,#cc7223,#e6a029,#f7ca40,#f7d87c,#581414,#7b402a,#a76542,#ca8655,#064022,#066625,#39a32a,#86cc3e,#c2f576,#2d0f84,#4044dc,#4085dc,#6ec1ed,#bbf5ff", "fleja-master-palette":"#1f1833,#2b2e42,#414859,#68717a,#90a1a8,#b6cbcf,#ffffff,#fcbf8a,#b58057,#8a503e,#5c3a41,#c93038,#de6a38,#ffad3b,#ffe596,#fcf960,#b4d645,#51c43f,#309c63,#236d7a,#264f6e,#233663,#417291,#4c93ad,#63c2c9,#94d2d4,#b8fdff,#3c2940,#46275c,#826481,#f7a48b,#c27182,#852d66", "today-land-palette":"#141414,#383838,#67615f,#a69f96,#f0eeec,#611732,#ae2633,#e86c18,#f1bb3b,#f26864,#4a2426,#844239,#c47540,#efb681,#d4705c,#206348,#42ad37,#b4e357,#1a363f,#20646c,#2bad96,#a1e4a0,#222664,#264fa4,#1f95e1,#6de0e5,#431c58,#8d2f7c,#e4669b,#f0b4ad,#32384a,#4f6872,#88a7a0", "voodo34":"#111426,#373d5f,#626789,#838ea8,#bdd0ef,#1c2153,#2d4280,#5a77b9,#8dc9f2,#33275d,#6a448a,#a467c3,#ec98f7,#29484a,#149d63,#55bf41,#a0e772,#3ac390,#80f3b5,#f4fbf8,#6b1830,#c6224e,#f84284,#fe95cd,#c72d1e,#e15d2c,#e8931f,#f2d833,#3a2222,#653223,#865234,#7a6240,#b98968,#f8d094", "star34":"#0d1219,#1b1d46,#3f2668,#6c3296,#d33cf2,#f0687d,#ffffff,#f1223c,#8e2436,#531f28,#2c121d,#253169,#2d478d,#366dc0,#5cc4f9,#b3b3e1,#747aa5,#444c6c,#202838,#321615,#512520,#7b392a,#aa6439,#d9995a,#eeca92,#ffce5f,#f59e3f,#ec812f,#ba5d2f,#111f19,#22442b,#356d32,#60a33d,#afef49", "pear36":"#5e315b,#8c3f5d,#ba6156,#f2a65e,#ffe478,#cfff70,#8fde5d,#3ca370,#3d6e70,#323e4f,#322947,#473b78,#4b5bab,#4da6ff,#66ffe3,#ffffeb,#c2c2d1,#7e7e8f,#606070,#43434f,#272736,#3e2347,#57294b,#964253,#e36956,#ffb570,#ff9166,#eb564b,#b0305c,#73275c,#422445,#5a265e,#80366b,#bd4882,#ff6b97,#ffb5b5", "blk-36":"#000000,#12173d,#293268,#464b8c,#6b74b2,#909edd,#c1d9f2,#ffffff,#ffccd0,#e5959f,#c16a7d,#8c4b63,#66334b,#3f233c,#29174c,#412866,#643499,#8c51cc,#b991f2,#a5e6ff,#5ab9e5,#4185d8,#354ab2,#36277f,#0a2a33,#0f4a4c,#14665b,#22896e,#42bc7f,#8cff9b,#ffe091,#ff965f,#cc5250,#872a38,#d83843,#ff6866", "endesga-36":"#dbe0e7,#a3acbe,#67708b,#4e5371,#393a56,#26243a,#141020,#7bcf5c,#509b4b,#2e6a42,#1a453b,#0f2738,#0d2f6d,#0f4da3,#0e82ce,#13b2f2,#41f3fc,#f0d2af,#e5ae78,#c58158,#945542,#623530,#46211f,#97432a,#e57028,#f7ac37,#fbdf6b,#fe979b,#ed5259,#c42c36,#781f2c,#351428,#4d2352,#7f3b86,#b45eb3,#e38dd6", "lux2k":"#25131a,#3d253b,#523b40,#1f3736,#2a5a39,#427f3b,#80a53f,#bbc44e,#96c641,#ccf61f,#8a961f,#5c6b53,#895a45,#d1851e,#ffd569,#bf704d,#e1a171,#e6deca,#9b4c51,#802954,#d01946,#e84444,#40369f,#7144ff,#af69bf,#eaa5ff,#5880cc,#62abd4,#9bf0fd,#cae6f5,#ffffff,#a7acba,#606060,#56587b,#9a8571,#dfbbb3" }
var assert = require('assert'); var convert = require('../js/convert.js'); describe('convert', function() { describe('datePickerFormatTest', function() { it('should return dd.mm.yyyy for date format d.m.Y', function() { assert.equal(convert.datepicker_format('d.m.Y'), 'dd.mm.yyyy'); }); it('should return HH:i for time format H:i:s', function() { assert.equal(convert.datepicker_format('H:i:s'), 'HH:i'); }); it('should remove trailing comma', function() { assert.equal(convert.datepicker_format('H:i:'), 'HH:i'); }); }); describe('getWorkDaysTest', function () { it('should return datepicker days format', function() { var days = ['monday', 'tuesday', 'wednesday']; var result = convert.get_work_days(days, false); var expectation = [true, 2, 3, 4]; assert.equal(JSON.stringify(result), JSON.stringify(expectation)); }); it('should return datepicker days format for monday as first day', function() { var days = ['monday', 'tuesday', 'wednesday']; var result = convert.get_work_days(days, true); var expectation = [true, 1, 2, 3]; assert.equal(JSON.stringify(result), JSON.stringify(expectation)); }); }); describe('convertTimeToArray', function () { it('should return array from timeformat', function() { var result = convert.convertTimeToArray('12:35', false); var expectation = ['12', '35']; assert.equal(JSON.stringify(result), JSON.stringify(expectation)); }); it('should return array from timeformat', function() { var result = convert.convertTimeToArray('12', false); var expectation = ['12', 0]; assert.equal(JSON.stringify(result), JSON.stringify(expectation)); }); }); });
'use strict'; var expect = require('chai').expect; var colorString = require('../src/utils/color_string'); describe('color_string.js', function() { it("works", function(){ expect(colorString("someString")).to.equal("#4D5D13") }) })
/* vim:st=2:sts=2:sw=2: * ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Jetpack. * * The Initial Developer of the Original Code is Mozilla. * Portions created by the Initial Developer are Copyright (C) 2007 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Atul Varma <atul@mozilla.com> * Irakli Gozalishvili <gozala@mozilla.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var timer = require("timer"); exports.findAndRunTests = function findAndRunTests(options) { var TestFinder = require("unit-test-finder").TestFinder; var finder = new TestFinder({ dirs: options.dirs, filter: options.filter, testInProcess: options.testInProcess, testOutOfProcess: options.testOutOfProcess }); var runner = new TestRunner({fs: options.fs}); finder.findTests( function (tests) { runner.startMany({tests: tests, onDone: options.onDone}); }); }; var TestRunner = exports.TestRunner = function TestRunner(options) { if (options) { this.fs = options.fs; } memory.track(this); this.passed = 0; this.failed = 0; this.testRunSummary = []; }; TestRunner.prototype = { toString: function toString() "[object TestRunner]", DEFAULT_PAUSE_TIMEOUT: 10000, PAUSE_DELAY: 500, _logTestFailed: function _logTestFailed(why) { this.test.errors[why]++; if (!this.testFailureLogged) { console.error("TEST FAILED: " + this.test.name + " (" + why + ")"); this.testFailureLogged = true; } }, makeSandboxedLoader: function makeSandboxedLoader(options) { if (!this.fs) console.error("Hey, either you didn't pass .fs when building the" + " TestRunner, or you used 'new' when calling" + " test.makeSandboxedLoader. Don't do that."); if (!options) options = {console: console}; options.fs = this.fs; var Cuddlefish = require("cuddlefish"); if ("moduleOverrides" in options) { var moduleOverrides = options.moduleOverrides; delete options.moduleOverrides; function getModuleExports(basePath, module) { if (module in moduleOverrides) return moduleOverrides[module]; return null; } options.getModuleExports = getModuleExports; } return new Cuddlefish.Loader(options); }, pass: function pass(message) { console.info("pass:", message); this.passed++; this.test.passed++; }, fail: function fail(message) { this._logTestFailed("failure"); console.error("fail:", message); console.trace(); this.failed++; this.test.failed++; }, exception: function exception(e) { this._logTestFailed("exception"); console.exception(e); this.failed++; this.test.failed++; }, assertMatches: function assertMatches(string, regexp, message) { if (regexp.test(string)) { if (!message) message = uneval(string) + " matches " + uneval(regexp); this.pass(message); } else { var no = uneval(string) + " doesn't match " + uneval(regexp); if (!message) message = no; else message = message + " (" + no + ")"; this.fail(message); } }, assertRaises: function assertRaises(func, predicate, message) { try { func(); if (message) this.fail(message + " (no exception thrown)"); else this.fail("function failed to throw exception"); } catch (e) { var errorMessage; if (typeof(e) == "string") errorMessage = e; else errorMessage = e.message; if (typeof(predicate) == "string") this.assertEqual(errorMessage, predicate, message); else this.assertMatches(errorMessage, predicate, message); } }, assert: function assert(a, message) { if (!a) { if (!message) message = "assertion failed, value is " + a; this.fail(message); } else this.pass(message || "assertion successful"); }, assertNotEqual: function assertNotEqual(a, b, message) { if (a != b) { if (!message) message = "a != b != " + uneval(a); this.pass(message); } else { var equality = uneval(a) + " == " + uneval(b); if (!message) message = equality; else message += " (" + equality + ")"; this.fail(message); } }, assertEqual: function assertEqual(a, b, message) { if (a == b) { if (!message) message = "a == b == " + uneval(a); this.pass(message); } else { var inequality = uneval(a) + " != " + uneval(b); if (!message) message = inequality; else message += " (" + inequality + ")"; this.fail(message); } }, assertNotStrictEqual: function assertNotStrictEqual(a, b, message) { if (a !== b) { if (!message) message = "a !== b !== " + uneval(a); this.pass(message); } else { var equality = uneval(a) + " === " + uneval(b); if (!message) message = equality; else message += " (" + equality + ")"; this.fail(message); } }, assertStrictEqual: function assertStrictEqual(a, b, message) { if (a === b) { if (!message) message = "a === b === " + uneval(a); this.pass(message); } else { var inequality = uneval(a) + " !== " + uneval(b); if (!message) message = inequality; else message += " (" + inequality + ")"; this.fail(message); } }, done: function done() { if (!this.isDone) { this.isDone = true; if (this.waitTimeout !== null) { timer.clearTimeout(this.waitTimeout); this.waitTimeout = null; } if (this.test.passed == 0 && this.test.failed == 0) { this._logTestFailed("empty test"); this.failed++; this.test.failed++; } this.testRunSummary.push({ name: this.test.name, passed: this.test.passed, failed: this.test.failed, errors: [error for (error in this.test.errors)].join(", ") }); if (this.onDone !== null) { var onDone = this.onDone; var self = this; this.onDone = null; timer.setTimeout(function() { onDone(self); }, 0); } } }, // Set of assertion functions to wait for an assertion to become true // These functions take the same arguments as the TestRunner.assert* methods. waitUntil: function waitUntil() { return this._waitUntil(this.assert, arguments); }, waitUntilNotEqual: function waitUntilNotEqual() { return this._waitUntil(this.assertNotEqual, arguments); }, waitUntilEqual: function waitUntilEqual() { return this._waitUntil(this.assertEqual, arguments); }, waitUntilMatches: function waitUntilMatches() { return this._waitUntil(this.assertMatches, arguments); }, /** * Internal function that waits for an assertion to become true. * @param {Function} assertionMethod * Reference to a TestRunner assertion method like test.assert, * test.assertEqual, ... * @param {Array} args * List of arguments to give to the previous assertion method. * All functions in this list are going to be called to retrieve current * assertion values. */ _waitUntil: function waitUntil(assertionMethod, args) { let count = 0; let maxCount = this.DEFAULT_PAUSE_TIMEOUT / this.PAUSE_DELAY; let callback = null; let finished = false; let test = this; function loop() { // Build a mockup object to fake TestRunner API and intercept calls to // pass and fail methods, in order to retrieve nice error messages // and assertion result let mock = { pass: function (msg) { test.pass(msg); if (callback) callback(); finished = true; }, fail: function (msg) { if (++count > maxCount) { test.fail(msg); if (callback) callback(); finished = true; return; } timer.setTimeout(loop, test.PAUSE_DELAY); } }; // Automatically call args closures in order to build arguments for // assertion function let appliedArgs = []; for (let i = 0, l = args.length; i < l; i++) { let a = args[i]; if (typeof a == "function") { try { a = a(); } catch(e) { mock.fail("Exception when calling asynchronous assertion: " + e); } } appliedArgs.push(a); } // Finally call assertion function with current assertion values assertionMethod.apply(mock, appliedArgs); } loop(); // Return an object with `then` method, to offer a way to execute // some code when the assertion passed or failed return { then: function (c) { callback = c; // In case of immediate positive result, we need to execute callback // immediately here: if (finished) callback(); } }; }, waitUntilDone: function waitUntilDone(ms) { if (ms === undefined) ms = this.DEFAULT_PAUSE_TIMEOUT; var self = this; function tiredOfWaiting() { self._logTestFailed("timed out"); self.failed++; self.test.failed++; self.done(); } this.waitTimeout = timer.setTimeout(tiredOfWaiting, ms); }, startMany: function startMany(options) { function runNextTest(self) { var test = options.tests.shift(); if (test) self.start({test: test, onDone: runNextTest}); else options.onDone(self); } runNextTest(this); }, start: function start(options) { this.test = options.test; this.test.passed = 0; this.test.failed = 0; this.test.errors = {}; this.isDone = false; this.onDone = options.onDone; this.waitTimeout = null; this.testFailureLogged = false; try { this.test.testFunction(this); } catch (e) { this.exception(e); } if (this.waitTimeout === null) this.done(); } };
require.config({ paths: { angular: '../../bower_components/angular/angular', domReady: '../../bower_components/requirejs-domready/domReady', angularRoute: '../../bower_components/angular-route/angular-route', uiBootstrap: '../../bower_components/angular-bootstrap/ui-bootstrap-tpls', }, shim: { 'angular' : { exports : 'angular' }, 'angularRoute': ['angular'], 'uiBootstrap': ['angular'] } }); window.name = "NG_DEFER_BOOTSTRAP!"; require( [ 'angular', 'domReady', 'app', 'routes' ], function(ng, domReady, app) { domReady(function (document) { ng.resumeBootstrap([app['name']]); }); });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), User = mongoose.model('User'), async = require('async'), config = require('meanio').loadConfig(), crypto = require('crypto'), nodemailer = require('nodemailer'), templates = require('../template'), _ = require('lodash'), jwt = require('jsonwebtoken'); //https://npmjs.org/package/node-jsonwebtoken /** * Send reset password email */ function sendMail(mailOptions) { var transport = nodemailer.createTransport(config.mailer); transport.sendMail(mailOptions, function(err, response) { if (err) return err; return response; }); } module.exports = function(MeanUser) { return { /** * Auth callback */ authCallback: function(req, res) { var payload = req.user; var escaped = JSON.stringify(payload); escaped = encodeURI(escaped); // We are sending the payload inside the token var token = jwt.sign(escaped, config.secret, { expiresInMinutes: 60*5 }); res.cookie('token', token); var destination = config.strategies.landingPage; if(!req.cookies.redirect) res.cookie('redirect', destination); res.redirect(destination); }, /** * Show login form */ signin: function(req, res) { if (req.isAuthenticated()) { return res.redirect('/'); } res.redirect('/login'); }, /** * Logout */ signout: function(req, res) { MeanUser.events.publish({ action: 'logged_out', user: { name: req.user.name } }); req.logout(); res.redirect('/'); }, /** * Session */ session: function(req, res) { res.redirect('/'); }, /** * Create user */ create: function(req, res, next) { var user = new User(req.body); user.provider = 'local'; // because we set our user.provider to local our models/user.js validation will always be true req.assert('hats', 'Select at least 1 Hat').notEmpty(); req.assert('name', 'You must enter a name').notEmpty(); req.assert('email', 'You must enter a valid email address').isEmail(); req.assert('password', 'Password must be between 8-20 characters long').len(8, 20); req.assert('username', 'Username cannot be more than 20 characters').len(1, 20); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); var errors = req.validationErrors(); if (errors) { return res.status(400).send(errors); } // Hard coded for now. Will address this with the user permissions system in v0.3.5 user.roles = ['authenticated']; user.save(function(err) { if (err) { switch (err.code) { case 11000: case 11001: res.status(400).json([{ msg: 'Username already taken', param: 'username' }]); break; default: var modelErrors = []; if (err.errors) { for (var x in err.errors) { modelErrors.push({ param: x, msg: err.errors[x].message, value: err.errors[x].value }); } res.status(400).json(modelErrors); } } return res.status(400); } var payload = user; payload.redirect = req.body.redirect; var escaped = JSON.stringify(payload); escaped = encodeURI(escaped); req.logIn(user, function(err) { if (err) { return next(err); } MeanUser.events.publish({ action: 'created', user: { name: req.user.name, username: user.username, email: user.email } }); // We are sending the payload inside the token var token = jwt.sign(escaped, config.secret, { expiresInMinutes: 60*5 }); res.json({ token: token, redirect: config.strategies.landingPage }); }); res.status(200); }); }, /** * Send User */ me: function(req, res) { if (!req.user || !req.user.hasOwnProperty('_id')) return res.send(null); User.findOne({ _id: req.user._id }).exec(function(err, user) { if (err || !user) return res.send(null); var dbUser = user.toJSON(); var id = req.user._id; delete dbUser._id; delete req.user._id; var eq = _.isEqual(dbUser, req.user); if (eq) { req.user._id = id; return res.json(req.user); } var payload = user; var escaped = JSON.stringify(payload); escaped = encodeURI(escaped); var token = jwt.sign(escaped, config.secret, { expiresInMinutes: 60*5 }); res.json({ token: token }); }); }, /** * Find user by id */ user: function(req, res, next, id) { User.findOne({ _id: id }).exec(function(err, user) { if (err) return next(err); if (!user) return next(new Error('Failed to load User ' + id)); req.profile = user; next(); }); }, /** * Resets the password */ resetpassword: function(req, res, next) { User.findOne({ resetPasswordToken: req.params.token, resetPasswordExpires: { $gt: Date.now() } }, function(err, user) { if (err) { return res.status(400).json({ msg: err }); } if (!user) { return res.status(400).json({ msg: 'Token invalid or expired' }); } req.assert('password', 'Password must be between 8-20 characters long').len(8, 20); req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password); var errors = req.validationErrors(); if (errors) { return res.status(400).send(errors); } user.password = req.body.password; user.resetPasswordToken = undefined; user.resetPasswordExpires = undefined; user.save(function(err) { MeanUser.events.publish({ action: 'reset_password', user: { name: user.name } }); req.logIn(user, function(err) { if (err) return next(err); return res.send({ user: user }); }); }); }); }, /** * Callback for forgot password link */ forgotpassword: function(req, res, next) { async.waterfall([ function(done) { crypto.randomBytes(20, function(err, buf) { var token = buf.toString('hex'); done(err, token); }); }, function(token, done) { User.findOne({ $or: [{ email: req.body.text }, { username: req.body.text }] }, function(err, user) { if (err || !user) return done(true); done(err, user, token); }); }, function(user, token, done) { user.resetPasswordToken = token; user.resetPasswordExpires = Date.now() + 3600000; // 1 hour user.save(function(err) { done(err, token, user); }); }, function(token, user, done) { var mailOptions = { to: user.email, from: config.emailFrom }; mailOptions = templates.forgot_password_email(user, req, token, mailOptions); sendMail(mailOptions); done(null, user); } ], function(err, user) { var response = { message: 'Mail successfully sent', status: 'success' }; if (err) { response.message = 'User does not exist'; response.status = 'danger'; } MeanUser.events.publish({ action: 'forgot_password', user: { name: req.body.text } }); res.json(response); }); } }; }
import React from 'react'; import ReplSuggestions from './components/ReplSuggestions'; import ReplPreferences from './components/ReplPreferences'; import Repl from './components/Repl'; import ReplConstants from './constants/ReplConstants'; import ReplFonts from './common/ReplFonts'; import _ from 'lodash'; import remote from 'remote'; import webFrame from 'web-frame'; (() => { // Temporary fix for node bug : https://github.com/nodejs/node/issues/3158 let ownPropertyNames = Object.getOwnPropertyNames.bind(Object); Object.getOwnPropertyNames = (o) => { let result = ownPropertyNames(o); let keys = Object.keys(o); let difference = _.difference(keys, result); return difference.length ? result.concat(difference) : result; }; })(); // preferences & user data path (() => { let preferences = JSON.parse(localStorage.getItem('preferences') || '{}'); let defaults = { "mode": "Magic", "theme": "Dark Theme", "timeout": ReplConstants.EXEC_TIMEOUT, "babel": false, "suggestionDelay": 250, "toggleShiftEnter": false, "asyncWrap": true, "autoCompleteOnEnter": false, "toggleAutomaticAutoComplete": false, "lang": "js", "fontFamily": "Droid Sans Mono", "pageZoomFactor": 1, "watermark": true, "transpile": false, "loadScript": null, "promptOnClose": false, "autoCloseSymbol": false }; _.each(_.keys(defaults), (key) => { if(!(key in preferences)) { preferences[key] = defaults[key]; } }); global.Mancy = { preferences: preferences }; localStorage.setItem('preferences', JSON.stringify(preferences)); global.Mancy.userData = remote.require('app').getPath('userData'); global.Mancy.session = { lang: preferences.lang, mode: preferences.mode }; })(); function onLoadSettings() { // font family ReplFonts.setFontFamily(global.Mancy.preferences.fontFamily); // page zoom factor webFrame.setZoomFactor(global.Mancy.preferences.pageZoomFactor); // water mark if(global.Mancy.preferences.watermark) { document.body.dataset.watermarkLogo = ReplConstants.REPL_WATERMARK_LOGO; document.body.dataset.watermarkMsg = ReplConstants.REPL_WATERMARK_MSG; } } // react entry point (() => { onLoadSettings(); const repl = document.getElementById('node-repl-plus'); React.render(<Repl />, repl); const suggestion = document.getElementById('node-repl-prompt-suggestions'); React.render(<ReplSuggestions />, suggestion); const preferences = document.getElementById('node-repl-preferences'); React.render(<ReplPreferences />, preferences); })();
import PropTypes from 'prop-types'; export default { directionsService: PropTypes.object, directionsDisplay: PropTypes.object, google: PropTypes.object, map: PropTypes.object, };
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '9a77fe4ce91faf96b4359ba5f44354ce', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // }, /*************************************************************************** * * * Uncomment the following lines to set up a Redis session store that can * * be shared across multiple Sails.js servers. * * * * Requires connect-redis (https://www.npmjs.com/package/connect-redis) * * * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * * * https://github.com/visionmedia/connect-redis * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password>, // prefix: 'sess:', /*************************************************************************** * * * Uncomment the following lines to set up a MongoDB session store that can * * be shared across multiple Sails.js servers. * * * * Requires connect-mongo (https://www.npmjs.com/package/connect-mongo) * * Use version 0.8.2 with Node version <= 0.12 * * Use the latest version with Node >= 4.0 * * * ***************************************************************************/ // adapter: 'mongo', // url: 'mongodb://user:password@localhost:27017/dbname', // user, password and port optional /*************************************************************************** * * * Optional Values: * * * * See https://github.com/kcbanner/connect-mongo for more * * information about connect-mongo options. * * * * See http://bit.ly/mongooptions for more information about options * * available in `mongoOptions` * * * ***************************************************************************/ // collection: 'sessions', // stringify: true, // mongoOptions: { // server: { // ssl: true // } // } };
<<<<<<< HEAD function drawDataChart() { $.ajax({ url: '../v1.0/id/1/ch/1/dp', type: 'GET', async: true, dataType: 'json', success: function(data, textStatus) { var dataJSON = JSON.parse(data); var dataArray = new Array(); for (var i=0; i<dataJSON.length; i++) { dataArray[i] = parseFloat(dataJSON[i].val); } $('#container').highcharts('StockChart', { rangeSelector : { selected : 1, inputEnabled: $('#container').width() > 480 }, title : { text : 'iot-pro test page' }, series : [{ name : 'AAPL', data : dataArray, tooltip: { valueDecimals: 2 } }] }); }, error: function(data, textStatus) { console.log("Net Error"); } }); ======= function drawDataChart() { $.ajax({ url: '../v1.0/id/1/ch/1/dp', type: 'GET', async: true, dataType: 'json', success: function(data, textStatus) { var dataJSON = JSON.parse(data); var dataArray = new Array(); for (var i=0; i<dataJSON.length; i++) { dataArray[i] = parseFloat(dataJSON[i].val); } $('#container').highcharts('StockChart', { rangeSelector : { selected : 1, inputEnabled: $('#container').width() > 480 }, title : { text : 'iot-pro test page' }, series : [{ name : 'AAPL', data : dataArray, tooltip: { valueDecimals: 2 } }] }); }, error: function(data, textStatus) { console.log("Net Error"); } }); >>>>>>> 0fdc7460992ccc9607177bb2a90a839ebda9db47 };
// Copyright (c) 2012 Ecma International. All rights reserved. // Ecma International makes this code available under the terms and conditions set // forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the // "Use Terms"). Any redistribution of this code must retain the above // copyright and this notice and otherwise comply with the Use Terms. /*--- es5id: 15.2.3.13-2-26 description: > Object.isExtensible returns false if O is not extensible and has a prototype that is extensible includes: [runTestCase.js] ---*/ function testcase() { var proto = {}; var ConstructFun = function () { }; ConstructFun.prototype = proto; var obj = new ConstructFun(); Object.preventExtensions(obj); return !Object.isExtensible(obj); } runTestCase(testcase);
// NOTE object below must be a valid JSON window.BookShelf = $.extend(true, window.BookShelf, { "config": { "layoutSet": "navbar", "navigation": [ { "title": "To Read", "onExecute": "#LaterList", "icon": "bsicon bsicon-toread" }, { "title": "Finished", "onExecute": "#FinishedList", "icon": "bsicon bsicon-finished" }, { "title": "Settings", "onExecute": "#Settings", "icon": "bsicon bsicon-settings" } ], "commandMapping": { "ios-header-toolbar": { "defaults": { "showIcon": false, "location": "after" }, "commands": [ { "id": "filterBooks" }, { "id": "applyFilter" }, { "id": "addBook" }, { "id": "saveBook" }, { "id": "editBook" }, { "id": "saveNotes" }, { "id": "addTag" }, { "id": "saveTag" } ] } } } });
'use strict'; var gulp = require('gulp'); var del = require('del'); gulp.task('reset', ['clean'], function (done) { del([global.path.src + '/lib/jspm', 'node_modules', '.sass-cache'], done); });
import React from 'react'; import ReactDOM from 'react-dom'; import MonkeyUi from '../../lib/monkeyui.js'; // Upload, Icon, Modal const {Upload,Icon,Modal,Button,PreviewPicture}=MonkeyUi; /* 资助图片列表 诊疗图片列表 [ { name:'typeName', zlList:[] } ] */ class PicturesWall extends React.Component { constructor(props){ super(props); this.state={ visible:false } } componentWillReceiveProps(nextProps){ } componentWillMount(){ } componentWillUnmount() { } componentDidMount() { } onPreview(file,type){ this.setState({visible:true}) console.log('yulan') console.log(type) } onRemove(e,file){ console.log('remove'); console.log(e) console.log(file) } del(e,data){ e.preventDefault(); e.stopPropagation(); console.log('del') console.log(e) console.log(data) } render() { const props = { action: '/upload.do', listType: 'picture', defaultFileList: [{ uid: -1, name: 'xxx.png', type:'资助申请表', status: 'done', fileId:'001', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', }, { uid: -2, name: 'yyy.png', status: 'done', type:'资助申请表', fileId:'002', url: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', thumbUrl: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', },{ uid: -3, name: 'xxx.png', type:'资助申请表', status: 'done', fileId:'001', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', }, { uid: -4, name: 'yyy.png', status: 'done', type:'资助申请表', fileId:'002', url: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', thumbUrl: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', }, { uid: -5, name: 'xxx.png', type:'资助申请表', status: 'done', fileId:'001', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', }, { uid: -6, name: 'yyy.png', status: 'done', type:'资助申请表', fileId:'002', url: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', thumbUrl: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', },{ uid: -7, name: 'xxx.png', type:'资助申请表', status: 'done', fileId:'001', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', }, { uid: -8, name: 'yyy.png', status: 'done', type:'资助申请表', fileId:'002', url: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', thumbUrl: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', },{ uid: -9, name: 'xxx.png', type:'资助申请表', status: 'done', fileId:'001', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', thumbUrl: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png', }, { uid: -10, name: 'yyy.png', status: 'done', type:'资助申请表', fileId:'002', url: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', thumbUrl: 'http://pic17.nipic.com/20111122/6759425_152002413138_2.jpg', }], }; let _props={ fileList:props.defaultFileList, visible:this.state.visible, del:this.del, delFlag:'block', title:"诊疗图片列表/住院报告单" } return ( <div> <Upload {...props} className="upload-list-inline" onPreview={(file)=>this.onPreview(file,"资助申请表")} onRemove={(e,file)=>this.onRemove(e,file)} > <Button> <Icon type="upload" /> upload </Button> </Upload> <PreviewPicture {..._props}/> </div> ); } } export default PicturesWall;
fs = require('fs'); console.log('module.exports=' + JSON.stringify( fs.readFileSync(process.argv[2]).toString()));
/* ========================================================= *  基于bootstrap-alert的提示框组件 * huweixuan * ========================================================= */ define(function(require) { var $ = require('jquery'); require('bootstrap'); var Alert = function() { //this.init(); }; Alert.prototype = { constructor: Alert, init: function() { var self = this; $('.app').append(this.getHTML()); this.$element = $('#_alert'); this.$element.alert(); this.$element.bind('closed', function () { self.$element.removeClass('alert-success').removeClass('alert-error'); if(typeof self._callback === 'function') { self._callback.apply(); } }); $('#_alert_close').bind('click', function () { self.$element.alert('close'); }); }, _show: function(msg) { $('#_alert_message').html(msg); }, error: function(msg, callback) { this.init(); this._callback = callback; this.$element.addClass('alert-error'); this._show(msg); }, success: function(msg, callback) { this.init(); this._callback = callback; this.$element.addClass('alert-success'); this._show(msg); }, warn: function(msg) { this.init(); this._show(msg); }, getHTML: function() { var html = '<div class="alert alert-block app-alert fade in" id="_alert">' + '<button type="button" class="close" data-dismiss="alert">×</button>' + '<p id="_alert_message" class="alert-message"></p>' + '<p><button class="btn" id="_alert_close">确定</button></p>' + '</div>'; return html; } }; return new Alert(); });
import React from "react"; import { render } from "react-dom"; import { Provider } from "react-redux"; import { Router, browserHistory } from "react-router"; import routes from "./routes"; import configureStore from "./store/configureStore"; import { syncHistoryWithStore } from 'react-router-redux'; import "./public/main.css"; import "../../css/react-select/react-select.min.css"; const store = configureStore(); // Create an enhanced history that syncs navigation events with the store const history = syncHistoryWithStore(browserHistory, store) render(( <Provider store={store}> <Router history={history}> {routes} </Router> </Provider> ), document.getElementById("app"));
var HTMLService = (function () { var productsList; var totalPrice; function updateCart(products) { updateList(products); updateTotalPrice(products); } function updateTotalPrice(products) { calculateTotalPrice(products); var a = document.getElementById('totalPrice'); a.innerHTML = ''; var price = buildTotalPrice(); a.appendChild(price); } function buildTotalPrice() { var div = buildListItem(); var price = buildPrice(totalPrice); var total = buildTotalLabel(); div.appendChild(price); div.appendChild(total); return div; } function buildTotalLabel() { var div = document.createElement('div'); div.innerHTML = 'Total'; return div; } function calculateTotalPrice(products) { totalPrice = 0; products.forEach(sum); } function sum(product) { totalPrice += product.price; } function updateList(products) { productsList = document.getElementById('productsList'); productsList.innerHTML = ''; if(products.length === 0) { appendEmptyLabel(); } products.forEach(appendProduct); } function appendEmptyLabel() { var element = buildEmptyLabel(); productsList.appendChild(element); } function buildEmptyLabel() { var a = document.createElement('a'); a.classList.add('list-group-item'); a.innerHTML = 'Your cart is empty.'; return a; } function appendProduct(product) { var element = buildProduct(product); productsList.appendChild(element); } function buildProduct(product) { var item = buildListItem(); var price = buildPrice(product.price); var name = buildProductName(product); item.appendChild(price); item.appendChild(name); return item; } function buildProductName(product) { var div = document.createElement('div'); div.innerHTML = product.name; return div; } function buildPrice(price) { var span = document.createElement('span'); span.classList.add('badge'); span.classList.add('badge-price'); span.innerHTML = formatPrice(price); return span; } function buildListItem() { var a = document.createElement('a'); a.classList.add('list-group-item'); return a; } function formatPrice(price) { if (hasDecimalDigit(price)) { var length = getDigitCount(price); return price.toPrecision(2 + getDigitCount(price)); } else { return price + '.00'; } } function getDigitCount(price) { price = price.toString(); return price.substring(0, price.indexOf('.')).length; } function hasDecimalDigit(price) { return (price - Math.floor(price)) != 0; } return { updateCart: updateCart } })();
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <g><path d="M10 10v5h2V4h2v11h2V4h2V2h-8C7.79 2 6 3.79 6 6s1.79 4 4 4zm-2 7v-3l-4 4 4 4v-3h12v-2H8z" /></g> , 'FormatTextdirectionRToL');
import React from 'react'; import $ from 'jquery'; import fecha from 'fecha'; import { Link } from 'react-router-component'; import i18next from 'i18next'; import Constants from './../../constants'; import EpisodeCard from './../episodeCard'; module.exports = React.createClass({ propTypes: { slug: React.PropTypes.string.isRequired, nowPlayingSlug: React.PropTypes.string.isRequired, }, getInitialState: function getInitialState() { return { name: '', episodes: [], }; }, componentDidMount: function componentDidMount() { document.title = `${i18next.t('artist')} | ${i18next.t('freqAsia')}`; $.getJSON(Constants.API_URL + 'artists/' + this.props.slug) .done((data) => { data.episodes.forEach((episode) => { episode.date = fecha.format(new Date(episode.start_time), 'dddd / MMMM D YYYY'); }); this.setState({ name: data.name, episodes: data.episodes, }); document.title = `${data.name} | ${i18next.t('freqAsia')}`; }); }, renderEpisodeCards: function renderEpisodeCards() { return this.state.episodes.map((episode) => { return <EpisodeCard key={ episode.slug } nowPlayingSlug={ this.props.nowPlayingSlug } { ...episode } />; }); }, render: function render() { return ( <div className="o-content-block"> <section className="c-content"> <div className="row"> <div className="col"> <h1><Link className="u-no-border" href="/wiki">{ i18next.t('wiki') }</Link> &rsaquo; <Link className="u-no-border" href="/wiki/artists">{ i18next.t('artists') }</Link> &rsaquo; { this.state.name }</h1> <h2 id="location-data"></h2> { this.renderEpisodeCards() } </div> </div> </section> </div> ); }, });
import React from "react" import Link from "gatsby-link" import { rhythm } from "../utils/typography" const MainLayout = ({ children, location }) => ( <div css={{ maxWidth: 600, margin: `0 auto`, padding: `${rhythm(1)} ${rhythm(3 / 4)}`, }} > {location.pathname !== `/` && ( <h4 css={{ margin: 0 }}> <Link to={`/`}>Home</Link> </h4> )} {children()} </div> ) export default MainLayout
import { sanitizeAuthor, sanitizeCategories, sanitizeId, sanitizeImages, sanitizeIsOfficial, sanitizeKeywords, sanitizeLogo, sanitizeMinimumVersion, sanitizePermissions, sanitizeSize, sanitizeSource, sanitizeTitle, sanitizeUrls, sanitizeVersion } from './config-sanitizers' export class PluginConfiguration { constructor ({ id, author, categories, keywords, description, logo, images, homepage, isOfficial, minimumVersion, permissions, size, source, title, urls, version }) { this.id = id this.author = author this.categories = categories this.keywords = keywords this.description = description this.logo = logo this.images = images this.homepage = homepage this.isOfficial = isOfficial this.minimumVersion = minimumVersion this.permissions = permissions this.size = size this.source = source this.title = title this.urls = urls this.version = version } static async sanitize (config, pluginPath = null) { return new PluginConfiguration({ id: sanitizeId(config.name), author: sanitizeAuthor(config), categories: sanitizeCategories(config), keywords: sanitizeKeywords(config.keywords), description: config.description, logo: sanitizeLogo(config), images: sanitizeImages(config), homepage: config.homepage, isOfficial: sanitizeIsOfficial(config.name), minimumVersion: sanitizeMinimumVersion(config), permissions: sanitizePermissions(config), size: await sanitizeSize(config, pluginPath) || 0, source: sanitizeSource(config), title: sanitizeTitle(config), urls: sanitizeUrls(config), version: sanitizeVersion(config.version) }) } validate () { if (!this.id) { throw new Error('Plugin ID not found') } else if (!/^[@/a-z-0-9-]+$/.test(this.id)) { throw new Error('Invalid Plugin ID') } } }
aethernauts.service('world', ['renderer', function(renderer) { var service = {}; service.data = null; return service; }]);
import test from 'ava' import { isNumber, isObject, isString, isUrl } from './matchers' import queryWithFragments from './fixtures/queryWithFragments' import mock from '../src/index' test('it can mock a query with a nested fragment', t => { const { avatar } = mock(queryWithFragments) t.true(isObject(avatar)) t.true(isNumber(avatar.id)) t.true(isUrl(avatar.url)) }) test('it can mock a query with a nested list fragment', t => { const result = mock(queryWithFragments) t.true(Array.isArray(result.friends)) const friend = result.friends[0] t.true(isNumber(friend.id)) t.true(isString(friend.name)) }) test('it can mock a fragment nested within a fragment', t => { const result = mock(queryWithFragments) const { avatar } = result.friends[0] t.true(isNumber(avatar.id)) t.true(isUrl(avatar.url)) })
import isAndroid from './isAndroid' const mockUserAgent = (userAgent) => { Object.defineProperty(navigator, 'userAgent', { value: userAgent, writable: true }) } const mockUndefinedNavigator = () => { Object.defineProperty(global, 'navigator', { value: undefined, writable: true }) } describe('isAndroid', () => { test('returns false when navigator.userAgent does not contain android string', () => { mockUserAgent('safari browser') const result = isAndroid() expect(result).toEqual(false) }) test('returns true when navigator.userAgent contains android string', () => { mockUserAgent('android browser') const result = isAndroid() expect(result).toEqual(true) }) test('returns false when navigator is undefined', () => { mockUndefinedNavigator() const result = isAndroid() expect(result).toEqual(false) }) })
/* * Copyright (c) 2016-present, Parse, LLC * All rights reserved. * * This source code is licensed under the license found in the LICENSE file in * the root directory of this source tree. */ import React from 'react'; import Field from 'components/Field/Field.react'; import Fieldset from 'components/Fieldset/Fieldset.react'; import Label from 'components/Label/Label.react'; import MoneyInput from 'components/MoneyInput/MoneyInput.react'; class Wrapper extends React.Component { render() { return <div>{this.props.children}</div>; } } export const component = MoneyInput; export const demos = [ { render: () => ( <Wrapper> <Fieldset> <Field label={<Label text='Money input' />} input={<MoneyInput value={100.2} onChange={() => {}} />} /> <Field label={<Label text='Disabled' />} input={<MoneyInput value={9.99} enabled={false} onChange={() => {}} />} /> </Fieldset> </Wrapper> ) } ];
import React from 'react' import PropTypes from 'prop-types' import { FormattedMessage } from 'react-intl' import { Flex } from 'rebass/styled-components' import { Text } from 'components/UI' import { CryptoSelector, CryptoValue } from 'containers/UI' import messages from './messages' const ChannelBalance = ({ channelBalance, ...rest }) => { return ( <Flex alignItems="center" as="section" {...rest}> <Text fontWeight="normal" mr={2}> <FormattedMessage {...messages.total_capacity} /> </Text> <CryptoValue value={channelBalance} /> <CryptoSelector ml={2} /> </Flex> ) } ChannelBalance.propTypes = { channelBalance: PropTypes.string.isRequired, } export default ChannelBalance
<%- banner %> import * as axMocks from 'laxar-mocks'; describe( 'The <%= name %>', () => { beforeEach( axMocks.setupForWidget() ); beforeEach( () => { axMocks.widget.configure( {} ); } ); beforeEach( axMocks.widget.load ); afterEach( axMocks.tearDown ); /////////////////////////////////////////////////////////////////////////////////////////////////////////// it( 'still needs some tests', () => { // ... first test here } ); } );
var searchData= [ ['callaction',['callAction',['../index_8php.html#a6e8525da6dad002542958c13132118e4',1,'index.php']]], ['checkusercanedittasks',['checkUserCanEditTasks',['../tasks_8php.html#a17b2ff0082f478470dc8ca4d28b6568f',1,'tasks.php']]], ['connect',['connect',['../classDB.html#a031c0b13b6803f486c377a4c98774f4d',1,'DB\connect()'],['../classDB__PostgreSQL.html#a35c72d161281997ab74e7d2db24e3b4e',1,'DB_PostgreSQL\connect()']]], ['count',['count',['../classDBResult__Postgresql.html#a0e38325eb55607dea2d44147e983111c',1,'DBResult_Postgresql\count()'],['../classDBRow__SQL.html#a04f36c0947b2b0f9f27bcbb2745dc04b',1,'DBRow_SQL\count()']]], ['create',['create',['../classDB.html#aebc4d944d05977ab3fc55d910bec39a4',1,'DB']]], ['createpasswordhash',['createPasswordHash',['../password_8php.html#a26fb1747283617276edce7e87b038e96',1,'password.php']]], ['current',['current',['../classDBResult__Postgresql.html#abba9dd676c95a2719e80e5610d76e3f6',1,'DBResult_Postgresql']]] ];
// @flow export function longString(str: string, nb: number) { if (str.length > nb) { return str.slice(0, nb) + '...'; } else { return str; } }
const fs = require('fs') const evalSourceMapMiddleware = require('react-dev-utils/evalSourceMapMiddleware') const noopServiceWorkerMiddleware = require('react-dev-utils/noopServiceWorkerMiddleware') const ignoredFiles = require('react-dev-utils/ignoredFiles') const redirectServedPath = require('react-dev-utils/redirectServedPathMiddleware') const paths = require('./paths') const getHttpsConfig = require('./getHttpsConfig') const host = process.env.HOST || '0.0.0.0' const sockHost = process.env.WDS_SOCKET_HOST const sockPath = process.env.WDS_SOCKET_PATH // default: '/ws' const sockPort = process.env.WDS_SOCKET_PORT module.exports = function (proxy, allowedHost) { const disableFirewall = !proxy || process.env.DANGEROUSLY_DISABLE_HOST_CHECK === 'true' return { // WebpackDevServer 2.4.3 introduced a security fix that prevents remote // websites from potentially accessing local content through DNS rebinding: // https://github.com/webpack/webpack-dev-server/issues/887 // https://medium.com/webpack/webpack-dev-server-middleware-security-issues-1489d950874a // However, it made several existing use cases such as development in cloud // environment or subdomains in development significantly more complicated: // https://github.com/facebook/create-react-app/issues/2271 // https://github.com/facebook/create-react-app/issues/2233 // While we're investigating better solutions, for now we will take a // compromise. Since our WDS configuration only serves files in the `public` // folder we won't consider accessing them a vulnerability. However, if you // use the `proxy` feature, it gets more dangerous because it can expose // remote code execution vulnerabilities in backends like Django and Rails. // So we will disable the host check normally, but enable it if you have // specified the `proxy` setting. Finally, we let you override it if you // really know what you're doing with a special environment variable. // Note: ["localhost", ".localhost"] will support subdomains - but we might // want to allow setting the allowedHosts manually for more complex setups allowedHosts: disableFirewall ? 'all' : [allowedHost], headers: { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': '*', 'Access-Control-Allow-Headers': '*', }, // Enable gzip compression of generated files. compress: true, static: { // By default WebpackDevServer serves physical files from current directory // in addition to all the virtual build products that it serves from memory. // This is confusing because those files won’t automatically be available in // production build folder unless we copy them. However, copying the whole // project directory is dangerous because we may expose sensitive files. // Instead, we establish a convention that only files in `public` directory // get served. Our build script will copy `public` into the `build` folder. // In `index.html`, you can get URL of `public` folder with %PUBLIC_URL%: // <link rel="icon" href="%PUBLIC_URL%/favicon.ico"> // In JavaScript code, you can access it with `process.env.PUBLIC_URL`. // Note that we only recommend to use `public` folder as an escape hatch // for files like `favicon.ico`, `manifest.json`, and libraries that are // for some reason broken when imported through webpack. If you just want to // use an image, put it in `src` and `import` it from JavaScript instead. directory: paths.appPublic, publicPath: [paths.publicUrlOrPath], // By default files from `contentBase` will not trigger a page reload. watch: { // Reportedly, this avoids CPU overload on some systems. // https://github.com/facebook/create-react-app/issues/293 // src/node_modules is not ignored to support absolute imports // https://github.com/facebook/create-react-app/issues/1065 ignored: ignoredFiles(paths.appSrc), }, }, client: { webSocketURL: { // Enable custom sockjs pathname for websocket connection to hot reloading server. // Enable custom sockjs hostname, pathname and port for websocket connection // to hot reloading server. hostname: sockHost, pathname: sockPath, port: sockPort, }, overlay: { errors: true, warnings: false, }, }, devMiddleware: { // It is important to tell WebpackDevServer to use the same "publicPath" path as // we specified in the webpack config. When homepage is '.', default to serving // from the root. // remove last slash so user can land on `/test` instead of `/test/` publicPath: paths.publicUrlOrPath.slice(0, -1), }, https: getHttpsConfig(), host, historyApiFallback: { // Paths with dots should still use the history fallback. // See https://github.com/facebook/create-react-app/issues/387. disableDotRule: true, index: paths.publicUrlOrPath, }, // `proxy` is run between `before` and `after` `webpack-dev-server` hooks proxy, onBeforeSetupMiddleware(devServer) { // Keep `evalSourceMapMiddleware` // middlewares before `redirectServedPath` otherwise will not have any effect // This lets us fetch source contents from webpack for the error overlay devServer.app.use(evalSourceMapMiddleware(devServer)) if (fs.existsSync(paths.proxySetup)) { // This registers user provided middleware for proxy reasons require(paths.proxySetup)(devServer.app) } }, onAfterSetupMiddleware(devServer) { // Redirect to `PUBLIC_URL` or `homepage` from `package.json` if url not match devServer.app.use(redirectServedPath(paths.publicUrlOrPath)) // This service worker file is effectively a 'no-op' that will reset any // previous service worker registered for the same host:port combination. // We do this in development to avoid hitting the production cache if // it used the same host and port. // https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432 devServer.app.use(noopServiceWorkerMiddleware(paths.publicUrlOrPath)) }, } }