code
stringlengths
2
1.05M
/** * Very Important Transform */ function veryImportantTransform(foo = 'bar') { return "42"; }
import mod1999 from './mod1999'; var value=mod1999+1; export default value;
'use strict'; var _ = require('lodash'); var METHODS = require('./methods'); var Engine = (function () { var ENGINE = 'with(this) { #{BLOCK} }'; function Engine(template, data) { if (!_.isArray(data)) { duckType(data); } this.template = template; this.data = data; } function duckType(dataObj) { dataObj.forEach = function (iteratee) { iteratee(dataObj); }; } _.merge(Engine.prototype, METHODS); Engine.run = function (template, objects, callback) { var engine = new Engine(template, objects); engine.run(callback); }; Engine.prototype.reignite = function (template, options) { return new Engine(template, options.object); }; Engine.prototype.run = function (callback) { var engine = this; engine.data.forEach(function (datum) { engine.datum = datum; engine.resultObject = {}; engine.ignite(engine.template); engine.addToResults(engine.resultObject); }); callback(engine.result); }; Engine.prototype.ignite = function (template, options) { options = options || {}; var _this = options.object || this; var engine = ENGINE.replace('#{BLOCK}', template); (new Function(engine)).call(_this); // jshint ignore:line }; return Engine; })(); module.exports = Engine;
'use strict'; const getResources = require('../../src/aws/triggers/s3'); describe('S3 trigger getResources', function() { const funcName = 'AppHelloIndex'; context('with a basic trigger config', function() { const trigger = { event: 's3:ObjectCreated:Put', bucket: 'image-uploads' }; it('returns an S3 bucket resource and a permission resource', function() { const resources = getResources(trigger, funcName); expect(resources).to.have.property('RiseimageuploadsBucket'); const bucketResource = resources['RiseimageuploadsBucket']; expect(bucketResource).to.have.property('Type', 'AWS::S3::Bucket'); expect(bucketResource).to.have.property('Properties'); const bucketProps = bucketResource.Properties; expect(bucketProps).to.have.property('BucketName', 'image-uploads'); expect(bucketProps).to.have.deep.property('NotificationConfiguration.LambdaConfigurations'); expect(bucketProps.NotificationConfiguration.LambdaConfigurations).to.have.lengthOf(1); const lambdaCfg = bucketProps.NotificationConfiguration.LambdaConfigurations[0]; expect(lambdaCfg).to.deep.equal({ Event: 's3:ObjectCreated:Put', Function: { 'Fn::GetAtt': [ funcName, 'Arn' ] } }); const permissionResourceName = `${funcName}imageuploadsS3TriggerLambdaPermission`; expect(resources).to.have.property(permissionResourceName); const permissionResource = resources[`${funcName}imageuploadsS3TriggerLambdaPermission`]; expect(permissionResource).to.have.property('Type', 'AWS::Lambda::Permission'); expect(permissionResource).to.have.property('Properties'); const permissionProps = permissionResource.Properties; expect(permissionProps).to.deep.equal({ FunctionName: { 'Fn::GetAtt': [ funcName, 'Arn' ] }, Action: 'lambda:InvokeFunction', Principal: 's3.amazonaws.com', SourceArn: 'arn:aws:s3:::image-uploads' }); }); }); context('when bucket is not specified', function() { const trigger = { event: 's3:ObjectCreated:Put' }; it('throws an error', function() { expect(function() { getResources(trigger, funcName); }).to.throw(Error, 'bucket is required for S3 triggers'); }); }); context('when event is not specified', function() { const trigger = { bucket: 'image-uploads' }; it('defaults to the s3:ObjectCreated:* event', function() { const resources = getResources(trigger, funcName); expect(resources['RiseimageuploadsBucket']).to.have.deep.property( 'Properties.NotificationConfiguration.LambdaConfigurations[0].Event', 's3:ObjectCreated:*' ); }); }); context('with prefix specified', function() { const trigger = { event: 's3:ObjectCreated:Put', bucket: 'image-uploads', prefix: 'images/' }; it('includes a filter rule on the S3 bucket resource', function() { const resources = getResources(trigger, funcName); expect(resources).to.have.property('RiseimageuploadsBucket'); const bucketResource = resources['RiseimageuploadsBucket']; expect(bucketResource).to.have.property('Type', 'AWS::S3::Bucket'); expect(bucketResource).to.have.property('Properties'); const bucketProps = bucketResource.Properties; expect(bucketProps).to.have.property('BucketName', 'image-uploads'); expect(bucketProps).to.have.deep.property('NotificationConfiguration.LambdaConfigurations'); expect(bucketProps.NotificationConfiguration.LambdaConfigurations).to.have.lengthOf(1); const lambdaCfg = bucketProps.NotificationConfiguration.LambdaConfigurations[0]; expect(lambdaCfg).to.deep.equal({ Event: 's3:ObjectCreated:Put', Function: { 'Fn::GetAtt': [ funcName, 'Arn' ] }, Filter: { S3Key: { Rules: [{ Name: 'prefix', Value: 'images/' }] } } }); }); }); context('with suffix specified', function() { const trigger = { event: 's3:ObjectCreated:Put', bucket: 'image-uploads', suffix: '.png' }; it('includes a filter rule on the S3 bucket resource', function() { const resources = getResources(trigger, funcName); expect(resources).to.have.property('RiseimageuploadsBucket'); const bucketResource = resources['RiseimageuploadsBucket']; expect(bucketResource).to.have.property('Type', 'AWS::S3::Bucket'); expect(bucketResource).to.have.property('Properties'); const bucketProps = bucketResource.Properties; expect(bucketProps).to.have.property('BucketName', 'image-uploads'); expect(bucketProps).to.have.deep.property('NotificationConfiguration.LambdaConfigurations'); expect(bucketProps.NotificationConfiguration.LambdaConfigurations).to.have.lengthOf(1); const lambdaCfg = bucketProps.NotificationConfiguration.LambdaConfigurations[0]; expect(lambdaCfg).to.deep.equal({ Event: 's3:ObjectCreated:Put', Function: { 'Fn::GetAtt': [ funcName, 'Arn' ] }, Filter: { S3Key: { Rules: [{ Name: 'suffix', Value: '.png' }] } } }); }); }); context('with prefix and suffix specified', function() { const trigger = { event: 's3:ObjectCreated:Put', bucket: 'image-uploads', prefix: 'images/', suffix: '.png' }; it('includes filter rules on the S3 bucket resource', function() { const resources = getResources(trigger, funcName); expect(resources).to.have.property('RiseimageuploadsBucket'); const bucketResource = resources['RiseimageuploadsBucket']; expect(bucketResource).to.have.property('Type', 'AWS::S3::Bucket'); expect(bucketResource).to.have.property('Properties'); const bucketProps = bucketResource.Properties; expect(bucketProps).to.have.property('BucketName', 'image-uploads'); expect(bucketProps).to.have.deep.property('NotificationConfiguration.LambdaConfigurations'); expect(bucketProps.NotificationConfiguration.LambdaConfigurations).to.have.lengthOf(1); const rules = bucketProps.NotificationConfiguration.LambdaConfigurations[0].Filter.S3Key.Rules; expect(rules).to.deep.have.members([ { Name: 'prefix', Value: 'images/' }, { Name: 'suffix', Value: '.png' } ]); }); }); });
var webpack = require('webpack'); var isProduction = process.env.NODE_ENV === "production"; var babelPlugins = []; var webpackPlugins = [ new webpack.optimize.OccurrenceOrderPlugin(true) ]; if (isProduction) { // Production webpack plugins webpackPlugins.push(new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false } })); webpackPlugins.push(new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify('production') } })); // Production babel plugins babelPlugins.push(["transform-react-remove-prop-types", { "mode": "wrap", "ignoreFilenames": ["node_modules"] }]); } var config = { entry: { app: './src/components/index.js' }, output: { path: __dirname + '/src/static/js', filename: 'demos.js' }, module: { rules: [ { // All JS/React files test: /\.js$/, exclude: [/node-modules/, /scripts/, /build/], use: [{ loader: 'babel-loader', options: { presets: ['es2015', 'react', 'stage-1'], plugins: babelPlugins } }] }, { // SCSS Compilation test: /\.(sass|scss)$/, use: [ 'style-loader', 'css-loader', 'sass-loader' ] }, { // JSON loader test: /\.json$/, loader: "json-loader" //JSON loader }, {// Fonts test: /\.(eot|svg|ttf|woff|woff2)$/, loader: 'url-loader' }, ] }, plugins: webpackPlugins, devtool: "eval-source-map", // Default development sourcemap }; // Change sourcemap if production if (process.env.NODE_ENV === "production") { config.devtool = "source-map"; } module.exports = config;
#!/usr/bin/env node (0, require('../lib/cli/seaworthy').run)(process.argv.slice(2));
var mongoose = require('mongoose'); var connected = false; mongoose.connect(process.env.MONGO_DB_URI || 'mongodb://localhost/mongo-constant-test'); exports.connect = function(done) { if (connected) return done(); mongoose.connection.once('open', function() { connected = true; done(); }); mongoose.connection.on('error', done); }; exports.reset = function(done) { mongoose.models = {}; mongoose.connection.db.dropDatabase(done); };
'use strict'; import config from './helpers/config'; /** * Query configured leak databases * * @param {object} context the context object * @return a promise resolving to a map of new leaks for each account, if any */ export default async function checkLeaks(context) { // Get leaks from databases let databaseLeaks = await Promise.all((config.databases || []).map(async (database) => { return await checkLeakInDatabase(context, database, config.accounts || []); })); // Merge leak databases const leaks = mergeDatabaseLeaks(databaseLeaks); // See if we have new leaks from database const previousLeaks = await context.db.get('leaks') || {}; const newLeaks = leakDiff(leaks, previousLeaks); // Save leaks to database await context.db.set('leaks', leaks); return [newLeaks, leaks]; } /** * @private * * Search for leaks in a specific database * * @param {object} context the context object * @param {string} database the database to search in * @param {[string]} accounts the account ids to search for * @return a promise resolving to the list of leaks for each of `accounts` in `database` */ async function checkLeakInDatabase(context, database, accounts) { const db = require(`./databases/${database}`).default; const leakResult = await Promise.resolve(db(accounts)); return leakResult; } /** * @private * * Merges leak results [{account: [leaks]}, {account, [leaks2]}] => [{account: {leak: ..., leak2: ...}}] * * @param {object} databaseLeaks the individual leaks to merge * @return the merged leaks */ function mergeDatabaseLeaks(databaseLeaks) { leaks = {}; config.accounts.forEach((account) => { const data = {}; Object.assign.bind(null, data).apply(null, config.databases.map((db, i) => databaseLeaks[i][account] || {})); if (Object.keys(data).length) leaks[account] = data; }); return leaks; } /** * @private * * Returns the difference between two sets of leaks * * @param {object} fresh the fresh leaks * @param {object} previous the previous leaks * @return the leak difference */ function leakDiff(fresh, previous) { const diff = {}; config.accounts.forEach((account) => { const freshAccount = fresh[account] || {}; const previousAccount = previous[account] || {}; const previousAccountKeys = Object.keys(previousAccount); const leakDiff = Object.keys(freshAccount).filter((leak) => previousAccountKeys.indexOf(leak) === -1); if (leakDiff.length) { diff[account] = {}; leakDiff.forEach(leakKey => diff[account][leakKey] = freshAccount[leakKey]); } }); return diff; }
"use strict"; var fs = require("fs"); var path = require("path"); var nlsvParser = new Parser("nlsv"); var htmlParser = new Parser("html"); var str1 = ' <pre class=" language-javascript"><a title="Copy to clipboard" class="_pre-clip"></a><span spellcheck="true" class="token comment">// Pull off a header delimited by \n\n</span>'; var str2 = '</span>'; var str3 = '<a href="/cpp/" class="_list-item _icon-cpp _list-disabled" data-slug="cpp" title="C++"> <span class="_list-enable" data-'; var str4 = '<a href="/cpp/ class="_list-item _icon-cpp _list-disabled" data-slug="cpp" title="C++">'; var str5 = '<p>'; var str6 = '<span></span>'; var str7 = '<br/><br><hr/>'; var str8 = '<a>mere end > og mindre <</a><</span>// hello world</span></pre>'; var str9 = '</presss></a></span>'; var str10 = "there should be <a>\n\t\t\t\t\t\tnewline but text should\n\t\t\t\t\t\tinclude newline"; var htmlFile = "test/data/html.htm"; var htmlFile2 = "test/data/html2.htm"; var nlsvFile1 = path.resolve(__dirname, "../test/data/wordlist_tail"); var nlsvFile2 = "/test/data/wordlist"; var nlsvData = "a\n\t\t\t\t\t\t\t\t\ta\n\t\t\t\t\t\t\t\t\ta's\n\t\t\t\t\t\t\t\t\ta's\n\t\t\t\t\t\t\t\t\tab's\n\t\t\t\t\t\t\t\t\tabaci\n\t\t\t\t\t\t\t\t\taback\n\t\t\t\t\t\t\t\t\tabacus\n\t\t\t\t\t\t\t\t\tabacus's\n\t\t\t\t\t\t\t\t\tabacuses\n\t\t\t\t\t\t\t\t\t"; /*const promise = wait(data => { htmlParser.parse(data, { newline: true, space: true}) }, 0, str3)*/ /*const promise = wait(data => { nlsvParser.parse(data, { newline: true, space: true}) }, 0, nlsvData) promise.catch(err => { console.error(err) return {}// visual studio has a wrong return type for promise.catch() }) promise.then(process.exit.bind(process, 0))*/ fs.readFile(nlsvFile1, { encoding: "utf8" }, function (err, data) { if (err) throw err; nlsvParser.parse(data); //htmlParser.parse(data) }); function Tokenize(type) { this.tokens = []; this.type = type; } Tokenize.prototype.read = function (str) { var options = arguments.length <= 1 || arguments[1] === undefined ? { newline: false, space: false } : arguments[1]; /*try { this.tokenReader[this.type].read(str1, this.tokens) } catch (er) { console.log(er) }*/ var tokenReader = this.tokenReader[this.type]; if (!tokenReader) throw "Unknown data type " + this.type; var promise = tokenReader.read(str, this.tokens, options); /*console.log(this.tokens.slice(-10)) if(this.type === "nlsv") { console.log(this.tokens.slice(-10).map(x => { if(x instanceof tokenReader.Word) return "Word" if(x instanceof tokenReader.NewLine) return "NewLine" if(x instanceof tokenReader.Space) return "Space" if(x instanceof tokenReader.InvalidString) return "InvalidString" })) } if(this.type === "html") { console.log(this.tokens.slice(-10).map(x => { if(x instanceof tokenReader.Html) return "Html" if(x instanceof tokenReader.Text) return "Text" if(x instanceof tokenReader.InvalidHtml) return "InvalidHtml" if(x instanceof tokenReader.NewLine) return "NewLine" if(x instanceof tokenReader.Space) return "Space" })) }*/ }; Tokenize.prototype.getTokens = function () { var tokens = this.tokens; this.tokens = []; return tokens; }; Tokenize.prototype.tokenReader = { nlsv: { read: function read(str, tokens) { var options = arguments.length <= 2 || arguments[2] === undefined ? { newline: false, space: false } : arguments[2]; if (str.length === 0) return; if (this.regexWord.test(str)) { var word = this.regexWord.exec(str)[0], rest = str.substr(word.length); console.log(this.regexWord.exec(str)); tokens.push(new this.Word(word)); return this.read(rest, tokens, options); //setTimeout(this.read.bind(this, rest, tokens, options), 0) } if (this.regexNewLine.test(str)) { var newline = this.regexNewLine.exec(str)[0], rest = str.substr(newline.length); console.log(newline, this.regexNewLine.exec(str)); if (options.newline) tokens.push(new this.NewLine(newline)); return this.read(rest, tokens, options); //setTimeout(this.read.bind(this, rest, tokens, options), 0) } if (this.regexSpace.test(str)) { var space = this.regexSpace.exec(str)[0], rest = str.substr(space.length); if (options.space) tokens.push(new this.Space(space)); console.log(this.regexSpace.exec(str)); return this.read(rest, tokens, options); //setTimeout(this.read.bind(this, rest, tokens, options), 0) } else tokens.push(new this.InvalidString(str)); }, regexWord: /^[^(\r\n|\n|\s)]+/, regexSpace: /^\s+/, //TODO: why does this match newline? regexNewLine: /^\r\n|^\n/, Word: function Word(str) { this.value = str; }, InvalidString: function InvalidString(str) { this.value = str; }, NewLine: function NewLine(str) { this.value = str; }, Space: function Space(str) { this.value = str; } }, csv: {}, tsv: {}, html: { read: function read(str, tokens) { var options = arguments.length <= 2 || arguments[2] === undefined ? { newline: false, space: false } : arguments[2]; if (str.length === 0) return; if (this.regexHtmlTag.test(str)) { var html = this.regexHtmlTag.exec(str)[0], rest = str.substr(html.length); //console.log("html match") tokens.push(new this.Html(html)); return this.read(rest, tokens, options); } if (this.regexNewLine.test(str)) { var newline = this.regexNewLine.exec(str)[0], rest = str.substr(newline.length); //console.log("newline match", "options.newline is ", options.newline) if (options.newline) tokens.push(new this.NewLine(newline)); return this.read(rest, tokens, options); } if (this.regexSpace.test(str)) { var space = this.regexSpace.exec(str)[0], rest = str.substr(space.length); //console.log("space match")//, space, space.length, rest) if (options.space) tokens.push(new this.Space(space)); return this.read(rest, tokens, options); } if (this.regexText.test(str)) { var text = this.regexText.exec(str)[0], rest = str.substr(text.length); //console.log("text match")//, text, text.length, rest) tokens.push(new this.Text(text)); return this.read(rest, tokens, options); } else { //console.log("nothing matched") tokens.push(new this.InvalidHtml(str)); } //else throw "Can not tokenize " + str.slice(0, 240) }, //regexHtmlTag: /^<[.\w\s="'\-_\d\/.…\:;+\(\)&,\.]+>(?:<\/\w+>)?|^<\/\w+>/, //TODO: lookup utf8 code table //regexHtmlTag: /^<[^<>]+>(<\/\w+>)?|^<\/\w+>/, regexHtmlTag: /^<(\w+)[^<>]*>(<\/\1+>)?|^<\/\w+>/, regexSpace: /^\s+/, regexNewLine: /^\r\n|^\n/, //regexText: /^[.\w\s\d\r\n\\\/,\.\[\]\{\}\(\)='";:!\?+\-@©—]+/, //TODO: lookup utf8 code table regexText: /^[^<]+|^<(?!\/?\w+)/, Html: function Html(html) { this.value = html; this.tagName = /<\/?(\w+)/.exec(html)[1]; this.isEmpty = /><\/\w+>$|<\w{2,}\/?>$/.test(html); this.isStartTag = this.isEmpty ? false : /^<\w/.test(html); this.isEndTag = this.isEmpty ? false : /^<\//.test(html); }, Text: function Text(text) { this.value = text; }, InvalidHtml: function InvalidHtml(str) { this.value = str; this.tagName = null; this.isEmpty = false; this.isStartTag = false; this.isEndTag = false; }, NewLine: function NewLine(str) { this.value = str; }, Space: function Space(str) { this.value = str; } } }; function Parser() { var type = arguments.length <= 0 || arguments[0] === undefined ? "html" : arguments[0]; this.tokenize = new Tokenize(type); } Parser.prototype.parse = function (str) { var _this = this; var options = arguments.length <= 1 || arguments[1] === undefined ? { newline: false, space: false } : arguments[1]; this.tokenize.read(str, options); var c = 0; setInterval(function () { c = _this.lexer(_this.tokenize.tokens); if (c > 1048574 /*198350*/) process.exit(0); }, 500); //return this.lexer(this.tokenize.tokens) }; Parser.prototype.lexer = function (tokens) { console.log("lexer got %d tokens", tokens.length); console.log("last token is ", tokens[tokens.length - 1]); return tokens.length; }; function Stream(head, tailPromise) { if (typeof head != 'undefined') { this.headValue = head; } if (typeof tailPromise == 'undefined') { tailPromise = function () { return new Stream(); }; } this.tailPromise = tailPromise; } //wait :: (a -> any) -> b -> c -> Promise function wait(fn, delay) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } return new Promise(function (resolve, reject) { setTimeout(function () { try { resolve(fn.apply(undefined, args)); } catch (err) { reject(err); } }, delay); }); } //span :: (a -> Bool) -> [a] -> ([a], [a]) function span(pred, str) { return spanAcc([], str); function spanAcc(_x6, _x7) { var _again = true; _function: while (_again) { var acc = _x6, list = _x7; _again = false; if (list.length === 0) return [acc, list]; var c = list[0], cs = list.slice(1); if (pred(c)) { _x6 = acc.concat(c); _x7 = cs; _again = true; c = cs = undefined; continue _function; } else return [acc, list]; } } }
import { struct } from 'brisky-struct' import parent from '../render/dom/parent' import delegate from './delegate' import listen from './listener' // import { property } from '../render/static' const emitterProperty = struct.props.on.struct.props.default const cache = {} const injectable = {} const isTouch = typeof window !== 'undefined' && ( ('ontouchstart' in global || global.DocumentTouch && document instanceof global.DocumentTouch) || navigator.msMaxTouchPoints || false) // const clear = () => { block = null } // const blockMouse = () => { // if (block) clearTimeout(block) // block = setTimeout(clear, 300) // } // var block var blockClick export default injectable const isNidium = global.__nidium__ if (isNidium) { // make seperate file } else { injectable.on = { props: { error: {}, remove: {}, default: (t, val, key) => { if (!cache[key]) { cache[key] = true listen(key, e => delegate(key, e)) } t._p.set({ hasEvents: true }, false) emitterProperty(t, val, key) }, move: (t, val) => { t.set({ mousemove: val, touchmove: val }) }, click: (t, val, key) => { if (!cache[key]) { cache[key] = true listen(key, e => { const d = Date.now() - blockClick return d < 500 && delegate(key, e) }) } t._p.set({ hasEvents: true }, false) emitterProperty(t, val, key) }, down: (t, val, key) => { if (!cache[key]) { cache[key] = true if (!isTouch) { listen('mousedown', e => { blockClick = Date.now() // if (!block) delegate(key, e) delegate(key, e) }) } else { listen('touchstart', e => { blockClick = Date.now() // blockMouse() delegate(key, e) }) } } t._p.set({ hasEvents: true }, false) emitterProperty(t, val, key) } // up: (t, val, key) => { // if (!cache[key]) { // cache[key] = true // listen('mouseup', e => { // delegate(key, e) // // !block && delegate(key, e) // }) // listen('touchend', e => { // // blockMouse() // delegate(key, e) // }) // } // t._p.set({ hasEvents: true }, false) // emitterProperty(t, val, key) // } } } if (isTouch) { injectable.on.props.move = (t, val) => t.set({ touchmove: val }) // injectable.on.props.down = (t, val) => t.set({ touchstart: val }) injectable.on.props.up = (t, val) => t.set({ touchend: val }) } else { injectable.on.props.move = (t, val) => t.set({ mousemove: val }) // injectable.on.props.down = (t, val) => t.set({ mousedown: val }) injectable.on.props.up = (t, val) => t.set({ mouseup: val }) } injectable.props = { hasEvents: { type: 'property', subscriptionType: 'switch', forceSubscriptionMethod: 's', $: true, render: { state (target, s, type, subs, tree, id, pid) { const node = parent(tree, pid) if (node) { if (s) { node._sc = s.storeContext() node._s = s } if (!('_' in node)) { node._ = target.parent() } } } } } } }
import template from './admin.tpl.html'; import '../header/header.tpl.html'; import adminUsers from './users/index.js'; import uiAuth from '../common/uiAuth/index.js'; angular.module('sp.editor.admin', [ 'sp.editor.admin.users', 'uiAuth' //'resources.organisations', //'resources.users' ]) .config(function($stateProvider, authProvider) { $stateProvider.state('admin.admin', { url: '/admin', templateUrl: template, controller: 'AdminCtrl' }); }) .controller('AdminCtrl', function($scope, user) { console.log('AdminCtrl', user); }) ;
'use strict'; var test = require('ava'); var omit = require('lodash/omit'); var config = require('../../src/es5'); var baseFixture = require('../fixtures/eslint-config-es5'); var warningFixture = require('../fixtures/eslint-config-es5-warning'); test('base config matches expected eslint config', function(t) { t.plan(7); var expectedOutput = omit(baseFixture, ['extends', 'globals']); t.deepEqual(config.base.env, expectedOutput.env); t.deepEqual(config.base.rules, expectedOutput.rules); t.deepEqual(config.base.parserOptions, expectedOutput.parserOptions); t.deepEqual(config.base.plugins, expectedOutput.plugins); t.deepEqual(config.base.settings, expectedOutput.settings); t.deepEqual(config.base.ecmaFeatures, expectedOutput.ecmaFeatures); t.deepEqual(config.base, expectedOutput); }); test('warning config matches expected eslint config', function(t) { t.plan(7); var expectedOutput = omit(warningFixture, ['extends', 'globals']); t.deepEqual(config.warning.env, expectedOutput.env); t.deepEqual(config.warning.rules, expectedOutput.rules); t.deepEqual(config.warning.parserOptions, expectedOutput.parserOptions); t.deepEqual(config.warning.plugins, expectedOutput.plugins); t.deepEqual(config.warning.settings, expectedOutput.settings); t.deepEqual(config.warning.ecmaFeatures, expectedOutput.ecmaFeatures); t.deepEqual(config.warning, expectedOutput); });
version https://git-lfs.github.com/spec/v1 oid sha256:17bf96e421f3fb3531c5d5c3f93ec33f5691538b10c2729f518950bb8cc1d2dd size 7840
/** * @overview ccm component for acoordion * @see https://github.com/mozilla/pdf.js/ * @author Tea Kless <tea.kless@web.de>, 2018 * @license The MIT License (MIT) */ { var component = { /** * unique component name * @type {string} */ name: 'accordion', /** * recommended used framework version * @type {string} */ ccm: 'https://akless.github.io/ccm/ccm.js', /** * default instance configuration * @type {object} */ config: { title: 'success', //basic, default, primary, info, success, warning, danger, link (see https://www.w3schools.com/bootstrap/bootstrap_buttons.asp) data: { key: 'demo', entries: [ { "title": "Learning Goals", "content": "..." }, { "title": "Lecture", "content": "<source src=\"../table/ccm.table.js\"> <p>Hier steht <i>ccm</i>-Komponente</p> <ccm-table key='[\"ccm.get\",\"../table/resources/configs.js\",\"demo\"]'></ccm-table>" }, { "title": "Additional Materials", "content": "..." }, { "title": "Exercises", "content": "..." }, { "title": "Bibliography", "content": "..." } ] }, content: [ "ccm.component", "https://akless.github.io/ccm-components/content/versions/beta/ccm.content-4.0.0.js" ], css: [ "ccm.load", { context: 'head', url: '../../ccm-components/libs/bootstrap/css/font-face.css' }, '../../ccm-components/libs/bootstrap/css/bootstrap.css', 'default.css' ] }, Instance: function () { /** * own reference for inner functions * @type {Instance} */ const self = this; /** * privatized instance members * @type {object} */ let my; /** * shortcut to help functions * @type {Object.<string,function>} */ let $; this.ready = callback => { // set shortcut to help functions $ = self.ccm.helper; // privatize all possible instance members my = $.privatize( self ); if ( self.logger ) self.logger.log( 'ready', my ); callback(); }; /** * starts the instance * @param {function} [callback] - called after all synchronous and asynchronous operations are complete */ this.start = callback => { // render accordion $.setContent( self.element, $.html( accordion( my.inner || data() ) ) ); if( callback ) callback(); function accordion( data ) { const acc = data; prepare(); acc.querySelectorAll('button').forEach( function (button) { button.addEventListener( 'click', function ( ) { let content_div = this.nextElementSibling; if (content_div.style.maxHeight) { content_div.style.maxHeight = null; changeIcon( button.querySelector( 'span' ), 'glyphicon-triangle-right' ); } else { content_div.style.maxHeight = content_div.scrollHeight + "px"; changeIcon( this.querySelector( 'span' ), 'glyphicon-triangle-bottom' ); closeOpenContents(); function closeOpenContents() { button.classList.add( 'open' ); content_div.classList.add( 'open' ); acc.querySelectorAll( 'button:not(.open)' ).forEach( button => { changeIcon( button.querySelector( 'span' ), 'glyphicon-triangle-right' ); }); acc.querySelectorAll( 'div:not(.open)' ).forEach( div => { div.style.maxHeight = null; }); content_div.classList.remove('open'); button.classList.remove( 'open' ); } } function changeIcon( span, icon ) { span.classList.remove( span.className.split(' ').pop() ); span.classList.add( icon ); } }); } ); function prepare() { // prepare span tag for icon let span_tag = document.createElement( 'span' ); span_tag.classList.add( 'glyphicon', 'glyphicon-triangle-right' ); /* * replace title tag with button tag */ acc.querySelectorAll( 'title' ).forEach( title => { // insert icon span-tag before title title.classList.add( 'btn', 'btn-lg', 'btn-' + my.title); title.prepend( span_tag.cloneNode( true )); title.outerHTML = title.outerHTML.replace( 'title', 'button' ); }); /* * replace content tag with div * pass light-DOM to content-component if set in config */ acc.querySelectorAll( 'content' ).forEach( content => { const fragment = document.createDocumentFragment(); [ ...content.children ].map( child => fragment.appendChild( child ) ); const div = document.createElement( 'div' ); div.classList.add('content'); content.parentNode.replaceChild( div, content ); const p = document.createElement( 'p' ); div.appendChild( p ); if( my.content ) my.content.start( { inner: fragment, root: p } ); else { p.appendChild( fragment ); } } ); } return acc; } /* * forms my.inner structure from given data (my.data) */ function data() { const div = document.createElement( 'div' ); const title = document.createElement( 'title' ); const content = document.createElement( 'content' ); const p = document.createElement( 'p' ); my.data.entries.map( entry => { const title_clone = title.cloneNode( true ); const content_clone = content.cloneNode( true ); const p_clone = p.cloneNode( true ); title_clone.innerHTML = entry.title; $.setContent( p_clone, $.html( entry.content ) ); content_clone.appendChild( p_clone ); div.appendChild( title_clone ); div.appendChild( content_clone ); } ); return div; } }; } }; function p(){window.ccm[v].component(component)}const f="ccm."+component.name+(component.version?"-"+component.version.join("."):"")+".js";if(window.ccm&&null===window.ccm.files[f])window.ccm.files[f]=component;else{const n=window.ccm&&window.ccm.components[component.name];n&&n.ccm&&(component.ccm=n.ccm),"string"==typeof component.ccm&&(component.ccm={url:component.ccm});var v=component.ccm.url.split("/").pop().split("-");if(v.length>1?(v=v[1].split("."),v.pop(),"min"===v[v.length-1]&&v.pop(),v=v.join(".")):v="latest",window.ccm&&window.ccm[v])p();else{const e=document.createElement("script");document.head.appendChild(e),component.ccm.integrity&&e.setAttribute("integrity",component.ccm.integrity),component.ccm.crossorigin&&e.setAttribute("crossorigin",component.ccm.crossorigin),e.onload=function(){p(),document.head.removeChild(e)},e.src=component.ccm.url}} }
define([], function() { function Stack() { var array = []; this.push = function(obj) { array.push(obj); }; this.peek = function() { if (!array.length) { return undefined; } return array[array.length - 1]; }; this.pop = function() { if (!array.length) { throw new Error("empty"); } return array.pop(); }; } return Stack; });
import createHistory from 'history/createBrowserHistory'; import React from 'react'; import {render} from 'react-dom'; import {createStore} from 'redux'; import {enableFocusMode} from './actions'; import {locationToReference} from './data/model'; import {updateStoreWithPassageText} from './data/fetcher'; import preferences from './data/preferences'; import recentReferenceTracker from './data/recent-reference-tracker'; import reducer, {DEFAULT} from './reducer'; import registerServiceWorker from './service-worker/register'; import App from './ui/app'; import {READ_PATH_RE} from './ui/nav'; import './ui/normalize.css'; import './ui/index.css'; const store = createStore(reducer, DEFAULT); const history = createHistory(); if (sessionStorage.redirect) { history.replace(sessionStorage.redirect); delete sessionStorage.redirect; } history.listen((location, action) => READ_PATH_RE.exec(location.pathname)? updateStoreWithPassageText(store, locationToReference(location)) : store.dispatch(enableFocusMode(false))); render(<App store={store} history={history}/>, document.getElementById('root')); if (READ_PATH_RE.exec(window.location.pathname)) updateStoreWithPassageText(store, locationToReference(window.location)); recentReferenceTracker(store); preferences(store); registerServiceWorker();
import { report, ruleMessages, validateOptions } from "../../utils" export const ruleName = "comment-empty-line-before" export const messages = ruleMessages(ruleName, { expected: "Expected empty line before comment", rejected: "Unexpected empty line before comment", }) export default function (expectation) { return (root, result) => { const validOptions = validateOptions(result, ruleName, { actual: expectation, possible: [ "always", "never", ], }) if (!validOptions) { return } root.walkComments(comment => { // Ignore the first node if (comment === root.first) { return } const before = comment.raw("before") // Ignore inline comments if (before.indexOf("\n") === -1) { return } const expectEmptyLineBefore = (expectation === "always") ? true : false const emptyLineBefore = before.indexOf("\n\n") !== -1 || before.indexOf("\r\n\r\n") !== -1 // Return if the exceptation is met if (expectEmptyLineBefore === emptyLineBefore) { return } const message = expectEmptyLineBefore ? messages.expected : messages.rejected report({ message: message, node: comment, result, ruleName, }) }) } }
Template.postUpvote.helpers({ upvoted: function(){ var user = Meteor.user(); if(!user) return false; return _.include(this.upvoters, user._id); } }); Template.postUpvote.events({ 'click .upvote-link': function(e){ var post = this; e.preventDefault(); if(!Meteor.user()){ Router.go('atSignIn'); Messages.flash(i18n.t("please_log_in_first"), "info"); } Meteor.call('upvotePost', post, function(){ Events.track("post upvoted", {'_id': post._id}); }); } });
'use strict'; import visit from 'unist-util-visit'; // base unist object models const elementPre = (props, hProps) => ({ type: 'inlineCode', data: { hName: 'pre', hProperties: {...hProps} }, ...props }) const elementCode = (children, props) => ({ type: 'element', tagName: 'code', properties: {...props}, children: children }) /* Workaround for mdhighlight * Since the mdhighlight plugin is processed * before this plugin, children are parsed for * the '---↵' delimiter so that the title/delimiter * elements can be skipped. * * Currently, PrismJS tokenize() processes the * delimiter as two separate tokens. */ const getContentOffset = children => { let _children = []; // extract 'value' props from children for (const child of children) { _children.push(child.children ? child.children[0].value : ''); } // iterate children until delimiter elements are found for (let i = 0; i < _children.length;) { const cur = _children[i++], next = _children[i]; if (cur === '--' && next === '-\n') return ++i; } } const createChildren = (node) => { const {data = {hChildren: {}}, lang, value} = node; const test = /\n---\n/.exec(value); if (!test) return [node]; const hStr = node.value.slice(0, test.index); const bStr = node.value.slice(test.index + 5); // index + match length const nodeHeader = elementPre({value: hStr}, {className: 'code-header'}); const nodeParent = elementPre(null, {className: 'code-body'}); // Syntax highlighting compat -- use node's current hChildren (skipping title/delimiter elements) // Normally hChildren should be empty. const offset = Array.isArray(data.hChildren) && getContentOffset(data.hChildren); const nodeChildren = offset ? data.hChildren.slice(offset) : [{type: 'text', value: bStr}]; const {hProperties = lang ? {className: `language-${lang}`} : {}} = data; nodeParent.data.hChildren = [elementCode(nodeChildren, hProperties)]; return [nodeHeader, nodeParent] } export default function attacher() { return transformer; } const transformer = ast => { const children = ast.children; let indexes = []; let newChildren = []; // Find indexes of all 'code' type children visit(ast, 'code', (node, index) => indexes.push(index)); if (indexes.length === 0) return; indexes.map((index, i) => { const node = ast.children[index]; if (!node) return; const nextIndex = indexes[i + 1] || indexes[i]; const childNodes = createChildren(node); newChildren = [...newChildren, ...childNodes, ...children.slice(index + 1, nextIndex)] }) const firstIndex = indexes[0]; const lastIndex = indexes[indexes.length - 1]; // AST children until 1st significant index, processed nodes, AST children after last significant index ast.children = [...children.slice(0, firstIndex), ...newChildren, ...children.slice(lastIndex + 1)]; }
/* * Author Ricardo Alcantara<richpolis@gmail.com>. * Twitter: @richpolis * * Codigos fuentes * * numberFormat: http://www.yoelprogramador.com/formatear-numeros-con-javascript/ * * Validador de numeros: http://blog.freshware.es/solo-permitir-numeros-en-input-text-html/ * * Validar email: http://ismaelgsan.com/validar-un-email-con-javascript-de-forma-rapida-y-sencilla/ * */ var $estado = null; var $delegacion = null; var $colonia = null; var $codigo = null; var formatNumber = { separador: ",", // separador para los miles sepDecimal: '.', // separador para los decimales formatear: function (num) { num += ''; var splitStr = num.split('.'); var splitLeft = splitStr[0]; var splitRight = splitStr.length > 1 ? this.sepDecimal + splitStr[1] : ''; var regx = /(\d+)(\d{3})/; while (regx.test(splitLeft)) { splitLeft = splitLeft.replace(regx, '$1' + this.separador + '$2'); } return this.simbol + splitLeft + splitRight; }, new : function (num, simbol) { this.simbol = simbol || ''; return this.formatear(num); } } $(document).on('ready', function () { $(".item-perfil").on('click', function () { location.href = $(this).data('url'); }); $("#interactivevalley_pakmailbundle_envio_direccionFiscal_pais").on('change', function () { if ($(this).val() == "Mexico") { bootbox.prompt("¿Cual es tu código postal?", function (codigo) { if (codigo === null) { alert("El valor no fue ingresado"); } else { llamarAMetodosCodigoPostal(codigo, "#interactivevalley_pakmailbundle_envio_direccionFiscal"); } }); } else if ($(this).val() == "Otro") { agregarPais("#interactivevalley_pakmailbundle_envio_direccionFiscal"); activarCampos("#interactivevalley_pakmailbundle_envio_direccionFiscal"); } else { activarCampos("#interactivevalley_pakmailbundle_envio_direccionFiscal"); } }); $("#interactivevalley_pakmailbundle_envio_direccionRemitente_pais").on('change', function () { if ($(this).val() == "Mexico") { bootbox.prompt("¿Cual es tu código postal?", function (codigo) { if (codigo === null) { alert("El valor no fue ingresado"); } else { llamarAMetodosCodigoPostal(codigo, "#interactivevalley_pakmailbundle_envio_direccionRemitente"); } }); } else if ($(this).val() == "Otro") { agregarPais("#interactivevalley_pakmailbundle_envio_direccionRemitente"); activarCampos("#interactivevalley_pakmailbundle_envio_direccionRemitente"); } else { activarCampos("#interactivevalley_pakmailbundle_envio_direccionRemitente"); } }); $("#interactivevalley_pakmailbundle_envio_direccionDestino_pais").on('change', function () { if ($(this).val() == "Mexico") { bootbox.prompt("¿Cual es tu código postal?", function (codigo) { if (codigo === null) { alert("El valor no fue ingresado"); } else { llamarAMetodosCodigoPostal(codigo, "#interactivevalley_pakmailbundle_envio_direccionDestino"); } }); } else if ($(this).val() == "Otro") { agregarPais("#interactivevalley_pakmailbundle_envio_direccionDestino"); activarCampos("#interactivevalley_pakmailbundle_envio_direccionDestino"); } else { activarCampos("#interactivevalley_pakmailbundle_envio_direccionDestino"); } }); if (creacionEnvio && !perfilGuardado) { bootbox.confirm('<h3>Gracias, nos pondremos en contacto con usted a la brevedad. Su envío se generó con el número: ' + creacionEnvio +'</h3><p>¿Desea guardar el envío en sus perfiles de envío?<br/><span style=\"font-size: .8em;\">*Al guardar un perfil de envío usted podra autorellenar sus campos en futuras operaciones.</span></p>', function (result) { if (result) { bootbox.prompt('<p>Por favor introduzca un nombre de referencia para este perfil de envío.<br/><span style=\"font-size: .8em;\">Usted puede editar sus perfiles de envío en cualquier momento,<br/>ingresando al area de Perfiles de Envío de lado izquierdo.</span></p>', function (nombrePerfil) { if (nombrePerfil === null) { bootbox.alert("Nombre de perfil no recibido!"); } else { if (nombrePerfil.length > 0) { $.ajax({ url: urlCrear, type: 'POST', dataType: 'json', data: {'nombre': nombrePerfil, 'envio': creacionEnvio}, success: function (data) { bootbox.alert("Perfil ha sido guardado!"); console.log(data); location.reload(); }, error: function (data) { bootbox.alert("Error: no se ha podido realizar la operacion solicitada!"); console.log(data); } }); } } }); } }); } else if (creacionEnvio) { bootbox.alert("Tu envío se genero con el número: " + creacionEnvio); } revisarCampos("#interactivevalley_pakmailbundle_envio_direccionFiscal"); revisarCampos("#interactivevalley_pakmailbundle_envio_direccionRemitente"); revisarCampos("#interactivevalley_pakmailbundle_envio_direccionDestino"); var $requeridos = $(".required"); $requeridos.on("blur", function () { var $input = $(this); var $parent = $input.parent(); if ($input.val() == "") { $parent.addClass('has-error').removeClass('has-success'); } else { if($input.hasClass('email')){ if(!validarEmail($input.val())){ $parent.addClass('has-error').removeClass('has-success'); }else{ $parent.addClass('has-success').removeClass('has-error'); } }else{ $parent.addClass('has-success').removeClass('has-error'); } } }); $requeridos.parent().addClass('form-group'); var $asegurarEnvio = $("#interactivevalley_pakmailbundle_envio_asegurarEnvio"); var $montoSeguro = $("#interactivevalley_pakmailbundle_envio_montoSeguro"); var $importeSeguro = $("#interactivevalley_pakmailbundle_envio_importeSeguro"); var $precio = $("#interactivevalley_pakmailbundle_envio_precio"); var $valorDeclarado = $("#interactivevalley_pakmailbundle_envio_valorDeclarado"); var $generaGastosAduana = $("#interactivevalley_pakmailbundle_envio_generarGastosAduana"); $asegurarEnvio.on('click',function(e){ if($(this).is(":checked")){ $montoSeguro.parent().parent().addClass('has-warning'); $importeSeguro.parent().parent().addClass('has-warning'); }else{ $montoSeguro.parent().parent().removeClass('has-warning'); $importeSeguro.parent().parent().removeClass('has-warning'); } }); $generaGastosAduana.on('click',function(e){ if($(this).is(":checked")){ $valorDeclarado.parent().parent().addClass('has-warning'); }else{ $valorDeclarado.parent().parent().removeClass('has-warning'); } }); $('.money,.number').on('keypress', function (e) { var keynum = window.event ? window.event.keyCode : e.which; if ((keynum == 0) || (keynum == 8) || (keynum == 46)) return true; return /\d/.test(String.fromCharCode(keynum)); }); $precio.on('keyup', function (e) { $(".visualizar_precio").html(formatNumber.new($(this).val(), "$")); }); $valorDeclarado.on('keyup', function (e) { $(".visualizar_valor_declarado").html(formatNumber.new($(this).val(), "$")); }); $montoSeguro.on('keyup', function (e) { $(".visualizar_monto_seguro").html(formatNumber.new($(this).val(), "$")); calcularImporteSeguro(); }); $montoSeguro.on('change', function (e) { calcularImporteSeguro(); }); $importeSeguro.attr('readonly','readonly'); function calcularImporteSeguro(){ var monto = $montoSeguro.val(); if (monto > 0) { $importeSeguro.val(monto * .03); $(".visualizar_importe_seguro").html(formatNumber.new($importeSeguro.val(), "$")); } } $precio.keyup(); $montoSeguro.keyup(); $valorDeclarado.keyup(); $("form").on('submit',function(e){ var liberar = true; var $emails = $(".email"); for(var cont=0;cont<$emails.length;cont++){ if(!validarEmail($emails[cont].value)){ alert("El email: " + $emails[cont].value+' es incorrecto'); var offset = $($emails[cont]).offset().top - 180; $('html, body').animate({ scrollTop : offset }, 'slow'); liberar = false; break; } } for(var cont=0;cont<$requeridos.length;cont++){ if($requeridos[cont].value == ""){ alert("Favor de ingresar todos los datos requeridos"); var offset = $($requeridos[cont]).offset().top - 180; $('html, body').animate({ scrollTop : offset }, 'slow'); liberar = false; break; } } return liberar; }); function validarEmail( email ) { expr = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; return ( expr.test(email) ); } }); function llamarAMetodosCodigoPostal(codigo, idDireccion) { if (codigo.length < 5) { codigo = "0" + codigo; } //$("#interactivevalley_pakmailbundle_envio_direccionFiscal" + elemento) $estado = $(idDireccion + "_estado"); $delegacion = $(idDireccion + "_delegacion"); $colonia = $(idDireccion + "_poblacion"); $codigo = $(idDireccion + "_cp"); var url = 'https://api-codigos-postales.herokuapp.com/codigo_postal/' + codigo; $.ajax({ url: url, type: 'get', dataType: 'json', success: function (data) { if (data.length > 0) { $estado.val(data[0].estado); $delegacion.val(data[0].municipio); $codigo.val(codigo); desactivarCampos(idDireccion); } else { alert("No se encontro el código postal ingresado"); return false; } if (data.length == 1) { // solo hay una colonia $colonia.val(data[0].colonia); } else { // cuando hay mas de una colonia var options = ""; for (var cont = 0; data.length > cont; cont++) { options += '<option value="' + data[cont].colonia + '">' + data[cont].colonia + '</option>'; } bootbox.dialog({ title: "Selecciona tu colonia.", message: '<div class="row"> ' + '<div class="col-md-12"> ' + '<form class="form-horizontal"> ' + '<div class="form-group"> ' + '<label class="col-md-4 control-label" for="colonia">Colonia</label> ' + '<div class="col-md-4"> ' + '<select id="colonia" name="colonia" type="text" placeholder="Seleccionar colonia" class="form-control"> ' + options + '</select>' + '</div> ' + '</div> ' + '</form> </div> </div>', buttons: { success: { label: "Seleccionar", className: "btn-success", callback: function () { var colonia = $('#colonia').val(); $colonia.val(colonia) } } } }); } } }); } function agregarPais(idDireccion) { var $pais = $(idDireccion + "_pais"); var $opciones = $(idDireccion + "_pais option"); bootbox.prompt("Cual es el pais?", function (paisIngresado) { debugger; if (paisIngresado === null) { alert("No se ha ingresado ningun pais"); } else { debugger; var pais = new String(paisIngresado); pais.toLowerCase(); var Letra = pais[0]; var encontrado = false; Letra.toUpperCase(); pais[0] = Letra; for (var cont = 0; cont < $opciones.length; cont++) { if ($opciones[cont].value == pais) { encontrado = true; break; } } if (!encontrado) { var opcionUltima = $opciones[$opciones.length - 1]; var opcionOtro = $('<option value="Otro">'); opcionOtro.html("Otro..."); opcionUltima.value = pais; opcionUltima.innerHTML = pais; $pais.append(opcionOtro); } } }); } function activarCampos(idDireccion) { //$("#interactivevalley_pakmailbundle_envio_direccionFiscal" + elemento) /*$(idDireccion+ "_estado").removeAttr('readonly'); $(idDireccion+ "_delegacion").removeAttr('readonly'); $(idDireccion+ "_poblacion").removeAttr('readonly'); $(idDireccion+ "_cp").removeAttr('readonly');*/ } function desactivarCampos(idDireccion) { //$("#interactivevalley_pakmailbundle_envio_direccionFiscal" + elemento) /*$(idDireccion+ "_estado").attr('readonly','readonly'); $(idDireccion+ "_delegacion").attr('readonly','readonly'); $(idDireccion+ "_poblacion").attr('readonly','readonly'); $(idDireccion+ "_cp").attr('readonly','readonly');*/ } function revisarCampos(idDireccion) { if ($(idDireccion + "_pais").val() == "Mexico") { //desactivarCampos(idDireccion) } else { //activarCampos(idDireccion) } }
'use strict'; const fs = require('fs'); const Discord = require("discord.js"); const bot = new Discord.Client(); const config = require('./config.json'); // Initialize **or load** the server configurations const Enmap = require('enmap'); const Provider = require('enmap-sqlite'); // I attach settings to client to avoid confusion especially when moving to a modular bot. bot.settings = new Enmap({provider: new Provider({name: "settings"})}); // Just setting up a default configuration object here, to have somethign to insert. const defaultSettings = { prefix: '<@!299851881746923520>', modLogChannel: "mod-log", modRole: "Moderator", adminRole: "Administrator" } // Colorful Console Logging const chalk = require('chalk'); var clk = new chalk.constructor({enabled: true}); var cWarn = clk.bgYellow.black; var cError = clk.bgRed.black; var cDebug = clk.bgWhite.black; var cGreen = clk.bold.green; var cGrey = clk.bold.grey; var cYellow = clk.bold.yellow; var cBlue = clk.bold.blue; var cRed = clk.bold.red; var cServer = clk.bold.magenta; var cUYellow = clk.bold.underline.yellow; var cBgGreen = clk.bgGreen.black; // Create New Guild Webhook const hooks = config.webhooks; const newGuildHook = new Discord.WebhookClient(hooks.newGuild.id, hooks.newGuild.token); const blacklistHook = new Discord.WebhookClient(hooks.blacklist.id, hooks.blacklist.token); const botLogHook = new Discord.WebhookClient(hooks.botLog.id, hooks.botLog.token); const banned = require('./banned.json'); const safe = require('./safe.json'); const about = config.about; let dictionary = ''; let serverSorrows = []; var http = require('http'); var options = { host: 'malikdh.com', path: '/obscure-sorrows/api/dictionary' } var request = http.request(options, function (res) { var data = ''; res.on('data', function (chunk) { data += chunk; }); res.on('end', function () { dictionary = data; }); }); request.on('error', function (e) { console.log(e.message); }); request.end(); bot.on('ready', () => { bot.guilds.forEach(guild => { if(!bot.settings.has(guild.id)) { bot.settings.set(guild.id, defaultSettings); } }); checkBlacklist(bot, blacklistHook); console.log(cBlue(`Ready to serve in ${bot.channels.size} channels on ${bot.guilds.size} servers, for a total of ${bot.users.size} users.`)); }); // response when messages are sent in a channel bot.on("message", async (message) => { var lexicon = JSON.parse(dictionary); for (var word in lexicon) { serverSorrows.push(lexicon[word]); } const messagePrefix = message.content.split(" ")[0]; // Let's load the config. If it doesn't exist, use the default settings. // This is an extra security measure, in case enmap fails (it won't. better safe than sorry!) const guildConf = bot.settings.get(message.guild.id) || defaultSettings; // We also stop processing if the message does not start with our prefix. if (messagePrefix !== guildConf.prefix) return; if(!message.guild || message.author.bot) return; if (message.author.id == about.ownerID) return; if (message.channel.type == 'dm') return; if (message.channel.type !== 'text') return; // Then we use the config prefix to get our arguments and command: // const args = message.content.split(/\s+/g); // const command = args.shift().slice(guildConf.prefix.length).toLowerCase(); let command = message.content.split(" ")[1]; let args = message.content.split(" ").slice(2); // console.log("args: " + args); // console.log("command: " + command); var rn = Math.floor(Math.random() * (serverSorrows.length - 1)); var path = './commands/'; try { let commandFile = require(`${path}${command}.js`); commandFile.run(bot, message, args, serverSorrows, about, guildConf, rn, botUptime, banned, safe, checkID, checkWord, convertTime, displayWords, singleWord); } catch (err) { console.error(err); console.log(cRed(`From Guild: ${message.guild.name}`)); console.log(cRed(`Guild ID: ${message.guild.id}`)); console.log(cRed(`Owner ID: ${message.guild.owner.id}\n`)); console.log(cRed(`Author Username: ${message.author.username}`)); console.log(cRed(`Author ID: ${message.author.id}`)); } }); // When the bot joins a new server bot.on("guildCreate", server => { // Initialize Default Settings for a new guild bot.settings.set(server.id, defaultSettings); let criticalInfo = { "name": server.name, "id": server.id, "ownerName": server.owner.displayName, "ownerID": server.owner.id, "memberCount": server.members.size, "botCount": server.members.filter(m => m.user.bot).size, "humanCount": server.members.filter(m => !m.user.bot).size, "joined": server.joinedTimestamp } if (criticalInfo.botCount / criticalInfo.memberCount * 100 >= 75 || criticalInfo.id == '302952448484704257') { if (checkID(bot, criticalInfo.id, 'blacklist')) { blacklistHook.send("**Bot Farm:** " + criticalInfo.name + " (" + criticalInfo.id + ") tried to add me within their server. Bots: " + criticalInfo.botCount).then(message => console.log(`\nSent message:\n${message.content}`)).catch(console.error); return server.leave(); } else { banned.blacklist.push(criticalInfo.id); fs.writeFile("./banned.json", JSON.stringify(banned, "", "\t"), err => { bot.users.get("266000833676705792").send("**Bot Farm blacklisted:** " + criticalInfo.name + " (" + criticalInfo.id + ")\n" + (err ? "Failed to update database" : "Database updated.")) }) return server.leave(); } } newServer(server, newGuildHook, criticalInfo); }); bot.on("guildDelete", guild => { bot.settings.delete(guild.id); }); // Error stuff bot.on('error', (e) => console.error(cError(e))); bot.on('warn', (e) => console.warn(cWarn(e))); // Bot logging online bot.login(config.token); // Bot attempting to login if disconnected bot.on("disconnected", () => { console.log(cRed("Disconnected") + " from Discord"); botLogHook.send(`Disconnected from Discord on ${convertTime()}`); setTimeout(() => { console.log(cBlue("Attempting to log in...")); bot.login(config.token, (err, token) => { if (err) { console.log(err); setTimeout(() => { process.exit(1); }, 2000); } if (!token) { console.log(cWarn(" WARN ") + " failed to connect"); setTimeout(() => { process.exit(0); }, 2000); } console.log(cServer('Connection to Discord has been reestablished.')); }); }); }); // Converting time to a readable format function convertTime(timestamp) { if (timestamp) { timestamp = new Date(timestamp).toString() return timestamp } timestamp = new Date().toString() return timestamp } // send new guild information to the new guild channel function newServer(server, hook, criticalInfo) { function convertTime(timestamp) { timestamp = new Date(timestamp).toString() return timestamp } // send information to channel about a new server the bot has joined hook.send(`\n\n**New Server: ${criticalInfo.name}**\nServer ID: ${criticalInfo.id}\nServer Owner: ${criticalInfo.ownerName}\nServer Owner ID: ${criticalInfo.ownerID}\nHumans: ${criticalInfo.humanCount}\nBots: ${criticalInfo.botCount}\nJoined: ${convertTime(criticalInfo.joined)}`).then(message => console.log(cDebug(`\nSent message:\n${message.content}`))).catch(console.error); } // check if a guild's id exist function checkID(bot, id, location) { let servers = bot.guilds; if (location == 'blacklist') { if (banned.blacklist.includes(id)) { return true } else { return false } } else if (location == 'other') { for (let server of servers) { if (server.includes(id)) { return true } else { return false } } } } // check blacklist with guilds the bot // has joined and leave any if there's a match function checkBlacklist(bot, hook) { for (let guild of bot.guilds) { guild = guild[1]; let serverName = guild.name, serverID = guild.id, ownerID = guild.ownerID; if (banned.blacklist.includes(serverID)) { guild.leave(); return hook.send(`Removed Guild: ${serverName}!`).then(message => console.log(cDebug(`Sent message:\n${message.content}`))).catch(console.error); } } } // translating bot uptime function botUptime(milliseconds) { function numberEnding (number) { return (number > 1) ? 's' : ''; } var temp = Math.floor(milliseconds / 1000); var years = Math.floor(temp / 31536000); if (years) { return years + ' year' + numberEnding(years); } var days = Math.floor((temp %= 31536000) / 86400); if (days) { return days + ' day' + numberEnding(days); } var hours = Math.floor((temp %= 86400) / 3600); if (hours) { return hours + ' hour' + numberEnding(hours); } var minutes = Math.floor((temp %= 3600) / 60); if (minutes) { return minutes + ' minute' + numberEnding(minutes); } var seconds = temp % 60; if (seconds) { return seconds + ' second' + numberEnding(seconds); } return 'just now'; } // check if word submitted exists in the dictionary function checkWord(sorrows, w) { var l = ''; var word = w; var last = sorrows.length - 1; for (const sorrow of sorrows) { w = w.toUpperCase(); l = sorrow.title; l = l.toUpperCase(); if( word == sorrow.title || w == l ) { return true } } if (sorrows[last].title !== w) { return false } } // find and return one word with all information function singleWord(sorrows, w) { var word = w; var l = ''; for (let sorrow of sorrows) { w = w.toUpperCase(); l = sorrow.title.toUpperCase(); if (word == sorrow.title || w == l) { return sorrow } } } // find all words and return only their name function displayWords(sorrows) { var lexicon = ``; let i = 1; let j = 0; // init array var wordList = []; // adding words into array for (const sorrow of sorrows) { wordList.push(sorrow.title.toLocaleLowerCase()); } // sorting alphabetically wordList.sort(); // adding numbers for each word for (const word of wordList) { if (j !== (wordList.length - 1)) { lexicon += `${i}. ${word}\n`; j++ i++ } else { lexicon += `${i}. ${word}`; } } // display complete list when function is called return lexicon }
// Copyright (c) 2012 Titanium I.T. LLC. All rights reserved. See LICENSE.txt for details. /*global desc, task, jake, fail, complete, directory, require, console, process */ (function () { "use strict"; var lint = require("./build/util/lint_runner.js"); var karma = require("./build/util/karma_runner.js"); var version = require("./build/util/version_checker.js"); var TESTED_BROWSERS = [ // "IE 8.0 (Windows)", // DOES NOT WORK -- no SVG support // "IE 9.0 (Windows)", // DOES NOT WORK -- no Int32Array support and shim causes 'Out of memory' error "IE 10.0.0 (Windows 7)", "Firefox 36.0.0 (Mac OS X 10.10)", "Chrome 40.0.2214 (Mac OS X 10.10.2)", "Safari 8.0.3 (Mac OS X 10.10.2)", "Mobile Safari 7.0.0 (iOS 7.1)", "IE 11.0.0 (Windows 7)" ]; var NODE_VERSION = "v0.10.32"; var KARMA_CONFIG = "./build/config/karma.conf.js"; desc("Lint and test"); task("default", ["lint", "test"], function() { console.log("\n\nBUILD OK"); }); desc("Start Karma server -- run this first"); task("karma", function() { karma.serve(KARMA_CONFIG, complete, fail); }, {async: true}); desc("Start HTTP server for manual testing"); task("run", function() { jake.exec("node ./node_modules/http-server/bin/http-server ./src", { interactive: true }, complete); }, {async: true}); desc("Lint everything"); task("lint", ["nodeVersion"], function () { var passed = lint.validateFileList(nodeFilesToLint(), nodeLintOptions(), {}); passed = lint.validateFileList(browserFilesToLint(), browserLintOptions(), browserLintGlobals()) && passed; if (!passed) fail("Lint failed"); }); desc("Test browser code"); task("test", function() { karma.runTests({ configFile: KARMA_CONFIG, browsers: TESTED_BROWSERS, strict: true }, complete, fail); }, {async: true}); // desc("Ensure installed version of Node is same as known-good version"); task("nodeVersion", [], function() { var installedVersion = process.version; version.check("Node", !process.env.loose, NODE_VERSION, installedVersion, fail); }); function nodeFilesToLint() { var files = new jake.FileList(); files.include("build/util/**/*.js"); files.include("Jakefile.js"); return files.toArray(); } function browserFilesToLint() { var files = new jake.FileList(); files.include("src/*.js"); return files.toArray(); } function sharedLintOptions() { return { bitwise:true, curly:false, eqeqeq:true, forin:true, immed:true, latedef:false, newcap:true, noarg:true, noempty:true, nonew:true, regexp:true, undef:true, strict:true, trailing:true }; } function nodeLintOptions() { var options = sharedLintOptions(); options.node = true; return options; } function browserLintOptions() { var options = sharedLintOptions(); options.browser = true; return options; } function browserLintGlobals() { return { jdls: true, console: false, mocha: false, describe: false, it: false, expect: false, dump: false, beforeEach: false, afterEach: false }; } }());
//import Rx from 'rx'; import clone from 'clone'; /// concretizeConstructors transforms [Constructor] attributes on interfaces and dictionaries /// into {type: 'operation', name: 'constructor'} member nodes. export default function concretizeConstructors(astRoots: Rx.Observable): Rx.Observable { return astRoots.map(root => { var isCloned = false; function cloneOnce() { if (!isCloned) { root = clone(root); isCloned = true; } } if (root.type === 'interface' || root.type === 'dictionary') { var ctorAttrs = root.extAttrs .filter(attr => attr.name === 'Constructor'); if (ctorAttrs.length) { cloneOnce(); root.extAttrs = root.extAttrs.filter(attr => attr.name !== 'Constructor'); root.members.unshift(...ctorAttrs.map(attr => Object.assign({ type: 'operation' }, attr, { name: 'constructor', idlType: 'void', }))); } } return root; }); }
'use strict'; /** * @ngdoc function * @name beetlApp.factory:apiHandler * @description * # apiHandler * Factory of the beetlApp */ angular.module('beetlApp').factory('apiHandler', ['$http', function($http) { // Set standard content-type for all requests $http.defaults.headers.common['Content-Type'] = 'application/json'; // Prequisites var urlBase = 'http://beetl.blackroosteraudio.com:30123'; var apiHandler = {}; // Authentication apiHandler.login = function(objCredentials) { return $http.post(urlBase + '/auth/', objCredentials); }; // User management apiHandler.getUserList = function () { return $http.get(urlBase + '/user'); }; apiHandler.getUser = function (id) { return $http.get(urlBase + '/user/' + id); }; apiHandler.setUser = function (objUser) { return $http.post(urlBase + '/user/', objUser); }; apiHandler.updateUser = function (objUser) { return $http.put(urlBase + '/user/' + objUser._id, objUser); }; apiHandler.deleteUser = function (id) { return $http.delete(urlBase + '/user/' + id); }; // Catalogue Management apiHandler.getCatalogueList = function () { return $http.get(urlBase + '/catalogue'); }; apiHandler.getCatalogue = function (id) { return $http.get(urlBase + '/catalogue/' + id); }; apiHandler.setCatalogue = function () { return $http.post(urlBase + '/catalogue', { title : 'New Catalogue' }); }; apiHandler.updateCatalogue = function (objCatalogue) { return $http.put(urlBase + '/catalogue/' + objCatalogue._id, objCatalogue); }; apiHandler.deleteCatalogue = function (id) { return $http.delete(urlBase + '/catalogue/' + id); }; // Project Management apiHandler.getProjectList = function () { return $http.get(urlBase + '/project'); }; apiHandler.getProject = function (id) { return $http.get(urlBase + '/project/' + id); }; apiHandler.setProject = function () { return $http.post(urlBase + '/project', { title : 'New Project' }); }; apiHandler.updateProject = function (objProject) { return $http.put(urlBase + '/project/' + objProject._id, objProject); }; apiHandler.deleteProject = function (id) { return $http.delete(urlBase + '/project/' + id); }; // Result Management apiHandler.getResultList = function () { return $http.get(urlBase + '/result'); }; apiHandler.getResult = function (resultId) { return $http.get(urlBase + '/result/' + resultId); }; apiHandler.getResultByCatalogue = function (catalogueId) { return $http.get(urlBase + '/result/catalogue/' + catalogueId); }; apiHandler.setResult = function (objResult) { return $http.post(urlBase + '/result', objResult); }; apiHandler.updateResult = function (objResult) { return $http.put(urlBase + '/result/' + objResult._id, objResult); }; apiHandler.deleteResult = function (id) { return $http.delete(urlBase + '/result/' + id); }; return apiHandler; }]);
// Generated on 2014-12-23 using // generator-webapp 0.5.1 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // If you want to recursively match all subfolders, use: // 'test/spec/**/*.js' module.exports = function (grunt) { // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Configurable paths var config = { app: 'app', dist: 'dist' }; // Define the configuration for all the tasks grunt.initConfig({ // Project settings config: config, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['wiredep'] }, js: { files: ['<%= config.app %>/scripts/{,*/}*.js'], tasks: ['jshint'], options: { livereload: true } }, jstest: { files: ['test/spec/{,*/}*.js'], tasks: ['test:watch'] }, gruntfile: { files: ['Gruntfile.js'] }, styles: { files: ['<%= config.app %>/styles/{,*/}*.css'], tasks: ['newer:copy:styles', 'autoprefixer'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= config.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '<%= config.app %>/images/{,*/}*' ] } }, // The actual grunt server settings connect: { options: { port: 9000, open: true, livereload: 35729, // Change this to '0.0.0.0' to access the server from outside hostname: 'localhost' }, livereload: { options: { middleware: function(connect) { return [ connect.static('.tmp'), connect().use('/bower_components', connect.static('./bower_components')), connect.static(config.app) ]; } } }, test: { options: { open: false, port: 9001, middleware: function(connect) { return [ connect.static('.tmp'), connect.static('test'), connect().use('/bower_components', connect.static('./bower_components')), connect.static(config.app) ]; } } }, dist: { options: { base: '<%= config.dist %>', livereload: false } } }, // Empties folders to start fresh clean: { dist: { files: [{ dot: true, src: [ '.tmp', '<%= config.dist %>/*', '!<%= config.dist %>/.git*' ] }] }, server: '.tmp' }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= config.app %>/scripts/{,*/}*.js', '!<%= config.app %>/scripts/vendor/*', 'test/spec/{,*/}*.js' ] }, // Mocha testing framework configuration options mocha: { all: { options: { run: true, urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/index.html'] } } }, // Add vendor prefixed styles autoprefixer: { options: { browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1'] }, dist: { files: [{ expand: true, cwd: '.tmp/styles/', src: '{,*/}*.css', dest: '.tmp/styles/' }] } }, // Automatically inject Bower components into the HTML file wiredep: { app: { ignorePath: /^\/|\.\.\//, src: ['<%= config.app %>/index.html'], exclude: ['bower_components/bootstrap/dist/js/bootstrap.js'] } }, // Renames files for browser caching purposes rev: { dist: { files: { src: [ '<%= config.dist %>/scripts/{,*/}*.js', '<%= config.dist %>/styles/{,*/}*.css', '<%= config.dist %>/images/{,*/}*.*', '<%= config.dist %>/styles/fonts/{,*/}*.*', '<%= config.dist %>/*.{ico,png}' ] } } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { options: { dest: '<%= config.dist %>' }, html: '<%= config.app %>/index.html' }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { options: { assetsDirs: [ '<%= config.dist %>', '<%= config.dist %>/images', '<%= config.dist %>/styles' ] }, html: ['<%= config.dist %>/{,*/}*.html'], css: ['<%= config.dist %>/styles/{,*/}*.css'] }, // The following *-min tasks produce minified files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/images', src: '{,*/}*.{gif,jpeg,jpg,png}', dest: '<%= config.dist %>/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/images', src: '{,*/}*.svg', dest: '<%= config.dist %>/images' }] } }, htmlmin: { dist: { options: { collapseBooleanAttributes: true, collapseWhitespace: true, conservativeCollapse: true, removeAttributeQuotes: true, removeCommentsFromCDATA: true, removeEmptyAttributes: true, removeOptionalTags: true, removeRedundantAttributes: true, useShortDoctype: true }, files: [{ expand: true, cwd: '<%= config.dist %>', src: '{,*/}*.html', dest: '<%= config.dist %>' }] } }, // By default, your `index.html`'s <!-- Usemin block --> will take care // of minification. These next options are pre-configured if you do not // wish to use the Usemin blocks. // cssmin: { // dist: { // files: { // '<%= config.dist %>/styles/main.css': [ // '.tmp/styles/{,*/}*.css', // '<%= config.app %>/styles/{,*/}*.css' // ] // } // } // }, // uglify: { // dist: { // files: { // '<%= config.dist %>/scripts/scripts.js': [ // '<%= config.dist %>/scripts/scripts.js' // ] // } // } // }, // concat: { // dist: {} // }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= config.app %>', dest: '<%= config.dist %>', src: [ '*.{ico,png,txt}', 'images/{,*/}*.webp', '{,*/}*.html', 'styles/fonts/{,*/}*.*' ] }, { src: 'node_modules/apache-server-configs/dist/.htaccess', dest: '<%= config.dist %>/.htaccess' }, { expand: true, dot: true, cwd: 'bower_components/bootstrap/dist', src: 'fonts/*', dest: '<%= config.dist %>' }] }, styles: { expand: true, dot: true, cwd: '<%= config.app %>/styles', dest: '.tmp/styles/', src: '{,*/}*.css' } }, // Run some tasks in parallel to speed up build process concurrent: { server: [ 'copy:styles' ], test: [ 'copy:styles' ], dist: [ 'copy:styles', 'imagemin', 'svgmin' ] } }); grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) { if (grunt.option('allow-remote')) { grunt.config.set('connect.options.hostname', '0.0.0.0'); } if (target === 'dist') { return grunt.task.run(['build', 'connect:dist:keepalive']); } grunt.task.run([ 'clean:server', 'wiredep', 'concurrent:server', 'autoprefixer', 'connect:livereload', 'watch' ]); }); grunt.registerTask('server', function (target) { grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.'); grunt.task.run([target ? ('serve:' + target) : 'serve']); }); grunt.registerTask('test', function (target) { if (target !== 'watch') { grunt.task.run([ 'clean:server', 'concurrent:test', 'autoprefixer' ]); } grunt.task.run([ 'connect:test', 'mocha' ]); }); grunt.registerTask('build', [ 'clean:dist', 'wiredep', 'useminPrepare', 'concurrent:dist', 'autoprefixer', 'concat', 'cssmin', 'uglify', 'copy:dist', 'rev', 'usemin', 'htmlmin' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); };
var ctrl = new Meteoris.ThemeAdminController(); Template.meteoris_themeAdminMain.onCreated(function() { var self = this; self.autorun(function() { self.subscribe('meteoris_themeAdmin', ctrl.getId()); }); }); Template.meteoris_themeAdminMain.helpers({ model: function(){ return ctrl.main().model; }, });
// Load modules var Bluebird = require('bluebird'); var CatboxMemory = require('catbox-memory'); var Code = require('code'); var Hapi = require('..'); var Lab = require('lab'); // Declare internals var internals = {}; // Test shortcuts var lab = exports.lab = Lab.script(); var describe = lab.describe; var it = lab.it; var expect = Code.expect; describe('Methods', function () { it('registers a method', function (done) { var add = function (a, b, next) { return next(null, a + b); }; var server = new Hapi.Server(); server.method('add', add); server.methods.add(1, 5, function (err, result) { expect(result).to.equal(6); done(); }); }); it('registers a method with leading _', function (done) { var _add = function (a, b, next) { return next(null, a + b); }; var server = new Hapi.Server(); server.method('_add', _add); server.methods._add(1, 5, function (err, result) { expect(result).to.equal(6); done(); }); }); it('registers a method with leading $', function (done) { var $add = function (a, b, next) { return next(null, a + b); }; var server = new Hapi.Server(); server.method('$add', $add); server.methods.$add(1, 5, function (err, result) { expect(result).to.equal(6); done(); }); }); it('registers a method with _', function (done) { var _add = function (a, b, next) { return next(null, a + b); }; var server = new Hapi.Server(); server.method('add_._that', _add); server.methods.add_._that(1, 5, function (err, result) { expect(result).to.equal(6); done(); }); }); it('registers a method with $', function (done) { var $add = function (a, b, next) { return next(null, a + b); }; var server = new Hapi.Server(); server.method('add$.$that', $add); server.methods.add$.$that(1, 5, function (err, result) { expect(result).to.equal(6); done(); }); }); it('registers a method (no callback)', function (done) { var add = function (a, b) { return a + b; }; var server = new Hapi.Server(); server.method('add', add, { callback: false }); expect(server.methods.add(1, 5)).to.equal(6); done(); }); it('registers a method (promise)', function (done) { var addAsync = function (a, b, next) { return next(null, a + b); }; var add = Bluebird.promisify(addAsync); var server = new Hapi.Server(); server.method('add', add, { callback: false }); server.methods.add(1, 5).then(function (result) { expect(result).to.equal(6); done(); }); }); it('registers a method with nested name', function (done) { var add = function (a, b, next) { return next(null, a + b); }; var server = new Hapi.Server(); server.connection(); server.method('tools.add', add); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.tools.add(1, 5, function (err, result) { expect(result).to.equal(6); done(); }); }); }); it('registers a method with bind and callback', function (done) { var server = new Hapi.Server(); server.connection(); var context = { name: 'Bob' }; server.method('user', function (id, next) { return next(null, { id: id, name: this.name }); }, { bind: context }); server.route({ method: 'GET', path: '/user/{id}', config: { pre: [ 'user(params.id)' ], handler: function (request, reply) { return reply(request.pre.user); } } }); server.inject('/user/5', function (res) { expect(res.result).to.deep.equal({ id: '5', name: 'Bob' }); done(); }); }); it('registers two methods with shared nested name', function (done) { var add = function (a, b, next) { return next(null, a + b); }; var sub = function (a, b, next) { return next(null, a - b); }; var server = new Hapi.Server(); server.connection(); server.method('tools.add', add); server.method('tools.sub', sub); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.tools.add(1, 5, function (err, result1) { expect(result1).to.equal(6); server.methods.tools.sub(1, 5, function (err, result2) { expect(result2).to.equal(-4); done(); }); }); }); }); it('throws when registering a method with nested name twice', function (done) { var add = function (a, b, next) { return next(null, a + b); }; var server = new Hapi.Server(); server.method('tools.add', add); expect(function () { server.method('tools.add', add); }).to.throw('Server method function name already exists: tools.add'); done(); }); it('throws when registering a method with name nested through a function', function (done) { var add = function (a, b, next) { return next(null, a + b); }; var server = new Hapi.Server(); server.method('add', add); expect(function () { server.method('add.another', add); }).to.throw('Invalid segment another in reach path add.another'); done(); }); it('calls non cached method multiple times', function (done) { var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: gen++ }); }; var server = new Hapi.Server(); server.connection(); server.method('test', method); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(result1.gen).to.equal(0); server.methods.test(1, function (err, result2) { expect(result2.gen).to.equal(1); done(); }); }); }); }); it('caches method value', function (done) { var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: gen++ }); }; var server = new Hapi.Server(); server.connection(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(err).to.not.exist(); expect(result1.gen).to.equal(0); server.methods.test(1, function (err, result2) { expect(err).to.not.exist(); expect(result2.gen).to.equal(0); done(); }); }); }); }); it('caches method value (no callback)', function (done) { var gen = 0; var method = function (id) { return { id: id, gen: gen++ }; }; var server = new Hapi.Server(); server.connection(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 }, callback: false }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(err).to.not.exist(); expect(result1.gen).to.equal(0); server.methods.test(1, function (err, result2) { expect(err).to.not.exist(); expect(result2.gen).to.equal(0); done(); }); }); }); }); it('caches method value (promise)', function (done) { var gen = 0; var methodAsync = function (id, next) { if (id === 2) { return next(new Error('boom')); } return next(null, { id: id, gen: gen++ }); }; var method = Bluebird.promisify(methodAsync); var server = new Hapi.Server(); server.connection(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 }, callback: false }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(err).to.not.exist(); expect(result1.gen).to.equal(0); server.methods.test(1, function (err, result2) { expect(err).to.not.exist(); expect(result2.gen).to.equal(0); server.methods.test(2, function (err, result3) { expect(err).to.exist(); expect(err.message).to.equal('boom'); done(); }); }); }); }); }); it('reuses cached method value with custom key function', function (done) { var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: gen++ }); }; var server = new Hapi.Server(); server.connection(); var generateKey = function (id) { return '' + (id + 1); }; server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 }, generateKey: generateKey }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(result1.gen).to.equal(0); server.methods.test(1, function (err, result2) { expect(result2.gen).to.equal(0); done(); }); }); }); }); it('errors when custom key function return null', function (done) { var method = function (id, next) { return next(null, { id: id }); }; var server = new Hapi.Server(); server.connection(); var generateKey = function (id) { return null; }; server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 }, generateKey: generateKey }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result) { expect(err).to.exist(); expect(err.message).to.equal('Invalid method key when invoking: test'); done(); }); }); }); it('does not cache when custom key function returns a non-string', function (done) { var method = function (id, next) { return next(null, { id: id }); }; var server = new Hapi.Server(); server.connection(); var generateKey = function (id) { return 123; }; server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 }, generateKey: generateKey }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result) { expect(err).to.exist(); expect(err.message).to.equal('Invalid method key when invoking: test'); done(); }); }); }); it('does not cache value when ttl is 0', function (done) { var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: gen++ }, 0); }; var server = new Hapi.Server(); server.connection(); server.method('test', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(result1.gen).to.equal(0); server.methods.test(1, function (err, result2) { expect(result2.gen).to.equal(1); done(); }); }); }); }); it('generates new value after cache drop', function (done) { var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: gen++ }); }; var server = new Hapi.Server(); server.connection(); server.method('dropTest', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.dropTest(2, function (err, result1) { expect(result1.gen).to.equal(0); server.methods.dropTest.cache.drop(2, function (err) { expect(err).to.not.exist(); server.methods.dropTest(2, function (err, result2) { expect(result2.gen).to.equal(1); done(); }); }); }); }); }); it('errors on invalid drop key', function (done) { var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: gen++ }); }; var server = new Hapi.Server(); server.connection(); server.method('dropErrTest', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.dropErrTest.cache.drop(function () { }, function (err) { expect(err).to.exist(); done(); }); }); }); it('throws an error when name is not a string', function (done) { expect(function () { var server = new Hapi.Server(); server.method(0, function () { }); }).to.throw('name must be a string'); done(); }); it('throws an error when name is invalid', function (done) { expect(function () { var server = new Hapi.Server(); server.method('0', function () { }); }).to.throw('Invalid name: 0'); expect(function () { var server = new Hapi.Server(); server.method('a..', function () { }); }).to.throw('Invalid name: a..'); expect(function () { var server = new Hapi.Server(); server.method('a.0', function () { }); }).to.throw('Invalid name: a.0'); expect(function () { var server = new Hapi.Server(); server.method('.a', function () { }); }).to.throw('Invalid name: .a'); done(); }); it('throws an error when method is not a function', function (done) { expect(function () { var server = new Hapi.Server(); server.method('user', 'function'); }).to.throw('method must be a function'); done(); }); it('throws an error when options is not an object', function (done) { expect(function () { var server = new Hapi.Server(); server.method('user', function () { }, 'options'); }).to.throw(/Invalid method options \(user\)/); done(); }); it('throws an error when options.generateKey is not a function', function (done) { expect(function () { var server = new Hapi.Server(); server.method('user', function () { }, { generateKey: 'function' }); }).to.throw(/Invalid method options \(user\)/); done(); }); it('throws an error when options.cache is not valid', function (done) { expect(function () { var server = new Hapi.Server({ cache: CatboxMemory }); server.method('user', function () { }, { cache: { x: 'y', generateTimeout: 10 } }); }).to.throw(/Invalid cache policy configuration/); done(); }); it('throws an error when genreateTimeout is not present', function (done) { var server = new Hapi.Server(); expect(function () { server.method('test', function () { }, { cache: {} }); }).to.throw('Method caching requires a timeout value in generateTimeout: test'); done(); }); it('allows genreateTimeout to be false', function (done) { var server = new Hapi.Server(); expect(function () { server.method('test', function () { }, { cache: { generateTimeout: false } }); }).to.throw('Method caching requires a timeout value in generateTimeout: test'); done(); }); it('returns a valid result when calling a method without using the cache', function (done) { var server = new Hapi.Server(); var method = function (id, next) { return next(null, { id: id }); }; server.method('user', method); server.methods.user(4, function (err, result) { expect(result.id).to.equal(4); done(); }); }); it('returns a valid result when calling a method when using the cache', function (done) { var server = new Hapi.Server(); server.connection(); server.initialize(function (err) { expect(err).to.not.exist(); var method = function (id, str, next) { return next(null, { id: id, str: str }); }; server.method('user', method, { cache: { expiresIn: 1000, generateTimeout: 10 } }); server.methods.user(4, 'something', function (err, result) { expect(result.id).to.equal(4); expect(result.str).to.equal('something'); done(); }); }); }); it('returns an error result when calling a method that returns an error', function (done) { var server = new Hapi.Server(); var method = function (id, next) { return next(new Error()); }; server.method('user', method); server.methods.user(4, function (err, result) { expect(err).to.exist(); done(); }); }); it('returns a different result when calling a method without using the cache', function (done) { var server = new Hapi.Server(); var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: ++gen }); }; server.method('user', method); server.methods.user(4, function (err, result1) { expect(result1.id).to.equal(4); expect(result1.gen).to.equal(1); server.methods.user(4, function (err, result2) { expect(result2.id).to.equal(4); expect(result2.gen).to.equal(2); done(); }); }); }); it('returns a valid result when calling a method using the cache', function (done) { var server = new Hapi.Server({ cache: CatboxMemory }); server.connection(); var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: ++gen }); }; server.method('user', method, { cache: { expiresIn: 2000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); var id = Math.random(); server.methods.user(id, function (err, result1) { expect(result1.id).to.equal(id); expect(result1.gen).to.equal(1); server.methods.user(id, function (err, result2) { expect(result2.id).to.equal(id); expect(result2.gen).to.equal(1); done(); }); }); }); }); it('returns timeout when method taking too long using the cache', function (done) { var server = new Hapi.Server({ cache: CatboxMemory }); server.connection(); var gen = 0; var method = function (id, next) { setTimeout(function () { return next(null, { id: id, gen: ++gen }); }, 5); }; server.method('user', method, { cache: { expiresIn: 2000, generateTimeout: 3 } }); server.initialize(function (err) { expect(err).to.not.exist(); var id = Math.random(); server.methods.user(id, function (err, result1) { expect(err.output.statusCode).to.equal(503); setTimeout(function () { server.methods.user(id, function (err, result2) { expect(result2.id).to.equal(id); expect(result2.gen).to.equal(1); done(); }); }, 3); }); }); }); it('supports empty key method', function (done) { var server = new Hapi.Server({ cache: CatboxMemory }); server.connection(); var gen = 0; var terms = 'I agree to give my house'; var method = function (next) { return next(null, { gen: gen++, terms: terms }); }; server.method('tos', method, { cache: { expiresIn: 2000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.tos(function (err, result1) { expect(result1.terms).to.equal(terms); expect(result1.gen).to.equal(0); server.methods.tos(function (err, result2) { expect(result2.terms).to.equal(terms); expect(result2.gen).to.equal(0); done(); }); }); }); }); it('returns valid results when calling a method (with different keys) using the cache', function (done) { var server = new Hapi.Server({ cache: CatboxMemory }); server.connection(); var gen = 0; var method = function (id, next) { return next(null, { id: id, gen: ++gen }); }; server.method('user', method, { cache: { expiresIn: 2000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); var id1 = Math.random(); server.methods.user(id1, function (err, result1) { expect(result1.id).to.equal(id1); expect(result1.gen).to.equal(1); var id2 = Math.random(); server.methods.user(id2, function (err, result2) { expect(result2.id).to.equal(id2); expect(result2.gen).to.equal(2); done(); }); }); }); }); it('errors when key generation fails', function (done) { var server = new Hapi.Server({ cache: CatboxMemory }); server.connection(); var method = function (id, next) { return next(null, { id: id }); }; server.method([{ name: 'user', method: method, options: { cache: { expiresIn: 2000, generateTimeout: 10 } } }]); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.user(1, function (err, result1) { expect(result1.id).to.equal(1); server.methods.user(function () { }, function (err, result2) { expect(err).to.exist(); expect(err.message).to.equal('Invalid method key when invoking: user'); done(); }); }); }); }); it('sets method bind without cache', function (done) { var method = function (id, next) { return next(null, { id: id, gen: this.gen++ }); }; var server = new Hapi.Server(); server.connection(); server.method('test', method, { bind: { gen: 7 } }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(result1.gen).to.equal(7); server.methods.test(1, function (err, result2) { expect(result2.gen).to.equal(8); done(); }); }); }); }); it('sets method bind with cache', function (done) { var method = function (id, next) { return next(null, { id: id, gen: this.gen++ }); }; var server = new Hapi.Server(); server.connection(); server.method('test', method, { bind: { gen: 7 }, cache: { expiresIn: 1000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(result1.gen).to.equal(7); server.methods.test(1, function (err, result2) { expect(result2.gen).to.equal(7); done(); }); }); }); }); it('shallow copies bind config', function (done) { var bind = { gen: 7 }; var method = function (id, next) { return next(null, { id: id, gen: this.gen++, bound: (this === bind) }); }; var server = new Hapi.Server(); server.connection(); server.method('test', method, { bind: bind, cache: { expiresIn: 1000, generateTimeout: 10 } }); server.initialize(function (err) { expect(err).to.not.exist(); server.methods.test(1, function (err, result1) { expect(result1.gen).to.equal(7); expect(result1.bound).to.equal(true); server.methods.test(1, function (err, result2) { expect(result2.gen).to.equal(7); done(); }); }); }); }); describe('_add()', function () { it('normalizes no callback into callback (direct)', function (done) { var add = function (a, b) { return a + b; }; var server = new Hapi.Server(); server.method('add', add, { callback: false }); var result = server.methods.add(1, 5); expect(result).to.equal(6); done(); }); it('normalizes no callback into callback (direct error)', function (done) { var add = function (a, b) { return new Error('boom'); }; var server = new Hapi.Server(); server.method('add', add, { callback: false }); var result = server.methods.add(1, 5); expect(result).to.be.instanceof(Error); expect(result.message).to.equal('boom'); done(); }); it('normalizes no callback into callback (direct throw)', function (done) { var add = function (a, b) { throw new Error('boom'); }; var server = new Hapi.Server(); server.method('add', add, { callback: false }); expect(function () { server.methods.add(1, 5); }).to.throw('boom'); done(); }); it('normalizes no callback into callback (normalized)', function (done) { var add = function (a, b) { return a + b; }; var server = new Hapi.Server(); server.method('add', add, { callback: false }); server._methods._normalized.add(1, 5, function (err, result) { expect(result).to.equal(6); done(); }); }); it('normalizes no callback into callback (normalized error)', function (done) { var add = function (a, b) { return new Error('boom'); }; var server = new Hapi.Server(); server.method('add', add, { callback: false }); server._methods._normalized.add(1, 5, function (err, result) { expect(err).to.exist(); expect(err.message).to.equal('boom'); done(); }); }); it('normalizes no callback into callback (normalized throw)', function (done) { var add = function (a, b) { throw new Error('boom'); }; var server = new Hapi.Server(); server.method('add', add, { callback: false }); server._methods._normalized.add(1, 5, function (err, result) { expect(err).to.exist(); expect(err.message).to.equal('boom'); done(); }); }); }); it('normalizes no callback into callback (cached)', function (done) { var add = function (a, b) { return a + b; }; var server = new Hapi.Server(); server.method('add', add, { cache: { expiresIn: 10, generateTimeout: 10 }, callback: false }); server._methods._normalized.add(1, 5, function (err, result) { expect(result).to.equal(6); done(); }); }); it('normalizes no callback into callback (cached error)', function (done) { var add = function (a, b) { return new Error('boom'); }; var server = new Hapi.Server(); server.method('add', add, { cache: { expiresIn: 10, generateTimeout: 10 }, callback: false }); server._methods._normalized.add(1, 5, function (err, result) { expect(err).to.exist(); expect(err.message).to.equal('boom'); done(); }); }); it('normalizes no callback into callback (cached throw)', function (done) { var add = function (a, b) { throw new Error('boom'); }; var server = new Hapi.Server(); server.method('add', add, { cache: { expiresIn: 10, generateTimeout: 10 }, callback: false }); server._methods._normalized.add(1, 5, function (err, result) { expect(err).to.exist(); expect(err.message).to.equal('boom'); done(); }); }); it('throws an error if unknown keys are present when making a server method using an object', function (done) { var fn = function () { }; var server = new Hapi.Server(); expect(function () { server.method({ name: 'fn', method: fn, cache: {} }); }).to.throw(); done(); }); });
import { BasePlugin } from '../../../src/index'; import React, {Component} from 'react'; // eslint-disable-line no-unused-vars import ImageRenderer from './image-renderer'; import InsertImage from './insert-image'; import ImageSerializer from './image-serializer'; /** * This is our plugin */ class AltImagePlugin extends BasePlugin { constructor(config) { config.uiComponents = [{component: InsertImage, type: 'block-image'}]; config.renderComponentsDescriptors = [{component: ImageRenderer, type: 'block-image', outerElement: 'span'}]; config.serializers = [new ImageSerializer()]; config.theme = { imageWrapper: 'imageWrapper', imageLoader: 'imageLoader', image: 'image' }; super(config); } } export default AltImagePlugin;
/** * Ladder library * Pokemon Showdown - http://pokemonshowdown.com/ * * This file handles ladders. * * @license MIT license */ 'use strict'; let Ladders = module.exports = getLadder; const fs = require('fs'); function getLadder(formatid) { return new Ladder(formatid); } // tells the client to ask the server for format information Ladders.formatsListPrefix = '|,LL'; // ladderCaches = {formatid: ladder OR Promise(ladder)} // Use Ladders(formatid).ladder to guarantee a Promise(ladder). // ladder is basically a 2D array representing the corresponding ladder.tsv // with userid in front // ladder = [[userid, elo, username, w, l, t]] let ladderCaches = Ladders.ladderCaches = Object.create(null); function Ladder(formatid) { this.formatid = toId(formatid); this.loadedLadder = null; this.ladder = this.load(); } Ladder.prototype.load = function () { // ladderCaches[formatid] if (this.formatid in ladderCaches) { let cachedLadder = ladderCaches[this.formatid]; if (cachedLadder.then) { let self = this; return cachedLadder.then(function (ladder) { self.loadedLadder = ladder; return ladder; }); } else { return Promise.resolve(this.loadedLadder = cachedLadder); } } let self = this; return (ladderCaches[this.formatid] = new Promise(function (resolve, reject) { fs.readFile('config/ladders/' + self.formatid + '.tsv', function (err, data) { if (err) { self.loadedLadder = ladderCaches[self.formatid] = []; console.log('Ladders(' + self.formatid + ') err loading tsv: ' + JSON.stringify(self.loadedLadder)); resolve(self.loadedLadder); return; } let ladder = []; let dataLines = ('' + data).split('\n'); for (let i = 1; i < dataLines.length; i++) { let line = dataLines[i].trim(); if (!line) continue; let row = line.split('\t'); ladder.push([toId(row[1]), Number(row[0]), row[1], Number(row[2]), Number(row[3]), Number(row[4]), row[5]]); } self.loadedLadder = ladderCaches[self.formatid] = ladder; console.log('Ladders(' + self.formatid + ') loaded tsv: ' + JSON.stringify(self.loadedLadder)); resolve(self.loadedLadder); }); })); }; Ladder.prototype.save = function () { if (this.saving) return; this.saving = true; if (!this.loadedLadder) { let self = this; this.ladder.then(function () { self.save(); }); return; } if (!this.loadedLadder.length) { this.saving = false; return; } let stream = fs.createWriteStream('config/ladders/' + this.formatid + '.tsv'); stream.write('Elo\tUsername\tW\tL\tT\tLast update\r\n'); for (let i = 0; i < this.loadedLadder.length; i++) { let row = this.loadedLadder[i]; stream.write(row.slice(1).join('\t') + '\r\n'); } stream.end(); this.saving = false; }; Ladder.prototype.indexOfUser = function (username, createIfNeeded) { let userid = toId(username); for (let i = 0; i < this.loadedLadder.length; i++) { if (this.loadedLadder[i][0] === userid) return i; } if (createIfNeeded) { let index = this.loadedLadder.length; this.loadedLadder.push([userid, 1000, username, 0, 0, 0]); return index; } return -1; }; Ladder.prototype.getTop = function () { let formatid = this.formatid; let name = Tools.getFormat(formatid).name; return this.ladder.then(function (ladder) { let buf = '<h3>' + name + ' Top 100</h3>'; buf += '<table>'; buf += '<tr><th>' + ['', 'Username', '<abbr title="Elo rating">Elo</abbr>', 'W', 'L', 'T'].join('</th><th>') + '</th></tr>'; for (let i = 0; i < ladder.length; i++) { let row = ladder[i]; buf += '<tr><td>' + [ i + 1, row[2], '<strong>' + Math.round(row[1]) + '</strong>', row[3], row[4], row[5] ].join('</td><td>') + '</td></tr>'; } return [formatid, buf]; }); }; Ladder.prototype.getRating = function (userid) { let formatid = this.formatid; let user = Users.getExact(userid); if (user && user.mmrCache[formatid]) { return Promise.resolve(user.mmrCache[formatid]); } let self = this; return this.ladder.then(function () { if (user.userid !== userid) return; let index = self.indexOfUser(userid); if (index < 0) return (user.mmrCache[formatid] = 1000); return (user.mmrCache[formatid] = self.loadedLadder[index][1]); }); }; Ladder.prototype.updateRow = function (row, score, foeElo) { let elo = row[1]; // The K factor determines how much your Elo changes when you win or // lose games. Larger K means more change. // In the "original" Elo, K is constant, but it's common for K to // get smaller as your rating goes up let K = 50; // dynamic K-scaling (optional) if (elo < 1200) { if (score < 0.5) { K = 10 + (elo - 1000) * 40 / 200; } else if (score > 0.5) { K = 90 - (elo - 1000) * 40 / 200; } } else if (elo > 1350) { K = 40; } else if (elo > 1600) { K = 32; } // main Elo formula let E = 1 / (1 + Math.pow(10, (foeElo - elo) / 400)); elo += K * (score - E); if (elo < 1000) elo = 1000; row[1] = elo; if (score > 0.6) { row[3]++; // win } else if (score < 0.4) { row[4]++; // loss } else { row[5]++; // tie } row[6] = '' + new Date(); }; Ladder.prototype.updateRating = function (p1name, p2name, p1score, room) { let formatid = this.formatid; let self = this; this.ladder.then(function () { if (!room.battle) { console.log('room expired before ladder update was received'); return; } let p1newElo, p2newElo; try { let p1index = self.indexOfUser(p1name, true); let p1elo = self.loadedLadder[p1index][1]; let p2index = self.indexOfUser(p2name, true); let p2elo = self.loadedLadder[p2index][1]; self.updateRow(self.loadedLadder[p1index], p1score, p2elo); self.updateRow(self.loadedLadder[p2index], 1 - p1score, p1elo); p1newElo = self.loadedLadder[p1index][1]; p2newElo = self.loadedLadder[p2index][1]; // console.log('L: ' + self.loadedLadder.map(r => ''+Math.round(r[1])+' '+r[2]).join('\n')); // move p1 to its new location let newIndex = p1index; while (newIndex > 0 && self.loadedLadder[newIndex - 1][1] <= p1newElo) newIndex--; while (newIndex === p1index || (self.loadedLadder[newIndex] && self.loadedLadder[newIndex][1] > p1newElo)) newIndex++; // console.log('ni='+newIndex+', p1i='+p1index); if (newIndex !== p1index && newIndex !== p1index + 1) { let row = self.loadedLadder.splice(p1index, 1)[0]; // adjust for removed row if (newIndex > p1index) newIndex--; if (p2index > p1index) p2index--; self.loadedLadder.splice(newIndex, 0, row); // adjust for inserted row if (p2index >= newIndex) p2index++; } // move p2 newIndex = p2index; while (newIndex > 0 && self.loadedLadder[newIndex - 1][1] <= p2newElo) newIndex--; while (newIndex === p2index || (self.loadedLadder[newIndex] && self.loadedLadder[newIndex][1] > p2newElo)) newIndex++; // console.log('ni='+newIndex+', p2i='+p2index); if (newIndex !== p2index && newIndex !== p2index + 1) { let row = self.loadedLadder.splice(p2index, 1)[0]; // adjust for removed row if (newIndex > p2index) newIndex--; self.loadedLadder.splice(newIndex, 0, row); } let reasons = '' + (Math.round(p1newElo) - Math.round(p1elo)) + ' for ' + (p1score > 0.9 ? 'winning' : (p1score < 0.1 ? 'losing' : 'tying')); if (reasons.charAt(0) !== '-') reasons = '+' + reasons; room.addRaw(Tools.escapeHTML(p1name) + '\'s rating: ' + Math.round(p1elo) + ' &rarr; <strong>' + Math.round(p1newElo) + '</strong><br />(' + reasons + ')'); reasons = '' + (Math.round(p2newElo) - Math.round(p2elo)) + ' for ' + (p1score > 0.9 ? 'losing' : (p1score < 0.1 ? 'winning' : 'tying')); if (reasons.charAt(0) !== '-') reasons = '+' + reasons; room.addRaw(Tools.escapeHTML(p2name) + '\'s rating: ' + Math.round(p2elo) + ' &rarr; <strong>' + Math.round(p2newElo) + '</strong><br />(' + reasons + ')'); let p1 = Users.getExact(p1name); if (p1) p1.mmrCache[formatid] = +p1newElo; let p2 = Users.getExact(p2name); if (p2) p2.mmrCache[formatid] = +p2newElo; self.save(); room.update(); } catch (e) { room.addRaw('There was an error calculating rating changes:'); room.add(e.stack); room.update(); } if (!Tools.getFormat(formatid).noLog) { room.logBattle(p1score, p1newElo, p2newElo); } }); };
import * as workITypes from 'src/workI/store/mutation-types' import * as dashTypes from 'src/dash/store/mutation-types' import workI from 'src/workI/api' import swal from 'sweetalert' import store from 'src/store' export default { state: { indexDisp: true, detailDisp: false, workI: [{}], workIDetail: [[{}]] }, getters: { [workITypes.GET_WORKI_INDEX_DISP] (state) { return state.indexDisp }, [workITypes.GET_WORKI_DETAIL_DISP] (state) { return state.detailDisp }, [workITypes.GET_WORKI] (state) { return state.workI }, [workITypes.GET_WORKI_DETAIL] (state) { return state.workIDetail } }, mutations: { [workITypes.SET_WORKI_TOGGLE_PAGE] (state, page) { state.indexDisp = false state.detailDisp = false switch (page) { case 'index': state.indexDisp = true break case 'detail': state.detailDisp = true break default: state.indexDisp = true break } }, [workITypes.SET_WORKI] (state, workI) { state.workI = workI }, [workITypes.SET_WORKI_DETAIL] (state, workIDetail) { state.workIDetail = workIDetail } }, actions: { [workITypes.RECEIVED_WORKI] ({ commit }) { store.commit(dashTypes.SET_DASH_BODY_LOADING, true) workI.getWorkI() .then((response) => { const data = JSON.parse(response.request.response) commit(workITypes.SET_WORKI, data) store.commit(dashTypes.SET_DASH_BODY_LOADING, false) }) .catch((error) => { const data = error.response.data swal({title: '', text: data.response, html: true, type: 'error'}) }) }, [workITypes.RECEIVED_WORKI_DETAIL] ({ commit }, folder) { store.commit(dashTypes.SET_DASH_BODY_LOADING, true) workI.getWorkIDetail(folder) .then((response) => { const data = JSON.parse(response.request.response) commit(workITypes.SET_WORKI_DETAIL, data) store.commit(dashTypes.SET_DASH_BODY_LOADING, false) }) .catch((error) => { const data = error.response.data swal({title: '', text: data.response, html: true, type: 'error'}) }) } } }
const path = require('path'); const webpack = require('webpack'); const ExtractTextPlugin=require('extract-text-webpack-plugin'); module.exports = { devtool:'source-map', context: path.resolve(__dirname,'..'), entry: { app: ['./src/index.js'], }, output: { path: path.join(__dirname,'..','dist'), filename: '[name].bundle.js', publicPath: '/', }, module: { loaders: [ { test: /\.(js|jsx)?$/, exclude: /node_modules/, loader: 'babel', }, { test: /\.css$/, loader:ExtractTextPlugin.extract('style-loader','css-loader'), }, {test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'file-loader?name=fonts/[name].[ext]&mimetype=application/octet-stream'} ], }, progress: true, resolve: { modulesDirectories: [ 'node_modules', 'src', ], extensions: ['', '.json', '.js', '.jsx'], }, plugins: [ new webpack.DefinePlugin({ 'process.env': { 'NODE_ENV': JSON.stringify('production'), 'API':'https://universal-redux-excel.herokuapp.com' }, }), new webpack.optimize.DedupePlugin(), new webpack.optimize.OccurenceOrderPlugin(), new ExtractTextPlugin('[name].css', { allChunks: true, }), ], };
(function ($, window, document, undefined) { 'use strict'; $(function () { var obj = $('html'); $('.js .menu-open').on('click', function(){ if (obj.hasClass('js-menu-open')) { obj.removeClass('js-menu-open'); } else { obj.addClass('js-menu-open'); } return false; }); }); })(jQuery, window, document);
var Worker = require("workerjs"); var path = require("path"); exports.test = function(notUsed, assert, done) { var target = process.argv[2]; var file = target ? "sql-"+target : "sql"; var worker = new Worker(path.join(__dirname, "../js/worker."+file+".js")); worker.onmessage = function(event) { var data = event.data; assert.strictEqual(data.id, 1, "Return the given id in the correct format"); assert.deepEqual(data, {id:1, ready:true}, 'Correct data answered to the "open" query'); worker.onmessage = function(event) { var data = event.data; assert.strictEqual(data.id, 2, "Correct id"); var results = data.results; assert.strictEqual(Array.isArray(results), true, 'Correct result type'); var row = results[0]; assert.strictEqual(typeof row, 'object', 'Type of the returned row'); assert.deepEqual(row.columns, ['num', 'str', 'hex'], 'Reading column names'); assert.strictEqual(row.values[0][0], 1, 'Reading number'); assert.strictEqual(row.values[0][1], 'a', 'Reading string'); assert.deepEqual(Array.from(row.values[0][2]), [0x00, 0x42], 'Reading BLOB'); worker.onmessage = function(event) { var data = event.data; if (!data.finished) { data.row.hex = Array.from(data.row.hex); assert.deepEqual(data.row, {num:1, str:'a', hex: [0x00, 0x42]}, "Read row from db.each callback"); } else { worker.onmessage = function(event, a) { var data = event.data; buffer = [] for(var p in data.buffer) { buffer += data.buffer[p] } assert.equal(typeof buffer.length, 'number', 'Export returns data'); assert.notEqual(buffer.length, 0, 'Data returned is not empty'); done(); } worker.postMessage({action:'export'}); } } worker.postMessage ({ action: 'each', sql: 'SELECT * FROM test' }) } var sqlstr = "CREATE TABLE test (num, str, hex);"; sqlstr += "INSERT INTO test VALUES (1, 'a', x'0042');"; sqlstr += "SELECT * FROM test;"; worker.postMessage({ id: 2, action: 'exec', sql: sqlstr }); } worker.onerror = function (e) { console.log("Threw error: ", e); assert.fail(new Error(e),null,"Sould not throw an error"); done(); } worker.postMessage({id:1, action: 'open'}); setTimeout(function ontimeout (){ assert.fail(new Error("Worker should answer in less than 3 seconds")); done(); }, 3000); } if (!Array.from) { Array.from = function(pseudoarray) { return Array.prototype.slice.call(pseudoarray); }; } if (module == require.main) { var assert = require("assert"); var done = function(){process.exit(0)}; exports.test(null, assert, done); }
define("ui", [], function() { var views = {}; var overlays = {}; var ready = false; var ready_callbacks = []; function renderTemplate(id, data) { data = data || {}; var text = $('script[type="text/template"]#' + id).text(); return text.replace(/{{(.+?)}}/g, function(_, name) { return data[name]; }); } function init() { $('.view').addClass('container'); $(document).on('click', '.view a, .view button', function(e) { if (($(this).attr('href') || '').indexOf('#') == 0) { e.preventDefault(); e.stopPropagation(); if ($(this).hasClass('disabled')) return; var target = $(this).attr('href').substr(1).split('/'); if (target.length == 1) { getElementView($(this)).dispatch(target[0], $(this)); } else if (target[0] == 'view') { hideView(getElementView($(this)).id); showView(target[1]); } else if (target[0] == 'ui') { if (target[1] == 'hide') hideView(getElementView($(this)).id); } } }); var view_modules = $('.view').map(function() { return "ui/" + this.id; }).toArray(); require(view_modules, function() { $('.view').each(function() { registerView(this.id, new (require("ui/" + this.id))($(this))); }); ready = true; ready_callbacks.forEach(function(f) { f(); }); }); } function onReady(func) { if (ready) func(); else ready_callbacks.push(func); } function registerView(id, view) { views[id] = view; views[id].id = id; views[id].elt = $('.view#' + id); } function getView(id) { if (!views[id]) throw new Error("bad view id: " + id); return views[id]; } function getElementView($elt) { $elt = $elt || $(this); var id = $elt.parents('.view').first().attr('id'); if (views[id]) return views[id]; throw new Error("bad view id: " + id); } function View() { } View.prototype = { dispatch: function(action, $element) { return this[action]($element); }, show: function() { this.draw(); }, draw: function() {}, hide: function() {}, } function showView(id, data) { if (!views[id]) throw new Error("bad view id: " + id); views[id].data = data; views[id].show(); views[id].elt.show(); if (views[id].modal) { if (!overlays[id]) { overlays[id] = $('<div>').addClass('overlay').appendTo('body').click(function() { hideView(id); }); } overlays[id].show(); $('body').css('overflow', 'hidden'); } } function hideView(id) { if (!views[id]) throw new Error("bad view id: " + id); views[id].hide(); views[id].elt.hide(); if (overlays[id]) { overlays[id].hide(); $('body').css('overflow', 'auto'); } } return { renderTemplate: renderTemplate, init: init, onReady: onReady, View: View, getView: getView, showView: showView, hideView: hideView, }; });
const bmoor = require('bmoor'); function makeSwitchableUrl(){ const ctx = {}; const keys = []; const fn = function(args){ let dex = null; for( let i = 0, c = keys.length; i < c && !dex; i++ ){ if (keys[i] in args){ dex = keys[i]; } } let rtn = ctx[dex]; if (bmoor.isFunction(rtn)){ rtn = rtn(args); } return rtn; }; fn.append = function(key, urlGenerator){ ctx[key] = urlGenerator; keys.push(key); }; return fn; } module.exports = { makeSwitchableUrl };
/* The MIT License Copyright (c) 2015 Juan Cruz Viotti. https://jviotti.github.io. 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. */ var Promise, fs, _; _ = require('lodash'); Promise = require('bluebird'); fs = Promise.promisifyAll(require('fs')); /** * @summary Map trough object values using a promise iterator * @function * @protected * * @param {Object} object - input object * @param {Function} iterator - promised iterator * * @returns {Promise<Object>} mapped object * * @example * utils.promiseMapValues * a: 1 * b: 2 * , (n) -> * Promise.try -> * return n * 3 * .then (result) -> * console.log(result) */ exports.promiseMapValues = function(object, iterator) { return Promise.props(_.mapValues(object, iterator)); };
'use strict'; // Project details var name = 'richrdkng-support', description = 'GitHub Support Page', version = '1.0.0', homepage = 'http://richrdkng.github.io/support/', repository = { credentials: null, git: 'https://github.com/richrdkng/support.git' }, issues = '', authors = [ ['Richard King', 'richrdkng@gmail.com', 'https://github.com/richrdkng'] ], license = [ 'MIT' ], keywords = [], dependencies = { dependencies: {}, peerDependencies: {}, devDependencies: {} }, // Paths p = require('path'), root = p.dirname(__dirname), path = { root: root, master: root, ghpages: root, project: p.normalize(root+'/project'), image: p.normalize(root+'/image'), markup: p.normalize(root+'/markup'), script: p.normalize(root+'/script'), style: p.normalize(root+'/style') }, log = console.log; module.exports = { name: name, description: description, version: version, path: path, repository: repository };
function swapDisplay(a, b) { var tmp = document.getElementById(a).style.display; document.getElementById(a).style.display = document.getElementById(b).style.display; document.getElementById(b).style.display = tmp; } function submitFormTriggeringCallback(formName, callbackKey, value) { if (value) { var ele = document.createElement("input"); ele.type = "hidden"; ele.name = callbackKey; ele.value = value; document.forms[formName].appendChild(ele) } submitForm(formName) } function submitForm(formName) { document.forms[formName].submit(); } function chooseOther(select, hiddenId, p) { value = prompt(p); document.getElementById(hiddenId).value = value; select.options[select.options.length-1].text = value; } function enableChoice(enableID, disableID) { document.getElementById(enableID).disabled = false; document.getElementById(disableID).disabled = true; } function setFocus(elementId) { document.getElementById(elementId).focus(); } function setSelection(elementId, start, stop) { var input = document.getElementById(elementId); input.focus(); /* When stop parameter not supplied, all field is selected */ if (!start) start = 1; if (!stop) stop = input.value.length + 1; if (typeof document.selection != "undefined") { /* Place selection in MS-IE */ var range = document.selection.createRange(); range.moveStart("character", start - 1); range.moveEnd("character", stop - start); range.select(); } else if (typeof input.selectionStart != "undefined") { /* Place selection in Gecko browsers */ input.selectionStart = start - 1; input.selectionEnd = stop - 1; } else { /* Other browsers, please feel free to implement */ alert("unknown browser"); } }
module.exports = Polygon; var util = require('util'); var Geometry = require('./geometry'); var Types = require('./types'); var Point = require('./point'); var BinaryWriter = require('./binarywriter'); function Polygon(exteriorRing, interiorRings, srid) { Geometry.call(this); this.exteriorRing = exteriorRing || []; this.interiorRings = interiorRings || []; this.srid = srid; if (this.exteriorRing.length > 0) { this.hasZ = this.exteriorRing[0].hasZ; this.hasM = this.exteriorRing[0].hasM; } } util.inherits(Polygon, Geometry); Polygon.Z = function (exteriorRing, interiorRings, srid) { var polygon = new Polygon(exteriorRing, interiorRings, srid); polygon.hasZ = true; return polygon; }; Polygon.M = function (exteriorRing, interiorRings, srid) { var polygon = new Polygon(exteriorRing, interiorRings, srid); polygon.hasM = true; return polygon; }; Polygon.ZM = function (exteriorRing, interiorRings, srid) { var polygon = new Polygon(exteriorRing, interiorRings, srid); polygon.hasZ = true; polygon.hasM = true; return polygon; }; Polygon._parseWkt = function (value, options) { var polygon = new Polygon(); polygon.srid = options.srid; polygon.hasZ = options.hasZ; polygon.hasM = options.hasM; if (value.isMatch(['EMPTY'])) return polygon; value.expectGroupStart(); value.expectGroupStart(); polygon.exteriorRing.push.apply(polygon.exteriorRing, value.matchCoordinates(options)); value.expectGroupEnd(); while (value.isMatch([','])) { value.expectGroupStart(); polygon.interiorRings.push(value.matchCoordinates(options)); value.expectGroupEnd(); } value.expectGroupEnd(); return polygon; }; Polygon._parseWkb = function (value, options) { var polygon = new Polygon(); polygon.srid = options.srid; polygon.hasZ = options.hasZ; polygon.hasM = options.hasM; var ringCount = value.readUInt32(); if (ringCount > 0) { var exteriorRingCount = value.readUInt32(); for (var i = 0; i < exteriorRingCount; i++) polygon.exteriorRing.push(Point._readWkbPoint(value, options)); for (i = 1; i < ringCount; i++) { var interiorRing = []; var interiorRingCount = value.readUInt32(); for (var j = 0; j < interiorRingCount; j++) interiorRing.push(Point._readWkbPoint(value, options)); polygon.interiorRings.push(interiorRing); } } return polygon; }; Polygon._parseTwkb = function (value, options) { var polygon = new Polygon(); polygon.hasZ = options.hasZ; polygon.hasM = options.hasM; if (options.isEmpty) return polygon; var previousPoint = new Point(0, 0, options.hasZ ? 0 : undefined, options.hasM ? 0 : undefined); var ringCount = value.readVarInt(); var exteriorRingCount = value.readVarInt(); for (var i = 0; i < exteriorRingCount; i++) polygon.exteriorRing.push(Point._readTwkbPoint(value, options, previousPoint)); for (i = 1; i < ringCount; i++) { var interiorRing = []; var interiorRingCount = value.readVarInt(); for (var j = 0; j < interiorRingCount; j++) interiorRing.push(Point._readTwkbPoint(value, options, previousPoint)); polygon.interiorRings.push(interiorRing); } return polygon; }; Polygon._parseGeoJSON = function (value) { var polygon = new Polygon(); if (value.coordinates.length > 0 && value.coordinates[0].length > 0) polygon.hasZ = value.coordinates[0][0].length > 2; for (var i = 0; i < value.coordinates.length; i++) { if (i > 0) polygon.interiorRings.push([]); for (var j = 0; j < value.coordinates[i].length; j++) { if (i === 0) polygon.exteriorRing.push(Point._readGeoJSONPoint(value.coordinates[i][j])); else polygon.interiorRings[i - 1].push(Point._readGeoJSONPoint(value.coordinates[i][j])); } } return polygon; }; Polygon.prototype.toWkt = function () { if (this.exteriorRing.length === 0) return this._getWktType(Types.wkt.Polygon, true); return this._getWktType(Types.wkt.Polygon, false) + this._toInnerWkt(); }; Polygon.prototype._toInnerWkt = function () { var innerWkt = '(('; for (var i = 0; i < this.exteriorRing.length; i++) innerWkt += this._getWktCoordinate(this.exteriorRing[i]) + ','; innerWkt = innerWkt.slice(0, -1); innerWkt += ')'; for (i = 0; i < this.interiorRings.length; i++) { innerWkt += ',('; for (var j = 0; j < this.interiorRings[i].length; j++) { innerWkt += this._getWktCoordinate(this.interiorRings[i][j]) + ','; } innerWkt = innerWkt.slice(0, -1); innerWkt += ')'; } innerWkt += ')'; return innerWkt; }; Polygon.prototype.toWkb = function (parentOptions) { var wkb = new BinaryWriter(this._getWkbSize()); wkb.writeInt8(1); this._writeWkbType(wkb, Types.wkb.Polygon, parentOptions); if (this.exteriorRing.length > 0) { wkb.writeUInt32LE(1 + this.interiorRings.length); wkb.writeUInt32LE(this.exteriorRing.length); } else { wkb.writeUInt32LE(0); } for (var i = 0; i < this.exteriorRing.length; i++) this.exteriorRing[i]._writeWkbPoint(wkb); for (i = 0; i < this.interiorRings.length; i++) { wkb.writeUInt32LE(this.interiorRings[i].length); for (var j = 0; j < this.interiorRings[i].length; j++) this.interiorRings[i][j]._writeWkbPoint(wkb); } return wkb.buffer; }; Polygon.prototype.toTwkb = function () { var twkb = new BinaryWriter(0, true); var precision = Geometry.getTwkbPrecision(5, 0, 0); var isEmpty = this.exteriorRing.length === 0; this._writeTwkbHeader(twkb, Types.wkb.Polygon, precision, isEmpty); if (this.exteriorRing.length > 0) { twkb.writeVarInt(1 + this.interiorRings.length); twkb.writeVarInt(this.exteriorRing.length); var previousPoint = new Point(0, 0, 0, 0); for (var i = 0; i < this.exteriorRing.length; i++) this.exteriorRing[i]._writeTwkbPoint(twkb, precision, previousPoint); for (i = 0; i < this.interiorRings.length; i++) { twkb.writeVarInt(this.interiorRings[i].length); for (var j = 0; j < this.interiorRings[i].length; j++) this.interiorRings[i][j]._writeTwkbPoint(twkb, precision, previousPoint); } } return twkb.buffer; }; Polygon.prototype._getWkbSize = function () { var coordinateSize = 16; if (this.hasZ) coordinateSize += 8; if (this.hasM) coordinateSize += 8; var size = 1 + 4 + 4; if (this.exteriorRing.length > 0) size += 4 + (this.exteriorRing.length * coordinateSize); for (var i = 0; i < this.interiorRings.length; i++) size += 4 + (this.interiorRings[i].length * coordinateSize); return size; }; Polygon.prototype.toGeoJSON = function (options) { var geoJSON = Geometry.prototype.toGeoJSON.call(this, options); geoJSON.type = Types.geoJSON.Polygon; geoJSON.coordinates = []; if (this.exteriorRing.length > 0) { var exteriorRing = []; for (var i = 0; i < this.exteriorRing.length; i++) { if (this.hasZ) exteriorRing.push([this.exteriorRing[i].x, this.exteriorRing[i].y, this.exteriorRing[i].z]); else exteriorRing.push([this.exteriorRing[i].x, this.exteriorRing[i].y]); } geoJSON.coordinates.push(exteriorRing); } for (var j = 0; j < this.interiorRings.length; j++) { var interiorRing = []; for (var k = 0; k < this.interiorRings[j].length; k++) { if (this.hasZ) interiorRing.push([this.interiorRings[j][k].x, this.interiorRings[j][k].y, this.interiorRings[j][k].z]); else interiorRing.push([this.interiorRings[j][k].x, this.interiorRings[j][k].y]); } geoJSON.coordinates.push(interiorRing); } return geoJSON; };
var isStream = false ; function __log(e, data) { console.log(e); } var audio_context; var recorder; function startUserMedia(stream) { var input = audio_context.createMediaStreamSource(stream); __log('Media stream created.'); // Uncomment if you want the audio to feedback directly //input.connect(audio_context.destination); //__log('Input connected to audio context destination.'); recorder = new Recorder(input); __log('Recorder initialised.'); isStream = stream ; startRecording() ; } function startRecording(button) { recorder && recorder.record(); // button.disabled = true; // button.nextElementSibling.disabled = false; __log('Recording...'); } function stopRecording(handle) { recorder && recorder.stop(); // button.disabled = true; // button.previousElementSibling.disabled = false; __log('Stopped recording.'); if(isStream){ isStream.getAudioTracks().forEach(function(track){ track.stop() ; }) ; isStream = false ; } // create WAV download link using audio data blob createDownloadLink(handle); recorder.clear(); } function createDownloadLink(handle) { recorder && recorder.exportWAV(function(blob) { var url = URL.createObjectURL(blob); var li = document.createElement('li'); var au = document.createElement('audio'); var hf = document.createElement('a'); au.controls = true; au.src = url; hf.href = url; hf.download = new Date().toISOString() + '.wav'; hf.innerHTML = hf.download; var R = new FileReader() ; R.readAsDataURL(blob) ; R.onload = function(){ if(handle) handle(R.result) ; } ; }); } function commencer(handle){ navigator.getUserMedia = navigator.getUserMedia || navigator.mozGetUserMedia || navigator.webkitGetUserMedia; navigator.getUserMedia({audio: true}, function(stream){ startUserMedia(stream) ; handle() ; }, /* error case */ function(e) { __log('No live audio input: ' + e); }); } window.addEventListener('load', function(){ try { // webkit shim window.AudioContext = window.AudioContext || window.webkitAudioContext|| window.mozAudioContext; window.URL = window.URL || window.webkitURL, window.mozURL; audio_context = new AudioContext ; __log('Audio context set up.'); __log('navigator.getUserMedia ' + (navigator.getUserMedia ? 'available.' : 'not present!')); } catch (e) { alert('No web audio support in this browser!'); } });
var util = require('util'), Lock = require('../base'), _ = require('lodash'), mongo = Lock.use('mongodb'), mongoVersion = Lock.use('mongodb/package.json').version, isNew = mongoVersion.indexOf('1.') !== 0, ObjectID = isNew ? mongo.ObjectID : mongo.BSONPure.ObjectID; function Mongo(options) { Lock.call(this, options); var defaults = { host: 'localhost', port: 27017, dbName: 'domain', collectionName: 'aggregatelock'//, // heartbeat: 60 * 1000 }; _.defaults(options, defaults); var defaultOpt = { ssl: false }; options.options = options.options || {}; if (isNew) { defaultOpt.autoReconnect = false; defaultOpt.useNewUrlParser = true; defaultOpt.useUnifiedTopology = true; _.defaults(options.options, defaultOpt); } else { defaultOpt.auto_reconnect = false; _.defaults(options.options, defaultOpt); } this.options = options; } util.inherits(Mongo, Lock); _.extend(Mongo.prototype, { connect: function (callback) { var self = this; var options = this.options; var connectionUrl; if (options.url) { connectionUrl = options.url; } else { var members = options.servers ? options.servers : [{host: options.host, port: options.port}]; var memberString = _(members).map(function(m) { return m.host + ':' + m.port; }); var authString = options.username && options.password ? options.username + ':' + options.password + '@' : ''; var optionsString = options.authSource ? '?authSource=' + options.authSource : ''; connectionUrl = 'mongodb://' + authString + memberString + '/' + options.dbName + optionsString; } var client; if (mongo.MongoClient.length === 2) { client = new mongo.MongoClient(connectionUrl, options.options); client.connect(function(err, cl) { if (err) { debug(err); if (callback) callback(err); return; } self.db = cl.db(cl.s.options.dbName); if (!self.db.close) { self.db.close = cl.close.bind(cl); } initDb(); }); } else { client = new mongo.MongoClient(); client.connect(connectionUrl, options.options, function(err, db) { if (err) { debug(err); if (callback) callback(err); return; } self.db = db; initDb(); }); } function initDb() { self.db.on('close', function() { self.emit('disconnect'); self.stopHeartbeat(); }); var finish = function (err) { self.lock = self.db.collection(options.collectionName); self.lock.ensureIndex({ 'aggregateId': 1, date: 1 }, function() {}); if (!err) { self.emit('connect'); if (self.options.heartbeat) { self.startHeartbeat(); } } if (callback) callback(err, self); }; finish(); } }, stopHeartbeat: function () { if (this.heartbeatInterval) { clearInterval(this.heartbeatInterval); delete this.heartbeatInterval; } }, startHeartbeat: function () { var self = this; var gracePeriod = Math.round(this.options.heartbeat / 2); this.heartbeatInterval = setInterval(function () { var graceTimer = setTimeout(function () { if (self.heartbeatInterval) { console.error((new Error ('Heartbeat timeouted after ' + gracePeriod + 'ms (mongodb)')).stack); self.disconnect(); } }, gracePeriod); self.db.command({ ping: 1 }, function (err) { if (graceTimer) clearTimeout(graceTimer); if (err) { console.error(err.stack || err); self.disconnect(); } }); }, this.options.heartbeat); }, disconnect: function (callback) { this.stopHeartbeat(); if (!this.db) { if (callback) callback(null); return; } this.db.close(callback || function () {}); }, getNewId: function(callback) { callback(null, new ObjectID().toString()); }, reserve: function(workerId, aggregateId, callback) { this.lock.save({ _id: workerId, aggregateId: aggregateId, date: new Date() }, { safe: true }, function (err) { if (callback) callback(err); }); }, getAll: function(aggregateId, callback) { this.lock.find({ aggregateId: aggregateId }, { sort: { date: 1 } }).toArray(function (err, res) { if (err) { return callback(err); } callback(null, _.map(res, function (entry) { return entry._id; })); }); }, resolve: function(aggregateId, callback) { this.lock.remove({ aggregateId: aggregateId }, { safe: true }, function (err) { if (callback) callback(err); }); }, clear: function (callback) { this.lock.remove({}, { safe: true }, callback); } }); module.exports = Mongo;
var Tree = (function(Tree) { $.fn.extend({ treed: function() { return this.each(function() { //initialize each of the top levels var tree = $(this); tree.addClass("tree"); tree.find('li').has("ul").each(function () { var branch = $(this); //li with children ul branch.prepend("<i class='indicator glyphicon glyphicon-plus-sign'></i>"); branch.addClass('branch'); branch.on('click', function (e) { if (this == e.target) { var icon = $(this).children('i:first'); icon.toggleClass("glyphicon-minus-sign glyphicon-plus-sign"); $(this).children().children().toggle(); } }) branch.children().children().toggle(); }); //fire event from the dynamically added icon $('.branch .indicator').on('click',function(){ $(this).closest('li').click(); }); //fire event to open branch if the li contains an anchor instead of text $('.branch a').on('click',function(e){ $(this).closest('li').click(); e.preventDefault(); }); //fire event to open branch if the li contains a button instead of text $('.branch button').on('click',function(e){ $(this).closest('li').click(); e.preventDefault(); }); }); } }); function buildHierachy(childs, className) { var ul = $("<ul>"); childs.forEach(function (item) { var li = $("<li>"); li.addClass(className ||""); var a = $("<a>").text(item.name).click(function() { Editor.createInspectorFor(item); }); li.append(a); if (item._childs.length) { li.append(buildHierachy(item._childs)); } ul.append(li); }); return ul; } function updateTree(root) { $(".hierachy").empty(); $(".hierachy").append(buildHierachy([root])); $('.hierachy').treed(); } Tree.updateTree = updateTree; return Tree })({});
var React = require('react'); var ReactDOM = require('react-dom'); var listOfItems = <ul className="list-of-items"> <li className="item-1">Item 1</li> <li className="item-2">Item 2</li> <li className="item-3">Item 3</li> </ul>; ReactDOM.render(listOfItems, document.getElementById('react-application'));
(function (views) { views.PaginationView = Backbone.View.extend({ events: { 'click a.filter': 'search', 'click a.first': 'gotoFirst', 'click a.prev': 'gotoPrev', 'click a.next': 'gotoNext', 'click a.last': 'gotoLast', 'click a.page': 'gotoPage', 'click .howmany a': 'changeCount', 'click a.sortAsc': 'sortByAscending', 'click a.sortDsc': 'sortByDescending', }, tagName: 'aside', pagingTemplate: _.template($('#tmpClientPagination').html()), initialize: function () { this.collection.on('reset', this.render, this); this.$el.appendTo('#pagination'); }, search: function() { var that = this; this.collection.server_api.keywords = $('#filterString').val(); this.collection.reset(); this.collection.fetch({reset: false, success: function(model) { $('aside').remove(); app.collections.paginatedItems = new app.collections.PaginatedCollection(); app.views.app = new app.views.AppView({collection: app.collections.paginatedItems}); app.views.pagination = new app.views.PaginationView({collection: app.collections.paginatedItems}); that.render() }} )}, render: function () { var html = this.pagingTemplate(this.collection.info()); this.$el.html(html); }, gotoFirst: function (e) { e.preventDefault(); this.collection.goTo(1); }, gotoPrev: function (e) { e.preventDefault(); this.collection.previousPage(); }, gotoNext: function (e) { e.preventDefault(); this.collection.nextPage(); }, gotoLast: function (e) { e.preventDefault(); this.collection.goTo(this.collection.information.lastPage); }, gotoPage: function (e) { e.preventDefault(); var page = $(e.target).text(); this.collection.goTo(page); }, changeCount: function (e) { e.preventDefault(); var per = $(e.target).text(); this.collection.howManyPer(per); }, sortByAscending: function (e) { e.preventDefault(); var currentSort = this.getSortOption(); this.collection.setSort(currentSort, 'asc'); this.collection.pager(); this.preserveSortOption(currentSort); }, getSortOption: function () { return $('#sortByOption').val(); }, preserveSortOption: function (option) { $('#sortByOption').val(option); }, sortByDescending: function (e) { e.preventDefault(); var currentSort = this.getSortOption(); this.collection.setSort(currentSort, 'desc'); this.collection.pager(); this.preserveSortOption(currentSort); }, getFilterField: function () { return $('#filterByOption').val(); }, getFilterValue: function () { return $('#filterString').val(); }, preserveFilterField: function (field) { $('#filterByOption').val(field); }, preserveFilterValue: function (value) { $('#filterString').val(value); }, filter: function (e) { e.preventDefault(); var fields = this.getFilterField(); /*Note that this is an example! * You can create an array like * * fields = ['Name', 'Description', ...]; * *Or an object with rules like * * fields = { * 'Name': {cmp_method: 'levenshtein', max_distance: 7}, * 'Description': {cmp_method: 'regexp'}, * 'Rating': {} // This will default to 'regexp' * }; */ var filter = this.getFilterValue(); this.collection.setFilter(fields, filter); this.collection.pager(); this.preserveFilterField(fields); this.preserveFilterValue(filter); } }); })( app.views );
var gulp = require('gulp'); var shell = require('gulp-shell'); var clean = require('gulp-clean'); var htmlreplace = require('gulp-html-replace'); var runSequence = require('run-sequence'); var Builder = require('systemjs-builder'); var builder = new Builder('', 'systemjs.config.js'); var browserSync = require('browser-sync'); var superstatic = require('superstatic'); var csslint = require('gulp-csslint'); var tslint = require('gulp-tslint'); var bundleHash = new Date().getTime(); var mainBundleName = bundleHash + '.main.bundle.js'; var vendorBundleName = bundleHash + '.vendor.bundle.js'; // This is main task for production use gulp.task('dist', function(done) { runSequence('clean', 'compile_ts', 'bundle', 'copy_assets', function() { done(); }); }); gulp.task('bundle', ['bundle:vendor', 'bundle:app'], function () { return gulp.src('index.html') .pipe(htmlreplace({ 'app': mainBundleName, 'vendor': vendorBundleName })) .pipe(gulp.dest('./dist')); }); gulp.task('bundle:vendor', function () { return builder .buildStatic('app/vendor.js', './dist/' + vendorBundleName) .catch(function (err) { console.log('Vendor bundle error'); console.log(err); }); }); gulp.task('bundle:app', function () { return builder .buildStatic('app/main.js', './dist/' + mainBundleName) .catch(function (err) { console.log('App bundle error'); console.log(err); }); }); gulp.task('compile_ts', ['clean:ts'], shell.task([ 'tsc' ])); gulp.task('copy_assets', function() { return gulp.src(['./assets/**/*'], {base:"."}) .pipe(gulp.dest('./dist')); }); gulp.task('clean', ['clean:ts', 'clean:dist']); gulp.task('clean:dist', function () { return gulp.src(['./dist'], {read: false}) .pipe(clean()); }); gulp.task('clean:ts', function () { return gulp.src(['./app/assets/**/*.js', './app/**/*.js.map'], {read: false}) .pipe(clean()); }); gulp.task('css-lint', function() { gulp.src('./assets/**/*.css') .pipe(csslint()) .pipe(csslint.formatter()); }); gulp.task('watch', function () { gulp.watch(['./app/**/*.ts'], ['compile_ts', browserSync.reload]); gulp.watch(['./app/**/*.html'], ['compile_ts', browserSync.reload]); gulp.watch(['./assets/**/*.css'], ['compile_ts', browserSync.reload]); }); gulp.task('serve', ['compile_ts', 'watch'], function(done) { browserSync({ open: true, port: 3000, file: ['index.html','.app/**/*.js'], injectChanges:true, server: { baseDir: ['./app'], middleware: [superstatic({debug:false})] } }, done); });
const DEFAULT_TIME_ZONE = { label: '(GMT+00:00) London', value: 'Europe/London' } const TIME_ZONES = [ { label: '(GMT-11:00) Niue', value: 'Pacific/Niue' }, { label: '(GMT-11:00) Pago Pago', value: 'Pacific/Pago_Pago' }, { label: '(GMT-10:00) Hawaii Time', value: 'Pacific/Honolulu' }, { label: '(GMT-10:00) Rarotonga', value: 'Pacific/Rarotonga' }, { label: '(GMT-10:00) Tahiti', value: 'Pacific/Tahiti' }, { label: '(GMT-09:30) Marquesas', value: 'Pacific/Marquesas' }, { label: '(GMT-09:00) Alaska Time', value: 'America/Anchorage' }, { label: '(GMT-09:00) Gambier', value: 'Pacific/Gambier' }, { label: '(GMT-08:00) Pacific Time', value: 'America/Los_Angeles' }, { label: '(GMT-08:00) Pacific Time - Tijuana', value: 'America/Tijuana' }, { label: '(GMT-08:00) Pacific Time - Vancouver', value: 'America/Vancouver' }, { label: '(GMT-08:00) Pacific Time - Whitehorse', value: 'America/Whitehorse' }, { label: '(GMT-08:00) Pitcairn', value: 'Pacific/Pitcairn' }, { label: '(GMT-07:00) Mountain Time - Dawson Creek', value: 'America/Dawson_Creek' }, { label: '(GMT-07:00) Mountain Time', value: 'America/Denver' }, { label: '(GMT-07:00) Mountain Time - Edmonton', value: 'America/Edmonton' }, { label: '(GMT-07:00) Mountain Time - Hermosillo', value: 'America/Hermosillo' }, { label: '(GMT-07:00) Mountain Time - Chihuahua,Mazatlan', value: 'America/Mazatlan' }, { label: '(GMT-07:00) Mountain Time - Arizona', value: 'America/Phoenix' }, { label: '(GMT-07:00) Mountain Time - Yellowknife', value: 'America/Yellowknife' }, { label: '(GMT-06:00) Belize', value: 'America/Belize' }, { label: '(GMT-06:00) Central Time', value: 'America/Chicago' }, { label: '(GMT-06:00) Costa Rica', value: 'America/Costa_Rica' }, { label: '(GMT-06:00) El Salvador', value: 'America/El_Salvador' }, { label: '(GMT-06:00) Guatemala', value: 'America/Guatemala' }, { label: '(GMT-06:00) Managua', value: 'America/Managua' }, { label: '(GMT-06:00) Central Time - Mexico City', value: 'America/Mexico_City' }, { label: '(GMT-06:00) Central Time - Regina', value: 'America/Regina' }, { label: '(GMT-06:00) Central Time - Tegucigalpa', value: 'America/Tegucigalpa' }, { label: '(GMT-06:00) Central Time - Winnipeg', value: 'America/Winnipeg' }, { label: '(GMT-06:00) Galapagos', value: 'Pacific/Galapagos' }, { label: '(GMT-05:00) Bogota', value: 'America/Bogota' }, { label: '(GMT-05:00) America Cancun', value: 'America/Cancun' }, { label: '(GMT-05:00) Cayman', value: 'America/Cayman' }, { label: '(GMT-05:00) Guayaquil', value: 'America/Guayaquil' }, { label: '(GMT-05:00) Havana', value: 'America/Havana' }, { label: '(GMT-05:00) Eastern Time - Iqaluit', value: 'America/Iqaluit' }, { label: '(GMT-05:00) Jamaica', value: 'America/Jamaica' }, { label: '(GMT-05:00) Lima', value: 'America/Lima' }, { label: '(GMT-05:00) Nassau', value: 'America/Nassau' }, { label: '(GMT-05:00) Eastern Time', value: 'America/New_York' }, { label: '(GMT-05:00) Panama', value: 'America/Panama' }, { label: '(GMT-05:00) Port-au-Prince', value: 'America/Port-au-Prince' }, { label: '(GMT-05:00) Rio Branco', value: 'America/Rio_Branco' }, { label: '(GMT-05:00) Eastern Time - Toronto', value: 'America/Toronto' }, { label: '(GMT-05:00) Easter Island', value: 'Pacific/Easter' }, { label: '(GMT-04:30) Caracas', value: 'America/Caracas' }, { label: '(GMT-03:00) Asuncion', value: 'America/Asuncion' }, { label: '(GMT-04:00) Barbados', value: 'America/Barbados' }, { label: '(GMT-04:00) Boa Vista', value: 'America/Boa_Vista' }, { label: '(GMT-03:00) Campo Grande', value: 'America/Campo_Grande' }, { label: '(GMT-03:00) Cuiaba', value: 'America/Cuiaba' }, { label: '(GMT-04:00) Curacao', value: 'America/Curacao' }, { label: '(GMT-04:00) Grand Turk', value: 'America/Grand_Turk' }, { label: '(GMT-04:00) Guyana', value: 'America/Guyana' }, { label: '(GMT-04:00) Atlantic Time - Halifax', value: 'America/Halifax' }, { label: '(GMT-04:00) La Paz', value: 'America/La_Paz' }, { label: '(GMT-04:00) Manaus', value: 'America/Manaus' }, { label: '(GMT-04:00) Martinique', value: 'America/Martinique' }, { label: '(GMT-04:00) Port of Spain', value: 'America/Port_of_Spain' }, { label: '(GMT-04:00) Porto Velho', value: 'America/Porto_Velho' }, { label: '(GMT-04:00) Puerto Rico', value: 'America/Puerto_Rico' }, { label: '(GMT-04:00) Santo Domingo', value: 'America/Santo_Domingo' }, { label: '(GMT-04:00) Thule', value: 'America/Thule' }, { label: '(GMT-04:00) Bermuda', value: 'Atlantic/Bermuda' }, { label: '(GMT-03:30) Newfoundland Time - St. Johns', value: 'America/St_Johns' }, { label: '(GMT-03:00) Araguaina', value: 'America/Araguaina' }, { label: '(GMT-03:00) Buenos Aires', value: 'America/Argentina/Buenos_Aires' }, { label: '(GMT-03:00) Salvador', value: 'America/Bahia' }, { label: '(GMT-03:00) Belem', value: 'America/Belem' }, { label: '(GMT-03:00) Cayenne', value: 'America/Cayenne' }, { label: '(GMT-03:00) Fortaleza', value: 'America/Fortaleza' }, { label: '(GMT-03:00) Godthab', value: 'America/Godthab' }, { label: '(GMT-03:00) Maceio', value: 'America/Maceio' }, { label: '(GMT-03:00) Miquelon', value: 'America/Miquelon' }, { label: '(GMT-03:00) Montevideo', value: 'America/Montevideo' }, { label: '(GMT-03:00) Paramaribo', value: 'America/Paramaribo' }, { label: '(GMT-03:00) Recife', value: 'America/Recife' }, { label: '(GMT-03:00) Santiago', value: 'America/Santiago' }, { label: '(GMT-02:00) Sao Paulo', value: 'America/Sao_Paulo' }, { label: '(GMT-03:00) Palmer', value: 'Antarctica/Palmer' }, { label: '(GMT-03:00) Rothera', value: 'Antarctica/Rothera' }, { label: '(GMT-03:00) Stanley', value: 'Atlantic/Stanley' }, { label: '(GMT-02:00) Noronha', value: 'America/Noronha' }, { label: '(GMT-02:00) South Georgia', value: 'Atlantic/South_Georgia' }, { label: '(GMT-01:00) Scoresbysund', value: 'America/Scoresbysund' }, { label: '(GMT-01:00) Azores', value: 'Atlantic/Azores' }, { label: '(GMT-01:00) Cape Verde', value: 'Atlantic/Cape_Verde' }, { label: '(GMT+00:00) Abidjan', value: 'Africa/Abidjan' }, { label: '(GMT+00:00) Accra', value: 'Africa/Accra' }, { label: '(GMT+00:00) Bissau', value: 'Africa/Bissau' }, { label: '(GMT+00:00) Casablanca', value: 'Africa/Casablanca' }, { label: '(GMT+00:00) El Aaiun', value: 'Africa/El_Aaiun' }, { label: '(GMT+00:00) Monrovia', value: 'Africa/Monrovia' }, { label: '(GMT+00:00) Danmarkshavn', value: 'America/Danmarkshavn' }, { label: '(GMT+00:00) Canary Islands', value: 'Atlantic/Canary' }, { label: '(GMT+00:00) Faeroe', value: 'Atlantic/Faroe' }, { label: '(GMT+00:00) Reykjavik', value: 'Atlantic/Reykjavik' }, { label: '(GMT+00:00) GMT (no daylight saving)', value: 'Etc/GMT' }, { label: '(GMT+00:00) Dublin', value: 'Europe/Dublin' }, { label: '(GMT+00:00) Lisbon', value: 'Europe/Lisbon' }, DEFAULT_TIME_ZONE, { label: '(GMT+01:00) Algiers', value: 'Africa/Algiers' }, { label: '(GMT+01:00) Ceuta', value: 'Africa/Ceuta' }, { label: '(GMT+01:00) Lagos', value: 'Africa/Lagos' }, { label: '(GMT+01:00) Ndjamena', value: 'Africa/Ndjamena' }, { label: '(GMT+01:00) Tunis', value: 'Africa/Tunis' }, { label: '(GMT+02:00) Windhoek', value: 'Africa/Windhoek' }, { label: '(GMT+01:00) Amsterdam', value: 'Europe/Amsterdam' }, { label: '(GMT+01:00) Andorra', value: 'Europe/Andorra' }, { label: '(GMT+01:00) Central European Time - Belgrade', value: 'Europe/Belgrade' }, { label: '(GMT+01:00) Berlin', value: 'Europe/Berlin' }, { label: '(GMT+01:00) Brussels', value: 'Europe/Brussels' }, { label: '(GMT+01:00) Budapest', value: 'Europe/Budapest' }, { label: '(GMT+01:00) Copenhagen', value: 'Europe/Copenhagen' }, { label: '(GMT+01:00) Gibraltar', value: 'Europe/Gibraltar' }, { label: '(GMT+01:00) Luxembourg', value: 'Europe/Luxembourg' }, { label: '(GMT+01:00) Madrid', value: 'Europe/Madrid' }, { label: '(GMT+01:00) Malta', value: 'Europe/Malta' }, { label: '(GMT+01:00) Monaco', value: 'Europe/Monaco' }, { label: '(GMT+01:00) Oslo', value: 'Europe/Oslo' }, { label: '(GMT+01:00) Paris', value: 'Europe/Paris' }, { label: '(GMT+01:00) Central European Time - Prague', value: 'Europe/Prague' }, { label: '(GMT+01:00) Rome', value: 'Europe/Rome' }, { label: '(GMT+01:00) Stockholm', value: 'Europe/Stockholm' }, { label: '(GMT+01:00) Tirane', value: 'Europe/Tirane' }, { label: '(GMT+01:00) Vienna', value: 'Europe/Vienna' }, { label: '(GMT+01:00) Warsaw', value: 'Europe/Warsaw' }, { label: '(GMT+01:00) Zurich', value: 'Europe/Zurich' }, { label: '(GMT+02:00) Cairo', value: 'Africa/Cairo' }, { label: '(GMT+02:00) Johannesburg', value: 'Africa/Johannesburg' }, { label: '(GMT+02:00) Maputo', value: 'Africa/Maputo' }, { label: '(GMT+02:00) Tripoli', value: 'Africa/Tripoli' }, { label: '(GMT+02:00) Amman', value: 'Asia/Amman' }, { label: '(GMT+02:00) Beirut', value: 'Asia/Beirut' }, { label: '(GMT+02:00) Damascus', value: 'Asia/Damascus' }, { label: '(GMT+02:00) Gaza', value: 'Asia/Gaza' }, { label: '(GMT+02:00) Jerusalem', value: 'Asia/Jerusalem' }, { label: '(GMT+02:00) Nicosia', value: 'Asia/Nicosia' }, { label: '(GMT+02:00) Athens', value: 'Europe/Athens' }, { label: '(GMT+02:00) Bucharest', value: 'Europe/Bucharest' }, { label: '(GMT+02:00) Chisinau', value: 'Europe/Chisinau' }, { label: '(GMT+02:00) Helsinki', value: 'Europe/Helsinki' }, { label: '(GMT+02:00) Istanbul', value: 'Europe/Istanbul' }, { label: '(GMT+02:00) Moscow-01 - Kaliningrad', value: 'Europe/Kaliningrad' }, { label: '(GMT+02:00) Kiev', value: 'Europe/Kiev' }, { label: '(GMT+02:00) Riga', value: 'Europe/Riga' }, { label: '(GMT+02:00) Sofia', value: 'Europe/Sofia' }, { label: '(GMT+02:00) Tallinn', value: 'Europe/Tallinn' }, { label: '(GMT+02:00) Vilnius', value: 'Europe/Vilnius' }, { label: '(GMT+03:00) Khartoum', value: 'Africa/Khartoum' }, { label: '(GMT+03:00) Nairobi', value: 'Africa/Nairobi' }, { label: '(GMT+03:00) Syowa', value: 'Antarctica/Syowa' }, { label: '(GMT+03:00) Baghdad', value: 'Asia/Baghdad' }, { label: '(GMT+03:00) Qatar', value: 'Asia/Qatar' }, { label: '(GMT+03:00) Riyadh', value: 'Asia/Riyadh' }, { label: '(GMT+03:00) Minsk', value: 'Europe/Minsk' }, { label: '(GMT+03:00) Moscow+00 - Moscow', value: 'Europe/Moscow' }, { label: '(GMT+03:30) Tehran', value: 'Asia/Tehran' }, { label: '(GMT+04:00) Baku', value: 'Asia/Baku' }, { label: '(GMT+04:00) Dubai', value: 'Asia/Dubai' }, { label: '(GMT+04:00) Tbilisi', value: 'Asia/Tbilisi' }, { label: '(GMT+04:00) Yerevan', value: 'Asia/Yerevan' }, { label: '(GMT+04:00) Moscow+01 - Samara', value: 'Europe/Samara' }, { label: '(GMT+04:00) Mahe', value: 'Indian/Mahe' }, { label: '(GMT+04:00) Mauritius', value: 'Indian/Mauritius' }, { label: '(GMT+04:00) Reunion', value: 'Indian/Reunion' }, { label: '(GMT+04:30) Kabul', value: 'Asia/Kabul' }, { label: '(GMT+05:00) Mawson', value: 'Antarctica/Mawson' }, { label: '(GMT+05:00) Aqtau', value: 'Asia/Aqtau' }, { label: '(GMT+05:00) Aqtobe', value: 'Asia/Aqtobe' }, { label: '(GMT+05:00) Ashgabat', value: 'Asia/Ashgabat' }, { label: '(GMT+05:00) Dushanbe', value: 'Asia/Dushanbe' }, { label: '(GMT+05:00) Karachi', value: 'Asia/Karachi' }, { label: '(GMT+05:00) Tashkent', value: 'Asia/Tashkent' }, { label: '(GMT+05:00) Moscow+02 - Yekaterinburg', value: 'Asia/Yekaterinburg' }, { label: '(GMT+05:00) Kerguelen', value: 'Indian/Kerguelen' }, { label: '(GMT+05:00) Maldives', value: 'Indian/Maldives' }, { label: '(GMT+05:30) India Standard Time', value: 'Asia/Calcutta' }, { label: '(GMT+05:30) Colombo', value: 'Asia/Colombo' }, { label: '(GMT+05:45) Katmandu', value: 'Asia/Katmandu' }, { label: '(GMT+06:00) Vostok', value: 'Antarctica/Vostok' }, { label: '(GMT+06:00) Almaty', value: 'Asia/Almaty' }, { label: '(GMT+06:00) Bishkek', value: 'Asia/Bishkek' }, { label: '(GMT+06:00) Dhaka', value: 'Asia/Dhaka' }, { label: '(GMT+06:00) Moscow+03 - Omsk,Novosibirsk', value: 'Asia/Omsk' }, { label: '(GMT+06:00) Thimphu', value: 'Asia/Thimphu' }, { label: '(GMT+06:00) Chagos', value: 'Indian/Chagos' }, { label: '(GMT+06:30) Rangoon', value: 'Asia/Rangoon' }, { label: '(GMT+06:30) Cocos', value: 'Indian/Cocos' }, { label: '(GMT+07:00) Davis', value: 'Antarctica/Davis' }, { label: '(GMT+07:00) Bangkok', value: 'Asia/Bangkok' }, { label: '(GMT+07:00) Hovd', value: 'Asia/Hovd' }, { label: '(GMT+07:00) Jakarta', value: 'Asia/Jakarta' }, { label: '(GMT+07:00) Moscow+04 - Krasnoyarsk', value: 'Asia/Krasnoyarsk' }, { label: '(GMT+07:00) Hanoi', value: 'Asia/Saigon' }, { label: '(GMT+07:00) Christmas', value: 'Indian/Christmas' }, { label: '(GMT+08:00) Casey', value: 'Antarctica/Casey' }, { label: '(GMT+08:00) Brunei', value: 'Asia/Brunei' }, { label: '(GMT+08:00) Choibalsan', value: 'Asia/Choibalsan' }, { label: '(GMT+08:00) Hong Kong', value: 'Asia/Hong_Kong' }, { label: '(GMT+08:00) Moscow+05 - Irkutsk', value: 'Asia/Irkutsk' }, { label: '(GMT+08:00) Kuala Lumpur', value: 'Asia/Kuala_Lumpur' }, { label: '(GMT+08:00) Macau', value: 'Asia/Macau' }, { label: '(GMT+08:00) Makassar', value: 'Asia/Makassar' }, { label: '(GMT+08:00) Manila', value: 'Asia/Manila' }, { label: '(GMT+08:00) China Time - Beijing', value: 'Asia/Shanghai' }, { label: '(GMT+08:00) Singapore', value: 'Asia/Singapore' }, { label: '(GMT+08:00) Taipei', value: 'Asia/Taipei' }, { label: '(GMT+08:00) Ulaanbaatar', value: 'Asia/Ulaanbaatar' }, { label: '(GMT+08:00) Western Time - Perth', value: 'Australia/Perth' }, { label: '(GMT+08:30) Pyongyang', value: 'Asia/Pyongyang' }, { label: '(GMT+09:00) Dili', value: 'Asia/Dili' }, { label: '(GMT+09:00) Jayapura', value: 'Asia/Jayapura' }, { label: '(GMT+09:00) Seoul', value: 'Asia/Seoul' }, { label: '(GMT+09:00) Tokyo', value: 'Asia/Tokyo' }, { label: '(GMT+09:00) Moscow+06 - Yakutsk', value: 'Asia/Yakutsk' }, { label: '(GMT+09:00) Palau', value: 'Pacific/Palau' }, { label: '(GMT+10:30) Central Time - Adelaide', value: 'Australia/Adelaide' }, { label: '(GMT+09:30) Central Time - Darwin', value: 'Australia/Darwin' }, { label: "(GMT+10:00) Dumont D'Urville", value: 'Antarctica/DumontDUrville' }, { label: '(GMT+10:00) Moscow+07 - Magadan', value: 'Asia/Magadan' }, { label: '(GMT+10:00) Moscow+07 - Yuzhno-Sakhalinsk', value: 'Asia/Vladivostok' }, { label: '(GMT+10:00) Eastern Time - Brisbane', value: 'Australia/Brisbane' }, { label: '(GMT+11:00) Eastern Time - Hobart', value: 'Australia/Hobart' }, { label: '(GMT+11:00) Eastern Time - Melbourne,Sydney', value: 'Australia/Sydney' }, { label: '(GMT+10:00) Truk', value: 'Pacific/Chuuk' }, { label: '(GMT+10:00) Guam', value: 'Pacific/Guam' }, { label: '(GMT+10:00) Port Moresby', value: 'Pacific/Port_Moresby' }, { label: '(GMT+11:00) Efate', value: 'Pacific/Efate' }, { label: '(GMT+11:00) Guadalcanal', value: 'Pacific/Guadalcanal' }, { label: '(GMT+11:00) Kosrae', value: 'Pacific/Kosrae' }, { label: '(GMT+11:00) Norfolk', value: 'Pacific/Norfolk' }, { label: '(GMT+11:00) Noumea', value: 'Pacific/Noumea' }, { label: '(GMT+11:00) Ponape', value: 'Pacific/Pohnpei' }, { label: '(GMT+12:00) Moscow+09 - Petropavlovsk-Kamchatskiy', value: 'Asia/Kamchatka' }, { label: '(GMT+13:00) Auckland', value: 'Pacific/Auckland' }, { label: '(GMT+13:00) Fiji', value: 'Pacific/Fiji' }, { label: '(GMT+12:00) Funafuti', value: 'Pacific/Funafuti' }, { label: '(GMT+12:00) Kwajalein', value: 'Pacific/Kwajalein' }, { label: '(GMT+12:00) Majuro', value: 'Pacific/Majuro' }, { label: '(GMT+12:00) Nauru', value: 'Pacific/Nauru' }, { label: '(GMT+12:00) Tarawa', value: 'Pacific/Tarawa' }, { label: '(GMT+12:00) Wake', value: 'Pacific/Wake' }, { label: '(GMT+12:00) Wallis', value: 'Pacific/Wallis' }, { label: '(GMT+14:00) Apia', value: 'Pacific/Apia' }, { label: '(GMT+13:00) Enderbury', value: 'Pacific/Enderbury' }, { label: '(GMT+13:00) Fakaofo', value: 'Pacific/Fakaofo' }, { label: '(GMT+13:00) Tongatapu', value: 'Pacific/Tongatapu' }, { label: '(GMT+14:00) Kiritimati', value: 'Pacific/Kiritimati' } ] export {TIME_ZONES, DEFAULT_TIME_ZONE}
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React, { Component } from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import AppBar from 'material-ui/AppBar'; import { createStructuredSelector } from 'reselect'; import { selectIsAuthenticated, selectUser } from './selectors'; import Main from './Main'; import Container from './Container'; import NavigationBar from '../NavigationBar'; import NotificationList from '../NotificationList'; import RequestHandler from '../RequestHandler'; class App extends Component { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; handleTouchTap(e) { e.preventDefault(); browserHistory.push('/'); } render() { const { isAuthenticated, user } = this.props; return ( <div> <NavigationBar isAuthenticated={isAuthenticated} user={user} /> <Main> <AppBar title="My Awesome App Name" onTitleTouchTap={this.handleTouchTap} /> <Container> {React.Children.toArray(this.props.children)} </Container> <NotificationList /> <RequestHandler /> </Main> </div> ); } } const mapStateToProps = createStructuredSelector({ isAuthenticated: selectIsAuthenticated(), user: selectUser(), }); App.propTypes = { isAuthenticated: React.PropTypes.bool, user: React.PropTypes.object, }; export default connect(mapStateToProps)(App);
// ------------------------------------------- // Pipe resources to/from another source // ------------------------------------------- export default function db(ripple, { db = {} } = {}){ log('creating') ripple.on('change.db', crud(ripple)) ripple.adaptors = ripple.adaptors || {} ripple.connections = keys(db) .map(k => connect(ripple)(k, db[k])) .reduce(to.obj, {}) return ripple } const connect = ripple => (id, config) => { if (!config) return { id, invalid: err('no connection string', id) } is.str(config) && (config = { type : (config = config.split('://')).shift() , user : (config = config.join('://').split(':')).shift() , database: (config = config.join(':').split('/')).pop() , port : (config = config.join('/').split(':')).pop() , host : (config = config.join(':').split('@')).pop() , password: config.join('@') }) if (values(config).some(not(Boolean))) return { id, invalid: err('incorrect connection string', id, config) } const connection = (ripple.adaptors[config.type] || noop)(config) return connection ? (connection.id = id, connection) : ({ id, invalid: err('invalid connection', id) }) } const crud = ripple => (name, change) => { const { key, value, type } = change || {} , res = ripple.resources[name] if (!header('content-type', 'application/data')(res)) return if (header('silentdb')(res)) return delete res.headers.silentdb if (!type) return const updated = values(ripple.connections) .filter(con => con.change && con.change(type)(res, change)) .map(d => d.id) if (updated.length) log('crud', type, name, updated.join(',').grey) } import header from 'utilise/header' import values from 'utilise/values' import noop from 'utilise/noop' import keys from 'utilise/keys' import not from 'utilise/not' import is from 'utilise/is' import to from 'utilise/to' const err = require('utilise/err')('[ri/db]') , log = require('utilise/log')('[ri/db]')
var twgl = window.twgl; var mat4 = require('gl-matrix').mat4; var vec3 = require('gl-matrix').vec3; function Entity(gl) { this.gl = gl; this.model = mat4.create(); this.inc = 0; this.program = null; this.programwrap = null; this.uniforms = { model: this.model }; }; Entity.prototype.bindMesh = function(mesh) { this.mesh = mesh; this.program = mesh.program; this.programwrap = mesh.programWrap; }; Entity.prototype.render = function() { this.mesh.render(); }; Entity.prototype.applyCustomUniforms = function(customUniforms) { for (var i = 0; i < customUniforms.length; i++) { this.uniforms[customUniforms[i][0]] = customUniforms[i][1]; }; }; Entity.prototype.setUniform = function(uniformKey, data) { this.uniforms[uniformKey] = data; }; Entity.prototype.setCustomUniforms = function() { //Set uniforms // console.log(this.uniforms); twgl.setUniforms(this.programwrap, this.uniforms); }; module.exports = Entity;
/** * Templates */ Template.messages.helpers({ messages: function() { return Messages.find({}, { sort: { time: -1}}); } }) Template.input.events = { 'keydown input#message' : function (event) { if (event.which == 13) { // 13 is the enter key event if (Meteor.user()) var name = Meteor.user().profile.name; else var name = 'Anonymous'; var message = document.getElementById('message'); if (message.value != '') { Messages.insert({ name: name, message: message.value, time: Date.now(), }); document.getElementById('message').value = ''; message.value = ''; } } } }
/** * Token Scheduler * @namespace Services */ (() => { 'use strict'; angular .module('admin') .service('TokenScheduler', TokenScheduler); function TokenScheduler($interval, $http, TokenService) { this.refresh = refresh; //// function refresh(interval) { $interval(function () { $http.get('/api/refresh').then(function (res) { TokenService.save(res.data.data.token) }); }, interval || 1000); } } })();
/** * INSPINIA - Responsive Admin Theme * * Inspinia theme use AngularUI Router to manage routing and views * Each view are defined as state. * Initial there are written stat for all view in theme. * */ function config($stateProvider, $urlRouterProvider) { $urlRouterProvider.otherwise("/index/main"); $stateProvider .state('index', { abstract: true, url: "/index", templateUrl: "views/common/content.html" }) .state('index.main', { url: "/main", templateUrl: "views/main.html", data: { pageTitle: 'Example view' } }) .state('index.question1', { url: "/question1", templateUrl: "views/question1.html", data: { pageTitle: 'Example view' } }) .state('index.question2', { url: "/question2", templateUrl: "views/question2.html", data: { pageTitle: 'Example view' } }) .state('index.question3', { url: "/question3", templateUrl: "views/question3.html", data: { pageTitle: 'Example view' } }) .state('index.question4', { url: "/question4", templateUrl: "views/question4.html", data: { pageTitle: 'Example view' } }) .state('index.question5', { url: "/question5", templateUrl: "views/question5.html", data: { pageTitle: 'Example view' } }) .state('index.map', { url: "/map", templateUrl: "views/map.html", data: { pageTitle: 'Example view' }, controller: "mapCtrl" }) } angular .module('inspinia') .config(config) .run(function($rootScope, $state) { $rootScope.$state = $state; });
// Generated by CoffeeScript 1.12.4 var actions, continueIterator, debug, debugAction, debugging, evaluateDebugStatus, flagPause, iterator, memory, onmessage, output, representation, resume, sendPaused, vm; importScripts('/lib/cmm/index.min.js'); memory = new cmm.Memory; debug = new cmm.Debugger; vm = null; iterator = null; debugging = false; flagPause = false; output = function(string) { return postMessage({ event: "output", data: { string: string } }); }; actions = {}; actions.input = function(arg) { var input, wasWaiting; input = arg.input; if (debugging) { wasWaiting = vm.isWaitingForInput(); vm.input(input); if (vm.isWaitingForInput()) { return evaluateDebugStatus(vm); } else if (wasWaiting && (iterator != null)) { return continueIterator(); } } else { return resume(input); } }; actions.compile = function(arg) { var ast, code, description, error, goingToRun, message, program, ref; code = arg.code, goingToRun = arg.goingToRun; try { ref = cmm.compile(code), program = ref.program, ast = ref.ast; } catch (error1) { error = error1; message = error.getMessage(code); description = error.description; postMessage({ event: "compilationError", data: { message: message, description: description } }); return; } postMessage({ event: "compilationSuccessful", data: { instructions: program.instructionsToString(), ast: ast.toString(), goingToRun: goingToRun } }); return program; }; resume = function(input) { var inputted; if (iterator == null) { throw "Not started"; } if (vm != null) { if (input != null) { vm.input(input); } inputted = true; } if (!(vm != null ? vm.isWaitingForInput() : void 0)) { postMessage({ event: "resumeRunning" }); vm = iterator.next().value; if ((input != null) && !inputted) { vm.input(input); } while (!(vm.finished || vm.isWaitingForInput())) { vm = iterator.next().value; } if (vm.finished) { iterator.next(); postMessage({ event: "executionFinish", data: { status: vm.status } }); return iterator = vm = null; } else { return postMessage({ event: "waitingForInput" }); } } else { return postMessage({ event: "waitingForInput" }); } }; actions.run = function(arg) { var code, input, program; code = arg.code, input = arg.input; program = actions.compile({ code: code, goingToRun: true }); if (program != null) { postMessage({ event: "startRunning" }); debugging = false; program.attachMemory(memory); program.attachOutputListener(output); iterator = cmm.run(program); return resume(input); } }; representation = function(value, type) { if (type.id === 'CHAR') { return "'" + value.toString() + "'"; } else if (type.id === 'STRING') { return '"' + value.toString() + '"'; } else { return value; } }; sendPaused = function() { var isArray, isChar, ref, type, value, varId, variable, variables; variables = {}; ref = vm.instruction.visibleVariables; for (varId in ref) { variable = ref[varId]; type = variable.type; isChar = type.id === 'CHAR'; isArray = type.isArray; if (isArray) { value = type.castings.COUT(variable.memoryReference.getAddress()); } else { value = type.castings.COUT(variable.memoryReference.read(memory)); } variables[varId] = { type: type.getSymbol(), value: value, "const": variable.specifiers["const"], isArray: isArray, repr: representation(value, type), isChar: isChar }; } return postMessage({ event: "paused", data: { variables: variables } }); }; evaluateDebugStatus = function() { if (!vm.finished && vm.instruction.breakpoint) { sendPaused(); } else if (vm.isWaitingForInput()) { postMessage({ event: "waitingForInput" }); } else if (vm.finished) { postMessage({ event: "executionFinish", data: { status: vm.status } }); iterator = vm = null; } else { sendPaused(); } if ((vm != null ? vm.instruction.locations : void 0) != null) { return postMessage({ event: "currentLine", data: { line: vm.instruction.locations.lines.first } }); } }; continueIterator = function() { var done, ref, ref1, vmCopy; postMessage({ event: "resumeRunning" }); vmCopy = vm; ref = iterator.next(), vm = ref.value, done = ref.done; while (!(done || vm.isWaitingForInput())) { vmCopy = vm; ref1 = iterator.next(), vm = ref1.value, done = ref1.done; } if (done) { iterator = null; vm = vmCopy; } return evaluateDebugStatus(vm); }; actions.debug = function(arg) { var code, input, program; code = arg.code, input = arg.input; program = actions.compile({ code: code, goingToRun: true }); if (program != null) { postMessage({ event: "startDebugging" }); debugging = true; program.attachMemory(memory); program.attachOutputListener(output); iterator = debug.debug(program); vm = iterator.next().value; if (input != null) { vm.input(input); } vm = iterator.next().value; return evaluateDebugStatus(vm); } }; debugAction = function(name) { if (vm.isWaitingForInput()) { postMessage({ event: "waitingForInput" }); return iterator = debug[name](); } else { postMessage({ event: "resumeRunning" }); iterator = debug[name](); vm = iterator.next().value; return evaluateDebugStatus(vm); } }; actions.stepOver = function() { return debugAction('stepOver'); }; actions.stepInto = function() { return debugAction('stepInto'); }; actions.stepOut = function() { return debugAction('stepOut'); }; actions.stepInstruction = function() { return debugAction('stepInstruction'); }; actions.endOfInput = function() { if (vm != null) { vm.endOfInput(); return resume(); } }; actions["continue"] = function() { return debugAction('continue'); }; actions.addBreakpoint = function(arg) { var breakpoint; breakpoint = arg.breakpoint; return debug.addBreakpoints(breakpoint); }; actions.removeBreakpoint = function(arg) { var breakpoint; breakpoint = arg.breakpoint; return debug.removeBreakpoints(breakpoint); }; actions.setVariable = function(arg) { var cannotParse, error, id, reference, value, variable; id = arg.id, value = arg.value; variable = vm.instruction.visibleVariables[id]; try { value = variable.type.parse(value); } catch (error1) { error = error1; cannotParse = true; } if (cannotParse) { return postMessage({ event: "invalidVariableValue", data: { id: id, value: value } }); } else { reference = variable.memoryReference; reference.write(memory, value); value = variable.type.castings.COUT(value); return postMessage({ event: "variableSet", data: { id: id, value: value, repr: representation(value, variable.type) } }); } }; onmessage = function(e) { var command, data; data = e.data; command = data.command; if (actions[command] == null) { throw "invalid command " + command; } else { return actions[command](data); } };
var SwaggerTools = require('swagger-tools'); function validateOutputSwagger(swagger2Document) { var spec = require('swagger-tools').specs.v2; spec.validate(swagger2Document, function(err, result) { if (err) { throw err; } if (typeof result !== 'undefined') { if (result.errors.length > 0) { console.log('The output Swagger document is invalid...'); console.log(''); console.log('Errors'); console.log('------'); result.errors.forEach(function (err) { console.log('#/' + err.path.join('/') + ': ' + err.message); }); console.log(''); } if (result.warnings.length > 0) { console.log('Warnings'); console.log('--------'); result.warnings.forEach(function (warn) { console.log('#/' + warn.path.join('/') + ': ' + warn.message); }); } if (result.errors.length > 0) { process.exit(1); } } else { console.log('Output Swagger document is valid.'); } }); } function validateInputSwagger(resourceListing, apiDeclarations) { var spec = require('swagger-tools').specs.v1; spec.validate(resourceListing, apiDeclarations, function (err, result) { var errorCount = 0; if (typeof result !== 'undefined') { console.log('Invalid input Swagger document...'); console.log(''); if (result.errors.length > 0) { errorCount += result.errors.length; console.log('Errors'); console.log('------'); result.errors.forEach(function (err) { console.log('#/' + err.path.join('/') + ': ' + err.message); }); console.log(''); } if (result.warnings.length > 0) { console.log('Warnings'); console.log('--------'); result.warnings.forEach(function (warn) { console.log('#/' + warn.path.join('/') + ': ' + warn.message); }); console.log(''); } if (result.apiDeclarations) { result.apiDeclarations.forEach(function (adResult, index) { var errorHeader = 'API Declaration (' + apiDeclarations[index].resourcePath + ') Errors'; var warningHeader = 'API (' + apiDeclarations[index].resourcePath + ') Warnings'; if (adResult.errors.length > 0) { errorCount += adResult.errors.length; console.log(errorHeader); console.log(new Array(errorHeader.length + 1).join('-')); adResult.errors.forEach(function (err) { console.log('#/' + err.path.join('/') + ': ' + err.message); }); console.log(''); } if (adResult.warnings.length > 0) { console.log(warningHeader); console.log(new Array(warningHeader.length + 1).join('-')); adResult.warnings.forEach(function (warn) { console.log('#/' + warn.path.join('/') + ': ' + warn.message); }); console.log(''); } }); } if (errorCount > 0) { process.exit(1); } } else { console.log('Input Swagger document is valid... Continuing'); } }); } exports.validateInputSwagger = validateInputSwagger; exports.validateOutputSwagger = validateOutputSwagger;
import React, { Component, PropTypes } from 'react'; import { target } from 'react-aim'; const styles = { container: { position: 'absolute', width: '122px', height: '142px' }, progress: { backgroundColor: 'rgba(0, 0, 0, .1)', border: '1px solid rgba(0, 0, 0, .2)', height: '8px', width: '120px', position: 'relative', marginTop: '10px' }, bar: { width: '0%', height: '8px', backgroundColor: '#76e542' } }; @target( { mouseEnter: (props, component) => { component.setState({ over: true }); }, mouseLeave: (props, component) => { component.setState({ over: false }); }, aimMove: (props, component, distance) => { component.setState({ distance }); }, aimStart: (props, component, distance) => { component.setState({ distance }); }, aimStop: (props, component) => { component.setState({ distance: null }); } } ) class Item extends Component { static propTypes = { top: PropTypes.string, left: PropTypes.string, width: PropTypes.string, height: PropTypes.string, color: PropTypes.string }; constructor() { super(); this.state = { distance: null, over: false } } componentWillMount() { const maxX = window.innerWidth - parseInt(styles.container.width) + 1; const maxY = window.innerHeight - parseInt(styles.container.height) + 1; this.setState({ x: Math.floor(Math.random() * (maxX + 1)), y: Math.floor(Math.random() * (maxY + 1)), maxX, maxY }); } componentDidMount() { window.addEventListener('resize', this.resize) } componentWillUnmount() { window.removeEventListener('resize', this.resize) } resize = () => { const maxX = window.innerWidth - parseInt(styles.container.width) + 1; const maxY = window.innerHeight - parseInt(styles.container.height) + 1; this.setState({ x: 1 / this.state.maxX * maxX * this.state.x, y: 1 / this.state.maxY * maxY * this.state.y, maxX, maxY }); }; render() { const containerStyle = { ...styles.container, top: this.state.y + 'px', left: this.state.x + 'px' }; const barStyle = { ...styles.bar }; let targetColor = '#000000'; if (this.state.over) { barStyle.width = '100%'; targetColor = '#ff0000'; } else if (this.state.distance) { barStyle.width = (this.state.distance * 100) + '%'; targetColor = 'rgb(' + Math.round(this.state.distance * 255) + ', 0, 0)'; } return ( <div style={containerStyle}> <svg x="0px" y="0px" width="122px" height="122px" viewBox="0 0 122 122"> <path fill={targetColor} d="M61,0C27.4,0,0,27.4,0,61c0,33.6,27.4,61,61,61c33.6,0,61-27.4,61-61C122,27.4,94.6,0,61,0z M111.8,65.6 c-2.2,24.5-21.6,43.9-46.1,46.2l-3.3,0.3V91.3H60v20.8l-3.3-0.3C32,109.7,12.4,90.3,10.2,65.6l-0.3-3.3H31v-2.4H9.9l0.3-3.3 c2.1-24.8,21.7-44.4,46.5-46.5L60,9.9v21h2.4v-21l3.3,0.3c24.6,2.3,44,21.8,46.1,46.4l0.3,3.3H91.4v2.4h20.7L111.8,65.6z" /> </svg> <div style={styles.progress}><div style={barStyle}/></div> </div> ); } } export default Item;
(function() { "use strict"; var CommentModel = Backbone.Model.extend({ validate: function(attr) { if( !attr.email ) { alert('Email Required!'); return; } if ( !attr.content ) { alert('Comment field cannot be blank!'); return; } }, initialize: function() { this.content = this.get('content'); this.email = this.get('email') } }); var CommentsCollection = Backbone.Collection.extend({ model: CommentModel, localStorage: [], url: '/comments' }); var CommentView = Backbone.View.extend({ tagName: 'li', // Super anit-pattern terrible >.< template: "<header> <span class='author-email'><img src='http://gravatar.com/avatar/<%= hash %>" + "?s=32' alt='user picture' /></span>" + " <span class='date'><%= formatDate %></span> " + // the time will come when comments have to be deleted or break down and make an admin UI // " <nav> [<a href='#' class='delete'>x</a>] </nav>" + " </header> <div class='comment-content'> <%= content %> </div>", events: { 'click .delete': 'destroy', }, initialize: function(params) { if( !this.model ) { throw new Error('You must provide a Comment model'); }; this.$el.attr( "class", "list-group-item" ); this.listenTo( this.model, 'remove', this.remove ); this.listenTo( this.model, 'sync', this.render ); }, render: function(){ var commentInfo = { hash: md5(this.model.email), content: this.model.content, formatDate: this.model.get('created_at'), } var template = _.template( this.template ) this.$el.html( template(commentInfo) ); return this.$el; }, destroy: function(event){ event.preventDefault(); this.model.destroy(); }, formatDate: function(){ var date = this.model.get('created_at'); return date; }, }); var commentsApp = Backbone.View.extend({ el: $('.comments'), initialize: function() { this.collection = new CommentsCollection(); this.listenTo( this.collection, 'add', this.renderComment ); this.listenTo( this.collection, 'add', this.renderCommentCount ); this.collection.fetch(); }, events: { 'submit form': 'createComment', }, createComment: function(event) { event.preventDefault(); // Create a new Comment Model with the data in the form var comment = { content: this.$('form textarea').val(), email: this.$('#user-email').data('email'), created_at: +new Date() }; // The `validate` option ensures that empty comments aren't added this.collection.create( comment, { validate: true }); }, renderComment: function(model) { if (!model.content) return; model.view = new CommentView( { model:model } ); this.$('#comment-list').prepend( model.view.render() ); this.resetFormFields(); }, renderCommentCount: function() { var length = this.collection.length; var commentText = length === 1 ? ' Comment' : ' Comments'; $('.comment-count').text( length + commentText ) }, resetFormFields: function() { this.$('form textarea, form input[name="email"]').val(null); }, }); $(function(){ window.comments = new commentsApp(); browserid.onLogin = function(data) { window.location.reload(); } browserid.onLogout = function(data) { window.location.reload(); } // bootstrap modal fix // Mobile Modal fix $('.modal-dialog').css('display', 'none'); $('.project-container, #connect-trigger').on('click', function() { if ( $('.modal-dialog').css('display') === 'none' ) { $('.modal-dialog').css('display', 'block'); } }); $('.close').on('click', function() { if ( $('.modal-dialog').css('display') === 'block' ) { $('.modal-dialog').css('display', 'none'); } }); }); })();
version https://git-lfs.github.com/spec/v1 oid sha256:053a29e73c6de07154e69778eecfa87c5ba269386cbe5eb221b90c522d1f6c5a size 798
(function( jQuery, undefined ){ jQuery.fn.extend( { treeControl : function( x ) { var e; try{ $.map( this, function( el, idx ){ var rand = function(){ var dt = new Date(); return Math.floor( Math.random()*dt.getTime() ); } var treeRoot = function( className ){ var nm = '' + x.theme + '-tree-root'; if( className ){ return nm; }else{ return x.obj.find( 'ul.' + nm ); } } x.obj = $( el ); x.name = x.name || function( obj ){ return obj.name; } // function, returning name x.root = x.root || 'top' // root element & root query x.theme = x.theme || 'custom' // theme class predicate x.info = x.info || function(){}; x.animate = x.animate || 500; x.preloader = x.preloader || 1 // 0 -- do not use || 1 -- use at startup || use always x.classes = x.classes || {}; $.extend( x.classes , $.extend( { treeLeaf : 'tree-leaf' , heading : 'heading' , control : 'control' , status : 'status' , loader : 'loader' , selected : 'selected' , preloader : 'preloader' , hover : 'hover' } , x.classes ) ); x.control = x.control || { text : ['+', '&ndash;'], cls : 'open' }; // x.template must be jq.tmpl() x.template = x.template || '<li><span class = "' + x.classes.heading + '">${obj.name}</span><ul class = "' + x.classes.treeLeaf + '"></ul></li>'; x.ctrlTpl = x.ctrlTpl || '<span class = "' + x.classes.control + '"></span>'; x.statusTpl = x.statusTpl || '<span class = "' + x.classes.status + '"></span>'; x.current = null; // evt.data.x.current when x.handlers.select/blur x.handlers = x.handlers || {}; $.extend( x.handlers, $.extend( { control : false // function that fires after leaf control state changes +/- , select : false // function that fires after leaf heading select occures , blur : false // function that fires after leaf heading select blurs selection , leafsAdd : false // what to do after leaf add, attrs : ( leaf, controlObject ) } , x.handlers ) ); x.cbcs = { click : function( evt ){ try{ evt.stopPropagation(); var result2 = function(){ try{ var elem = evt.data.leaf; x.current = elem; $( x.current.elem.heading ).addClass( x.classes.selected ); try{ ( x.callbacks && x.callbacks.click) && x.callbacks.click ( elem ); }catch(e){ alert(e); } x.handlers.select && x.handlers.select( elem ); }catch(e){ alert(e); } } if( x.current ){ var result = function(){ $( x.current.elem.heading ).removeClass( x.classes.selected ); result2(); } if( x.handlers.blur ) { x.handlers.blur( x.current , result ) ; }else{ result(); } }else{ result2(); } }catch(e){ alert(e); } } , mouseover : function( evt ){ var elem = evt.data.leaf; $( elem.elem.heading ).addClass( x.classes.hover ); try{ ( x.callbacks && x.callbacks.mouseover) && x.callbacks.mouseover ( elem ); }catch(e){ alert(e); } } , mouseout : function( evt ){ var elem = evt.data.leaf; $( elem.elem.heading ).removeClass( x.classes.hover ); try{ ( x.callbacks && x.callbacks.mouseout) && x.callbacks.mouseout ( elem ); }catch(e){ alert(e); } } }; if( $.cookie ) { if( x.saveState !== undefined ){ if( typeof( x.saveState ) !== 'object' ) { x.saveState = { name : 'tree_control_cookie_name', opts : { expires: 7 } }; } if($.cookie( x.saveState.name ) == null){ $.cookie( x.saveState.name , '', x.saveState.opts ); } } } x.templateName = 'treeLeafTemplate' + rand(); $.template( x.templateName, x.template ); x.obj.on( 'click', function( evt ){ try{ // var tf = ( $(evt.target).parentsUntil('ul.'+x.classes.treeLeaf).length == 0 ); if( x.current ){ x.handlers.blur && x.handlers.blur( x.current , function(){ $( x.current.elem.heading ).removeClass( x.classes.selected ); x.current = null; }); } }catch(e){ alert(e); } } ); var getPath = function( leaf , parent ){ if( leaf ){ var arr = []; var construct = function( leaf ){ arr.push( leaf ); if( leaf.parent ){ construct( leaf.parent ); } }; construct( leaf ); arr.reverse(); parent && arr.pop(); var str = ''; $.map( arr, function(el){ str += '/' + el.name; } ); return { str : str, arr : arr , leaf : parent ? ( leaf.parent ? leaf.parent : treeViewModel ) : leaf }; }else{ return { str : '/' + treeViewModel.name , arr : [ treeViewModel ] , leaf : treeViewModel }; } } var gsCook = function( leafObj , ret ) { try{ if( $.cookie && x.saveState && leafObj ){ var cook = $.cookie( x.saveState.name ); if( cook.length > 0 ) { var cook = cook.split(','); var inarr = $.inArray( encodeURIComponent( getPath( leafObj ).str ), cook ); if( ret ) { if( inarr === ( -1 ) ){ return false; }else{ return true; } } else{ if( inarr === ( -1 ) ){ if( leafObj.obj.open == true ){ cook.push( encodeURIComponent( getPath( leafObj ).str ) ); } }else{ if( leafObj.obj.open == false ){ cook.splice( inarr, 1 ); } } } }else{ cook = []; if( ret ) { return false; } else { if ( leafObj.obj.open == true ){ cook.push( encodeURIComponent( getPath( leafObj ).str ) ); } } } $.cookie( x.saveState.name , cook.join(), x.saveState.opts ); }else{ if( ret ){ return false; } } }catch(e){ alert(e); if( ret ){ return false; } } } var makeLeaf = function( preObj , parent ){ try{ preObj = preObj || { name : '' }; var obj = { obj : preObj , name : preObj.name , children : [] , parent : parent }; obj.obj.name = x.name( preObj ); if( obj.obj.open ){ gsCook( obj ); } else{ obj.obj.open = gsCook( obj , true ); } return obj; }catch(e){ alert(e); return false; } } x.obj.addClass( treeRoot(true) ); x.obj.html( $('<ul class = "' + treeRoot( true ) + '"></ul>') ); var treeViewModel = makeLeaf( { name : x.root, open : true } ); treeViewModel.elem = {}; treeViewModel.elem.ul = x.obj.find( 'ul.' + treeRoot( true ) ); x.treeRoot = treeRoot; var makeElem = function( object, num ){ var elem = { li : object.find('li')[ num ] }; elem.ul = $( elem.li ).find( 'ul.' + x.classes.treeLeaf ); elem.heading = $( elem.li ).find( 'span.' + x.classes.heading ); elem.heading.before( x.ctrlTpl ); elem.heading.before( x.statusTpl ); elem.status = $( elem.li ).find( 'span.' + x.classes.status ); elem.control = $( elem.li ).find( 'span.' + x.classes.control ); return elem; } var leafControl = function( leaf , addCallback ){ if( leaf.obj.folder ){ if( leaf.obj.open ){ gsCook( leaf ); // ADD leaf.elem.control.html( x.control.text[1] ); leaf.elem.status.addClass( x.control.cls ); if( leaf.children.length == 0 ) { (function( leaf , cb ){ window.setTimeout( function(){ controlObject.leaf( leaf , cb ); }, x.animate ); })( leaf , addCallback ); }else{ leaf.elem.ul.slideDown( x.animate ); } }else{ gsCook( leaf ); // DELETE leaf.elem.control.html( x.control.text[0] ); leaf.elem.status.removeClass( x.control.cls ); leaf.elem.ul.slideUp( x.animate ); } }else{ leaf.elem.control.html( x.control.text[1] ); leaf.elem.control.removeClass( x.control.cls ); } x.handlers.control && x.handlers.control( leaf ); } var parseLeaf = function( leaf, obj, pl_callback ) { // where to add, what JSON to add, try{ object = leaf.elem.ul; object.hide(); object.empty(); leaf.children = []; // leafControl( leaf ); for( var i = 0; i < obj.length; i++ ){ leaf.children.push( makeLeaf( obj[i] , leaf ) ); } $.tmpl( x.templateName, leaf.children ).appendTo( object ); for( var i = 0; i < leaf.children.length; i++ ){ var child = leaf.children[ i ]; elem = makeElem( object, i ); child.obj.open = child.obj.open || false ; child.elem = elem; leafControl( child ); try{ elem.control.on( 'click', { leaf: child }, function( evt ) { var leaf = evt.data.leaf; leaf.obj.open = !leaf.obj.open; leafControl( leaf ); } ); for( var k in x.cbcs ){ ( function( evtype, callback ){ elem.heading.on( evtype, { leaf: child }, callback ); })( k, x.cbcs[ k ] ); } }catch(e){ alert(e); } } object.slideDown( x.animate , function(){ pl_callback && pl_callback( leaf , controlObject ); x.handlers.leafsAdd && x.handlers.leafsAdd( leaf , controlObject ); if( x.preloader > 0){ x.obj.removeClass( x.classes.preloader ); } } ); }catch(e){ alert(e); } } var controlObject = { leaf : function( leaf , callback ) { try{ var cb = function( data ){ try{ // leaf.elem.heading && leaf.elem.heading.removeClass( x.classes.loader ); controlObject.shLoader( leaf , false ); if( data !== '' ){ x.info( 'leaf data received :\n'+data); parseLeaf( leaf , $.parseJSON( data ) , callback ); } }catch(e){ alert(e); } } if( x.preloader > 1){ x.obj.addClass( x.classes.preloader ); } leaf.elem.heading && leaf.elem.heading.addClass( x.classes.loader ); controlObject.shLoader( leaf , true ); x.ws( getPath( leaf ).str, cb ); }catch(e){ alert(e); } } , shLoader : function( leaf , tf ){ try{ if( leaf.elem.heading ){ if( tf ){ leaf.elem.heading.addClass( x.classes.loader ); }else{ leaf.elem.heading.removeClass( x.classes.loader ); } } }catch(e){ alert(e); } } , getPath : getPath , currentPath : function( parent ){ return getPath( x.current , parent ); } , ws : x.ws , x : x , treeViewModel : treeViewModel , leafControl : leafControl }; try{ window.setTimeout( function(){ if( x.preloader > 0){ x.obj.addClass( x.classes.preloader ); } controlObject.leaf( treeViewModel ); }, x.init[0] ); }catch(e){ alert(e); } // x.obj.attr( 'tree' , controlObject ); // not working, because $.attr() sets it to 'string' x.obj.prop( 'tree' , controlObject ); //x.obj[0].tree = controlObject; return x.obj; } ); }catch(e){ alert(e); } } } ); })( jQuery );
var dgram = require('dgram'); function searchModulesNet() { var message = Buffer.from('vasily-rpi'); var client = dgram.createSocket('udp4'); //client.setBroadcast(true); //client.setMulticastLoopback(true); var client2 = dgram.createSocket('udp4'); //client2.setBroadcast(true); //client2.setMulticastLoopback(true); // search ESP8266 modules client.send(message, 3234, '239.255.255.50', (err) => { console.log(err) client.close(); }); // search Arduino modules client2.send(message, 3235, '239.255.255.51', (err) => { console.log(err) client2.close(); }); } exports.searchModulesNet = searchModulesNet;
if (typeof require !== 'undefined') var TilePosition = require('./tilePosition.js'); function GameState(tileBag = {}) { this.flowState = GameState.FlowStateEnum.NOTFLOWING; this.tilePositions = []; this.nextTile = undefined; this.tileBag = tileBag; this.timer = 0; this.entryTile = undefined; } GameState.prototype.inFlowState = function (flowState) { return this.flowState === flowState; } GameState.FlowStateEnum = { NOTFLOWING: 'Not Flowing', FLOWING: 'Flowing', Leaked: 'Leaked' } if (typeof require !== 'undefined') module.exports = GameState;
{ babelHelpers.classCallCheck(this, RandomComponent); return babelHelpers.possibleConstructorReturn( this, (RandomComponent.__proto__ || Object.getPrototypeOf(RandomComponent)).call( this ) ); }
/// <reference path="_references.js" /> var previousCard = null; var phone = navigator.userAgent.match(/Windows Phone/i); $(function () { // Notify the app host that we are running the onload operation. // This will ensure text resources are loaded. if (phone != null) { window.external.notify("onload"); } $("img").one('load', function () { }).each(function () { if (this.complete) $(this).load(); }); $('img').bind('dragstart', function (event) { event.preventDefault(); }); $(document).bind("dragstart", function () { return false; }); var tiles = $(".tile_narrow"); // If the external host is not available, we will make sure to run Initialize on our own. if (phone == null) { Initialize({ "AppBarButtonText": "add", "ResourceLanguage": "en-US", "Turtle": "Turtle", "By": "by:", "Dog": "Dog", "Cat": "Cat", "About": "<p>For more games, visit www.brain.no</p> <p>For your kids' protection, our apps and games for kids will not contain ads or links.</p> <p>Attributions:</p> <p> Martin L(EuroMagic), Magnus Bråth, elizabeth tersigni(ETersigni), John Talbot(jpctalbot), NoiseCollector, mich3d. </p> <p>All content used under Creative Commons Attribution. For complete attribution, visit brain.no</p>", "Mouse": "Mouse", "AboutBox": "About Image Cards", "AppBarMenuItemText": "Menu Item", "ResourceFlowDirection": "LeftToRight", "ApplicationTitle": "IMAGE CARDS FOR KIDS", "Bird": "Bird", "Version": "Version: 1.0" } , false); } }); function BackButton() { mainViewModel.CloseDialog(); } function Initialize(text, isJSON) { // Create the view model and apply bindings. var vm = new mainViewModel(); // Define the global MainViewModel property. mainViewModel = vm; // Parse the text resources, needs to be run before populateCards(). if (isJSON == null) { mainViewModel.Text(ko.mapping.fromJSON(text)); } else { mainViewModel.Text(ko.mapping.fromJS(text)); } mainViewModel.Cards = ko.observableArray(populateCards()); ko.applyBindings(mainViewModel, document.body); } var card = function (name, id) { var self = this; self._name = name; self.Id = ko.observable(id); self.Select = function (event, source) { if (previousCard != null) { previousCard.Selected(false); } previousCard = self; var target = $(source.currentTarget); target.removeClass("flip").addClass("flip"); var wait = window.setTimeout(function () { target.removeClass("flip") }, 1200 ); var wait = window.setTimeout(function () { self.Selected(true); var myVideo = document.getElementsByTagName('audio')[0]; myVideo.src = "Assets/Sounds/" + self.Id() + ".mp3"; myVideo.load(); myVideo.play(); }, 200); //self.Audio = new Audio("Assets/Sounds/" + self.Id() + ".mp3"); // buffers automatically when created //self.Audio.play(); } self.Selected = ko.observable(false); self.Url = ko.computed(function () { if (self.Selected()) { return "url(Assets/Images/" + self.Id() + ".jpg)"; } else { return "url()"; } }, self); self.Name = ko.computed(function () { if (self.Selected()) { return self._name; } else { return "?"; } }, self); } function changeTheme(theme) { mainViewModel.Theme(theme); if (theme == "Dark") { $("body").css("color", "white"); } else { $("body").css("color", "black"); } } function populateCards() { var cards = new Array(); cards[0] = new card(mainViewModel.Text().Dog(), "dog01"); cards[1] = new card(mainViewModel.Text().Dog(), "dog02"); cards[2] = new card(mainViewModel.Text().Dog(), "dog03"); cards[3] = new card(mainViewModel.Text().Dog(), "dog04"); cards[4] = new card(mainViewModel.Text().Cat(), "cat01"); cards[5] = new card(mainViewModel.Text().Cat(), "cat02"); cards[6] = new card(mainViewModel.Text().Cat(), "cat03"); cards[7] = new card(mainViewModel.Text().Cat(), "cat04"); cards[8] = new card(mainViewModel.Text().Bird(), "bird01"); cards[9] = new card(mainViewModel.Text().Bird(), "bird02"); cards[10] = new card(mainViewModel.Text().Bird(), "bird03"); cards[11] = new card(mainViewModel.Text().Bird(), "bird04"); cards[12] = new card(mainViewModel.Text().Mouse(), "mouse01"); cards[13] = new card(mainViewModel.Text().Mouse(), "mouse02"); cards[14] = new card(mainViewModel.Text().Mouse(), "mouse03"); cards[15] = new card(mainViewModel.Text().Turtle(), "turtle01"); cards[16] = new card(mainViewModel.Text().Turtle(), "turtle02"); cards[17] = new card(mainViewModel.Text().Turtle(), "turtle03"); arrayShuffle(cards); return cards; } function arrayShuffle(theArray) { var len = theArray.length; var i = len; while (i--) { var p = parseInt(Math.random() * len); var t = theArray[i]; theArray[i] = theArray[p]; theArray[p] = t; } }; var mainViewModel = function (text) { var self = this; self.PreviousCard = null; self.Text = ko.observable(); self.Cards = ko.observableArray(); self.Theme = ko.observable("Dark"); self.LogoUrl = ko.computed(function () { return "Assets/brain_" + self.Theme() + ".png"; }, self); self.BackIconUrl = ko.computed(function () { return "Assets/Icons/" + self.Theme() + "/back.png"; }, self); self.BackIconBackgroundUrl = ko.computed(function () { return "url(Assets/Icons/" + self.Theme() + "/basecircle.png)"; }, self); self.CloseDialog = function () { if ($("#about").is(":visible")) { self.About(); } } self.About = function () { if ($("#about").is(":visible")) { $("#about").hide(); $("#gameboard").fadeIn(); if (phone != null) { window.external.notify("closedialog"); } } else { $("#gameboard").hide(); $("#about").fadeIn(); if (phone != null) { window.external.notify("opendialog"); } } } }
var $mod$380 = core.VW.Ecma2015.Utils.module(require('../moment')); var symbolMap = { '1': '۱', '2': '۲', '3': '۳', '4': '۴', '5': '۵', '6': '۶', '7': '۷', '8': '۸', '9': '۹', '0': '۰' }, numberMap = { '۱': '1', '۲': '2', '۳': '3', '۴': '4', '۵': '5', '۶': '6', '۷': '7', '۸': '8', '۹': '9', '۰': '0' }; exports.default = $mod$380.default.defineLocale('fa', { months: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), monthsShort: 'ژانویه_فوریه_مارس_آوریل_مه_ژوئن_ژوئیه_اوت_سپتامبر_اکتبر_نوامبر_دسامبر'.split('_'), weekdays: 'یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه'.split('_'), weekdaysShort: 'یک‌شنبه_دوشنبه_سه‌شنبه_چهارشنبه_پنج‌شنبه_جمعه_شنبه'.split('_'), weekdaysMin: 'ی_د_س_چ_پ_ج_ش'.split('_'), weekdaysParseExact: true, longDateFormat: { LT: 'HH:mm', LTS: 'HH:mm:ss', L: 'DD/MM/YYYY', LL: 'D MMMM YYYY', LLL: 'D MMMM YYYY HH:mm', LLLL: 'dddd, D MMMM YYYY HH:mm' }, meridiemParse: /قبل از ظهر|بعد از ظهر/, isPM: function (input) { return /بعد از ظهر/.test(input); }, meridiem: function (hour, minute, isLower) { if (hour < 12) { return 'قبل از ظهر'; } else { return 'بعد از ظهر'; } }, calendar: { sameDay: '[امروز ساعت] LT', nextDay: '[فردا ساعت] LT', nextWeek: 'dddd [ساعت] LT', lastDay: '[دیروز ساعت] LT', lastWeek: 'dddd [پیش] [ساعت] LT', sameElse: 'L' }, relativeTime: { future: 'در %s', past: '%s پیش', s: 'چندین ثانیه', m: 'یک دقیقه', mm: '%d دقیقه', h: 'یک ساعت', hh: '%d ساعت', d: 'یک روز', dd: '%d روز', M: 'یک ماه', MM: '%d ماه', y: 'یک سال', yy: '%d سال' }, preparse: function (string) { return string.replace(/[۰-۹]/g, function (match) { return numberMap[match]; }).replace(/،/g, ','); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }).replace(/,/g, '\u060C'); }, ordinalParse: /\d{1,2}م/, ordinal: '%dم', week: { dow: 6, doy: 12 } });
/* * Formula.js - Rich form development * * Copyright (c) 2011 Stephen Roth (designbystephen-at-gmail-dot-com) * * For details, see the Formula web site: http://www.formulajs.com/ * * 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. */ var Formula = Class.create({ version: '0.0.12', Options: { /** * Initial Options */ defaultMessage: "Errors on this form are marked in red", ignoreValidation: false }, //Options{} initialize: function(){ Element.addMethods(this.Element); for(f in this.Array){ Array.prototype[f] = this.Array[f]; } document.observe('dom:loaded', function(){ Formula.load(); }); }, //initialize() load: function(){ /* * This function is loaded after page dom:loaded event */ // Prepare forms on this page this.prepareForms(); // Prepare placeholders on this page if unsupported by HTML5 var i = document.createElement('input'); if(!('placeholder' in i)){ this.preparePlaceholders(); } }, //load() preparePlaceholders: function(){ $$('input[placeholder]').each(function(plh){ plh.writeAttribute({ 'formula_placeholder': plh.readAttribute('placeholder') }); plh.value = plh.readAttribute('placeholder'); plh.addClassName('formula-placeholder'); // Events $w('click drop focus').each(function(ename){ plh.observe(ename, clearPlaceHolder.bind(plh)); }); plh.observe('blur', resetPlaceHolder.bind(plh)); plh.up('form', 0).observe('submit',clearPlaceHolder.bind(plh)); plh.up('form', 0).observe('reset', function(){ function rst(){ plh.value = plh.readAttribute('formula_placeholder'); plh.addClassName('formula-placeholder'); } rst.defer(); }); }); function clearPlaceHolder(e){ if(this.value == this.readAttribute('formula_placeholder')){ this.value = ''; this.removeClassName('formula-placeholder'); } } function resetPlaceHolder(e){ if(this.value == '' ){ this.value = this.readAttribute('formula_placeholder'); this.addClassName('formula-placeholder'); } } }, //preparePlaceholders log: function(errorString){ if(typeof(console) === 'undefined'){ var err = new Error('formula.js: ' + errorString); throw err; }else{ console.log(errorString); } }, //log() setup: function(options){ /** * Overide default options to setup Formula usage on a page */ Formula.Options = Formula.mate(Formula.Options, options); }, //setup() showErrorMessage: function(errors){ errors[0].ind.scrollTo(); var msg = errors[0].msg + '\r\n' + Formula.Options.defaultMessage; alert(msg); }, //showErrorMessage prepareForms: function(){ if($$('form').length<1){Formula.log('No forms exist on this page')} $$('form').each(function(form){ form._ignoreValidation = (form._ignoreValidation||false); form.valid = true; function validate(event){ Event.stop(event); form.valid = true; form.errors = []; form.fire('Formula:validate'); function checkForm(){ if (form.valid) { form.submit(); }else{ Formula.showErrorMessage(form.errors); } } checkForm.defer(); } form.observe('submit', validate.bind(this)); form._validateHandler = validate; form.observe('reset',function(){ function formulaReset(){ form.fire('Formula:reset'); } formulaReset.defer(); }); }); }, //prepareForms() Validation: Class.create({ // Basic information, can be inherited /* * Every Validation has the following: * Function that it runs to determine validity (f) * A user element that is being validated (element) * A form that the element belongs to * A set of options to extend the function beyond defaults */ initialize: function(element, func, defaultMsg, options){ // Make sure element exists element = $(element); options = (options ||{}); // Grab element's parent form var form; if(element.isType('form')){ form = element; }else{ form = (element.up('form', 0)||null); } if(!form){ Formula.log('No form present for Validation element'); return null; } // Optional information must extend basic Validation class var _options = { cond: true, msg: null, ind: null, useControl: false } // Collect options data using defaults and user specified options options = Formula.mate(_options, options); /** * Establish Error Msg */ var titleMsg = function(title){ if(title){ return 'Please correct an error with "' + title + '"'; }else{ return false; } } options.msg = (options.msg||titleMsg(element.title)||defaultMsg); /** * Establish Error Indicator (ind) */ if(options.ind)options.ind=$(options.ind); if (!options.ind) { // User specified indicator not present if (options.useControl) { // User has not specified an indicator, element = textbox, and useControl is != false options.ind = element; }else{ // highlight a label if we find it $$('label').each(function(l){ if (l.htmlFor == element.id) { options.ind = l; } }); } } if(!options.ind){ // User specified and assumed ind not found Formula.log('Formula.Validation: an error indicator was not specified'); return null; } form.observe('Formula:validate', function(){ if(!Formula.Options.ignoreValidation && !form._ignoreValidation){ if(!element.displayed()){ form.unmarkError(options.ind); return; } if(Object.isString(options.cond) && eval(options.cond)===false){ form.unmarkError(options.ind); return; } if(Object.isFunction(options.cond) && options.cond()===false){ form.unmarkError(options.ind); return; } if(Object.isFunction(func)){ if (!func()) { form.valid = false; form.markError(options.ind, options.msg); }else{ form.unmarkError(options.ind); } }else{ if (eval(func) != true) { form.valid = false; form.markError(options.ind, options.msg); }else{ form.unmarkError(options.ind); } } } }); form.observe('Formula:reset',function(){ form.unmarkError(options.ind); }); return element; } }), //Validation{} Unveil: Class.create({ initialize: function(element, container, f, pEvent, options){ element = $(element); container = $(container); _options = { //default unveil options veil: false } options = Formula.mate(_options, (options||{})); var showHide = function(){ if(f()){ (options.veil) ? container.hide(): container.show(); }else{ (options.veil) ? container.show(): container.hide(); } } showHide(); element.observe(pEvent, function(){ showHide(); }); // Grab element's parent form var form = (container.up('form', 0) || null); if(!form){ Formula.log('Unveil No form present for Unveil container'); return null; } form.observe('Formula:reset',function(){ showHide(); }); } }), //Unveil{} mate: function(collection, extension){ /* * Used primarily to mimic inheritance of option collections for methods * Collection is the default set of options * Extension is the second set of options that: * inherits collection's properties and overwrites with new values if present */ var offspring = collection; for (var prop in extension) { offspring[prop] = extension[prop]; } return offspring; }, //mate() Element: { /** * Utility Methods */ toggleUpdate: function(element, text){ if(element.innerText != text){ element._innerText = element.innerText; element.innerText = text; }else{ element.innerText = element._innerText } return element; }, //toggleUpdate() displayed: function(element){ var visible = true; // Where element = any element element.ancestors().each(function (nest) { if (nest.style.display.toLowerCase() == 'none' || nest.style.visibility.toLowerCase() == 'hidden' || !(nest.offsetWidth > 0 && nest.offsetHeight > 0)) { visible = false; } }); return visible; }, //displayed() isType: function(element, type){ /* * Determines if element is of psuedotype 'type' * pseudotype is either tag name or input type * select, checkbox, textbox, radio */ element = $(element); var psuedotype; if(element.tagName.toLowerCase()!= 'input'){ psuedotype = element.tagName.toLowerCase(); }else{ psuedotype = element.type.toLowerCase(); } if($w(type).length > 1){ type = $w(type); } if(!Object.isArray(type)){ return psuedotype === type.toLowerCase(); }else{ var istype = false; type.each(function(t){ if(t.toLowerCase() == psuedotype){ istype = true; } }); return istype; } }, //Element.isType() /** * Validation Methods */ textRequire: function(element, options){ element = $(element); options = (options||{}); if(!element.isType('text textarea password')){ Formula.log('Element.textRequire requires a valid textbox, password or textarea element'); return null; } var f = function(){ if($F(element) == ''){ return false; }else{ return true; } } new Formula.Validation(element, f, 'A required textbox is blank', options); return element; }, //Element.textRequire() regexpRequire: function(element, regexp, options){ element = $(element); options = (options||{}); if(!element.isType('text textarea')){ Formula.log('Element.regexRequire requires a valid textbox or textarea element'); return null; } try { regexp = new RegExp(regexp); }catch(e){ Formula.log('Element.regexRequire regexp is not a valid Regular Expression'); return null; } var f = function(){ return regexp.test($F(element)); } new Formula.Validation(element, f, 'A textbox is in invalid format', options); return element; }, //Element.regexRequire() selectRequire: function(element, def, options){ element = $(element); options = (options||{}); if(!element.isType('select')){ Formula.log('Element.selectRequire requires a valid select element'); return null; } var f = function(){ def=(def||0); if(Object.isString(def)){ return element.options[element.selectedIndex].text!=def; } if(Object.isNumber(def)){ return element.selectedIndex != def; } } new Formula.Validation(element, f, 'A required dropdownlist is unchanged', options); return element; }, //Element.selectRequire() checkRequire: function(element, options){ element = $(element); options = (options || {}); if(!element.isType('checkbox')){ Formula.log('Element.checkRequire requires a valid checkbox element'); return null; } var f = function(){return element.checked}; new Formula.Validation(element, f, 'A required checkbox is unchecked', options); return element; }, //Element.checkRequire() checkGroupRequire: function(element, req, ind, options){ element = $(element); options = (options||{}); if(!ind){ Formula.log('Element.checkGroupRequire() requires an indicator argument'); return null; }else{ options.ind = ind; } if(element!=null){ //Container list var f = function(){ var cbCount = 0; element.select('input[type~="checkbox"]').each(function(cb){ if(cb.checked)cbCount+=1; }); if(Object.isString(req)){ var check = eval(cbCount+req); if(check==true || check==false){ return check; }else{ Formula.log('String based condition not found for Element.checkGroupRequire()'); return true; } } if(Object.isNumber(req)){ return cbCount >= req; } new Formula.Req(element, f, options); return element; } }else{ Formula.log('Element.checkGroupRequire() requires a container element'); return null; } new Formula.Validation(element, f, 'Required checkbox(es) from a group are unchecked', options); return element; }, //Element.checkGroupRequire() radioRequire: function(element, ind, options){ element = $(element); options=(options||{}); if(!element.name){ Formula.log('Element.radioRequire requires a radio element with a name'); return null; } if(!ind){ Formula.log('Element.radioRequire requires an indicator argument'); return null; }else{ options.ind = ind; } var f = function(){ var chk = false; $$('input[type~="radio"][name~="'+ element.name +'"]').each(function(rb){ if(rb.checked)chk=true; }); return chk; } new Formula.Validation(element, f, 'Required radio button group is unchecked', options); return name; }, //Element.radioGroupRequire() addCustomValidation: function(element, ind, msg, f, options){ element = $(element); options = (options||{}); if(!element.isType('form'))Formula.log('Element.addCustomValidation requires a form element'); options.ind = ind; options.msg = msg; new Formula.Validation(element, f, 'A required custom validator is false', options); return element; }, //Element.addCustomValidation() ignoreValidation: function(element){ element = $(element); if(!element.isType('form')){ Formula.log('Element.ignoreValidation requires a form element'); return null; } element._ignoreValidation = true; return element; }, //Element.ignoreValidation() escapeValidation: function(element){ /* * Used when you must submit a form while ignoring the validation. * This is useful if you only have one form on the page and you have other unrelated submit tasks. */ element = $(element); if(!element.isType('form')){ Formula.log('Element.escapeValidation requires a form element'); return null; } element.stopObserving('submit', element._validationHandler); return element; }, /** * Unveil Methods */ checkUnveil: function(element, container, options){ element = $(element); options = (options||{}); if(!element.isType('checkbox')){ Formula.log('Element.checkUnveil requires a checkbox element'); return null; } if(!container)Formula.log('Element.checkUnveil requires a container argument'); var f = function(){ return element.checked; } new Formula.Unveil(element, container, f, 'click', options); return element; }, //Element.checkUnveil() selectUnveil: function(element, values, container, options){ element = $(element); container = $(container); options = (options||{}); if(!element.isType('select'))Formula.log('Element.selectUnveil requires a dropdownlist element'); if(!container)Formula.log('Element.selectUnveil requires a container argument'); function selectEquals(value){ if(Object.isNumber(value)){ return element.selectedIndex == value; }else if(Object.isString(value)){ return $F(element) == value; }else{ return false; } } if(Object.isArray(values) && values.length > 0){ var f = function(){ var selected = false; values.each(function(v){ if(selectEquals(v)){ selected = true; } }); return selected; } }else{ var f = function(){ return selectEquals(values); } } new Formula.Unveil(element, container, f, 'change', options); return element; }, //Element.selectUnveil() radioUnveil: function(element, container, options){ element = $(element); container = $(container); if(!element.isType('radio')){ Formula.log('Element.radioUnveil requires a radiobutton element'); return null; } element.observe('click', function(){ element.fire('rb:change'); $$('input[type="radio"][name="' + element.name + '"]').each(function(rb){ if(rb!=element){ rb.fire('rb:change'); } }); }); function f(){ return element.checked; } new Formula.Unveil(element, container, f, 'rb:change', options); return element; },//Element.radioUnveil() addCustomUnveil: function(element, container, pEvent, f, options){ element = $(element); container = $(container); options = (options||{}); if(!container){ Formula.log('Element.addCustomUnveil requires a container element'); return null; } if(!element.isType('checkbox select text textarea radio password')){ Formula.log('Element.addCustomUnveil requires an input, or textarea as its element'); return null; } if(!Object.isString(pEvent)){ Formula.log('Element.addCustomUnveil requires an event string'); return null; } new Formula.Unveil(element, container, f, pEvent, options); return element; }, //Element.addCustomUnveil() /** * Check Methods/Other Methods */ toggleCheckAll: function(element, options){ element = $(element); options = (options||{}); var allCheck = true; element.select('input[type~="checkbox"]').each(function(cb){ if(!cb.checked)allCheck = false; }); element.select('input[type~="checkbox"]').each(function(cb){ (allCheck) ? cb.checked = false : cb.checked = true; }); }, //toggleCheckAll() checkGroup: function(element, req, options){ element = $(element); options = (options||{}); req = (req||1); if(!element){ Formula.log('Element.checkGroup() requires a container element'); return null; } var cbs = element.select('input[type~="checkbox"]'); if(!cbs || cbs.length==0){ Formula.log('Element.checkGroup() no checkboxes were found'); return null; } cbs.each(function(cb){ cb.observe('click', doCheck); }); function doCheck(event){ Event.stop(event); var checkCount = 0; cbs.each(function(cb){ if(cb.checked)checkCount+=1; }); function reqMet(){ if(Object.isNumber(req)){ if(checkCount>=req){ return true; }else{ return false; } } if(Object.isString(req)){ var check = eval(checkCount+req); if(check==true || check==false){ return check; }else{ Formula.log('String based condition not found for Element.checkGroup()'); return true; } } } if(reqMet()){ this.checked=false; }else{ this.checked=true; } } return element; }, //checkGroup() checkLimit: function(element, limit, options){ element = $(element); options = (options||{}); limit = (limit||1); if(!element){ Formula.log('Element.checkGroup() requires a container element'); return null; } var cbs = element.select('input[type~="checkbox"]'); if(!cbs || cbs.length==0){ Formula.log('Element.checkGroup() no checkboxes were found'); return null; } cbs.each(function(c){ c.observe('click', function(){ var checkCount=0; cbs.each(function(cb){ if(cb != c&&cb.checked){ checkCount+=1; } }); console.log(checkCount); if(checkCount+1>limit){ this.checked=false; } }); }); return element; }, //checkLimit() markError: function(form, ind, message){ if(!ind.hasClassName('formula-error-input') && ind.isType('text textarea select')){ ind.toggleClassName('formula-error-input'); } if(!ind.hasClassName('formula-error-text') && !ind.isType('text textarea select')){ ind.toggleClassName('formula-error-text'); } if(ind.style.display == 'none'){ ind._wasHidden = true; ind.show(); } form.errors.push({ind: ind, msg: message}); }, //markError() unmarkError: function(form, ind){ ind.removeClassName('formula-error-input'); ind.removeClassName('formula-error-text'); if(ind._wasHidden){ ind.style.display = 'none'; } } //unmarkError() }, //Element{} Array: { checkGroup: function(req, options){ options = (options||{}); req = (req||1); var list = this; if(!list || list.length==0){ Formula.log('Array.checkGroup() no checkboxes were found'); return null; } list.each(function(cb){ var cb = $(cb); if(!cb.isType('checkbox')){ Formula.log('Array.checkGroup: list items need to be checkboxes'); return null; }else{ cb.observe('click', doCheck); } }); function doCheck(event){ Event.stop(event); var checkCount = 0; list.each(function(cb){ cb = $(cb); if(cb.checked)checkCount+=1; }); function reqMet(){ if(Object.isNumber(req)){ if(checkCount>=req){ return true; }else{ return false; } } if(Object.isString(req)){ var check = eval(checkCount+req); if(check==true || check==false){ return check; }else{ Formula.log('String based condition not found for Element.checkGroup()'); return true; } } } if(reqMet()){ this.checked=false; }else{ this.checked=true; } } }//Array.checkGroup() } //Array{} }); if(typeof Prototype == 'undefined'){ throw('Missing Required Scripts'); }else{ Formula = new Formula(); }
var a00353 = [ [ "HID_DEVICES_MAX", "a00843.html#ga49053c3cd6d48fe5f468ce010ac0a9ef", null ], [ "HID_PACKET_MAX", "a00843.html#ga6cdff3589b286ebcdd7771bb425fbf73", null ], [ "atcahid_t", "a00843.html#ga2416cca7ee952e679d466e3349d65035", null ], [ "hid_device_t", "a00843.html#ga5f2f61628e945fd6538155628fc3a17a", null ] ];
/** * @author weism * copyright 2015 Qcplay All Rights Reserved. */ var InputTest = qc.defineBehaviour('qc.demo.InputTest', qc.Behaviour, function() { this.image = null; this.label = null; }, { image: qc.Serializer.NODE, label: qc.Serializer.NODE }); InputTest.prototype.awake = function() { var self = this; this.addListener(self.game.input.onPointerDown, this.onPointerDown, this); this.addListener(self.game.input.onPointerMove, this.onPointerMove, this); this.addListener(self.game.input.onPointerUp, this.onPointerUp, this); }; InputTest.prototype.onPointerDown = function(id, x, y) { console.log('id', id); this.oldPos = new qc.Point(this.image.anchoredX, this.image.anchoredY); this.image.anchoredX = x; this.image.anchoredY = y; this.label.text = 'X:' + x + ', Y:' + y; }; InputTest.prototype.onPointerMove = function(id, x, y) { console.log('id', id); this.image.anchoredX = x; this.image.anchoredY = y; this.label.text = 'X:' + x + ', Y:' + y; }; InputTest.prototype.onPointerUp = function(id, x, y) { console.log('id', id); this.image.anchoredX = this.oldPos.x; this.image.anchoredY = this.oldPos.y; this.label.text = 'X:' + x + ', Y:' + y + ', Mouse:' + this.game.input.isMouse(id); };
var Stream = require('stream'); var tap = require('tap'); var MS = require('../mute.js'); // some marker objects var END = {}; var PAUSE = {}; var RESUME = {}; function PassThrough () { Stream.call(this); this.readable = this.writable = true } PassThrough.prototype = Object.create(Stream.prototype, { constructor: { value: PassThrough }, write: { value: function (c) { this.emit('data', c); return true } }, end: { value: function (c) { if (c) this.write(c); this.emit('end') } }, pause: { value: function () { this.emit('pause') } }, resume: { value: function () { this.emit('resume') } } }); tap.test('incoming', function (t) { var ms = new MS; var str = new PassThrough; str.pipe(ms); var expect = ['foo', 'boo', END]; ms.on('data', function (c) { t.equal(c, expect.shift()) }); ms.on('end', function () { t.equal(END, expect.shift()); t.end() }); str.write('foo'); ms.mute(); str.write('bar'); ms.unmute(); str.write('boo'); ms.mute(); str.write('blaz'); str.end('grelb') }); tap.test('outgoing', function (t) { var ms = new MS; var str = new PassThrough; ms.pipe(str); var expect = ['foo', 'boo', END]; str.on('data', function (c) { t.equal(c, expect.shift()) }); str.on('end', function () { t.equal(END, expect.shift()); t.end() }); ms.write('foo'); ms.mute(); ms.write('bar'); ms.unmute(); ms.write('boo'); ms.mute(); ms.write('blaz'); ms.end('grelb') }); tap.test('isTTY', function (t) { var str = new PassThrough; str.isTTY = true; str.columns = 80; str.rows = 24; var ms = new MS; t.equal(ms.isTTY, false); t.equal(ms.columns, undefined); t.equal(ms.rows, undefined); ms.pipe(str); t.equal(ms.isTTY, true); t.equal(ms.columns, 80); t.equal(ms.rows, 24); str.isTTY = false; t.equal(ms.isTTY, false); t.equal(ms.columns, 80); t.equal(ms.rows, 24); str.isTTY = true; t.equal(ms.isTTY, true); t.equal(ms.columns, 80); t.equal(ms.rows, 24); ms.isTTY = false; t.equal(ms.isTTY, false); t.equal(ms.columns, 80); t.equal(ms.rows, 24); ms = new MS; t.equal(ms.isTTY, false); str.pipe(ms); t.equal(ms.isTTY, true); str.isTTY = false; t.equal(ms.isTTY, false); str.isTTY = true; t.equal(ms.isTTY, true); ms.isTTY = false; t.equal(ms.isTTY, false); t.end() }); tap.test('pause/resume incoming', function (t) { var str = new PassThrough; var ms = new MS; str.on('pause', function () { t.equal(PAUSE, expect.shift()) }); str.on('resume', function () { t.equal(RESUME, expect.shift()) }); var expect = [PAUSE, RESUME, PAUSE, RESUME]; str.pipe(ms); ms.pause(); ms.resume(); ms.pause(); ms.resume(); t.equal(expect.length, 0, 'saw all events'); t.end() }); tap.test('replace with *', function (t) { var str = new PassThrough; var ms = new MS({replace: '*'}); str.pipe(ms); var expect = ['foo', '*****', 'bar', '***', 'baz', 'boo', '**', '****']; ms.on('data', function (c) { t.equal(c, expect.shift()) }); str.write('foo'); ms.mute(); str.write('12345'); ms.unmute(); str.write('bar'); ms.mute(); str.write('baz'); ms.unmute(); str.write('baz'); str.write('boo'); ms.mute(); str.write('xy'); str.write('xyzΩ'); t.equal(expect.length, 0); t.end() }); tap.test('replace with ~YARG~', function (t) { var str = new PassThrough; var ms = new MS({replace: '~YARG~'}); str.pipe(ms); var expect = ['foo', '~YARG~~YARG~~YARG~~YARG~~YARG~', 'bar', '~YARG~~YARG~~YARG~', 'baz', 'boo', '~YARG~~YARG~', '~YARG~~YARG~~YARG~~YARG~']; ms.on('data', function (c) { t.equal(c, expect.shift()) }); // also throw some unicode in there, just for good measure. str.write('foo'); ms.mute(); str.write('ΩΩ'); ms.unmute(); str.write('bar'); ms.mute(); str.write('Ω'); ms.unmute(); str.write('baz'); str.write('boo'); ms.mute(); str.write('Ω'); str.write('ΩΩ'); t.equal(expect.length, 0); t.end() });
define([ 'lib/test', 'models/form', 'views/admin/form_item' ], function(test, FormModel, AdminFormItemView) { return new test.Suite('AdminFormItemView', { setUp: function() { this.form = new FormModel(); this.form.setId(1); this.form.setName("foo"); this.form.setProjectId(1); this.view = new AdminFormItemView(this.form); }, "inserts name": function() { var a = this.view.find('a'); this.assertEquals(a.innerHTML, "foo"); }, "inserts href": function() { var a = this.view.find('a'); this.assertEquals(a.getAttribute('href'), "/admin/forms/1"); }, "updates on change": function() { this.view.build(); this.form.setName("bar"); var a = this.view.find('a'); this.assertEquals(a.innerHTML, "bar"); }, }); });
import Layer from "./Layer"; export default class TileLayer extends Layer { metadata = { properties: { url: { type: "string" }, opacity: { type: "float" } } }; init() { this.container = L.tileLayer(); } setUrl(url) { this.setProperty("url", url); if (url) { this.container.setUrl(url); } } setOpacity(opacity) { this.setProperty("opacity", opacity); this.container.setOpacity(opacity); } }
// Handle input parameters var Logger = require('./eventlog'), optimist = require('optimist'), max = 60, p = require('path'), argv = optimist .demand('file') .alias('f','file') .describe('file','The absolute path of the script to be run as a process.') .check(function(argv){ require('fs').existsSync(p.resolve(argv.f),function(exists){ return exists; }); }) .demand('log') .alias('l','log') .describe('log','The descriptive name of the log for the process') .default('eventlog','APPLICATION') .alias('e','eventlog') .describe('eventlog','The event log container. This must be APPLICATION or SYSTEM.') .default('maxretries',-1) .alias('m','maxretries') .describe('maxretries','The maximim number of times the process will be auto-restarted.') .default('maxrestarts',5) .alias('r','maxrestarts') .describe('maxrestarts','The maximim number of times the process should be restarted within a '+max+' second period shutting down.') .default('wait',1) .alias('w','wait') .describe('wait','The number of seconds between each restart attempt.') .check(function(argv){ return argv.w >= 0; }) .default('grow',.25) .alias('g','grow') .describe('grow','A percentage growth rate at which the wait time is increased.') .check(function(argv){ return (argv.g >= 0 && argv.g <= 1); }) .default('abortonerror','no') .alias('a','abortonerror') .describe('abortonerror','Do not attempt to restart the process if it fails with an error,') .check(function(argv){ return ['y','n','yes','no'].indexOf(argv.a.trim().toLowerCase()) >= 0; }) .argv, log = new Logger(argv.e == undefined ? argv.l : {source:argv.l,eventlog:argv.e}), fork = require('child_process').fork, script = p.resolve(argv.f), wait = argv.w*1000, grow = argv.g+1, attempts = 0, startTime = null, starts = 0, child = null forcekill = false; if (typeof argv.m === 'string'){ argv.m = parseInt(argv.m); } // Set the absolute path of the file argv.f = p.resolve(argv.f); // Hack to force the wrapper process to stay open by launching a ghost socket server var server = require('net').createServer().listen(); /** * @method monitor * Monitor the process to make sure it is running */ var monitor = function(){ if(!child.pid){ // If the number of periodic starts exceeds the max, kill the process if (starts >= argv.r){ if (new Date().getTime()-(max*1000) <= startTime.getTime()){ log.error('Too many restarts within the last '+max+' seconds. Please check the script.'); process.exit(); } } setTimeout(function(){ wait = wait * grow; attempts += 1; if (attempts > argv.m && argv.m >= 0){ log.error('Too many restarts. '+argv.f+' will not be restarted because the maximum number of total restarts has been exceeded.'); process.exit(); } else { launch(); } },wait); } else { attempts = 0; wait = argv.w * 1000; } }; /** * @method launch * A method to start a process. */ var launch = function(){ if (forcekill){ return; } log.info('Starting '+argv.f); // Set the start time if it's null if (startTime == null) { startTime = startTime || new Date(); setTimeout(function(){ startTime = null; starts = 0; },(max*1000)+1); } starts += 1; // Fork the child process child = fork(script,{env:process.env}); // When the child dies, attempt to restart based on configuration child.on('exit',function(code){ log.warn(argv.f+' stopped running.'); // If an error is thrown and the process is configured to exit, then kill the parent. if (code !== 0 && argv.a == "yes"){ log.error(argv.f+' exited with error code '+code); process.exit(); //server.unref(); } // Monitor the process monitor(); }); }; var killkid = function(){ forcekill = true; child.kill(); /*if (child.pid) { require('child_process').exec('taskkill /F /PID '+child.pid,function(){ process.exit(0); }); }*/ } process.on('exit',killkid); process.on("SIGINT", killkid); process.on("SIGTERM", killkid); // Launch the process launch();
/** * [format description] * @param {[type]} time [new Date] * Thu May 18 2017 16:25:35 GMT+0800 (CST) * 16:25:35 * @return {[type]} [description] */ function format(time) { return time.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, '$1'); } function run(fn, options) { console.log('......run.......'); console.log(fn); const task = typeof fn.default === 'undefined' ? fn : fn.default; const start = new Date(); console.info(`[${format(start)}] Starting ${task.name}${options ? `(${options})` : ''}...`); return task(options).then((resolution) => { const end = new Date(); const time = end.getTime() - start.getTime(); console.info(`[${format(end)}] Finished ${task.name}${options ? `(${options})` : ''}...after${time}ms`); return resolution; }); } if (require.main === module && process.argv.length > 2) { console.log('hello world.ing...'); console.log(process.argv); // eslint-disable-next-line no-underscore-dangle delete require.cache[__filename]; // eslint-disable-next-line global-require, import/no-dynamic-require const module = require(`./${process.argv[2]}.js`).default; console.log(module); run(module).catch((err) => { console.error(err.stack); process.exit(1); }); } export default run;
var files = { "webgl": [ "webgl_animation_cloth", "webgl_animation_keyframes_json", "webgl_animation_scene", "webgl_animation_skinning_blending", "webgl_animation_skinning_morph", "webgl_camera", "webgl_camera_array", "webgl_camera_cinematic", "webgl_camera_logarithmicdepthbuffer", "webgl_clipping", "webgl_clipping_advanced", "webgl_clipping_intersection", "webgl_decals", "webgl_depth_texture", "webgl_effects_anaglyph", "webgl_effects_parallaxbarrier", "webgl_effects_peppersghost", "webgl_effects_stereo", "webgl_framebuffer_texture", "webgl_geometries", "webgl_geometries_parametric", "webgl_geometry_colors", "webgl_geometry_colors_blender", "webgl_geometry_colors_lookuptable", "webgl_geometry_convex", "webgl_geometry_cube", "webgl_geometry_dynamic", "webgl_geometry_extrude_shapes", "webgl_geometry_extrude_shapes2", "webgl_geometry_extrude_splines", "webgl_geometry_hierarchy", "webgl_geometry_hierarchy2", "webgl_geometry_minecraft", "webgl_geometry_minecraft_ao", "webgl_geometry_normals", "webgl_geometry_nurbs", "webgl_geometry_shapes", "webgl_geometry_spline_editor", "webgl_geometry_teapot", "webgl_geometry_terrain", "webgl_geometry_terrain_fog", "webgl_geometry_terrain_raycast", "webgl_geometry_text", "webgl_geometry_text_shapes", "webgl_gpgpu_birds", "webgl_gpgpu_water", "webgl_gpgpu_protoplanet", "webgl_gpu_particle_system", "webgl_hdr", "webgl_helpers", "webgl_interactive_buffergeometry", "webgl_interactive_cubes", "webgl_interactive_cubes_gpu", "webgl_interactive_instances_gpu", "webgl_interactive_cubes_ortho", "webgl_interactive_draggablecubes", "webgl_interactive_lines", "webgl_interactive_points", "webgl_interactive_raycasting_points", "webgl_interactive_voxelpainter", "webgl_kinect", "webgl_lensflares", "webgl_lights_hemisphere", "webgl_lights_physical", "webgl_lights_pointlights", "webgl_lights_pointlights2", "webgl_lights_spotlight", "webgl_lights_spotlights", "webgl_lights_rectarealight", "webgl_lines_colors", "webgl_lines_cubes", "webgl_lines_dashed", "webgl_lines_fat", "webgl_lines_sphere", "webgl_loader_3ds", "webgl_loader_3mf", "webgl_loader_amf", "webgl_loader_assimp", "webgl_loader_assimp2json", "webgl_loader_awd", "webgl_loader_babylon", "webgl_loader_bvh", "webgl_loader_collada", "webgl_loader_collada_kinematics", "webgl_loader_collada_skinning", "webgl_loader_ctm", "webgl_loader_ctm_materials", "webgl_loader_draco", "webgl_loader_fbx", "webgl_loader_fbx_nurbs", "webgl_loader_gcode", "webgl_loader_gltf", "webgl_loader_gltf_extensions", "webgl_loader_imagebitmap", "webgl_loader_json_blender", "webgl_loader_json_claraio", "webgl_loader_json_objconverter", "webgl_loader_kmz", "webgl_loader_md2", "webgl_loader_md2_control", "webgl_loader_mmd", "webgl_loader_mmd_pose", "webgl_loader_mmd_audio", "webgl_loader_msgpack", "webgl_loader_nodes", "webgl_loader_obj", "webgl_loader_obj_mtl", "webgl_loader_obj2", "webgl_loader_obj2_meshspray", "webgl_loader_obj2_options", "webgl_loader_obj2_run_director", "webgl_loader_nrrd", "webgl_loader_pcd", "webgl_loader_pdb", "webgl_loader_playcanvas", "webgl_loader_ply", "webgl_loader_prwm", "webgl_loader_sea3d", "webgl_loader_sea3d_hierarchy", "webgl_loader_sea3d_keyframe", "webgl_loader_sea3d_morph", "webgl_loader_sea3d_physics", "webgl_loader_sea3d_skinning", "webgl_loader_sea3d_sound", "webgl_loader_stl", "webgl_loader_texture_dds", "webgl_loader_texture_exr", "webgl_loader_texture_hdr", "webgl_loader_texture_ktx", "webgl_loader_texture_pvrtc", "webgl_loader_texture_tga", "webgl_loader_ttf", "webgl_loader_utf8", "webgl_loader_vrml", "webgl_loader_vtk", "webgl_loader_x", "webgl_lod", "webgl_marchingcubes", "webgl_materials", "webgl_materials_blending", "webgl_materials_blending_custom", "webgl_materials_bumpmap", "webgl_materials_bumpmap_skin", "webgl_materials_cars", "webgl_materials_channels", "webgl_materials_compile", "webgl_materials_cubemap", "webgl_materials_cubemap_balls_reflection", "webgl_materials_cubemap_balls_refraction", "webgl_materials_cubemap_dynamic", "webgl_materials_cubemap_dynamic2", "webgl_materials_cubemap_refraction", "webgl_materials_curvature", "webgl_materials_displacementmap", "webgl_materials_envmaps", "webgl_materials_envmaps_hdr", "webgl_materials_grass", "webgl_materials_lightmap", "webgl_materials_nodes", "webgl_materials_normalmap", "webgl_materials_parallaxmap", "webgl_materials_reflectivity", "webgl_materials_shaders_fresnel", "webgl_materials_skin", "webgl_materials_standard", "webgl_materials_texture_anisotropy", "webgl_materials_texture_canvas", "webgl_materials_texture_filters", "webgl_materials_texture_manualmipmap", "webgl_materials_texture_partialupdate", "webgl_materials_texture_rotation", "webgl_materials_transparency", "webgl_materials_variations_basic", "webgl_materials_variations_lambert", "webgl_materials_variations_phong", "webgl_materials_variations_standard", "webgl_materials_variations_physical", "webgl_materials_variations_toon", "webgl_materials_video", "webgl_materials_video_webcam", "webgl_materials_wireframe", "webgl_mirror", "webgl_mirror_nodes", "webgl_modifier_simplifier", "webgl_modifier_subdivision", "webgl_modifier_tessellation", "webgl_morphnormals", "webgl_morphtargets", "webgl_morphtargets_horse", "webgl_morphtargets_human", "webgl_morphtargets_sphere", "webgl_multiple_canvases_circle", "webgl_multiple_canvases_complex", "webgl_multiple_canvases_grid", "webgl_multiple_elements", "webgl_multiple_elements_text", "webgl_multiple_renderers", "webgl_multiple_views", "webgl_nearestneighbour", "webgl_objects_update", "webgl_octree", "webgl_octree_raycasting", "webgl_panorama_cube", "webgl_panorama_dualfisheye", "webgl_panorama_equirectangular", "webgl_performance", "webgl_performance_doublesided", "webgl_performance_static", "webgl_physics_cloth", "webgl_physics_convex_break", "webgl_physics_rope", "webgl_physics_terrain", "webgl_physics_volume", "webgl_points_billboards", "webgl_points_billboards_colors", "webgl_points_dynamic", "webgl_points_random", "webgl_points_sprites", "webgl_postprocessing", "webgl_postprocessing_advanced", "webgl_postprocessing_backgrounds", "webgl_postprocessing_crossfade", "webgl_postprocessing_dof", "webgl_postprocessing_dof2", "webgl_postprocessing_fxaa", "webgl_postprocessing_glitch", "webgl_postprocessing_godrays", "webgl_postprocessing_masking", "webgl_postprocessing_ssaa", "webgl_postprocessing_ssaa_unbiased", "webgl_postprocessing_nodes", "webgl_postprocessing_outline", "webgl_postprocessing_procedural", "webgl_postprocessing_sao", "webgl_postprocessing_smaa", "webgl_postprocessing_sobel", "webgl_postprocessing_ssao", "webgl_postprocessing_taa", "webgl_postprocessing_unreal_bloom", "webgl_raycast_texture", "webgl_read_float_buffer", "webgl_refraction", "webgl_rtt", "webgl_sandbox", "webgl_shader", "webgl_shader_lava", "webgl_shader2", "webgl_shaders_ocean", "webgl_shaders_ocean2", "webgl_shaders_sky", "webgl_shaders_tonemapping", "webgl_shaders_vector", "webgl_shading_physical", "webgl_shadowmap", "webgl_shadowmap_performance", "webgl_shadowmap_pointlight", "webgl_shadowmap_viewer", "webgl_shadowmesh", "webgl_skinning_simple", "webgl_sprites", "webgl_sprites_nodes", "webgl_terrain_dynamic", "webgl_test_memory", "webgl_test_memory2", "webgl_tonemapping", "webgl_trails", "webgl_video_panorama_equirectangular", "webgl_water", "webgl_water_flowmap" ], "webgl / advanced": [ "webgl_buffergeometry", "webgl_buffergeometry_constructed_from_geometry", "webgl_buffergeometry_custom_attributes_particles", "webgl_buffergeometry_drawcalls", "webgl_buffergeometry_indexed", "webgl_buffergeometry_instancing", "webgl_buffergeometry_instancing2", "webgl_buffergeometry_instancing_billboards", "webgl_buffergeometry_instancing_dynamic", "webgl_buffergeometry_instancing_interleaved_dynamic", "webgl_buffergeometry_lines", "webgl_buffergeometry_lines_indexed", "webgl_buffergeometry_points", "webgl_buffergeometry_points_interleaved", "webgl_buffergeometry_rawshader", "webgl_buffergeometry_selective_draw", "webgl_buffergeometry_uint", "webgl_custom_attributes", "webgl_custom_attributes_lines", "webgl_custom_attributes_points", "webgl_custom_attributes_points2", "webgl_custom_attributes_points3", "webgl_materials_modified", "webgl_raymarching_reflect", "webgl_shadowmap_pcss", "webgl_simple_gi", "webgl_tiled_forward", "webgl_worker_offscreencanvas" ], "webgl deferred": [ "webgldeferred_animation" ], /* "webgl2": [ "webgl2_sandbox" ], */ "webaudio": [ "webaudio_sandbox", "webaudio_timing", "webaudio_visualizer" ], "webvr": [ "webvr_cubes", "webvr_daydream", "webvr_gearvr", "webvr_panorama", "webvr_rollercoaster", "webvr_sandbox", "webvr_video", "webvr_vive", "webvr_vive_dragging", "webvr_vive_paint", "webvr_vive_sculpt" ], "misc": [ "misc_animation_authoring", "misc_animation_groups", "misc_animation_keys", "misc_controls_deviceorientation", "misc_controls_fly", "misc_controls_orbit", "misc_controls_pointerlock", "misc_controls_trackball", "misc_controls_transform", "misc_exporter_gltf", "misc_exporter_obj", "misc_fps", "misc_lights_test", "misc_lookat", "misc_ubiquity_test", "misc_ubiquity_test2", "misc_uv_tests" ], "css3d": [ "css3d_molecules", "css3d_panorama", "css3d_panorama_deviceorientation", "css3d_periodictable", "css3d_sandbox", "css3d_sprites", "css3d_youtube" ], "canvas": [ "canvas_ascii_effect", "canvas_camera_orthographic", "canvas_geometry_birds", "canvas_geometry_cube", "canvas_geometry_earth", "canvas_geometry_hierarchy", "canvas_geometry_nurbs", "canvas_geometry_panorama", "canvas_geometry_panorama_fisheye", "canvas_geometry_shapes", "canvas_geometry_terrain", "canvas_geometry_text", "canvas_interactive_cubes", "canvas_interactive_cubes_tween", "canvas_interactive_particles", "canvas_interactive_voxelpainter", "canvas_lights_pointlights", "canvas_lines", "canvas_lines_colors", "canvas_lines_colors_2d", "canvas_lines_dashed", "canvas_lines_sphere", "canvas_materials", "canvas_materials_normal", "canvas_materials_reflection", "canvas_materials_video", "canvas_morphtargets_horse", "canvas_particles_floor", "canvas_particles_random", "canvas_particles_sprites", "canvas_particles_waves", "canvas_performance", "canvas_sandbox" ], "raytracing": [ "raytracing_sandbox" ], "software": [ "software_geometry_earth", "software_lines_splines", "software_sandbox" ], "svg": [ "svg_lines", "svg_sandbox" ] };
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ require('es6-symbol/implement'); require('es6-map/implement'); require('es6-set/implement'); require('es5-ext/array/from/implement'); // require('es5-ext/array/#/find/implement'); // require('es5-ext/array/#/find-index/implement'); require('es5-ext/array/#/@@iterator/implement'); },{"es5-ext/array/#/@@iterator/implement":4,"es5-ext/array/from/implement":10,"es6-map/implement":58,"es6-set/implement":64,"es6-symbol/implement":74}],2:[function(require,module,exports){ 'use strict'; var copy = require('es5-ext/object/copy') , normalizeOptions = require('es5-ext/object/normalize-options') , ensureCallable = require('es5-ext/object/valid-callable') , map = require('es5-ext/object/map') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , bind = Function.prototype.bind, defineProperty = Object.defineProperty , hasOwnProperty = Object.prototype.hasOwnProperty , define; define = function (name, desc, options) { var value = validValue(desc) && callable(desc.value), dgs; dgs = copy(desc); delete dgs.writable; delete dgs.value; dgs.get = function () { if (!options.overwriteDefinition && hasOwnProperty.call(this, name)) return value; desc.value = bind.call(value, options.resolveContext ? options.resolveContext(this) : this); defineProperty(this, name, desc); return this[name]; }; return dgs; }; module.exports = function (props/*, options*/) { var options = normalizeOptions(arguments[1]); if (options.resolveContext != null) ensureCallable(options.resolveContext); return map(props, function (desc, name) { return define(name, desc, options); }); }; },{"es5-ext/object/copy":30,"es5-ext/object/map":39,"es5-ext/object/normalize-options":40,"es5-ext/object/valid-callable":45,"es5-ext/object/valid-value":46}],3:[function(require,module,exports){ 'use strict'; var assign = require('es5-ext/object/assign') , normalizeOpts = require('es5-ext/object/normalize-options') , isCallable = require('es5-ext/object/is-callable') , contains = require('es5-ext/string/#/contains') , d; d = module.exports = function (dscr, value/*, options*/) { var c, e, w, options, desc; if ((arguments.length < 2) || (typeof dscr !== 'string')) { options = value; value = dscr; dscr = null; } else { options = arguments[2]; } if (dscr == null) { c = w = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); w = contains.call(dscr, 'w'); } desc = { value: value, configurable: c, enumerable: e, writable: w }; return !options ? desc : assign(normalizeOpts(options), desc); }; d.gs = function (dscr, get, set/*, options*/) { var c, e, options, desc; if (typeof dscr !== 'string') { options = set; set = get; get = dscr; dscr = null; } else { options = arguments[3]; } if (get == null) { get = undefined; } else if (!isCallable(get)) { options = get; get = set = undefined; } else if (set == null) { set = undefined; } else if (!isCallable(set)) { options = set; set = undefined; } if (dscr == null) { c = true; e = false; } else { c = contains.call(dscr, 'c'); e = contains.call(dscr, 'e'); } desc = { get: get, set: set, configurable: c, enumerable: e }; return !options ? desc : assign(normalizeOpts(options), desc); }; },{"es5-ext/object/assign":27,"es5-ext/object/is-callable":33,"es5-ext/object/normalize-options":40,"es5-ext/string/#/contains":47}],4:[function(require,module,exports){ "use strict"; if (!require("./is-implemented")()) { Object.defineProperty(Array.prototype, require("es6-symbol").iterator, { value: require("./shim"), configurable: true, enumerable: false, writable: true }); } },{"./is-implemented":5,"./shim":6,"es6-symbol":75}],5:[function(require,module,exports){ "use strict"; var iteratorSymbol = require("es6-symbol").iterator; module.exports = function () { var arr = ["foo", 1], iterator, result; if (typeof arr[iteratorSymbol] !== "function") return false; iterator = arr[iteratorSymbol](); if (!iterator) return false; if (typeof iterator.next !== "function") return false; result = iterator.next(); if (!result) return false; if (result.value !== "foo") return false; if (result.done !== false) return false; return true; }; },{"es6-symbol":75}],6:[function(require,module,exports){ "use strict"; module.exports = require("../values/shim"); },{"../values/shim":9}],7:[function(require,module,exports){ // Inspired by Google Closure: // http://closure-library.googlecode.com/svn/docs/ // closure_goog_array_array.js.html#goog.array.clear "use strict"; var value = require("../../object/valid-value"); module.exports = function () { value(this).length = 0; return this; }; },{"../../object/valid-value":46}],8:[function(require,module,exports){ "use strict"; var numberIsNaN = require("../../number/is-nan") , toPosInt = require("../../number/to-pos-integer") , value = require("../../object/valid-value") , indexOf = Array.prototype.indexOf , objHasOwnProperty = Object.prototype.hasOwnProperty , abs = Math.abs , floor = Math.floor; module.exports = function (searchElement/*, fromIndex*/) { var i, length, fromIndex, val; if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments); length = toPosInt(value(this).length); fromIndex = arguments[1]; if (isNaN(fromIndex)) fromIndex = 0; else if (fromIndex >= 0) fromIndex = floor(fromIndex); else fromIndex = toPosInt(this.length) - floor(abs(fromIndex)); for (i = fromIndex; i < length; ++i) { if (objHasOwnProperty.call(this, i)) { val = this[i]; if (numberIsNaN(val)) return i; // Jslint: ignore } } return -1; }; },{"../../number/is-nan":21,"../../number/to-pos-integer":25,"../../object/valid-value":46}],9:[function(require,module,exports){ "use strict"; var ArrayIterator = require("es6-iterator/array"); module.exports = function () { return new ArrayIterator(this, "value"); }; },{"es6-iterator/array":51}],10:[function(require,module,exports){ "use strict"; if (!require("./is-implemented")()) { Object.defineProperty(Array, "from", { value: require("./shim"), configurable: true, enumerable: false, writable: true }); } },{"./is-implemented":12,"./shim":13}],11:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? Array.from : require("./shim"); },{"./is-implemented":12,"./shim":13}],12:[function(require,module,exports){ "use strict"; module.exports = function () { var from = Array.from, arr, result; if (typeof from !== "function") return false; arr = ["raz", "dwa"]; result = from(arr); return Boolean(result && result !== arr && result[1] === "dwa"); }; },{}],13:[function(require,module,exports){ "use strict"; var iteratorSymbol = require("es6-symbol").iterator , isArguments = require("../../function/is-arguments") , isFunction = require("../../function/is-function") , toPosInt = require("../../number/to-pos-integer") , callable = require("../../object/valid-callable") , validValue = require("../../object/valid-value") , isValue = require("../../object/is-value") , isString = require("../../string/is-string") , isArray = Array.isArray , call = Function.prototype.call , desc = { configurable: true, enumerable: true, writable: true, value: null } , defineProperty = Object.defineProperty; // eslint-disable-next-line complexity, max-lines-per-function module.exports = function (arrayLike/*, mapFn, thisArg*/) { var mapFn = arguments[1] , thisArg = arguments[2] , Context , i , j , arr , length , code , iterator , result , getIterator , value; arrayLike = Object(validValue(arrayLike)); if (isValue(mapFn)) callable(mapFn); if (!this || this === Array || !isFunction(this)) { // Result: Plain array if (!mapFn) { if (isArguments(arrayLike)) { // Source: Arguments length = arrayLike.length; if (length !== 1) return Array.apply(null, arrayLike); arr = new Array(1); arr[0] = arrayLike[0]; return arr; } if (isArray(arrayLike)) { // Source: Array arr = new Array((length = arrayLike.length)); for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; return arr; } } arr = []; } else { // Result: Non plain array Context = this; } if (!isArray(arrayLike)) { if ((getIterator = arrayLike[iteratorSymbol]) !== undefined) { // Source: Iterator iterator = callable(getIterator).call(arrayLike); if (Context) arr = new Context(); result = iterator.next(); i = 0; while (!result.done) { value = mapFn ? call.call(mapFn, thisArg, result.value, i) : result.value; if (Context) { desc.value = value; defineProperty(arr, i, desc); } else { arr[i] = value; } result = iterator.next(); ++i; } length = i; } else if (isString(arrayLike)) { // Source: String length = arrayLike.length; if (Context) arr = new Context(); for (i = 0, j = 0; i < length; ++i) { value = arrayLike[i]; if (i + 1 < length) { code = value.charCodeAt(0); // eslint-disable-next-line max-depth if (code >= 0xd800 && code <= 0xdbff) value += arrayLike[++i]; } value = mapFn ? call.call(mapFn, thisArg, value, j) : value; if (Context) { desc.value = value; defineProperty(arr, j, desc); } else { arr[j] = value; } ++j; } length = j; } } if (length === undefined) { // Source: array or array-like length = toPosInt(arrayLike.length); if (Context) arr = new Context(length); for (i = 0; i < length; ++i) { value = mapFn ? call.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; if (Context) { desc.value = value; defineProperty(arr, i, desc); } else { arr[i] = value; } } } if (Context) { desc.value = null; arr.length = length; } return arr; }; },{"../../function/is-arguments":14,"../../function/is-function":15,"../../number/to-pos-integer":25,"../../object/is-value":35,"../../object/valid-callable":45,"../../object/valid-value":46,"../../string/is-string":50,"es6-symbol":75}],14:[function(require,module,exports){ "use strict"; var objToString = Object.prototype.toString , id = objToString.call((function () { return arguments; })()); module.exports = function (value) { return objToString.call(value) === id; }; },{}],15:[function(require,module,exports){ "use strict"; var objToString = Object.prototype.toString , isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/); module.exports = function (value) { return typeof value === "function" && isFunctionStringTag(objToString.call(value)); }; },{}],16:[function(require,module,exports){ "use strict"; // eslint-disable-next-line no-empty-function module.exports = function () {}; },{}],17:[function(require,module,exports){ var naiveFallback = function () { if (typeof self === "object" && self) return self; if (typeof window === "object" && window) return window; throw new Error("Unable to resolve global `this`"); }; module.exports = (function () { if (this) return this; // Unexpected strict mode (may happen if e.g. bundled into ESM module) // Fallback to standard globalThis if available if (typeof globalThis === "object" && globalThis) return globalThis; // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis // In all ES5+ engines global object inherits from Object.prototype // (if you approached one that doesn't please report) try { Object.defineProperty(Object.prototype, "__global__", { get: function () { return this; }, configurable: true }); } catch (error) { // Unfortunate case of updates to Object.prototype being restricted // via preventExtensions, seal or freeze return naiveFallback(); } try { // Safari case (window.__global__ works, but __global__ does not) if (!__global__) return naiveFallback(); return __global__; } finally { delete Object.prototype.__global__; } })(); },{}],18:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? Math.sign : require("./shim"); },{"./is-implemented":19,"./shim":20}],19:[function(require,module,exports){ "use strict"; module.exports = function () { var sign = Math.sign; if (typeof sign !== "function") return false; return sign(10) === 1 && sign(-20) === -1; }; },{}],20:[function(require,module,exports){ "use strict"; module.exports = function (value) { value = Number(value); if (isNaN(value) || value === 0) return value; return value > 0 ? 1 : -1; }; },{}],21:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? Number.isNaN : require("./shim"); },{"./is-implemented":22,"./shim":23}],22:[function(require,module,exports){ "use strict"; module.exports = function () { var numberIsNaN = Number.isNaN; if (typeof numberIsNaN !== "function") return false; return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34); }; },{}],23:[function(require,module,exports){ "use strict"; module.exports = function (value) { // eslint-disable-next-line no-self-compare return value !== value; }; },{}],24:[function(require,module,exports){ "use strict"; var sign = require("../math/sign") , abs = Math.abs , floor = Math.floor; module.exports = function (value) { if (isNaN(value)) return 0; value = Number(value); if (value === 0 || !isFinite(value)) return value; return sign(value) * floor(abs(value)); }; },{"../math/sign":18}],25:[function(require,module,exports){ "use strict"; var toInteger = require("./to-integer") , max = Math.max; module.exports = function (value) { return max(0, toInteger(value)); }; },{"./to-integer":24}],26:[function(require,module,exports){ // Internal method, used by iteration functions. // Calls a function for each key-value pair found in object // Optionally takes compareFn to iterate object in specific order "use strict"; var callable = require("./valid-callable") , value = require("./valid-value") , bind = Function.prototype.bind , call = Function.prototype.call , keys = Object.keys , objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; module.exports = function (method, defVal) { return function (obj, cb/*, thisArg, compareFn*/) { var list, thisArg = arguments[2], compareFn = arguments[3]; obj = Object(value(obj)); callable(cb); list = keys(obj); if (compareFn) { list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : undefined); } if (typeof method !== "function") method = list[method]; return call.call(method, list, function (key, index) { if (!objPropertyIsEnumerable.call(obj, key)) return defVal; return call.call(cb, thisArg, obj[key], key, obj, index); }); }; }; },{"./valid-callable":45,"./valid-value":46}],27:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? Object.assign : require("./shim"); },{"./is-implemented":28,"./shim":29}],28:[function(require,module,exports){ "use strict"; module.exports = function () { var assign = Object.assign, obj; if (typeof assign !== "function") return false; obj = { foo: "raz" }; assign(obj, { bar: "dwa" }, { trzy: "trzy" }); return obj.foo + obj.bar + obj.trzy === "razdwatrzy"; }; },{}],29:[function(require,module,exports){ "use strict"; var keys = require("../keys") , value = require("../valid-value") , max = Math.max; module.exports = function (dest, src/*, …srcn*/) { var error, i, length = max(arguments.length, 2), assign; dest = Object(value(dest)); assign = function (key) { try { dest[key] = src[key]; } catch (e) { if (!error) error = e; } }; for (i = 1; i < length; ++i) { src = arguments[i]; keys(src).forEach(assign); } if (error !== undefined) throw error; return dest; }; },{"../keys":36,"../valid-value":46}],30:[function(require,module,exports){ "use strict"; var aFrom = require("../array/from") , assign = require("./assign") , value = require("./valid-value"); module.exports = function (obj/*, propertyNames, options*/) { var copy = Object(value(obj)), propertyNames = arguments[1], options = Object(arguments[2]); if (copy !== obj && !propertyNames) return copy; var result = {}; if (propertyNames) { aFrom(propertyNames, function (propertyName) { if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName]; }); } else { assign(result, obj); } return result; }; },{"../array/from":11,"./assign":27,"./valid-value":46}],31:[function(require,module,exports){ // Workaround for http://code.google.com/p/v8/issues/detail?id=2804 "use strict"; var create = Object.create, shim; if (!require("./set-prototype-of/is-implemented")()) { shim = require("./set-prototype-of/shim"); } module.exports = (function () { var nullObject, polyProps, desc; if (!shim) return create; if (shim.level !== 1) return create; nullObject = {}; polyProps = {}; desc = { configurable: false, enumerable: false, writable: true, value: undefined }; Object.getOwnPropertyNames(Object.prototype).forEach(function (name) { if (name === "__proto__") { polyProps[name] = { configurable: true, enumerable: false, writable: true, value: undefined }; return; } polyProps[name] = desc; }); Object.defineProperties(nullObject, polyProps); Object.defineProperty(shim, "nullPolyfill", { configurable: false, enumerable: false, writable: false, value: nullObject }); return function (prototype, props) { return create(prototype === null ? nullObject : prototype, props); }; })(); },{"./set-prototype-of/is-implemented":43,"./set-prototype-of/shim":44}],32:[function(require,module,exports){ "use strict"; module.exports = require("./_iterate")("forEach"); },{"./_iterate":26}],33:[function(require,module,exports){ // Deprecated "use strict"; module.exports = function (obj) { return typeof obj === "function"; }; },{}],34:[function(require,module,exports){ "use strict"; var isValue = require("./is-value"); var map = { function: true, object: true }; module.exports = function (value) { return (isValue(value) && map[typeof value]) || false; }; },{"./is-value":35}],35:[function(require,module,exports){ "use strict"; var _undefined = require("../function/noop")(); // Support ES3 engines module.exports = function (val) { return val !== _undefined && val !== null; }; },{"../function/noop":16}],36:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? Object.keys : require("./shim"); },{"./is-implemented":37,"./shim":38}],37:[function(require,module,exports){ "use strict"; module.exports = function () { try { Object.keys("primitive"); return true; } catch (e) { return false; } }; },{}],38:[function(require,module,exports){ "use strict"; var isValue = require("../is-value"); var keys = Object.keys; module.exports = function (object) { return keys(isValue(object) ? Object(object) : object); }; },{"../is-value":35}],39:[function(require,module,exports){ "use strict"; var callable = require("./valid-callable") , forEach = require("./for-each") , call = Function.prototype.call; module.exports = function (obj, cb/*, thisArg*/) { var result = {}, thisArg = arguments[2]; callable(cb); forEach(obj, function (value, key, targetObj, index) { result[key] = call.call(cb, thisArg, value, key, targetObj, index); }); return result; }; },{"./for-each":32,"./valid-callable":45}],40:[function(require,module,exports){ "use strict"; var isValue = require("./is-value"); var forEach = Array.prototype.forEach, create = Object.create; var process = function (src, obj) { var key; for (key in src) obj[key] = src[key]; }; // eslint-disable-next-line no-unused-vars module.exports = function (opts1/*, …options*/) { var result = create(null); forEach.call(arguments, function (options) { if (!isValue(options)) return; process(Object(options), result); }); return result; }; },{"./is-value":35}],41:[function(require,module,exports){ "use strict"; var forEach = Array.prototype.forEach, create = Object.create; // eslint-disable-next-line no-unused-vars module.exports = function (arg/*, …args*/) { var set = create(null); forEach.call(arguments, function (name) { set[name] = true; }); return set; }; },{}],42:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? Object.setPrototypeOf : require("./shim"); },{"./is-implemented":43,"./shim":44}],43:[function(require,module,exports){ "use strict"; var create = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {}; module.exports = function (/* CustomCreate*/) { var setPrototypeOf = Object.setPrototypeOf, customCreate = arguments[0] || create; if (typeof setPrototypeOf !== "function") return false; return getPrototypeOf(setPrototypeOf(customCreate(null), plainObject)) === plainObject; }; },{}],44:[function(require,module,exports){ /* eslint no-proto: "off" */ // Big thanks to @WebReflection for sorting this out // https://gist.github.com/WebReflection/5593554 "use strict"; var isObject = require("../is-object") , value = require("../valid-value") , objIsPrototypeOf = Object.prototype.isPrototypeOf , defineProperty = Object.defineProperty , nullDesc = { configurable: true, enumerable: false, writable: true, value: undefined } , validate; validate = function (obj, prototype) { value(obj); if (prototype === null || isObject(prototype)) return obj; throw new TypeError("Prototype must be null or an object"); }; module.exports = (function (status) { var fn, set; if (!status) return null; if (status.level === 2) { if (status.set) { set = status.set; fn = function (obj, prototype) { set.call(validate(obj, prototype), prototype); return obj; }; } else { fn = function (obj, prototype) { validate(obj, prototype).__proto__ = prototype; return obj; }; } } else { fn = function self(obj, prototype) { var isNullBase; validate(obj, prototype); isNullBase = objIsPrototypeOf.call(self.nullPolyfill, obj); if (isNullBase) delete self.nullPolyfill.__proto__; if (prototype === null) prototype = self.nullPolyfill; obj.__proto__ = prototype; if (isNullBase) defineProperty(self.nullPolyfill, "__proto__", nullDesc); return obj; }; } return Object.defineProperty(fn, "level", { configurable: false, enumerable: false, writable: false, value: status.level }); })( (function () { var tmpObj1 = Object.create(null) , tmpObj2 = {} , set , desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__"); if (desc) { try { set = desc.set; // Opera crashes at this point set.call(tmpObj1, tmpObj2); } catch (ignore) {} if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set: set, level: 2 }; } tmpObj1.__proto__ = tmpObj2; if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 }; tmpObj1 = {}; tmpObj1.__proto__ = tmpObj2; if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 }; return false; })() ); require("../create"); },{"../create":31,"../is-object":34,"../valid-value":46}],45:[function(require,module,exports){ "use strict"; module.exports = function (fn) { if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); return fn; }; },{}],46:[function(require,module,exports){ "use strict"; var isValue = require("./is-value"); module.exports = function (value) { if (!isValue(value)) throw new TypeError("Cannot use null or undefined"); return value; }; },{"./is-value":35}],47:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? String.prototype.contains : require("./shim"); },{"./is-implemented":48,"./shim":49}],48:[function(require,module,exports){ "use strict"; var str = "razdwatrzy"; module.exports = function () { if (typeof str.contains !== "function") return false; return str.contains("dwa") === true && str.contains("foo") === false; }; },{}],49:[function(require,module,exports){ "use strict"; var indexOf = String.prototype.indexOf; module.exports = function (searchString/*, position*/) { return indexOf.call(this, searchString, arguments[1]) > -1; }; },{}],50:[function(require,module,exports){ "use strict"; var objToString = Object.prototype.toString, id = objToString.call(""); module.exports = function (value) { return ( typeof value === "string" || (value && typeof value === "object" && (value instanceof String || objToString.call(value) === id)) || false ); }; },{}],51:[function(require,module,exports){ "use strict"; var setPrototypeOf = require("es5-ext/object/set-prototype-of") , contains = require("es5-ext/string/#/contains") , d = require("d") , Symbol = require("es6-symbol") , Iterator = require("./"); var defineProperty = Object.defineProperty, ArrayIterator; ArrayIterator = module.exports = function (arr, kind) { if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'"); Iterator.call(this, arr); if (!kind) kind = "value"; else if (contains.call(kind, "key+value")) kind = "key+value"; else if (contains.call(kind, "key")) kind = "key"; else kind = "value"; defineProperty(this, "__kind__", d("", kind)); }; if (setPrototypeOf) setPrototypeOf(ArrayIterator, Iterator); // Internal %ArrayIteratorPrototype% doesn't expose its constructor delete ArrayIterator.prototype.constructor; ArrayIterator.prototype = Object.create(Iterator.prototype, { _resolve: d(function (i) { if (this.__kind__ === "value") return this.__list__[i]; if (this.__kind__ === "key+value") return [i, this.__list__[i]]; return i; }) }); defineProperty(ArrayIterator.prototype, Symbol.toStringTag, d("c", "Array Iterator")); },{"./":54,"d":3,"es5-ext/object/set-prototype-of":42,"es5-ext/string/#/contains":47,"es6-symbol":75}],52:[function(require,module,exports){ "use strict"; var isArguments = require("es5-ext/function/is-arguments") , callable = require("es5-ext/object/valid-callable") , isString = require("es5-ext/string/is-string") , get = require("./get"); var isArray = Array.isArray, call = Function.prototype.call, some = Array.prototype.some; module.exports = function (iterable, cb /*, thisArg*/) { var mode, thisArg = arguments[2], result, doBreak, broken, i, length, char, code; if (isArray(iterable) || isArguments(iterable)) mode = "array"; else if (isString(iterable)) mode = "string"; else iterable = get(iterable); callable(cb); doBreak = function () { broken = true; }; if (mode === "array") { some.call(iterable, function (value) { call.call(cb, thisArg, value, doBreak); return broken; }); return; } if (mode === "string") { length = iterable.length; for (i = 0; i < length; ++i) { char = iterable[i]; if (i + 1 < length) { code = char.charCodeAt(0); if (code >= 0xd800 && code <= 0xdbff) char += iterable[++i]; } call.call(cb, thisArg, char, doBreak); if (broken) break; } return; } result = iterable.next(); while (!result.done) { call.call(cb, thisArg, result.value, doBreak); if (broken) return; result = iterable.next(); } }; },{"./get":53,"es5-ext/function/is-arguments":14,"es5-ext/object/valid-callable":45,"es5-ext/string/is-string":50}],53:[function(require,module,exports){ "use strict"; var isArguments = require("es5-ext/function/is-arguments") , isString = require("es5-ext/string/is-string") , ArrayIterator = require("./array") , StringIterator = require("./string") , iterable = require("./valid-iterable") , iteratorSymbol = require("es6-symbol").iterator; module.exports = function (obj) { if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol](); if (isArguments(obj)) return new ArrayIterator(obj); if (isString(obj)) return new StringIterator(obj); return new ArrayIterator(obj); }; },{"./array":51,"./string":56,"./valid-iterable":57,"es5-ext/function/is-arguments":14,"es5-ext/string/is-string":50,"es6-symbol":75}],54:[function(require,module,exports){ "use strict"; var clear = require("es5-ext/array/#/clear") , assign = require("es5-ext/object/assign") , callable = require("es5-ext/object/valid-callable") , value = require("es5-ext/object/valid-value") , d = require("d") , autoBind = require("d/auto-bind") , Symbol = require("es6-symbol"); var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator; module.exports = Iterator = function (list, context) { if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'"); defineProperties(this, { __list__: d("w", value(list)), __context__: d("w", context), __nextIndex__: d("w", 0) }); if (!context) return; callable(context.on); context.on("_add", this._onAdd); context.on("_delete", this._onDelete); context.on("_clear", this._onClear); }; // Internal %IteratorPrototype% doesn't expose its constructor delete Iterator.prototype.constructor; defineProperties( Iterator.prototype, assign( { _next: d(function () { var i; if (!this.__list__) return undefined; if (this.__redo__) { i = this.__redo__.shift(); if (i !== undefined) return i; } if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; this._unBind(); return undefined; }), next: d(function () { return this._createResult(this._next()); }), _createResult: d(function (i) { if (i === undefined) return { done: true, value: undefined }; return { done: false, value: this._resolve(i) }; }), _resolve: d(function (i) { return this.__list__[i]; }), _unBind: d(function () { this.__list__ = null; delete this.__redo__; if (!this.__context__) return; this.__context__.off("_add", this._onAdd); this.__context__.off("_delete", this._onDelete); this.__context__.off("_clear", this._onClear); this.__context__ = null; }), toString: d(function () { return "[object " + (this[Symbol.toStringTag] || "Object") + "]"; }) }, autoBind({ _onAdd: d(function (index) { if (index >= this.__nextIndex__) return; ++this.__nextIndex__; if (!this.__redo__) { defineProperty(this, "__redo__", d("c", [index])); return; } this.__redo__.forEach(function (redo, i) { if (redo >= index) this.__redo__[i] = ++redo; }, this); this.__redo__.push(index); }), _onDelete: d(function (index) { var i; if (index >= this.__nextIndex__) return; --this.__nextIndex__; if (!this.__redo__) return; i = this.__redo__.indexOf(index); if (i !== -1) this.__redo__.splice(i, 1); this.__redo__.forEach(function (redo, j) { if (redo > index) this.__redo__[j] = --redo; }, this); }), _onClear: d(function () { if (this.__redo__) clear.call(this.__redo__); this.__nextIndex__ = 0; }) }) ) ); defineProperty( Iterator.prototype, Symbol.iterator, d(function () { return this; }) ); },{"d":3,"d/auto-bind":2,"es5-ext/array/#/clear":7,"es5-ext/object/assign":27,"es5-ext/object/valid-callable":45,"es5-ext/object/valid-value":46,"es6-symbol":75}],55:[function(require,module,exports){ "use strict"; var isArguments = require("es5-ext/function/is-arguments") , isValue = require("es5-ext/object/is-value") , isString = require("es5-ext/string/is-string"); var iteratorSymbol = require("es6-symbol").iterator , isArray = Array.isArray; module.exports = function (value) { if (!isValue(value)) return false; if (isArray(value)) return true; if (isString(value)) return true; if (isArguments(value)) return true; return typeof value[iteratorSymbol] === "function"; }; },{"es5-ext/function/is-arguments":14,"es5-ext/object/is-value":35,"es5-ext/string/is-string":50,"es6-symbol":75}],56:[function(require,module,exports){ // Thanks @mathiasbynens // http://mathiasbynens.be/notes/javascript-unicode#iterating-over-symbols "use strict"; var setPrototypeOf = require("es5-ext/object/set-prototype-of") , d = require("d") , Symbol = require("es6-symbol") , Iterator = require("./"); var defineProperty = Object.defineProperty, StringIterator; StringIterator = module.exports = function (str) { if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'"); str = String(str); Iterator.call(this, str); defineProperty(this, "__length__", d("", str.length)); }; if (setPrototypeOf) setPrototypeOf(StringIterator, Iterator); // Internal %ArrayIteratorPrototype% doesn't expose its constructor delete StringIterator.prototype.constructor; StringIterator.prototype = Object.create(Iterator.prototype, { _next: d(function () { if (!this.__list__) return undefined; if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; this._unBind(); return undefined; }), _resolve: d(function (i) { var char = this.__list__[i], code; if (this.__nextIndex__ === this.__length__) return char; code = char.charCodeAt(0); if (code >= 0xd800 && code <= 0xdbff) return char + this.__list__[this.__nextIndex__++]; return char; }) }); defineProperty(StringIterator.prototype, Symbol.toStringTag, d("c", "String Iterator")); },{"./":54,"d":3,"es5-ext/object/set-prototype-of":42,"es6-symbol":75}],57:[function(require,module,exports){ "use strict"; var isIterable = require("./is-iterable"); module.exports = function (value) { if (!isIterable(value)) throw new TypeError(value + " is not iterable"); return value; }; },{"./is-iterable":55}],58:[function(require,module,exports){ 'use strict'; if (!require('./is-implemented')()) { Object.defineProperty(require('es5-ext/global'), 'Map', { value: require('./polyfill'), configurable: true, enumerable: false, writable: true }); } },{"./is-implemented":59,"./polyfill":63,"es5-ext/global":17}],59:[function(require,module,exports){ 'use strict'; module.exports = function () { var map, iterator, result; if (typeof Map !== 'function') return false; try { // WebKit doesn't support arguments and crashes map = new Map([['raz', 'one'], ['dwa', 'two'], ['trzy', 'three']]); } catch (e) { return false; } if (String(map) !== '[object Map]') return false; if (map.size !== 3) return false; if (typeof map.clear !== 'function') return false; if (typeof map.delete !== 'function') return false; if (typeof map.entries !== 'function') return false; if (typeof map.forEach !== 'function') return false; if (typeof map.get !== 'function') return false; if (typeof map.has !== 'function') return false; if (typeof map.keys !== 'function') return false; if (typeof map.set !== 'function') return false; if (typeof map.values !== 'function') return false; iterator = map.entries(); result = iterator.next(); if (result.done !== false) return false; if (!result.value) return false; if (result.value[0] !== 'raz') return false; if (result.value[1] !== 'one') return false; return true; }; },{}],60:[function(require,module,exports){ // Exports true if environment provides native `Map` implementation, // whatever that is. 'use strict'; module.exports = (function () { if (typeof Map === 'undefined') return false; return (Object.prototype.toString.call(new Map()) === '[object Map]'); }()); },{}],61:[function(require,module,exports){ 'use strict'; module.exports = require('es5-ext/object/primitive-set')('key', 'value', 'key+value'); },{"es5-ext/object/primitive-set":41}],62:[function(require,module,exports){ 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , d = require('d') , Iterator = require('es6-iterator') , toStringTagSymbol = require('es6-symbol').toStringTag , kinds = require('./iterator-kinds') , defineProperties = Object.defineProperties , unBind = Iterator.prototype._unBind , MapIterator; MapIterator = module.exports = function (map, kind) { if (!(this instanceof MapIterator)) return new MapIterator(map, kind); Iterator.call(this, map.__mapKeysData__, map); if (!kind || !kinds[kind]) kind = 'key+value'; defineProperties(this, { __kind__: d('', kind), __values__: d('w', map.__mapValuesData__) }); }; if (setPrototypeOf) setPrototypeOf(MapIterator, Iterator); MapIterator.prototype = Object.create(Iterator.prototype, { constructor: d(MapIterator), _resolve: d(function (i) { if (this.__kind__ === 'value') return this.__values__[i]; if (this.__kind__ === 'key') return this.__list__[i]; return [this.__list__[i], this.__values__[i]]; }), _unBind: d(function () { this.__values__ = null; unBind.call(this); }), toString: d(function () { return '[object Map Iterator]'; }) }); Object.defineProperty(MapIterator.prototype, toStringTagSymbol, d('c', 'Map Iterator')); },{"./iterator-kinds":61,"d":3,"es5-ext/object/set-prototype-of":42,"es6-iterator":54,"es6-symbol":75}],63:[function(require,module,exports){ 'use strict'; var clear = require('es5-ext/array/#/clear') , eIndexOf = require('es5-ext/array/#/e-index-of') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , callable = require('es5-ext/object/valid-callable') , validValue = require('es5-ext/object/valid-value') , d = require('d') , ee = require('event-emitter') , Symbol = require('es6-symbol') , iterator = require('es6-iterator/valid-iterable') , forOf = require('es6-iterator/for-of') , Iterator = require('./lib/iterator') , isNative = require('./is-native-implemented') , call = Function.prototype.call , defineProperties = Object.defineProperties, getPrototypeOf = Object.getPrototypeOf , MapPoly; module.exports = MapPoly = function (/*iterable*/) { var iterable = arguments[0], keys, values, self; if (!(this instanceof MapPoly)) throw new TypeError('Constructor requires \'new\''); if (isNative && setPrototypeOf && (Map !== MapPoly)) { self = setPrototypeOf(new Map(), getPrototypeOf(this)); } else { self = this; } if (iterable != null) iterator(iterable); defineProperties(self, { __mapKeysData__: d('c', keys = []), __mapValuesData__: d('c', values = []) }); if (!iterable) return self; forOf(iterable, function (value) { var key = validValue(value)[0]; value = value[1]; if (eIndexOf.call(keys, key) !== -1) return; keys.push(key); values.push(value); }, self); return self; }; if (isNative) { if (setPrototypeOf) setPrototypeOf(MapPoly, Map); MapPoly.prototype = Object.create(Map.prototype, { constructor: d(MapPoly) }); } ee(defineProperties(MapPoly.prototype, { clear: d(function () { if (!this.__mapKeysData__.length) return; clear.call(this.__mapKeysData__); clear.call(this.__mapValuesData__); this.emit('_clear'); }), delete: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return false; this.__mapKeysData__.splice(index, 1); this.__mapValuesData__.splice(index, 1); this.emit('_delete', index, key); return true; }), entries: d(function () { return new Iterator(this, 'key+value'); }), forEach: d(function (cb/*, thisArg*/) { var thisArg = arguments[1], iterator, result; callable(cb); iterator = this.entries(); result = iterator._next(); while (result !== undefined) { call.call(cb, thisArg, this.__mapValuesData__[result], this.__mapKeysData__[result], this); result = iterator._next(); } }), get: d(function (key) { var index = eIndexOf.call(this.__mapKeysData__, key); if (index === -1) return; return this.__mapValuesData__[index]; }), has: d(function (key) { return (eIndexOf.call(this.__mapKeysData__, key) !== -1); }), keys: d(function () { return new Iterator(this, 'key'); }), set: d(function (key, value) { var index = eIndexOf.call(this.__mapKeysData__, key), emit; if (index === -1) { index = this.__mapKeysData__.push(key) - 1; emit = true; } this.__mapValuesData__[index] = value; if (emit) this.emit('_add', index, key); return this; }), size: d.gs(function () { return this.__mapKeysData__.length; }), values: d(function () { return new Iterator(this, 'value'); }), toString: d(function () { return '[object Map]'; }) })); Object.defineProperty(MapPoly.prototype, Symbol.iterator, d(function () { return this.entries(); })); Object.defineProperty(MapPoly.prototype, Symbol.toStringTag, d('c', 'Map')); },{"./is-native-implemented":60,"./lib/iterator":62,"d":3,"es5-ext/array/#/clear":7,"es5-ext/array/#/e-index-of":8,"es5-ext/object/set-prototype-of":42,"es5-ext/object/valid-callable":45,"es5-ext/object/valid-value":46,"es6-iterator/for-of":52,"es6-iterator/valid-iterable":57,"es6-symbol":75,"event-emitter":84}],64:[function(require,module,exports){ 'use strict'; if (!require('./is-implemented')()) { Object.defineProperty(require('es5-ext/global'), 'Set', { value: require('./polyfill'), configurable: true, enumerable: false, writable: true }); } },{"./is-implemented":65,"./polyfill":73,"es5-ext/global":17}],65:[function(require,module,exports){ 'use strict'; module.exports = function () { var set, iterator, result; if (typeof Set !== 'function') return false; set = new Set(['raz', 'dwa', 'trzy']); if (String(set) !== '[object Set]') return false; if (set.size !== 3) return false; if (typeof set.add !== 'function') return false; if (typeof set.clear !== 'function') return false; if (typeof set.delete !== 'function') return false; if (typeof set.entries !== 'function') return false; if (typeof set.forEach !== 'function') return false; if (typeof set.has !== 'function') return false; if (typeof set.keys !== 'function') return false; if (typeof set.values !== 'function') return false; iterator = set.values(); result = iterator.next(); if (result.done !== false) return false; if (result.value !== 'raz') return false; return true; }; },{}],66:[function(require,module,exports){ // Exports true if environment provides native `Set` implementation, // whatever that is. 'use strict'; module.exports = (function () { if (typeof Set === 'undefined') return false; return (Object.prototype.toString.call(Set.prototype) === '[object Set]'); }()); },{}],67:[function(require,module,exports){ 'use strict'; var setPrototypeOf = require('es5-ext/object/set-prototype-of') , contains = require('es5-ext/string/#/contains') , d = require('d') , Iterator = require('es6-iterator') , toStringTagSymbol = require('es6-symbol').toStringTag , defineProperty = Object.defineProperty , SetIterator; SetIterator = module.exports = function (set, kind) { if (!(this instanceof SetIterator)) return new SetIterator(set, kind); Iterator.call(this, set.__setData__, set); if (!kind) kind = 'value'; else if (contains.call(kind, 'key+value')) kind = 'key+value'; else kind = 'value'; defineProperty(this, '__kind__', d('', kind)); }; if (setPrototypeOf) setPrototypeOf(SetIterator, Iterator); SetIterator.prototype = Object.create(Iterator.prototype, { constructor: d(SetIterator), _resolve: d(function (i) { if (this.__kind__ === 'value') return this.__list__[i]; return [this.__list__[i], this.__list__[i]]; }), toString: d(function () { return '[object Set Iterator]'; }) }); defineProperty(SetIterator.prototype, toStringTagSymbol, d('c', 'Set Iterator')); },{"d":3,"es5-ext/object/set-prototype-of":42,"es5-ext/string/#/contains":47,"es6-iterator":54,"es6-symbol":68}],68:[function(require,module,exports){ 'use strict'; module.exports = require('./is-implemented')() ? Symbol : require('./polyfill'); },{"./is-implemented":69,"./polyfill":71}],69:[function(require,module,exports){ 'use strict'; var validTypes = { object: true, symbol: true }; module.exports = function () { var symbol; if (typeof Symbol !== 'function') return false; symbol = Symbol('test symbol'); try { String(symbol); } catch (e) { return false; } // Return 'true' also for polyfills if (!validTypes[typeof Symbol.iterator]) return false; if (!validTypes[typeof Symbol.toPrimitive]) return false; if (!validTypes[typeof Symbol.toStringTag]) return false; return true; }; },{}],70:[function(require,module,exports){ 'use strict'; module.exports = function (x) { if (!x) return false; if (typeof x === 'symbol') return true; if (!x.constructor) return false; if (x.constructor.name !== 'Symbol') return false; return (x[x.constructor.toStringTag] === 'Symbol'); }; },{}],71:[function(require,module,exports){ // ES2015 Symbol polyfill for environments that do not (or partially) support it 'use strict'; var d = require('d') , validateSymbol = require('./validate-symbol') , create = Object.create, defineProperties = Object.defineProperties , defineProperty = Object.defineProperty, objPrototype = Object.prototype , NativeSymbol, SymbolPolyfill, HiddenSymbol, globalSymbols = create(null) , isNativeSafe; if (typeof Symbol === 'function') { NativeSymbol = Symbol; try { String(NativeSymbol()); isNativeSafe = true; } catch (ignore) {} } var generateName = (function () { var created = create(null); return function (desc) { var postfix = 0, name, ie11BugWorkaround; while (created[desc + (postfix || '')]) ++postfix; desc += (postfix || ''); created[desc] = true; name = '@@' + desc; defineProperty(objPrototype, name, d.gs(null, function (value) { // For IE11 issue see: // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ // ie11-broken-getters-on-dom-objects // https://github.com/medikoo/es6-symbol/issues/12 if (ie11BugWorkaround) return; ie11BugWorkaround = true; defineProperty(this, name, d(value)); ie11BugWorkaround = false; })); return name; }; }()); // Internal constructor (not one exposed) for creating Symbol instances. // This one is used to ensure that `someSymbol instanceof Symbol` always return false HiddenSymbol = function Symbol(description) { if (this instanceof HiddenSymbol) throw new TypeError('Symbol is not a constructor'); return SymbolPolyfill(description); }; // Exposed `Symbol` constructor // (returns instances of HiddenSymbol) module.exports = SymbolPolyfill = function Symbol(description) { var symbol; if (this instanceof Symbol) throw new TypeError('Symbol is not a constructor'); if (isNativeSafe) return NativeSymbol(description); symbol = create(HiddenSymbol.prototype); description = (description === undefined ? '' : String(description)); return defineProperties(symbol, { __description__: d('', description), __name__: d('', generateName(description)) }); }; defineProperties(SymbolPolyfill, { for: d(function (key) { if (globalSymbols[key]) return globalSymbols[key]; return (globalSymbols[key] = SymbolPolyfill(String(key))); }), keyFor: d(function (s) { var key; validateSymbol(s); for (key in globalSymbols) if (globalSymbols[key] === s) return key; }), // To ensure proper interoperability with other native functions (e.g. Array.from) // fallback to eventual native implementation of given symbol hasInstance: d('', (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill('hasInstance')), isConcatSpreadable: d('', (NativeSymbol && NativeSymbol.isConcatSpreadable) || SymbolPolyfill('isConcatSpreadable')), iterator: d('', (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill('iterator')), match: d('', (NativeSymbol && NativeSymbol.match) || SymbolPolyfill('match')), replace: d('', (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill('replace')), search: d('', (NativeSymbol && NativeSymbol.search) || SymbolPolyfill('search')), species: d('', (NativeSymbol && NativeSymbol.species) || SymbolPolyfill('species')), split: d('', (NativeSymbol && NativeSymbol.split) || SymbolPolyfill('split')), toPrimitive: d('', (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill('toPrimitive')), toStringTag: d('', (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill('toStringTag')), unscopables: d('', (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill('unscopables')) }); // Internal tweaks for real symbol producer defineProperties(HiddenSymbol.prototype, { constructor: d(SymbolPolyfill), toString: d('', function () { return this.__name__; }) }); // Proper implementation of methods exposed on Symbol.prototype // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype defineProperties(SymbolPolyfill.prototype, { toString: d(function () { return 'Symbol (' + validateSymbol(this).__description__ + ')'; }), valueOf: d(function () { return validateSymbol(this); }) }); defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d('', function () { var symbol = validateSymbol(this); if (typeof symbol === 'symbol') return symbol; return symbol.toString(); })); defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d('c', 'Symbol')); // Proper implementaton of toPrimitive and toStringTag for returned symbol instances defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toStringTag, d('c', SymbolPolyfill.prototype[SymbolPolyfill.toStringTag])); // Note: It's important to define `toPrimitive` as last one, as some implementations // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) // And that may invoke error in definition flow: // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 defineProperty(HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, d('c', SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive])); },{"./validate-symbol":72,"d":3}],72:[function(require,module,exports){ 'use strict'; var isSymbol = require('./is-symbol'); module.exports = function (value) { if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); return value; }; },{"./is-symbol":70}],73:[function(require,module,exports){ 'use strict'; var clear = require('es5-ext/array/#/clear') , eIndexOf = require('es5-ext/array/#/e-index-of') , setPrototypeOf = require('es5-ext/object/set-prototype-of') , callable = require('es5-ext/object/valid-callable') , d = require('d') , ee = require('event-emitter') , Symbol = require('es6-symbol') , iterator = require('es6-iterator/valid-iterable') , forOf = require('es6-iterator/for-of') , Iterator = require('./lib/iterator') , isNative = require('./is-native-implemented') , call = Function.prototype.call , defineProperty = Object.defineProperty, getPrototypeOf = Object.getPrototypeOf , SetPoly, getValues, NativeSet; if (isNative) NativeSet = Set; module.exports = SetPoly = function Set(/*iterable*/) { var iterable = arguments[0], self; if (!(this instanceof SetPoly)) throw new TypeError('Constructor requires \'new\''); if (isNative && setPrototypeOf) self = setPrototypeOf(new NativeSet(), getPrototypeOf(this)); else self = this; if (iterable != null) iterator(iterable); defineProperty(self, '__setData__', d('c', [])); if (!iterable) return self; forOf(iterable, function (value) { if (eIndexOf.call(this, value) !== -1) return; this.push(value); }, self.__setData__); return self; }; if (isNative) { if (setPrototypeOf) setPrototypeOf(SetPoly, NativeSet); SetPoly.prototype = Object.create(NativeSet.prototype, { constructor: d(SetPoly) }); } ee(Object.defineProperties(SetPoly.prototype, { add: d(function (value) { if (this.has(value)) return this; this.emit('_add', this.__setData__.push(value) - 1, value); return this; }), clear: d(function () { if (!this.__setData__.length) return; clear.call(this.__setData__); this.emit('_clear'); }), delete: d(function (value) { var index = eIndexOf.call(this.__setData__, value); if (index === -1) return false; this.__setData__.splice(index, 1); this.emit('_delete', index, value); return true; }), entries: d(function () { return new Iterator(this, 'key+value'); }), forEach: d(function (cb/*, thisArg*/) { var thisArg = arguments[1], iterator, result, value; callable(cb); iterator = this.values(); result = iterator._next(); while (result !== undefined) { value = iterator._resolve(result); call.call(cb, thisArg, value, value, this); result = iterator._next(); } }), has: d(function (value) { return (eIndexOf.call(this.__setData__, value) !== -1); }), keys: d(getValues = function () { return this.values(); }), size: d.gs(function () { return this.__setData__.length; }), values: d(function () { return new Iterator(this); }), toString: d(function () { return '[object Set]'; }) })); defineProperty(SetPoly.prototype, Symbol.iterator, d(getValues)); defineProperty(SetPoly.prototype, Symbol.toStringTag, d('c', 'Set')); },{"./is-native-implemented":66,"./lib/iterator":67,"d":3,"es5-ext/array/#/clear":7,"es5-ext/array/#/e-index-of":8,"es5-ext/object/set-prototype-of":42,"es5-ext/object/valid-callable":45,"es6-iterator/for-of":52,"es6-iterator/valid-iterable":57,"es6-symbol":68,"event-emitter":84}],74:[function(require,module,exports){ "use strict"; if (!require("./is-implemented")()) { Object.defineProperty(require("ext/global-this"), "Symbol", { value: require("./polyfill"), configurable: true, enumerable: false, writable: true }); } },{"./is-implemented":76,"./polyfill":82,"ext/global-this":86}],75:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? require("ext/global-this").Symbol : require("./polyfill"); },{"./is-implemented":76,"./polyfill":82,"ext/global-this":86}],76:[function(require,module,exports){ "use strict"; var global = require("ext/global-this") , validTypes = { object: true, symbol: true }; module.exports = function () { var Symbol = global.Symbol; var symbol; if (typeof Symbol !== "function") return false; symbol = Symbol("test symbol"); try { String(symbol); } catch (e) { return false; } // Return 'true' also for polyfills if (!validTypes[typeof Symbol.iterator]) return false; if (!validTypes[typeof Symbol.toPrimitive]) return false; if (!validTypes[typeof Symbol.toStringTag]) return false; return true; }; },{"ext/global-this":86}],77:[function(require,module,exports){ "use strict"; module.exports = function (value) { if (!value) return false; if (typeof value === "symbol") return true; if (!value.constructor) return false; if (value.constructor.name !== "Symbol") return false; return value[value.constructor.toStringTag] === "Symbol"; }; },{}],78:[function(require,module,exports){ "use strict"; var d = require("d"); var create = Object.create, defineProperty = Object.defineProperty, objPrototype = Object.prototype; var created = create(null); module.exports = function (desc) { var postfix = 0, name, ie11BugWorkaround; while (created[desc + (postfix || "")]) ++postfix; desc += postfix || ""; created[desc] = true; name = "@@" + desc; defineProperty( objPrototype, name, d.gs(null, function (value) { // For IE11 issue see: // https://connect.microsoft.com/IE/feedbackdetail/view/1928508/ // ie11-broken-getters-on-dom-objects // https://github.com/medikoo/es6-symbol/issues/12 if (ie11BugWorkaround) return; ie11BugWorkaround = true; defineProperty(this, name, d(value)); ie11BugWorkaround = false; }) ); return name; }; },{"d":81}],79:[function(require,module,exports){ "use strict"; var d = require("d") , NativeSymbol = require("ext/global-this").Symbol; module.exports = function (SymbolPolyfill) { return Object.defineProperties(SymbolPolyfill, { // To ensure proper interoperability with other native functions (e.g. Array.from) // fallback to eventual native implementation of given symbol hasInstance: d( "", (NativeSymbol && NativeSymbol.hasInstance) || SymbolPolyfill("hasInstance") ), isConcatSpreadable: d( "", (NativeSymbol && NativeSymbol.isConcatSpreadable) || SymbolPolyfill("isConcatSpreadable") ), iterator: d("", (NativeSymbol && NativeSymbol.iterator) || SymbolPolyfill("iterator")), match: d("", (NativeSymbol && NativeSymbol.match) || SymbolPolyfill("match")), replace: d("", (NativeSymbol && NativeSymbol.replace) || SymbolPolyfill("replace")), search: d("", (NativeSymbol && NativeSymbol.search) || SymbolPolyfill("search")), species: d("", (NativeSymbol && NativeSymbol.species) || SymbolPolyfill("species")), split: d("", (NativeSymbol && NativeSymbol.split) || SymbolPolyfill("split")), toPrimitive: d( "", (NativeSymbol && NativeSymbol.toPrimitive) || SymbolPolyfill("toPrimitive") ), toStringTag: d( "", (NativeSymbol && NativeSymbol.toStringTag) || SymbolPolyfill("toStringTag") ), unscopables: d( "", (NativeSymbol && NativeSymbol.unscopables) || SymbolPolyfill("unscopables") ) }); }; },{"d":81,"ext/global-this":86}],80:[function(require,module,exports){ "use strict"; var d = require("d") , validateSymbol = require("../../../validate-symbol"); var registry = Object.create(null); module.exports = function (SymbolPolyfill) { return Object.defineProperties(SymbolPolyfill, { for: d(function (key) { if (registry[key]) return registry[key]; return (registry[key] = SymbolPolyfill(String(key))); }), keyFor: d(function (symbol) { var key; validateSymbol(symbol); for (key in registry) { if (registry[key] === symbol) return key; } return undefined; }) }); }; },{"../../../validate-symbol":83,"d":81}],81:[function(require,module,exports){ "use strict"; var isValue = require("type/value/is") , isPlainFunction = require("type/plain-function/is") , assign = require("es5-ext/object/assign") , normalizeOpts = require("es5-ext/object/normalize-options") , contains = require("es5-ext/string/#/contains"); var d = (module.exports = function (dscr, value/*, options*/) { var c, e, w, options, desc; if (arguments.length < 2 || typeof dscr !== "string") { options = value; value = dscr; dscr = null; } else { options = arguments[2]; } if (isValue(dscr)) { c = contains.call(dscr, "c"); e = contains.call(dscr, "e"); w = contains.call(dscr, "w"); } else { c = w = true; e = false; } desc = { value: value, configurable: c, enumerable: e, writable: w }; return !options ? desc : assign(normalizeOpts(options), desc); }); d.gs = function (dscr, get, set/*, options*/) { var c, e, options, desc; if (typeof dscr !== "string") { options = set; set = get; get = dscr; dscr = null; } else { options = arguments[3]; } if (!isValue(get)) { get = undefined; } else if (!isPlainFunction(get)) { options = get; get = set = undefined; } else if (!isValue(set)) { set = undefined; } else if (!isPlainFunction(set)) { options = set; set = undefined; } if (isValue(dscr)) { c = contains.call(dscr, "c"); e = contains.call(dscr, "e"); } else { c = true; e = false; } desc = { get: get, set: set, configurable: c, enumerable: e }; return !options ? desc : assign(normalizeOpts(options), desc); }; },{"es5-ext/object/assign":27,"es5-ext/object/normalize-options":40,"es5-ext/string/#/contains":47,"type/plain-function/is":90,"type/value/is":92}],82:[function(require,module,exports){ // ES2015 Symbol polyfill for environments that do not (or partially) support it "use strict"; var d = require("d") , validateSymbol = require("./validate-symbol") , NativeSymbol = require("ext/global-this").Symbol , generateName = require("./lib/private/generate-name") , setupStandardSymbols = require("./lib/private/setup/standard-symbols") , setupSymbolRegistry = require("./lib/private/setup/symbol-registry"); var create = Object.create , defineProperties = Object.defineProperties , defineProperty = Object.defineProperty; var SymbolPolyfill, HiddenSymbol, isNativeSafe; if (typeof NativeSymbol === "function") { try { String(NativeSymbol()); isNativeSafe = true; } catch (ignore) {} } else { NativeSymbol = null; } // Internal constructor (not one exposed) for creating Symbol instances. // This one is used to ensure that `someSymbol instanceof Symbol` always return false HiddenSymbol = function Symbol(description) { if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor"); return SymbolPolyfill(description); }; // Exposed `Symbol` constructor // (returns instances of HiddenSymbol) module.exports = SymbolPolyfill = function Symbol(description) { var symbol; if (this instanceof Symbol) throw new TypeError("Symbol is not a constructor"); if (isNativeSafe) return NativeSymbol(description); symbol = create(HiddenSymbol.prototype); description = description === undefined ? "" : String(description); return defineProperties(symbol, { __description__: d("", description), __name__: d("", generateName(description)) }); }; setupStandardSymbols(SymbolPolyfill); setupSymbolRegistry(SymbolPolyfill); // Internal tweaks for real symbol producer defineProperties(HiddenSymbol.prototype, { constructor: d(SymbolPolyfill), toString: d("", function () { return this.__name__; }) }); // Proper implementation of methods exposed on Symbol.prototype // They won't be accessible on produced symbol instances as they derive from HiddenSymbol.prototype defineProperties(SymbolPolyfill.prototype, { toString: d(function () { return "Symbol (" + validateSymbol(this).__description__ + ")"; }), valueOf: d(function () { return validateSymbol(this); }) }); defineProperty( SymbolPolyfill.prototype, SymbolPolyfill.toPrimitive, d("", function () { var symbol = validateSymbol(this); if (typeof symbol === "symbol") return symbol; return symbol.toString(); }) ); defineProperty(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d("c", "Symbol")); // Proper implementaton of toPrimitive and toStringTag for returned symbol instances defineProperty( HiddenSymbol.prototype, SymbolPolyfill.toStringTag, d("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]) ); // Note: It's important to define `toPrimitive` as last one, as some implementations // implement `toPrimitive` natively without implementing `toStringTag` (or other specified symbols) // And that may invoke error in definition flow: // See: https://github.com/medikoo/es6-symbol/issues/13#issuecomment-164146149 defineProperty( HiddenSymbol.prototype, SymbolPolyfill.toPrimitive, d("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]) ); },{"./lib/private/generate-name":78,"./lib/private/setup/standard-symbols":79,"./lib/private/setup/symbol-registry":80,"./validate-symbol":83,"d":81,"ext/global-this":86}],83:[function(require,module,exports){ "use strict"; var isSymbol = require("./is-symbol"); module.exports = function (value) { if (!isSymbol(value)) throw new TypeError(value + " is not a symbol"); return value; }; },{"./is-symbol":77}],84:[function(require,module,exports){ 'use strict'; var d = require('d') , callable = require('es5-ext/object/valid-callable') , apply = Function.prototype.apply, call = Function.prototype.call , create = Object.create, defineProperty = Object.defineProperty , defineProperties = Object.defineProperties , hasOwnProperty = Object.prototype.hasOwnProperty , descriptor = { configurable: true, enumerable: false, writable: true } , on, once, off, emit, methods, descriptors, base; on = function (type, listener) { var data; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) { data = descriptor.value = create(null); defineProperty(this, '__ee__', descriptor); descriptor.value = null; } else { data = this.__ee__; } if (!data[type]) data[type] = listener; else if (typeof data[type] === 'object') data[type].push(listener); else data[type] = [data[type], listener]; return this; }; once = function (type, listener) { var once, self; callable(listener); self = this; on.call(this, type, once = function () { off.call(self, type, once); apply.call(listener, this, arguments); }); once.__eeOnceListener__ = listener; return this; }; off = function (type, listener) { var data, listeners, candidate, i; callable(listener); if (!hasOwnProperty.call(this, '__ee__')) return this; data = this.__ee__; if (!data[type]) return this; listeners = data[type]; if (typeof listeners === 'object') { for (i = 0; (candidate = listeners[i]); ++i) { if ((candidate === listener) || (candidate.__eeOnceListener__ === listener)) { if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; else listeners.splice(i, 1); } } } else { if ((listeners === listener) || (listeners.__eeOnceListener__ === listener)) { delete data[type]; } } return this; }; emit = function (type) { var i, l, listener, listeners, args; if (!hasOwnProperty.call(this, '__ee__')) return; listeners = this.__ee__[type]; if (!listeners) return; if (typeof listeners === 'object') { l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; listeners = listeners.slice(); for (i = 0; (listener = listeners[i]); ++i) { apply.call(listener, this, args); } } else { switch (arguments.length) { case 1: call.call(listeners, this); break; case 2: call.call(listeners, this, arguments[1]); break; case 3: call.call(listeners, this, arguments[1], arguments[2]); break; default: l = arguments.length; args = new Array(l - 1); for (i = 1; i < l; ++i) { args[i - 1] = arguments[i]; } apply.call(listeners, this, args); } } }; methods = { on: on, once: once, off: off, emit: emit }; descriptors = { on: d(on), once: d(once), off: d(off), emit: d(emit) }; base = defineProperties({}, descriptors); module.exports = exports = function (o) { return (o == null) ? create(base) : defineProperties(Object(o), descriptors); }; exports.methods = methods; },{"d":3,"es5-ext/object/valid-callable":45}],85:[function(require,module,exports){ var naiveFallback = function () { if (typeof self === "object" && self) return self; if (typeof window === "object" && window) return window; throw new Error("Unable to resolve global `this`"); }; module.exports = (function () { if (this) return this; // Unexpected strict mode (may happen if e.g. bundled into ESM module) // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis // In all ES5+ engines global object inherits from Object.prototype // (if you approached one that doesn't please report) try { Object.defineProperty(Object.prototype, "__global__", { get: function () { return this; }, configurable: true }); } catch (error) { // Unfortunate case of Object.prototype being sealed (via preventExtensions, seal or freeze) return naiveFallback(); } try { // Safari case (window.__global__ is resolved with global context, but __global__ does not) if (!__global__) return naiveFallback(); return __global__; } finally { delete Object.prototype.__global__; } })(); },{}],86:[function(require,module,exports){ "use strict"; module.exports = require("./is-implemented")() ? globalThis : require("./implementation"); },{"./implementation":85,"./is-implemented":87}],87:[function(require,module,exports){ "use strict"; module.exports = function () { if (typeof globalThis !== "object") return false; if (!globalThis) return false; return globalThis.Array === Array; }; },{}],88:[function(require,module,exports){ "use strict"; var isPrototype = require("../prototype/is"); module.exports = function (value) { if (typeof value !== "function") return false; if (!hasOwnProperty.call(value, "length")) return false; try { if (typeof value.length !== "number") return false; if (typeof value.call !== "function") return false; if (typeof value.apply !== "function") return false; } catch (error) { return false; } return !isPrototype(value); }; },{"../prototype/is":91}],89:[function(require,module,exports){ "use strict"; var isValue = require("../value/is"); // prettier-ignore var possibleTypes = { "object": true, "function": true, "undefined": true /* document.all */ }; module.exports = function (value) { if (!isValue(value)) return false; return hasOwnProperty.call(possibleTypes, typeof value); }; },{"../value/is":92}],90:[function(require,module,exports){ "use strict"; var isFunction = require("../function/is"); var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString; module.exports = function (value) { if (!isFunction(value)) return false; if (classRe.test(functionToString.call(value))) return false; return true; }; },{"../function/is":88}],91:[function(require,module,exports){ "use strict"; var isObject = require("../object/is"); module.exports = function (value) { if (!isObject(value)) return false; try { if (!value.constructor) return false; return value.constructor.prototype === value; } catch (error) { return false; } }; },{"../object/is":89}],92:[function(require,module,exports){ "use strict"; // ES3 safe var _undefined = void 0; module.exports = function (value) { return value !== _undefined && value !== null; }; },{}]},{},[1]);
import ApiClient from './ApiClient' import { SOURCE_Add_API, SOURCE_EDIT_API, SOURCE_INFO_API, SOURCE_GET_API, SOURCE_DELETE_API, SOURCE_LIST_API } from '../constants/api' export function get(params) { const uid = JSON.parse(localStorage.getItem('uid')) return ApiClient.get(SOURCE_GET_API, { ...params, account_id: uid }) } export function add(params) { return ApiClient.post(SOURCE_Add_API, params, { needAuth: true }) } export function edit(params) { return ApiClient.put(SOURCE_EDIT_API, params) } export function remove(params) { return ApiClient.remove(SOURCE_DELETE_API, params) } export function info(params) { const uid = JSON.parse(localStorage.getItem('uid')) return ApiClient.get(SOURCE_INFO_API, { ...params, account_id: uid }) } export function list(params) { const uid = JSON.parse(localStorage.getItem('uid')) return ApiClient.get(SOURCE_LIST_API, { ...params, account_id: uid }) }
'use strict'; //filter feature module angular.module('myApp.filter', ['ngRoute', 'exactFilter']) .config(['$routeProvider', function($routeProvider) { $routeProvider.when('/filter', { templateUrl: 'filter/filter.html', controller: 'FilterCtrl' }); }]) .controller('FilterCtrl', ['$http', '$scope', function($http, $scope) { $scope.search = ""; $scope.filter = 'oneOrMore'; $scope.photos = []; buildPhotoSetFromMongo(); $scope.filters = function(photo) { switch($scope.filter) { case 'oneOrMore': { return photo.points >= 1; } default: return true; } } $scope.changeFilterTo = function(filter) { if(filter !== 'choice') $scope.search = ""; $scope.filter = filter; } function buildPhotoSetFromMongo() { $http({ method: 'GET', url: '/images' }).then(function successCallback(response) { // this callback will be called asynchronously // when the response is available var source; for(var i = 0; i < response.data.length; i++) { //trim 'assets' source = response.data[i].src.substring(7, response.data[i].src.length); //no need to trim 'assets' img is archived if(response.data[i].archived === true) source = response.data[i].src; console.log(source); $scope.photos.push({ id: response.data[i].id, src: source, points: response.data[i].points.toString(), archived: response.data[i].archived}); } }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. }); } }]);
/** * @author Toru Nagashima * @copyright 2017 Toru Nagashima. All rights reserved. * See LICENSE file in root directory for full license. */ "use strict" //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const RuleTester = require("eslint").RuleTester const rule = require("../../../lib/rules/require-component-is") //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ const tester = new RuleTester({ parser: "vue-eslint-parser", parserOptions: {ecmaVersion: 2015}, }) tester.run("require-component-is", rule, { valid: [ { filename: "test.vue", code: "", }, { filename: "test.vue", code: "<template><component v-bind:is=\"type\"></component></template>", }, { filename: "test.vue", code: "<template><component :is=\"type\"></component></template>", }, ], invalid: [ { filename: "test.vue", code: "<template><component is=\"type\"></component></template>", errors: ["Expected '<component>' elements to have 'v-bind:is' attribute."], }, { filename: "test.vue", code: "<template><component v-foo:is=\"type\"></component></template>", errors: ["Expected '<component>' elements to have 'v-bind:is' attribute."], }, ], })
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var __extends = (this && this.__extends) || (function () { var extendStatics = function (d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); export var ListAriaRootRole; (function (ListAriaRootRole) { /** default tree structure role */ ListAriaRootRole["TREE"] = "tree"; /** role='tree' can interfere with screenreaders reading nested elements inside the tree row. Use FORM in that case. */ ListAriaRootRole["FORM"] = "form"; })(ListAriaRootRole || (ListAriaRootRole = {})); var ListError = /** @class */ (function (_super) { __extends(ListError, _super); function ListError(user, message) { return _super.call(this, "ListError [" + user + "] " + message) || this; } return ListError; }(Error)); export { ListError };
var async = require('async'), crypto = require('crypto'), request = require('request'), RateLimiter = require('limiter').RateLimiter; util = require('util'); var logger = require('../logger.js'), order = require('../order.js'), transaction = require('../transaction.js'), counter = require('../util.js').counter, pager = require('../util.js').pager, mergeObjects = require('../util.js').mergeObjects, BaseExchange = require('./base.js'); var BitfinexClient = function(key, secret) { this.version = 'v1' this.url = 'https://api.bitfinex.com/' + this.version; this.key = key || ''; this.secret = secret || ''; this.getNonce = counter(+new Date()); }; /** * Implement Bitfinex's strange header-based payloads. * * See: https://www.bitfinex.com/pages/api */ BitfinexClient.prototype.encode = function(params) { var payload = new Buffer(JSON.stringify(params)).toString('base64'); var signature = crypto.createHmac('sha384', this.secret).update(payload).digest('hex'); var headers = { 'X-BFX-APIKEY': this.key, 'X-BFX-PAYLOAD': payload, 'X-BFX-SIGNATURE': signature }; // We discard the form params, because they live in headers now. ¯\_(ツ)_/¯ return headers; }; BitfinexClient.prototype.call = function(method, resource, params, cb) { if (cb === undefined && typeof(params) == 'function') { cb = params; params = {}; } var req = { 'url': this.url + resource, 'json': true, 'method': method }; if (method == 'GET') { req['qs'] = params; } else { params['request'] = '/' + this.version + resource; params['nonce'] = String(this.getNonce()); req['headers'] = this.encode(params); } return request(req, cb); }; /** * Liquid trading interface to Bitfinex. * * @param {BitfinexClient} client * @param {number} delay Number of milliseconds to delay between ticks (default: 1000) * @param {boolean} pretend Don't execute any trades, just watch. */ var BitfinexExchange = module.exports = function(client, delay, pretend) { BitfinexExchange.super_.call(this, pretend, delay); this.client = client; // Use this rate limiter whenever using client. this.rateLimiter = new RateLimiter(55, 'minute'); // Actually 60 but we'll be careful. // This can be switched to async.map if nonce doesn't need to be strictly-incremental. // Use async.mapSeries if nonce must be strictly-incrementing, async.map otherwise. this.requestMap = async.mapSeries; }; util.inherits(BitfinexExchange, BaseExchange); BitfinexExchange.id = 'bitfinex'; BitfinexExchange.configKeys = ['BITFINEX_KEY', 'BITFINEX_SECRET']; /** * Instantiate necessary clients based on configuration and return a * {@code BitfinexExchange} instance. * * @static * @param {{BITFINEX_KEY: string, BITFINEX_SECRET: string}} * @return {BitfinexExchange} */ BitfinexExchange.fromConfig = function(config) { var client = new BitfinexClient(config.apiKeys.BITFINEX_KEY, config.apiKeys.BITFINEX_SECRET); return new BitfinexExchange(client, config.tickDelay || 1000, config.pretend); }; /** * Execute a unit of polling. */ BitfinexExchange.prototype.tick = function() { var exchange = this; var params = { // By default, the API returns ~1600 results. 'limit_bids': 20, 'limit_asks': 20 }; exchange.client.call('GET', '/book/btcusd', params, function(err, response, data) { exchange.requestLock.release(); // We only care about our orders. var err = err || toError(data); if (err) { logger.error('Failure during BitfinexExchange polling:', err.message); return; } exchange.emit('orderbook', toOrderbook(data)); }); }; /** * Authenticate to the API and start polling loop. * * @param {function=} callback Function called upon completion. */ BitfinexExchange.prototype.ready = function(callback) { this.debug('Preparing.'); this.cleanup(); var exchange = this; async.series([ function rateLimit(callback) { exchange.rateLimiter.removeTokens(2, callback); }, function loadOrders(callback) { exchange.client.call('POST', '/orders', function(err, response, data) { var err = err || toError(data); if (err) { logger.error('Failed to load BitfinexExchange placed orders:', err.message); callback.call(exchange, err); return; } var placedOrders = data.map(toOrder); placedOrders.forEach(function(order) { exchange.saveOrder(order); }); if (placedOrders.length) { exchange.debug('Loaded placed orders:', placedOrders.length); } callback.call(exchange, err); }); }, function checkBalance(callback) { // We don't really care what the minimums are at this point, we just // want to update the internal balance values. var minQuantity, minValue; exchange.checkBalance(minQuantity, minValue, callback); }, function ready(callback) { BitfinexExchange.super_.prototype.ready.call(exchange, callback); } ], callback); }; /** * Check whether there is sufficient balance. Callback with err if not. * * @param {number=} minQuantity Minimum BTC to expect in balance. * @param {number=} minValue Minimum USD to expect in balance. * @param {function=} callback Function called upon completion. */ BitfinexExchange.prototype.checkBalance = function(minQuantity, minValue, callback) { var exchange = this; exchange.client.call('POST', '/balances', function(err, response, data) { var err = err || toError(data); if (err) { logger.error('Failed to load BitfinexExchange balance:', err); callback && callback.call(exchange, err); return; } try { var balance = toBalance(data); } catch (err) { logger.error('Unexpected Bitfinex balance value:', data); callback && callback.call(exchange, err); return; } exchange.setBalance(balance.quantity, balance.value); if (minQuantity && exchange.balance.quantity.lt(minQuantity)) { err = new Error('Insufficient BTC balance on Bitfinex: ' + exchange.balance.quantity.toString()); } else if (minValue && exchange.balance.value.lt(minValue)) { err = new Error('Insufficient USD balance on Bitfinex: ' + exchange.balance.quantity.toString()); } callback && callback.call(exchange, err); }); }; /** * Place an instruction of orders for this exchange. * * @param {Array.<Order>} orders List of orders to place concurrently. * @param {function} callback */ BitfinexExchange.prototype.placeOrders = function(orders, callback) { var exchange = this; if (exchange.pretend) { orders.map(function(order) { logger.info('[exchange:bitfinex] Pretend placeOrder:', order.toString()); exchange.saveOrder(order); }); return; } // Bitfinex API limits multi operations to 10 orders. var pagedOrders = pager(orders, 10); exchange.requestMap(pagedOrders, function(page, callback) { var params = {"orders": page.map(function(order) { var side = { 'ASK': 'sell', 'BID': 'buy' }[order.type]; return { 'symbol': 'btcusd', // symbol (string): The name of the symbol (see `/symbols`). 'amount': order.quantity.toFixed(), // amount (decimal): Order size: how much to buy or sell. 'price': order.rate.toFixed(2), // price (price): Price to buy or sell at. May omit if a market order. 'exchange': 'all', // exchange (string): "bitfinex", "bitstamp", "all" (for no routing). 'side': side, // side (string): Either "buy" or "sell". 'type': 'exchange limit' // type (string): Either "market" / "limit" / "stop" / "trailing-stop" / "fill-or-kill" / "exchange market" / "exchange limit" / "exchange stop" / "exchange trailing-stop" / "exchange fill-or-kill". (type starting by "exchange " are exchange orders, others are margin trading orders) }; })}; exchange.rateLimiter.removeTokens(1, function() { exchange.requestLock.acquire(true /* exclusive */, function() { exchange.client.call('POST', '/order/new/multi', params, function(err, response, data) { exchange.requestLock.release(); var err = err || toError(data); if (err) { callback(err, response, data); return; } var orders = data['order_ids'].map(toOrder); if (orders.length !== page.length) { err = new Error('Bitfinex returned incorrect number of placed orders: ' + orders.length + ' of ' + page.length); err.orders = orders.map(String); callback(err); } orders.map(function(order, i) { exchange.debug('Placed %s (from: %s)', order.toString(), page[i].toString()); exchange.saveOrder(order); }); callback(); }); }); }); }, callback); }; /** * Cancel orders. * * @param {Array.<Order>} orders List of orders to cancel concurrently. * @param {function} callback */ BitfinexExchange.prototype.cancelOrders = function(orders, callback) { var exchange = this; if (exchange.pretend) { orders.map(function(order) { logger.info('[exchange:bitfinex] Pretend cancelOrder:', order.toString()); exchange.deleteOrder(order); }); return; } // Bitfinex API limits multi operations to 10 orders. var pagedOrders = pager(orders, 10); exchange.requestMap(pagedOrders, function(page, callback) { var params = { 'order_ids': page.map(function(order) { return order.id }) }; exchange.rateLimiter.removeTokens(1, function() { exchange.requestLock.acquire(true /* exclusive */, function() { exchange.client.call('POST', '/order/cancel/multi', params, function(err, response, data) { exchange.requestLock.release(); var err = err || toError(data); if (err) { callback(err, response, data); return; } // XXX: Not clear what this is supposed to return. callback(); }); }); }); }, callback); }; /** * Given a Bitfinex order (as returned by the API), return a corresponding * {@code Order} object. * * @static * @param {object} d * @param {boolean=} skipExecuted Don't count executed amount. * @return {Order} */ var toOrder = BitfinexExchange.toOrder = function(d, skipExecuted) { try{ var amount = d.original_amount; if (amount===undefined) { // New orders return this property instead for some reason. amount = d.originalamount; } if (!skipExecuted) { amount = d.remaining_amount; if(amount===undefined) { // New orders return this property instead for some reason. amount = d.amount; } } var side = d.side; if (side===undefined) { // Negative amount will get inverted. side = "ASK"; } else { side = { 'sell': 'ASK', 'buy': 'BID' }[side]; } var order_id = d.order_id; if (order_id===undefined) { // New orders return this property instead for some reason. order_id = d.id; } var o = new order.Order(order_id, side, amount, d.price, null, 'bitfinex'); } catch (e) { logger.warn('Failed to convert Bitfinex order:', d); throw e; } return o; }; /** * Given a Bitfinex orderbook (as returned by the API), return a corresponding * orderbook. * * @static * @param {object} d * @return {{asks: Array.<Order>, bids: Array.<Order>}} */ var toOrderbook = BitfinexExchange.toOrderbook = function(d) { return { 'asks': d.asks.map(function(o) { return new order.Order(null, 'ASK', o.amount, o.price, null, 'bitfinex'); }), 'bids': d.bids.map(function(o) { return new order.Order(null, 'BID', o.amount, o.price, null, 'bitfinex'); }) }; }; /** * Given a Bitfinex accounts list (as returned by the API), return normalized * parameters for {@code BaseExchange.prototype.setBalance}. * * @static * @param {object} accounts * @return {{value: string, quantity: string}} */ var toBalance = BitfinexExchange.toBalance = function(balance) { var args = { 'value': 0, 'quantity': 0 }; balance.forEach(function(account) { if (account['type'] !== 'exchange') return; // Skip other wallets. var type = account['currency']; var key = {'usd': 'value', 'btc': 'quantity'}[type]; if (!key) return; // Skip unknown currencies. args[key] += Number(account['available']); }); if (args['quantity'] < 0) { throw new Error('Balance quantity is negative.'); } else if (args['value'] < 0) { throw new Error('Balance value is negative.'); } return args; }; /** * Given a Bitfinex response body as parsed JSON, return an {@code Error} * instace if it contains an error, or null otherwise. * * @static * @param {object} * @return {Error|null} */ var toError = BitfinexExchange.toError = function(r) { if (!r || !r.message) return null; return new Error(r.message); };
// // PageScore.js import React, { Component } from 'react'; import Title from './Title' import MatchTabs from './MatchTabs' import ScoreSummaryContainer from '../containers/ScoreSummaryContainer' import RaisedButton from 'material-ui/RaisedButton'; import DeleteIcon from 'material-ui/svg-icons/action/delete-forever'; class PageScore extends Component { render () { var style = { body: { fontFamily: "Roboto", }, button: { margin: 12, }, }; return ( <div style={style.body}> <Title backgroundColor="#629749" banner={require('../../images/banner2.jpg')} text="S C O R E" /> <ScoreSummaryContainer/> <MatchTabs /> <div style={{marginTop: 20}}/> <RaisedButton label="Clear All Scores" primary={true} style={style.button} icon={<DeleteIcon />} onClick={this.props.deleteAll} /> </div> ) }; } export default PageScore;
import { registerEnumeration } from "lib/misc/factories"; // OPCUA Spec 1.02 Part 4 page 5.12.1.3 Monitoring Mode: // The monitoring mode parameter is used to enable and disable the sampling of a MonitoredItem, and also to provide // for independently enabling and disabling the reporting of Notifications. This capability allows a MonitoredItem to // be configured to sample, sample and report, or neither. Disabling sampling does not change the values of any of the // other MonitoredItem parameter, such as its sampling interval. // When a MonitoredItem is enabled (i.e. when the MonitoringMode is changed from DISABLED to SAMPLING or REPORTING) // or it is created in the enabled state, the Server shall report the first sample as soon as possible and the time // of this sample becomes the starting point for the next sampling interval. const MonitoringMode_Schema = { name: "MonitoringMode", enumValues: { /* * DISABLED_0 The item being monitored is not sampled or evaluated, and Notifications are not generated or * queued. Notification reporting is disabled. * */ Disabled: 0, /* * SAMPLING_1 The item being monitored is sampled and evaluated, and Notifications are generated and * queued. Notification reporting is disabled. */ Sampling: 1, /* * REPORTING_2 The item being monitored is sampled and evaluated, and Notifications are generated and * queued. Notification reporting is enabled */ Reporting: 2, Invalid: -1 } }; export {MonitoringMode_Schema}; export const MonitoringMode = registerEnumeration(MonitoringMode_Schema);
/*jshint esversion: 6 */ import { Template } from 'meteor/templating'; import './week.html'; import { attsToggleInvalidClass } from '../../utilities/attsToggleInvalidClass'; Template.afInputWeek_materialize.helpers({ atts: attsToggleInvalidClass });
angular .module("recordmate") .controller("collectionController", ['$scope', '$location', 'userAuth', 'Search', 'collection', function($scope, $location,userAuth, Search, collection){ //get username $scope.user = userAuth.getUser().name; //create variable to hold wishlist items $scope.items //create variable to pass to render function //var user = {user: $scope.user}; //render the wishlist var render = function() { collection.collectionRender($scope.user).success(function(data) { //if there are items fill wishlist, if not show empty wishlist message if (data.items[0]) { $scope.items = data.items; } else { $scope.empty = true; $scope.items = []; } }); }; //When user clicks remove, the function is called to remove the item from the wishlist $scope.collectRemove = function(artist, album) { var item = { username : $scope.user, artist : artist, album : album }; collection.collectionRemove(item).then(function() { render(); }); } //When user clicks on the album cover, call the albumsearch function and return them to album info page $scope.albumSearch = function(artist, album) { Search.albumSet(artist, album); } //calls the render function on page load render(); }]);
import React from 'react'; import classnames from 'classnames'; import style from './style'; const NavDrawer = (props) => { const rootClasses = classnames([style.navDrawer], { [style['permanent-' + props.permanentAt]]: props.permanentAt, [style.wide]: (props.width === 'wide'), [style.active]: props.active, [style.pinned]: props.pinned }, props.className); const drawerClasses = classnames(style.drawerContent, { [style.scrollY]: props.scrollY }); return ( <div data-react-toolbox='nav-drawer' className={rootClasses} onClick={props.onOverlayClick}> <div data-react-toolbox='nav-drawer-scrim' className={style.scrim}> <aside data-react-toolbox='nav-drawer-content' className={drawerClasses}> {props.children} </aside> </div> </div> ); }; NavDrawer.propTypes = { active: React.PropTypes.bool, children: React.PropTypes.any, className: React.PropTypes.string, onOverlayClick: React.PropTypes.func, permanentAt: React.PropTypes.oneOf(['sm', 'md', 'lg', 'xl', 'xxl', 'xxxl']), pinned: React.PropTypes.bool, scrollY: React.PropTypes.bool, width: React.PropTypes.oneOf(['normal', 'wide']) }; NavDrawer.defaultProps = { active: false, className: '', scrollY: false, width: 'normal' }; export default NavDrawer;
import React, { Component } from 'react'; import { StyleSheet, Text, View, Navigator, ScrollView, ListView, Alert, } from 'react-native'; import { AsyncStorage, Platform, TouchableHighlight, TouchableNativeFeedback, } from "react-native"; import NavigationBar from 'react-native-navbar'; import {GoogleSignin, GoogleSigninButton} from 'react-native-google-signin'; class SettingsPage extends Component { constructor(props, context) { super(props, context); this.state = { loggedIn: true, }; } googleSignOut() { GoogleSignin.revokeAccess().then(() => GoogleSignin.signOut()).then(() => { this.setState({user: null}); }) .done(); } logout () { console.log("log out"); try { AsyncStorage.removeItem("user"); this.googleSignOut(); } catch (error) { console.log("Error?"); console.log(error); } this.props.navigator.push({id: "LoginPage", name: "LoginPage"}); } addGroup () { console.log("add group"); this.props.navigator.push({id: "AddGroup", name: "AddGroup", passProps: {user: this.props.user}}); } leaveGroup () { this.props.navigator.push({id:"LeaveGroup", name: "LeaveGroup", passProps: {user: this.props.user}}); } createGroup () { console.log("create group"); //this.props.navigator.push({id:"AddGroup", name: "AddGroup"}); Alert.alert("Feature not operational", "This feature does not currently work.", [ {text: 'OK', onPress: () => console.log('ok pressed'), style: "cancel"}, ]); } manageGroup () { console.log("group management"); this.props.navigator.push({id:"GroupMgmt", name:"GroupMgmt", passProps: {user: this.props.user}}); } render () { return ( <Navigator renderScene={this.renderScene.bind(this)} navigator = {this.props.navigator} /> ); } renderScene (route, navigator) { var TouchableElement = TouchableHighlight; //console.log(TouchableElement); if (Platform.OS === 'android') { TouchableElement = TouchableNativeFeedback; } return ( <ScrollView> <NavigationBar title={{ title: "Settings", tintColor: 'black', }} style={{ backgroundColor: "white", }} statusBar={{ tintColor: "white", }} /> <TouchableElement onPress={() => this.logout()}> <View style={styles.submit}> <Text style={styles.submitText}>Log Out</Text> </View> </TouchableElement> <TouchableElement onPress={() => this.addGroup()}> <View style={styles.submit}> <Text style={styles.submitText}>Add Group</Text> </View> </TouchableElement> <TouchableElement onPress={() => this.leaveGroup()}> <View style={styles.submit}> <Text style={styles.submitText}>Leave Group</Text> </View> </TouchableElement> <TouchableElement onPress={() => this.createGroup()}> <View style={styles.submit}> <Text style={styles.submitText}>Create Group</Text> </View> </TouchableElement> <TouchableElement onPress={() => this.manageGroup()}> <View style={styles.submit}> <Text style={styles.submitText}>Group Management</Text> </View> </TouchableElement> </ScrollView> ); } } var styles = StyleSheet.create({ submit: { marginLeft: 10, backgroundColor: "lightgrey", justifyContent: "center", height: 40, marginRight: 10, marginTop: 30, }, submitText: { color: 'black', fontSize: 16 , fontWeight: 'normal', fontFamily: 'Helvetica Neue', alignSelf: "center", }, container: { flex: 1, flexDirection: 'row', justifyContent: 'center', alignItems: 'center', backgroundColor: '#ff7f50', }, rightContainer: { flex: 1, }, title: { fontSize: 20, marginBottom: 8, textAlign: 'center', }, year: { textAlign: 'center', }, thumbnail: { width: 53, height: 81, }, listView: { paddingTop: 20, backgroundColor: '#0000ff', marginBottom: 50, }, }); module.exports = SettingsPage;
/** * Copyright (c) 2014, 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. * * */ 'use strict'; const fs = require('graceful-fs'); const path = require('path'); function getJest(packageRoot) { const packageJSONPath = path.join(packageRoot, 'package.json'); const binPath = path.join(packageRoot, 'node_modules/jest-cli'); if (fs.existsSync(binPath)) { /* $FlowFixMe */ return require(binPath);} else { const jest = require('../jest'); // Check if Jest is specified in `package.json` but not installed. if (fs.existsSync(packageJSONPath)) { /* $FlowFixMe */ const packageJSON = require(packageJSONPath); const dependencies = packageJSON.dependencies; const devDependencies = packageJSON.devDependencies; if ( dependencies && dependencies['jest-cli'] || devDependencies && devDependencies['jest-cli']) { console.error( 'Please run `npm install` to use the version of Jest intended for ' + 'this project.'); process.on('exit', () => process.exit(1));}} return jest;}} module.exports = getJest;
// npm packages import request from 'supertest'; // our packages import app from '../src/app'; export default (test) => { test('GET /', (t) => { request(app) .get('/') .expect(200) .expect('Content-Type', /text\/html/) .end((err, res) => { const expectedBody = 'Hello world!'; const actualBody = res.text; t.error(err, 'No error'); t.equal(actualBody, expectedBody, 'Retrieve body'); t.end(); }); }); test('404 on nonexistant URL', (t) => { request(app) .get('/GETShouldFailOnRandomURL') .expect(404) .expect('Content-Type', /text\/html/) .end((err, res) => { const expectedBody = 'Cannot GET /GETShouldFailOnRandomURL\n'; const actualBody = res.text; t.error(err, 'No error'); t.equal(actualBody, expectedBody, 'Retrieve body'); t.end(); }); }); };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = toutSuite; var _synchronousPromise = require('synchronous-promise'); function isObject(obj) { return obj === Object(obj); } function fakeSetTimeout(f, d) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } f(...args); } function fakeSetImmediate(f) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } f(...args); } function toutSuite(block) { let realPromise = global.Promise; let realSetImmediate = global.setImmediate; let realSetTimeout = global.setTimeout; let realNextTick = process.nextTick; global.Promise = _synchronousPromise.SynchronousPromise; global.setImmediate = fakeSetImmediate; global.setTimeout = fakeSetTimeout; process.nextTick = fakeSetImmediate; try { let ret = block(); if (isObject(ret) && 'then' in ret) { let val; ret.then(x => val = x); return val; } } finally { global.Promise = realPromise; global.setImmediate = realSetImmediate; global.setTimeout = realSetTimeout; process.nextTick = realNextTick; } }
'use strict'; import React, { Component } from 'react'; import Project from './project'; import { projects } from '../../data'; import Modal from '../modal'; export default class Portfolio extends Component { constructor(props) { super(props); } render() { return ( <div> <section id='portfolio'> <div className='container'> <div className='row'> <div className='col-lg-12 text-center'> <h2>Projects</h2> <hr className='star-primary'/> </div> </div> <div className='row'> { projects.map((project, i) => <Project key={i + 1} link={project.link} img={project.img}/>) } </div> </div> </section> { projects.map((project, i) => <Modal key={i + 1} link={project.link} img={project.img} {...project.modal}/>) } </div> ); } }
module.exports = require('./dist/iso3166-1')
/*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/ /*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/ /*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/ /*global $:true, console:true*/ (function($) { /* ======== A Handy Little QUnit Reference ======== http://docs.jquery.com/QUnit Test methods: expect(numAssertions) stop(increment) start(decrement) Test assertions: ok(value, [message]) equal(actual, expected, [message]) notEqual(actual, expected, [message]) deepEqual(actual, expected, [message]) notDeepEqual(actual, expected, [message]) strictEqual(actual, expected, [message]) notStrictEqual(actual, expected, [message]) raises(block, [expected], [message]) */ module('jQuery#CoverPhoto', { setup: function() { this.div = $('#qunit-fixture .coverphoto'); } }); test('is chainable', 1, function() { // Not a bad test to run on collection methods. strictEqual(this.div.CoverPhoto(), this.div, 'should be chaninable'); }); test('will post photo to default url', 1, function() { this.div.CoverPhoto({ post: { url: '/update_cover_photo' } }); var action = $("form", this.div).attr("action"); strictEqual(action, '/update_cover_photo', 'postUrl is properly set'); }); test('should add edit button', 1, function() { this.div.CoverPhoto({ editable: true }); strictEqual($('.edit', this.div).length, 1, 'edit link is added'); }); }(jQuery));
'use strict' // region randomInclusive32 function randomInclusive32() { return Math.floor(Math.random() * 0x100000000) / 0xffffffff } // endregion // region randomInclusive function randomInclusive() { return Math.floor(Math.random() * 0x20000000000000) / 0x1fffffffffffff } // endregion export { randomInclusive, randomInclusive32 }
import Ember from 'ember'; import jQuery from 'jquery'; export default Ember.Component.extend({ focusOnKeyDown: function() { var newactiveIndex = this.get('activeIndex'); if (newactiveIndex >= 0) { this.toggleActiveClass(newactiveIndex); }else{ jQuery('li').removeClass(); } }.observes('attrs.activeIndex').on('init'), toggleActiveClass: function (activeIndex) { var element = 'li[tabindex='+ activeIndex +']' ; var indexEle = jQuery(element); indexEle.addClass('teal').siblings().removeClass(); indexEle.closest('ul.autolist').scrollTop(indexEle.index() * indexEle.outerHeight()); }, actions: { selectRes: function(result) { this.sendAction('selectRes', result.name); } } });
var ObjectId = require("mongodb").ObjectId; var Hashids = require("hashids"); var moment = require("moment"); module.exports = function() { var salt = new ObjectId().toString(); var hashids = new Hashids(salt, 8, "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"); var now = moment(); var begin = now.clone().startOf("month"); var diff = now.diff(begin); var code = `${hashids.encode(diff)}`; return code; };
'use strict'; var fs = require('fs'); var assert = require('assert'); var getRepo = require('get-repo'); var lex = require('pug-lexer'); var load = require('pug-load'); var parse = require('pug-parser'); var handleFilters = require('../').handleFilters; var customFilters = require('./custom-filters.js'); var existing = fs.readdirSync(__dirname + '/cases').filter(function (name) { return /\.input\.json$/.test(name); }); function getError (input, filename) { try { handleFilters(input, customFilters); throw new Error('Expected ' + filename + ' to throw an exception.'); } catch (ex) { if (!ex || !ex.code || !ex.code.indexOf('PUG:') === 0) throw ex; return { msg: ex.msg, code: ex.code, line: ex.line }; } } getRepo('pugjs', 'pug-parser').on('data', function (entry) { var match; if (entry.type === 'File' && (match = /^\/test\/cases\/(filters.*)\.expected\.json$/.exec(entry.path))) { var name = match[1]; var filename = name + '.input.json'; var alreadyExists = false; existing = existing.filter(function (existingName) { if (existingName === filename) { alreadyExists = true; return false; } return true; }); if (alreadyExists) { var actualInputAst = getLoadedAst(entry.body.toString('utf8')); try { var expectedInputAst = JSON.parse(fs.readFileSync(__dirname + '/cases/' + filename, 'utf8')); assert.deepEqual(expectedInputAst, actualInputAst); } catch (ex) { console.log('update: ' + filename); fs.writeFileSync(__dirname + '/cases/' + filename, JSON.stringify(actualInputAst, null, ' ')); } var actualAstStr = JSON.stringify(handleFilters(actualInputAst, customFilters), null, ' '); try { var expectedAstStr = fs.readFileSync(__dirname + '/cases/' + name + '.expected.json', 'utf8'); assert.equal(actualAstStr, expectedAstStr); } catch (ex) { console.log('update: ' + name + '.expected.json'); fs.writeFileSync(__dirname + '/cases/' + name + '.expected.json', actualAstStr); } } else { console.log('create: ' + filename); var inputAst = getLoadedAst(entry.body.toString('utf8')); fs.writeFileSync(__dirname + '/cases/' + filename, JSON.stringify(inputAst, null, ' ')); console.log('create: ' + name + '.expected.json'); var ast = handleFilters(inputAst, customFilters); fs.writeFileSync(__dirname + '/cases/' + name + '.expected.json', JSON.stringify(ast, null, ' ')); } } }).on('end', function () { existing.forEach(function (file) { fs.unlinkSync(__dirname + '/cases/' + file); }); var existingErrors = fs.readdirSync(__dirname + '/errors').filter(function (name) { return /\.input\.json$/.test(name); }); var pugRe = /\.pug$/; fs.readdirSync(__dirname + '/errors-src').forEach(function (name) { if (!pugRe.test(name)) return; name = name.replace(pugRe, ''); var filename = name + '.input.json'; var alreadyExists = false; existingErrors = existingErrors.filter(function (existingName) { if (existingName === filename) { alreadyExists = true; return false; } return true; }); if (alreadyExists) { var actualTokens = parse(lex(fs.readFileSync(__dirname + '/errors-src/' + name + '.pug', 'utf8'))); try { var expectedTokens = JSON.parse(fs.readFileSync(__dirname + '/errors/' + filename, 'utf8')); assert.deepEqual(actualTokens, expectedTokens); } catch (ex) { console.log('update: ' + filename); fs.writeFileSync(__dirname + '/errors/' + filename, JSON.stringify(actualTokens, null, ' ')); } var actual = getError(actualTokens, filename); try { var expected = JSON.parse(fs.readFileSync(__dirname + '/errors/' + name + '.expected.json', 'utf8')); assert.deepEqual(actual, expected); } catch (ex) { console.log('update: ' + name + '.expected.json'); fs.writeFileSync(__dirname + '/errors/' + name + '.expected.json', JSON.stringify(actual, null, ' ')); } } else { console.log('create: ' + filename); var ast = parse(lex(fs.readFileSync(__dirname + '/errors-src/' + name + '.pug', 'utf8'))); fs.writeFileSync(__dirname + '/errors/' + filename, JSON.stringify(ast, null, 2)); console.log('create: ' + name + '.expected.json'); var actual = getError(ast, filename); fs.writeFileSync(__dirname + '/errors/' + name + '.expected.json', JSON.stringify(actual, null, ' ')); } }); console.log('test cases updated'); }); function getLoadedAst(str) { return load(JSON.parse(str), { lex: function () { throw new Error('The lexer should not be used'); }, parse: function () { throw new Error('The parser should not be used'); }, resolve: function (filename, source, options) { return 'test/cases/' + filename.trim(); } }); }
// The MIT License (MIT) // // Copyright (c) 2017-2021 Camptocamp SA // // 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. import {unlistenByKey} from 'ol/events'; /** * @typedef {Object} RuleOptions * @property {boolean} [active=false] Whether the rule is active or not. Used by the `ngeo-rule` component. * @property {number|string} [expression] Deprecated. Use literal instead. Kept for compatibility with saved filters. * @property {number|string|string[]} [literal] The literal of the rule. The literal and boundaries are * mutually exclusives. * @property {boolean} [isCustom] Whether the rule is a custom one or not. Defaults to `true`. * @property {number} [lowerBoundary] The lower boundary of the rule. The literal and boundaries are * mutually exclusives. * @property {string} name The human-readable name of the rule. * @property {string} [operator] The rule operator. * @property {string[]} [operators] The rule operators. * @property {string} propertyName The property name (a.k.a. the attribute name). * @property {string} [type] The type of rule. * @property {number} [upperBoundary] The upper boundary of the rule. The literal and boundaries are * mutually exclusives. */ /** * @typedef {Object} RuleBaseValue * @property {string} operator The operator of the rule value. * @property {string} propertyName The property name of the rule value */ /** * @typedef {Object} RuleSimpleValue * @property {number|string|string[]} literal The literal of the rule value. * extends RuleBaseValue * @property {string} operator The operator of the rule value. * @property {string} propertyName The property name of the rule value */ /** * @typedef {Object} RuleRangeValue * @property {number} lowerBoundary The lower boundary of the rule value. * @property {number} upperBoundary The upper boundary of the rule value. * extends RuleBaseValue * @property {string} operator The operator of the rule value. * @property {string} propertyName The property name of the rule value */ /** * @enum {string} * @hidden */ export const RuleOperatorType = { BETWEEN: '..', EQUAL_TO: '=', GREATER_THAN: '>', GREATER_THAN_OR_EQUAL_TO: '>=', LESSER_THAN: '<', LESSER_THAN_OR_EQUAL_TO: '<=', LIKE: '~', NOT_EQUAL_TO: '!=', }; /** * @enum {string} * @hidden */ export const RuleSpatialOperatorType = { CONTAINS: 'contains', INTERSECTS: 'intersects', WITHIN: 'within', }; /** * @enum {string} * @hidden */ export const RuleTemporalOperatorType = { BEGINS: 'time_start', DURING: 'time_during', ENDS: 'time_end', EQUALS: 'time_equal', }; /** * @hidden */ export default class Rule { /** * The abstract class for all filter rules. * * Rules are used to define filters that can be applied on data sources. * A rule is usually a combination of 3 things: * * - a property name, for example 'city_name' * - an operator, for example 'is equal to' * - and an literal, for example 'Chicoutimi'. * * A rule is useful to hold those properties and change them on the fly. * For example, changing an operator from 'is equal to' to 'like'. * * Also, a rule is especially useful for its `value` getter, which returns * the combination of properties described above or `null` if there are some * missing. The `value` getter can be watched and used when the value is * not null. * * When the operator is `between`, the `lowerBoundary` and `upperBoundary` * properties are used instead of `literal`. * * @param {RuleOptions} options Options. */ constructor(options) { // === DYNAMIC properties (i.e. that can change / be watched === /** * Whether the rule is active or not. Used by the `ngeo-rule` component. * Defaults to `false`. * * @type {boolean} */ this.active = options.active === true; /** * The literal of the rule. The literal and boundaries are mutually * exclusives. * * @type {?number|string|string[]} * @protected */ this.literal_ = options.literal !== undefined ? options.literal : null; /** * The lower boundary of the rule. The literal and boundaries are * mutually exclusives. * * @type {?number} */ this.lowerBoundary = options.lowerBoundary !== undefined ? options.lowerBoundary : null; /** * The rule operator. * * @type {?string} */ this.operator = options.operator || null; /** * The upper boundary of the rule. The literal and boundaries are * mutually exclusives. * * @type {?number} */ this.upperBoundary = options.upperBoundary !== undefined ? options.upperBoundary : null; // === STATIC properties (i.e. that never change) === /** * Whether the rule is a custom one or not. * * @type {boolean} * @private */ this.isCustom_ = options.isCustom !== false; /** * The human-readable name of the rule. * * @type {string} * @private */ this.name_ = options.name; /** * A list of rule operators. * * @type {?string[]} * @private */ this.operators_ = options.operators || null; /** * The property name (a.k.a. the attribute name). * * @type {string} * @private */ this.propertyName_ = options.propertyName; /** * The type of rule. * * @type {string} * @private */ this.type_ = options.type; // === Other properties === /** * @type {import('ol/events').EventsKey[]} * @protected */ this.listenerKeys = []; } /** * @returns {?number|string|string[]} Literal */ get literal() { return this.literal_; } /** * @param {?number|string|string[]} literal Literal */ set literal(literal) { this.literal_ = literal; } // === Static property getters/setters === /** * @returns {boolean} Is custom. */ get isCustom() { return this.isCustom_; } /** * @returns {string} name */ get name() { return this.name_; } /** * @returns {?string[]} Operators */ get operators() { return this.operators_; } /** * @returns {string} Property name */ get propertyName() { return this.propertyName_; } /** * @returns {string} Type */ get type() { return this.type_; } // === Calculated property getters === /** * @returns {?RuleSimpleValue|RuleRangeValue} Value. */ get value() { let value = null; const literal = this.literal; const lowerBoundary = this.lowerBoundary; const operator = this.operator; const propertyName = this.propertyName; const upperBoundary = this.upperBoundary; if (operator) { if (operator === RuleOperatorType.BETWEEN || operator === RuleTemporalOperatorType.DURING) { if (lowerBoundary !== null && upperBoundary !== null) { value = { operator, lowerBoundary, propertyName, upperBoundary, }; } } else { if (literal !== null) { value = { literal, operator, propertyName, }; } } } return value; } // === Other utility methods === /** * Reset the following properties to `null`: literal, lowerBoundary, * upperBoundary. */ reset() { if (this.literal !== null) { this.literal = null; } if (this.lowerBoundary !== null) { this.lowerBoundary = null; } if (this.upperBoundary !== null) { this.upperBoundary = null; } } /** */ destroy() { this.listenerKeys.forEach(unlistenByKey); this.listenerKeys.length = 0; } }
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { dndStyles as defaultDndStyles, SortableGrid } from 'wix-style-react'; import { classes } from './SingleAreaGrid.st.css'; const generateId = () => Math.floor(Math.random() * 100000); export default class SingleAreaGrid extends React.Component { static propTypes = { withHandle: PropTypes.bool }; state = { items: [ { id: generateId(), text: 'Item 1' }, { id: generateId(), text: 'Item 2' }, { id: generateId(), text: 'Item 3' }, { id: generateId(), text: 'Item 4' }, { id: generateId(), text: 'Item 5' }, { id: generateId(), text: 'Item 6' }, { id: generateId(), text: 'Item 7' }, { id: generateId(), text: 'Item 8' }, { id: generateId(), text: 'Item 9' }, ], }; handleDrop = () => {}; renderHandle({ connectHandle, id, isPlaceholder }) { return connectHandle( <div className={classes.handle} style={{ opacity: isPlaceholder ? 0 : 1 }} data-hook={`card-${id}-handle`} > Drag Handle </div>, ); } renderItem = ({ isPlaceholder, isPreview, id, connectHandle, item, withStrip, isInitialPositionToDrop, }) => { const stripPositionClass = classNames({ [defaultDndStyles.withGridItemStrip]: withStrip, [defaultDndStyles.withGridItemStripRight]: withStrip === 'right', }); const _classes = classNames( classNames(defaultDndStyles.item, classes.item, stripPositionClass), { [classNames(defaultDndStyles.gridItemPreview)]: isPreview, [classNames(defaultDndStyles.gridItemPlaceholder)]: isPlaceholder, [classNames( defaultDndStyles.isInitialPositionToDrop, )]: isInitialPositionToDrop, }, ); return ( <div className={_classes} data-hook={`item-${id}`}> {item.text} {this.props.withHandle ? this.renderHandle({ connectHandle, id, isPlaceholder, }) : null} </div> ); }; render() { return ( <div className={classes.root}> <h3 className={classes.title}>Draggable Area</h3> <SortableGrid withHandle={this.props.withHandle} className={classes.sortableGrid} containerId="single-area-1" dataHook="grid-single-area" items={this.state.items} renderItem={this.renderItem} onDrop={this.handleDrop} startFixedElement={this.props.startFixedElement} /> </div> ); } }
export default function docTraverser(node) { switch(node.tagName) { case 'h2': case 'h3': node.children.unshift(makeHeadingAnchor(node.properties.id)) break case 'pre': if(node.children.length === 1 && node.children[0].tagName === 'code') { var textNodes = node.children[0].children // replace, don't recurse return makeCodeRow(textNodes) } break case 'div': node.children = wrapIntoSectionsByH2(node.children) break } if(node.children) node.children = node.children.map(docTraverser) return node } function wrapIntoSectionsByH2(children) { var sections = [] children.forEach( child => { if(child.tagName == 'h2') { var id = `section-${child.properties.id}` var newSection = makeSection(id, [child]) sections.push(newSection) } else if (child.value !== '\n') { if (sections.length < 1) sections.push(makeSection('first', [])) var currentSection = sections[sections.length - 1] currentSection.children.push(child) } }) return sections } function makeSection(id, children) { return { type: 'element', tagName: 'section', properties: { id }, children } } function makeHeadingAnchor(id) { return { type: 'element', tagName: 'a', properties: { href: `#${id}`, class: 'heading-anchor' }, children: [{ type: 'element', tagName: 'svg', properties: { ariaHidden: true, height: '16', version: '1.1', width: '16' }, children: [{ type: 'element', tagName: 'path', properties: { fill: '#666666', d: 'M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z' } }] }] } } function makeCodeRow(textNodes) { var code = textNodes.map(n => n.value).join('').trim() return { type: 'element', tagName: 'CodeSection', properties: { code }, children: [] } }
import Reflux from 'reflux'; var name = "chat"; var actions = Reflux.createActions([ "connect", "add" ]); var store = Reflux.createStore({ init() { this.chatCollection = [ {name: "Super Hooligan", text: "Yeah go manchester!!!"}, {name: "ChelseaDagger", text: "Go Chelsea. Manchester sucks!!!!"} ]; this.listenToMany(actions); }, onAdd({name, text}) { this.chatCollection = this.chatCollection.concat({name: name, text: text}); this.trigger(this.chatCollection); }, onConnect() { this.trigger(this.chatCollection); } }); export default { name, store, actions };
// You can also run hapi servers with a module named *rejoice* and compose // the server and its plugins in a configuration file // For this step run `rejoice -c manifest.json`
'use strict'; var d = require('d') , memoize = require('memoizee/weak-plain') , htmlDocument = require('dom-ext/html-document/valid-html-document'); module.exports = memoize(function (document) { var timeout, meta = {}; var reset = function () { timeout = null; Object.defineProperties(meta, { isRegular: d('ce', null), aHref: d('ce', null) }); }; reset(); htmlDocument(document).addEventListener('click', function (event) { var target = event.target; if (timeout) clearTimeout(timeout); while (target && target.nodeName.toLowerCase() !== "a") target = target.parentNode; Object.defineProperties(meta, { isRegular: d('ce', !event.metaKey && !event.ctrlKey && (event.which !== 2) && (event.which !== 3)), aHref: d('ce', target || null), stamp: d('ce', Date.now()) }); setTimeout(reset); }, true); return meta; });