code
stringlengths
2
1.05M
// npm i --save-dev gulp gulp-print gulp-util rimraf // Server JS // npm i --save-dev gulp-babel var gulp = require('gulp') var gutil = require('gulp-util') // Server JS var babel = require('gulp-babel') // Client JS var named = require('vinyl-named') var insert = require('gulp-insert') var rename = require('gulp-rename') var webpack = require('webpack-stream') // Other var rimraf = require('rimraf') function tellerror(err) { console.error('ERROR', err.message) this.emit('end') } gulp.task('default', [ 'js', 'client-js' ]) gulp.task('js', function() { return gulp.src([ 'src/{index,test}.js' ]) .pipe(babel()) .on('error', tellerror) .pipe(gulp.dest('build')) }) gulp.task('client-js', function(cb) { return gulp.src('src/client.js') .pipe(named()) .pipe(webpack({ output: { library: '__output', libraryTarget: 'var' }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel', }] } })).on('error', e => console.error(e.stack)) .pipe(insert.append(` if (typeof window != 'undefined') window.apiify = { client: __output.default } if (typeof module != 'undefined' && typeof module.exports != 'undefined') module.exports = __output `)) .pipe(rename('client.js')) .pipe(gulp.dest('build')) }) gulp.task('watch', [ 'default' ], function() { gulp.watch('src/**/*.js', [ 'js' ]) }) gulp.task('clean', function() { rimraf.sync('build') })
// ignore most things var IgnoreFile = require("../") , path = require('path') // set the ignores just for this test var c = require("./common.js") c.ignores( { ".ignore": ["*", "a", "c", "!a/b/c/.abc", "!/c/b/a/cba"] , "a/.ignore": [ "!*", ".ignore" ] // unignore everything , "a/a/.ignore": [ "*" ] // re-ignore everything , "a/b/.ignore": [ "*", "!/c/.abc" ] // original unignore , "a/c/.ignore": [ "*" ] // ignore everything again , "c/b/a/.ignore": [ "!cba", "!.cba", "!/a{bc,cb}" ] }) // the only files we expect to see var expected = [ "/a" , "/a/a" , "/a/b" , "/a/b/c" , "/a/b/c/.abc" , "/a/c" , "/c" , "/c/b" , "/c/b/a" , "/c/b/a/cba" , "/c/b/a/.cba" , "/c/b/a/abc" , "/c/b/a/acb" ].map(path.normalize) require("tap").test("basic ignore rules", function (t) { t.pass("start") IgnoreFile({ path: __dirname + "/fixtures" , ignoreFiles: [".ignore"] }) .on("child", function (e) { var p = e.path.substr(e.root.path.length) var i = expected.indexOf(p) if (i === -1) { console.log("not ok "+p) t.fail("unexpected file found", {found: p}) } else { t.pass(p) expected.splice(i, 1) } }) .on("close", function () { t.deepEqual(expected, [], "all expected files should be seen") t.end() }) })
'use strict' var test = require('tap').test var TrackerGroup = require('../index.js').TrackerGroup var testEvent = require('./lib/test-event.js') test('TrackerGroup', function (t) { var name = 'test' var track = new TrackerGroup(name) t.is(track.completed(), 0, 'Nothing todo is 0 completion') testEvent(track, 'change', afterFinishEmpty) track.finish() var a, b function afterFinishEmpty (er, onChangeName, completion) { t.is(er, null, 'finishEmpty: on change event fired') t.is(onChangeName, name, 'finishEmpty: on change emits the correct name') t.is(completion, 1, 'finishEmpty: passed through completion was correct') t.is(track.completed(), 1, 'finishEmpty: Finishing an empty group actually finishes it') track = new TrackerGroup(name) a = track.newItem('a', 10, 1) b = track.newItem('b', 10, 1) t.is(track.completed(), 0, 'Initially empty') testEvent(track, 'change', afterCompleteWork) a.completeWork(5) } function afterCompleteWork (er, onChangeName, completion) { t.is(er, null, 'on change event fired') t.is(onChangeName, 'a', 'on change emits the correct name') t.is(completion, 0.25, 'Complete half of one is a quarter overall') t.is(track.completed(), 0.25, 'Complete half of one is a quarter overall') testEvent(track, 'change', afterFinishAll) track.finish() } function afterFinishAll (er, onChangeName, completion) { t.is(er, null, 'finishAll: on change event fired') t.is(onChangeName, name, 'finishAll: on change emits the correct name') t.is(completion, 1, 'Finishing everything ') t.is(track.completed(), 1, 'Finishing everything ') track = new TrackerGroup(name) a = track.newItem('a', 10, 2) b = track.newItem('b', 10, 1) t.is(track.completed(), 0, 'weighted: Initially empty') testEvent(track, 'change', afterWeightedCompleteWork) a.completeWork(5) } function afterWeightedCompleteWork (er, onChangeName, completion) { t.is(er, null, 'weighted: on change event fired') t.is(onChangeName, 'a', 'weighted: on change emits the correct name') t.is(Math.floor(completion * 100), 33, 'weighted: Complete half of double weighted') t.is(Math.floor(track.completed() * 100), 33, 'weighted: Complete half of double weighted') testEvent(track, 'change', afterWeightedFinishAll) track.finish() } function afterWeightedFinishAll (er, onChangeName, completion) { t.is(er, null, 'weightedFinishAll: on change event fired') t.is(onChangeName, name, 'weightedFinishAll: on change emits the correct name') t.is(completion, 1, 'weightedFinishaAll: Finishing everything ') t.is(track.completed(), 1, 'weightedFinishaAll: Finishing everything ') track = new TrackerGroup(name) a = track.newGroup('a', 10) b = track.newGroup('b', 10) var a1 = a.newItem('a.1', 10) a1.completeWork(5) t.is(track.completed(), 0.25, 'nested: Initially quarter done') testEvent(track, 'change', afterNestedComplete) b.finish() } function afterNestedComplete (er, onChangeName, completion) { t.is(er, null, 'nestedComplete: on change event fired') t.is(onChangeName, 'b', 'nestedComplete: on change emits the correct name') t.is(completion, 0.75, 'nestedComplete: Finishing everything ') t.is(track.completed(), 0.75, 'nestedComplete: Finishing everything ') t.end() } }) test('cycles', function (t) { var track = new TrackerGroup('top') testCycle(track, track) var layer1 = track.newGroup('layer1') testCycle(layer1, track) t.end() function testCycle (addTo, toAdd) { try { addTo.addUnit(toAdd) t.fail(toAdd.name) } catch (ex) { console.log(ex) t.pass(toAdd.name) } } }) test('should properly handle finish calls when the group contains a stream', function (t) { var track = new TrackerGroup('test') track.newStream('test-stream', 100) try { track.finish() t.pass('did not error on `finish()` call') } catch (e) { t.fail('threw error on `finish()` call') } t.end() })
import { actionChangeMember, actionDeleteMember } from '../actions'; import { t } from '../util/locale'; import { utilDisplayLabel } from '../util'; import { validationIssue, validationIssueFix } from '../core/validator'; export function validationMissingRole() { var type = 'missing_role'; var validation = function(entity, context) { var issues = []; if (entity.type === 'way') { context.graph().parentRelations(entity).forEach(function(relation) { if (!relation.isMultipolygon()) { return; } var member = relation.memberById(entity.id); if (member && isMissingRole(member)) { issues.push(makeIssue(entity, relation, member, context)); } }); } else if (entity.type === 'relation' && entity.isMultipolygon()) { entity.indexedMembers().forEach(function(member) { var way = context.hasEntity(member.id); if (way && isMissingRole(member)) { issues.push(makeIssue(way, entity, member, context)); } }); } return issues; }; function isMissingRole(member) { return !member.role || !member.role.trim().length; } function makeIssue(way, relation, member, context) { return new validationIssue({ type: type, severity: 'warning', message: t('issues.missing_role.message', { member: utilDisplayLabel(way, context), relation: utilDisplayLabel(relation, context), }), tooltip: t('issues.missing_role.multipolygon.tip'), entities: [relation, way], info: {member: member}, fixes: [ makeAddRoleFix('inner', context), makeAddRoleFix('outer', context), new validationIssueFix({ icon: 'iD-operation-delete', title: t('issues.fix.remove_from_relation.title'), onClick: function() { context.perform( actionDeleteMember(this.issue.entities[0].id, this.issue.info.member.index), t('operations.delete_member.annotation') ); } }) ] }); } function makeAddRoleFix(role, context) { return new validationIssueFix({ title: t('issues.fix.set_as_' + role + '.title'), onClick: function() { var oldMember = this.issue.info.member; var member = { id: this.issue.entities[1].id, type: oldMember.type, role: role }; context.perform( actionChangeMember(this.issue.entities[0].id, member, oldMember.index), t('operations.change_role.annotation') ); } }); } validation.type = type; return validation; }
import assert from 'assert' import supertest from 'supertest' import { apiUrl } from '../../lib/cloudFormation' export function local () { } export function remote () { describe('Retrieve jobId', function () { it('should return 123', function (done) { supertest(apiUrl) .get('/jobs/123') .expect('Content-Type', /json/) .expect(200) .expect({ jobId: 123 }, done) }) }) }
require("node-test-helper"); var fs = require("fs"); describe(TEST_NAME, function() { var imageBuffer; before(function(done) { fs.readFile(jpg_image, function(err, data) { imageBuffer = data; done(err); }); }); describe(".copy()", function() { it("should return a copied data buffer of the given source file", function(done) { processor.copy({ path: jpg_image }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.true; done(err); }); }); it("accepts src as path parameter", function(done) { processor.copy({ src: jpg_image }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.true; done(err); }); }); it("accepts format parameter", function(done) { processor.copy({ src: jpg_image, format: "png" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isPng(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); }); describe(".crop()", function() { it("should return a cropped data buffer of the given source file", function(done) { processor.crop({ path: jpg_image, size: "50x50" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts offset parameter", function(done) { processor.crop({ src: jpg_image, size: "60x60", offset: "1,1" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts pos as offset parameter", function(done) { processor.crop({ src: jpg_image, size: "60x60", pos: "2,2" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts format parameter", function(done) { processor.crop({ src: jpg_image, size: "50x50", format: "png" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isPng(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); }); describe(".resize()", function() { it("should return a resized data buffer of the given source file", function(done) { processor.resize({ path: jpg_image, size: "50x50" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts > option", function(done) { processor.resize({ src: jpg_image, size: "50x50>" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts < option", function(done) { processor.resize({ src: jpg_image, size: "50x50<" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts ! option", function(done) { processor.resize({ src: jpg_image, size: "50x50!" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts % option", function(done) { processor.resize({ src: jpg_image, size: "50%" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts @ option", function(done) { processor.resize({ src: jpg_image, size: "50@" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isJpg(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); it("accepts format parameter", function(done) { processor.resize({ src: jpg_image, size: "50x50", format: "png" }, function(err, data) { expect(err).to.not.exist; expect(data).to.exist; expect(data).to.be.instanceof(Buffer); expect(helper.isPng(data)).to.be.true; expect(data.toString() === imageBuffer.toString()).to.be.false; done(err); }); }); }); });
import { select as d3_select } from 'd3-selection'; import { t } from '../util/locale'; import { geoScaleToZoom, geoVecLength } from '../geo'; import { utilPrefixCSSProperty, utilTiler } from '../util'; export function rendererTileLayer(context) { var transformProp = utilPrefixCSSProperty('Transform'); var tiler = utilTiler(); var _tileSize = 256; var _projection; var _cache = {}; var _tileOrigin; var _zoom; var _source; function tileSizeAtZoom(d, z) { var EPSILON = 0.002; // close seams return ((_tileSize * Math.pow(2, z - d[2])) / _tileSize) + EPSILON; } function atZoom(t, distance) { var power = Math.pow(2, distance); return [ Math.floor(t[0] * power), Math.floor(t[1] * power), t[2] + distance ]; } function lookUp(d) { for (var up = -1; up > -d[2]; up--) { var tile = atZoom(d, up); if (_cache[_source.url(tile)] !== false) { return tile; } } } function uniqueBy(a, n) { var o = []; var seen = {}; for (var i = 0; i < a.length; i++) { if (seen[a[i][n]] === undefined) { o.push(a[i]); seen[a[i][n]] = true; } } return o; } function addSource(d) { d.push(_source.url(d)); return d; } // Update tiles based on current state of `projection`. function background(selection) { _zoom = geoScaleToZoom(_projection.scale(), _tileSize); var pixelOffset; if (_source) { pixelOffset = [ _source.offset()[0] * Math.pow(2, _zoom), _source.offset()[1] * Math.pow(2, _zoom) ]; } else { pixelOffset = [0, 0]; } var translate = [ _projection.translate()[0] + pixelOffset[0], _projection.translate()[1] + pixelOffset[1] ]; tiler .scale(_projection.scale() * 2 * Math.PI) .translate(translate); _tileOrigin = [ _projection.scale() * Math.PI - translate[0], _projection.scale() * Math.PI - translate[1] ]; render(selection); } // Derive the tiles onscreen, remove those offscreen and position them. // Important that this part not depend on `_projection` because it's // rentered when tiles load/error (see #644). function render(selection) { if (!_source) return; var requests = []; var showDebug = context.getDebug('tile') && !_source.overlay; if (_source.validZoom(_zoom)) { tiler.skipNullIsland(!!_source.overlay); tiler().forEach(function(d) { addSource(d); if (d[3] === '') return; if (typeof d[3] !== 'string') return; // Workaround for #2295 requests.push(d); if (_cache[d[3]] === false && lookUp(d)) { requests.push(addSource(lookUp(d))); } }); requests = uniqueBy(requests, 3).filter(function(r) { // don't re-request tiles which have failed in the past return _cache[r[3]] !== false; }); } function load(d) { _cache[d[3]] = true; d3_select(this) .on('error', null) .on('load', null) .classed('tile-loaded', true); render(selection); } function error(d) { _cache[d[3]] = false; d3_select(this) .on('error', null) .on('load', null) .remove(); render(selection); } function imageTransform(d) { var ts = _tileSize * Math.pow(2, _zoom - d[2]); var scale = tileSizeAtZoom(d, _zoom); return 'translate(' + ((d[0] * ts) - _tileOrigin[0]) + 'px,' + ((d[1] * ts) - _tileOrigin[1]) + 'px) ' + 'scale(' + scale + ',' + scale + ')'; } function tileCenter(d) { var ts = _tileSize * Math.pow(2, _zoom - d[2]); return [ ((d[0] * ts) - _tileOrigin[0] + (ts / 2)), ((d[1] * ts) - _tileOrigin[1] + (ts / 2)) ]; } function debugTransform(d) { var coord = tileCenter(d); return 'translate(' + coord[0] + 'px,' + coord[1] + 'px)'; } // Pick a representative tile near the center of the viewport // (This is useful for sampling the imagery vintage) var dims = tiler.size(); var mapCenter = [dims[0] / 2, dims[1] / 2]; var minDist = Math.max(dims[0], dims[1]); var nearCenter; requests.forEach(function(d) { var c = tileCenter(d); var dist = geoVecLength(c, mapCenter); if (dist < minDist) { minDist = dist; nearCenter = d; } }); var image = selection.selectAll('img') .data(requests, function(d) { return d[3]; }); image.exit() .style(transformProp, imageTransform) .classed('tile-removing', true) .classed('tile-center', false) .each(function() { var tile = d3_select(this); window.setTimeout(function() { if (tile.classed('tile-removing')) { tile.remove(); } }, 300); }); image.enter() .append('img') .attr('class', 'tile') .style('width', _tileSize + 'px') .style('height', _tileSize + 'px') .attr('src', function(d) { return d[3]; }) .on('error', error) .on('load', load) .merge(image) .style(transformProp, imageTransform) .classed('tile-debug', showDebug) .classed('tile-removing', false) .classed('tile-center', function(d) { return d === nearCenter; }); var debug = selection.selectAll('.tile-label-debug') .data(showDebug ? requests : [], function(d) { return d[3]; }); debug.exit() .remove(); if (showDebug) { var debugEnter = debug.enter() .append('div') .attr('class', 'tile-label-debug'); debugEnter .append('div') .attr('class', 'tile-label-debug-coord'); debugEnter .append('div') .attr('class', 'tile-label-debug-vintage'); debug = debug.merge(debugEnter); debug .style(transformProp, debugTransform); debug .selectAll('.tile-label-debug-coord') .text(function(d) { return d[2] + ' / ' + d[0] + ' / ' + d[1]; }); debug .selectAll('.tile-label-debug-vintage') .each(function(d) { var span = d3_select(this); var center = context.projection.invert(tileCenter(d)); _source.getMetadata(center, d, function(err, result) { span.text((result && result.vintage && result.vintage.range) || t('info_panels.background.vintage') + ': ' + t('info_panels.background.unknown') ); }); }); } } background.projection = function(val) { if (!arguments.length) return _projection; _projection = val; return background; }; background.dimensions = function(val) { if (!arguments.length) return tiler.size(); tiler.size(val); return background; }; background.source = function(val) { if (!arguments.length) return _source; _source = val; _tileSize = _source.tileSize; _cache = {}; tiler.tileSize(_source.tileSize).zoomExtent(_source.zoomExtent); return background; }; return background; }
var React = require('react'); var ReactDOM = require('react-dom'); var Router = require('react-router').Router; var routes = require('./config/routes'); ReactDOM.render( <Router>{ routes }</Router>, document.getElementById('app') );
var typecast = require('../string/typecast') var isArray = require('../lang/isArray') var hasOwn = require('../object/hasOwn') // decode query string into an object of keys => vals function decode (queryStr, shouldTypecast) { var queryArr = (queryStr || '').replace('?', '').split('&') var reg = /([^=]+)=(.+)/ var i = -1 var obj = {} var equalIndex var cur var pValue var pName while ((cur = queryArr[++i])) { equalIndex = cur.indexOf('=') pName = cur.substring(0, equalIndex) pValue = decodeURIComponent(cur.substring(equalIndex + 1)) if (shouldTypecast !== false) pValue = typecast(pValue) if (hasOwn(obj, pName)) { if (isArray(obj[pName])) obj[pName].push(pValue) else obj[pName] = [obj[pName], pValue] } else { obj[pName] = pValue } } return obj } module.exports = decode
const log = require('../lib/Log').getLogger(`server[${process.pid}]`) const Library = require('../Library') const Prefs = require('./Prefs') const { LIBRARY_PUSH, PREFS_SET_PATH_PRIORITY, PREFS_PUSH, PREFS_SET, _ERROR, } = require('../../shared/actionTypes') const ACTION_HANDLERS = { [PREFS_SET]: async (sock, { payload }, acknowledge) => { if (!sock.user.isAdmin) { acknowledge({ type: PREFS_SET + _ERROR, error: 'Unauthorized', }) } await Prefs.set(payload.key, payload.data) log.info('%s (%s) set pref %s = %s', sock.user.name, sock.id, payload.key, payload.data) await pushPrefs(sock) }, [PREFS_SET_PATH_PRIORITY]: async (sock, { payload }, acknowledge) => { if (!sock.user.isAdmin) { acknowledge({ type: PREFS_SET_PATH_PRIORITY + _ERROR, error: 'Unauthorized', }) } await Prefs.setPathPriority(payload) log.info('%s re-prioritized media folders; pushing library to all', sock.user.name) await pushPrefs(sock) // invalidate cache Library.cache.version = null sock.server.emit('action', { type: LIBRARY_PUSH, payload: await Library.get(), }) }, } // helper to push prefs to admins const pushPrefs = async (sock) => { const admins = [] for (const s of sock.server.sockets.sockets.values()) { if (s.user && s.user.isAdmin) { admins.push(s.id) sock.server.to(s.id) } } if (admins.length) { sock.server.emit('action', { type: PREFS_PUSH, payload: await Prefs.get(), }) } } module.exports = ACTION_HANDLERS
"use strict" const debug = require("debug")("route4me") const platform = require("platform") const ActivityFeed = require("./resources/activity-feed") const Addresses = require("./resources/addresses") const AddressBook = require("./resources/address-book") const AvoidanceZones = require("./resources/avoidance-zones") const Geocoding = require("./resources/geocoding") const Members = require("./resources/members") const Notes = require("./resources/notes") const Optimizations = require("./resources/optimizations") const Orders = require("./resources/orders") const Routes = require("./resources/routes") const Territories = require("./resources/territories") const Tracking = require("./resources/tracking") const Vehicles = require("./resources/vehicles") const packageJson = require("./../package.json") // eslint-disable-line import/no-dynamic-require const utils = require("./utils") const errors = require("./errors") const RequestManager = require("./request-manager") /** * Route4Me main SDK class * * The main purpose of this class: to provide an access to API-methods and to keep * chore and routine in the shadow as long as possible. * * With `route4me` instance you should get responses from API easy-peasy. * * Main members of the instanse of `Route4Me` class: * * * [ActivityFeed ]{@link ActivityFeed} * * [Addresses ]{@link Addresses} * * [AddressBook ]{@link AddressBook} * * [AvoidanceZones]{@link AvoidanceZones} * * [Geocoding ]{@link Geocoding} * * [Members ]{@link Members} * * [Notes ]{@link Notes} * * [Optimizations ]{@link Optimizations} * * [Orders ]{@link Orders} * * [OrderCustomFields ]{@link OrderCustomFields} * * [Routes ]{@link Routes} * * [Territories ]{@link Territories} * * [Tracking ]{@link Tracking} * * [Vehicles ]{@link Vehicles} * * Each member corresponds to an bunch of methods, described in API-documentation, * but the most methods in this SDK have unified names: * * * `create` - to create new entity * * `get` - to get **one** entity (usually, by ID) * * `list` - returns a list of **all** entities (sometimes with `limit` and `offset`) * * `update` - allows to edit entity * * `remove` - removes/deletes the entity * * `search` - obviously: allows to search items by a set of criteria * * For most use cases it is necessary: * * 1. Create `route4me` instance (with your API-key) * 2. Call the appropriate method * 3. Get the result (as JSON object) * 4. **PROFIT** * * @summary Route4Me main SDK class * * @category Route4Me */ class Route4Me { /** * Create new API client * * @param {string} apiKey API KEY * @param {object} [options] Additional options for new instance * @param {string} [options.baseUrl="https://api.route4me.com"] Base URL for sending requests * @param {ILogger} [options.logger=null] Logger facility * @param {boolean|function} [options.promise=false] Use promises instead of * callbacks. Usage: * * `false` means _no promises, use callbacks_; * * `true` means _use global `Promise`_ as promises' constructor; * * `constructor (function)` forces to use explicit Promise library. * See also Examples section of this documentation. * * @param {module:route4me-node~ValidationCallback} [options.validate=false] * Validator for input and output parameters of the API methods. Set **falsey** * value to skip autovalidation (in favor of manual check). * * @return {Route4Me} New API client */ constructor(apiKey, options) { const opt = {} // check options opt["baseUrl"] = utils.get(options, "baseUrl", "https://api.route4me.com") opt["logger"] = utils.get(options, "logger", new utils.ILogger()) opt["promise"] = utils.get(options, "promise", false) opt["validate"] = utils.get(options, "validate", false) // TODO: decide, whether this param could be configured opt["userAgent"] = `superagent/3.3.2 (${platform.name} ${platform.version}; Route4Me-${platform.name}/${Route4Me.version}) ${platform.description}` debug("init", opt) debug("version", Route4Me.version) if (!apiKey) { throw new errors.Route4MeError("'apiKey' is not set") } const req = new RequestManager(apiKey, opt) this._logger = opt["logger"] /** * **ActivityFeed** related API calls * @type {ActivityFeed} * @since 0.1.12 */ this.ActivityFeed = new ActivityFeed(req) /** * **AddressBook** related API calls * @type {AddressBook} * @since 0.1.8 */ this.AddressBook = new AddressBook(req) /** * **Addresses** related API calls * @type {Addresses} * @since 0.1.8 */ this.Addresses = new Addresses(req) /** * **AvoidanceZones** related API calls * @type {AvoidanceZones} * @since 0.1.8 */ this.AvoidanceZones = new AvoidanceZones(req) /** * **Geocoding** related API calls * @type {Geocoding} * @since 0.1.9 */ this.Geocoding = new Geocoding(req) /* * **Members** related API calls * @type {Members} * @since 0.1.8 */ this.Members = new Members(req) /** * **Notes** related API calls * @type {Notes} * @since 0.1.9 */ this.Notes = new Notes(req) /** * **Optimizations** related API calls * @type {Optimizations} */ this.Optimizations = new Optimizations(req) /** * **Orders** related API calls * @type {Orders} */ this.Orders = new Orders(req) /** * **Routes** related API calls * @type {Routes} * @since 0.1.8 */ this.Routes = new Routes(req) /** * **Territories** related API calls * @type {Territories} */ this.Territories = new Territories(req) /** * **Tracking** related API calls * @type {Tracking} */ this.Tracking = new Tracking(req) /** * **Vehicles** related API calls * @type {Vehicles} */ this.Vehicles = new Vehicles(req) this._logger.debug({ msg: "initialized", version: Route4Me.version }) } /** * Version of this API client * * @since 0.1.3 * * @return {string} Version * @static * @readonly */ static get version() { return packageJson.version } /** * Version of this API client * * @since 0.2.0 * * @return {string} Version * @readonly */ get version() { // eslint-disable-line class-methods-use-this return packageJson.version } } module.exports = Route4Me
import PropTypes from 'prop-types'; import React from 'react'; import { CURRENT } from '../constants/modelStatus'; function ViewMusician({ data, urlStatus }) { if (!urlStatus || urlStatus !== CURRENT) { return <p> Loading ... </p>; } return ( <div className="row"> <div className="small-12 columns"> <h3>{data.username}</h3> <h5>Bio</h5> <p>{data.bio}</p> <h5>Instruments</h5> { data.instruments && data.instruments.length && <ul> {data.instruments.map((instrument) => <li key={instrument}>{instrument}</li>)} </ul> } </div> </div> ); } ViewMusician.propTypes = { data: PropTypes.shape({ bio: PropTypes.string.isRequired, instruments: PropTypes.array.isRequired, }), urlStatus: PropTypes.string.isRequired }; export default ViewMusician;
(function () { enyo.kind({ name: 'k2e.settings.SettingsSlideable', kind: 'enyo.Slideable', classes: 'k2e-settings', min: -100, max: 0, value: -100, unit: '%', draggable: true, overMoving: false, cookieModel: undefined, pendingToggle: undefined, events: { onToggleAnimateFinish: '', }, components: [ { name: 'scroller', kind: 'enyo.Scroller', strategyKind: 'ScrollStrategy', classes: 'full-height', components: [ { name: 'panel', kind: 'k2e.settings.SettingsPanel' }, ] }, ], bindings: [ { from: '.cookieModel', to: '.$.panel.cookieModel' }, { from: '.value', to: '.slidedToMin', transform: (value) => value === -100 }, ], handlers: { onAnimateFinish: 'handleAnimateFinish', }, toggle, handleAnimateFinish, }); ///////////////////////////////////////////////////////////// function toggle(emitAnimateEvent = false) { this.addClass('transition'); if (this.isAtMin()) { this.animateToMax(); if (emitAnimateEvent) { this.pendingToggle = { active: true }; } return true; } this.animateToMin(); if (emitAnimateEvent) { this.pendingToggle = { active: false }; } return false; } function handleAnimateFinish(/*inSender, inEvent*/) { this.removeClass('transition'); if (this.isAtMin()) { this.removeClass('active'); this.$.scroller.scrollToTop(); if (this.pendingToggle && this.pendingToggle.active === false) { this.pendingToggle = undefined; this.doToggleAnimateFinish(); } } else { this.addClass('active'); if (this.pendingToggle && this.pendingToggle.active) { this.pendingToggle = undefined; this.doToggleAnimateFinish(); } } } })();
var http = require('http') var app = require('./app') var appConfig = { port: (process.env.PORT || 3000) } http.createServer(app).listen(appConfig.port, function () { console.log('Server running ' + process.env.NODE_ENV + ', port ' + appConfig.port) })
var util = require('util') , events = require('events') , kue = require('kue') ; /* * We use a queue to process events when we must handle the events sequentially */ function Queue (q) { events.EventEmitter.call(this); var self = this; this.q = q && q.process ? q : kue.createQueue(); this.q.process('message', function (message, done) { self.emit('message', message); done(); }); } util.inherits(Queue, events.EventEmitter); /** * Makes a Queue * * @return Queue */ Queue.make = function (q) { return new Queue(q); }; /** * Sends a message to the queue * * @param object message * @return Queue */ Queue.prototype.send = function (message) { this.q.create('message', message).save(); return this; }; module.exports = Queue;
import $ from 'jquery'; import PowerSelectMultiple from 'ember-power-select/components/power-select-multiple'; import templateLayout from '../../templates/components/gh-token-input/select-multiple'; import {action} from '@ember/object'; import {bind} from '@ember/runloop'; import {layout, tagName} from '@ember-decorators/component'; // TODO: convert from jQuery to native DOM const END_ACTIONS = 'click.ghToken mouseup.ghToken touchend.ghToken'; // triggering focus on the search input within ESA's onfocus event breaks the // drag-n-drop functionality in ember-drag-drop so we watch for events that // could be the start of a drag and disable the default focus behaviour until // we get another event signalling the end of a drag export default @tagName('div') @layout(templateLayout) class GhTokenInputSelectMultiple extends PowerSelectMultiple { _canFocus = true; willDestroyElement() { super.willDestroyElement(...arguments); if (this._allowFocusListener) { $(window).off(END_ACTIONS, this._allowFocusListener); } } // actions @action optionMouseDown(event) { if (event.which === 1 && !event.ctrlKey) { this._denyFocus(event); } } @action optionTouchStart(event) { this._denyFocus(event); } @action handleFocus() { if (this._canFocus) { super.handleFocus(...arguments); } } // internal _denyFocus() { if (this._canFocus) { this._canFocus = false; this._allowFocusListener = bind(this, this._allowFocus); $(window).on(END_ACTIONS, this._allowFocusListener); } } _allowFocus() { this._canFocus = true; $(window).off(END_ACTIONS, this._allowFocusListener); this._allowFocusListener = null; } }
import React from 'react'; import ReactDOM from 'react-dom'; import TestUtils from 'react-addons-test-utils'; import chai from 'chai'; const expect = chai.expect; import NodeAsserter from './NodeAsserter'; export default class TreePaneAsserter { constructor(jsx) { this.element = document.createElement('div'); ReactDOM.render(jsx, this.element); } findRootNode() { let childNode = this.element.children[0].children[0]; return new NodeAsserter(this, childNode); } }
/* global Metro */ (function(Metro, $) { 'use strict'; var Utils = Metro.utils; var InfoBoxDefaultConfig = { infoboxDeferred: 0, type: "", width: 480, height: "auto", overlay: true, overlayColor: '#000000', overlayAlpha: .5, overlayClickClose: false, autoHide: 0, removeOnClose: false, closeButton: true, clsBox: "", clsBoxContent: "", clsOverlay: "", onOpen: Metro.noop, onClose: Metro.noop, onInfoBoxCreate: Metro.noop }; Metro.infoBoxSetup = function (options) { InfoBoxDefaultConfig = $.extend({}, InfoBoxDefaultConfig, options); }; if (typeof window["metroInfoBoxSetup"] !== undefined) { Metro.infoBoxSetup(window["metroInfoBoxSetup"]); } Metro.Component('info-box', { init: function( options, elem ) { this._super(elem, options, InfoBoxDefaultConfig, { overlay: null, id: Utils.elementId("info-box") }); return this; }, _create: function(){ var element = this.element; this._createStructure(); this._createEvents(); this._fireEvent("info-box-create", { element: element }); }, _overlay: function(){ var o = this.options; var overlay = $("<div>"); overlay.addClass("overlay").addClass(o.clsOverlay); if (o.overlayColor === 'transparent') { overlay.addClass("transparent"); } else { overlay.css({ background: Metro.colors.toRGBA(o.overlayColor, o.overlayAlpha) }); } return overlay; }, _createStructure: function(){ var element = this.element, o = this.options; var closer, content; if (o.overlay === true) { this.overlay = this._overlay(); } element.addClass("info-box").addClass(o.type).addClass(o.clsBox); closer = element.find("closer"); if (closer.length === 0) { closer = $("<span>").addClass("button square closer"); closer.appendTo(element); } if (o.closeButton !== true) { closer.hide(); } content = element.find(".info-box-content"); if (content.length > 0) { content.addClass(o.clsBoxContent); } element.css({ width: o.width, height: o.height, visibility: "hidden", top: '100%', left: ( $(window).width() - element.outerWidth() ) / 2 }); element.appendTo($('body')); }, _createEvents: function(){ var that = this, element = this.element; element.on(Metro.events.click, ".closer", function(){ that.close(); }); element.on(Metro.events.click, ".js-dialog-close", function(){ that.close(); }); $(window).on(Metro.events.resize, function(){ that.reposition(); }, {ns: this.id}); }, _setPosition: function(){ var element = this.element; element.css({ top: ( $(window).height() - element.outerHeight() ) / 2, left: ( $(window).width() - element.outerWidth() ) / 2 }); }, reposition: function(){ this._setPosition(); }, setContent: function(c){ var element = this.element; var content = element.find(".info-box-content"); if (content.length === 0) { return ; } content.html(c); this.reposition(); }, setType: function(t){ var element = this.element; element.removeClass("success info alert warning").addClass(t); }, open: function(){ var that = this, element = this.element, o = this.options; // if (o.overlay === true) { // this.overlay.appendTo($("body")); // } if (o.overlay === true && $(".overlay").length === 0) { this.overlay.appendTo($("body")); if (o.overlayClickClose === true) { this.overlay.on(Metro.events.click, function(){ that.close(); }); } } this._setPosition(); element.css({ visibility: "visible" }); this._fireEvent("open"); element.data("open", true); if (parseInt(o.autoHide) > 0) { setTimeout(function(){ that.close(); }, parseInt(o.autoHide)); } }, close: function(){ var element = this.element, o = this.options; if (o.overlay === true) { $('body').find('.overlay').remove(); } element.css({ visibility: "hidden", top: "100%" }); this._fireEvent("close"); element.data("open", false); if (o.removeOnClose === true) { this.destroy(); element.remove(); } }, isOpen: function(){ return this.element.data("open") === true; }, /* eslint-disable-next-line */ changeAttribute: function(attributeName){ }, destroy: function(){ var element = this.element; element.off("all"); $(window).off(Metro.events.resize, {ns: this.id}); return element; } }); Metro['infobox'] = { isInfoBox: function(el){ return Utils.isMetroObject(el, "infobox"); }, open: function(el, c, t){ if (!this.isInfoBox(el)) { return false; } var ib = Metro.getPlugin(el, "infobox"); if (c !== undefined) { ib.setContent(c); } if (t !== undefined) { ib.setType(t); } ib.open(); }, close: function(el){ if (!this.isInfoBox(el)) { return false; } var ib = Metro.getPlugin(el, "infobox"); ib.close(); }, setContent: function(el, c){ if (!this.isInfoBox(el)) { return false; } if (c === undefined) { c = ""; } var ib = Metro.getPlugin(el, "infobox"); ib.setContent(c); ib.reposition(); }, setType: function(el, t){ if (!this.isInfoBox(el)) { return false; } var ib = Metro.getPlugin(el, "infobox"); ib.setType(t); ib.reposition(); }, isOpen: function(el){ if (!this.isInfoBox(el)) { return false; } var ib = Metro.getPlugin(el, "infobox"); return ib.isOpen(); }, create: function(c, t, o, open){ var $$ = Utils.$(); var el, ib, box_type; box_type = t !== undefined ? t : ""; el = $$("<div>").appendTo($$("body")); $$("<div>").addClass("info-box-content").appendTo(el); var ib_options = $$.extend({}, { removeOnClose: true, type: box_type }, (o !== undefined ? o : {})); ib_options._runtime = true; el.infobox(ib_options); ib = Metro.getPlugin(el, 'infobox'); ib.setContent(c); if (open !== false) { ib.open(); } return el; } }; }(Metro, m4q));
var connectionString, db, mongoose, options; mongoose = require('mongoose'); var host = "127.0.0.1"; var port = "27017"; var db = "express-g-demo"; connectionString = 'mongodb://' + host + ':' + port + '/' + db + ''; options = { db: { native_parser: true }, server: { auto_reconnect: true, poolSize: 5 } }; console.log(connectionString); mongoose.connect(connectionString, options, function(err, res) { if (err) { console.log('[mongoose log] Error connecting to: ', +connectionString + '. ' + err); return process.exit(1); } else { return console.log('[mongoose log] Successfully connected to: ', +connectionString); } }); db = mongoose.connection; db.on('error', console.error.bind(console, 'mongoose connection error:')); db.once('open', function() { return console.log('mongoose open success'); }); module.exports = db;
var _this = this; // Collection Activities = new Mongo.Collection('activities'); Activities.helpers({ board: function() { return Boards.findOne(this.boardId); }, user: function() { return Users.findOne(this.userId); }, member: function() { return BoardMembers.findOne(this.memberId); }, list: function() { return Lists.findOne(this.listId); }, card: function() { return Cards.findOne(this.cardId); }, comment: function() { return CardComments.findOne(this.commentId); } }); // ACTIVITIES BEFORE HOOK INSERT Activities.before.insert(function(userId, doc) { doc.createdAt = new Date(); });
import Ember from 'ember'; import layout from '../templates/components/bulma-panel'; import { _helpers, _responsiveHelpers } from '../constants'; const { Component } = Ember; export default Component.extend({ layout, tagName: 'nav', classNames: ['panel'], classNameBindings: [].concat(_helpers, _responsiveHelpers) });
var alax = require('../dist/alax.js'); describe('Test001 - AlaX prototype',function(){ it('1. Save simple XLS/HTM file', function(done){ var res = alax([{a:1,b:10},{a:2,b:20}],"restest001.xlsx"); assert(res == 1); done(); }); });
export default String('\n\ #define PHONG\n\ \n\ uniform vec3 diffuse;\n\ uniform vec3 emissive;\n\ uniform vec3 specular;\n\ uniform float shininess;\n\ uniform float opacity;\n\ \n\ #include <common>\n\ #include <packing>\n\ #include <dithering_pars_fragment>\n\ #include <color_pars_fragment>\n\ #include <uv_pars_fragment>\n\ #include <uv2_pars_fragment>\n\ #include <map_pars_fragment>\n\ #include <alphamap_pars_fragment>\n\ #include <aomap_pars_fragment>\n\ #include <lightmap_pars_fragment>\n\ #include <emissivemap_pars_fragment>\n\ #include <envmap_pars_fragment>\n\ #include <gradientmap_pars_fragment>\n\ #include <fog_pars_fragment>\n\ #include <bsdfs>\n\ #include <lights_pars>\n\ #include <lights_phong_pars_fragment>\n\ #include <shadowmap_pars_fragment>\n\ #include <bumpmap_pars_fragment>\n\ #include <normalmap_pars_fragment>\n\ #include <specularmap_pars_fragment>\n\ #include <logdepthbuf_pars_fragment>\n\ #include <clipping_planes_pars_fragment>\n\ \n\ void main() {\n\ \n\ #include <clipping_planes_fragment>\n\ \n\ vec4 diffuseColor = vec4( diffuse, opacity );\n\ ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) );\n\ vec3 totalEmissiveRadiance = emissive;\n\ \n\ #include <logdepthbuf_fragment>\n\ #include <map_fragment>\n\ #include <color_fragment>\n\ #include <alphamap_fragment>\n\ #include <alphatest_fragment>\n\ #include <specularmap_fragment>\n\ #include <normal_flip>\n\ #include <normal_fragment>\n\ #include <emissivemap_fragment>\n\ \n\ // accumulation\n\ #include <lights_phong_fragment>\n\ #include <lights_template>\n\ \n\ // modulation\n\ #include <aomap_fragment>\n\ \n\ vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance;\n\ \n\ #include <envmap_fragment>\n\ \n\ gl_FragColor = vec4( outgoingLight, diffuseColor.a );\n\ \n\ #include <tonemapping_fragment>\n\ #include <encodings_fragment>\n\ #include <fog_fragment>\n\ #include <premultiplied_alpha_fragment>\n\ #include <dithering_fragment>\n\ \n\ }\n\ ').replace( /[ \t]*\/\/.*\n/g, '' ).replace( /[ \t]*\/\*[\s\S]*?\*\//g, '' ).replace( /\n{2,}/g, '\n' );
var googletag=googletag||{};googletag.cmd=googletag.cmd||[]; angular.module("ngDfp",[]).constant("ngDfpUrl","//www.googletagservices.com/tag/js/gpt.js").provider("DoubleClick",["ngDfpUrl",function(e){var d={},g={},c={},q=null,l=!0,m={},n=!1,h=!1,p=!0;this._createTag=function(a){if(l){var b=document.createElement("script"),f="https:"===document.location.protocol,c=document.getElementsByTagName("script")[0];b.async=!0;b.type="text/javascript";b.src=(f?"https:":"http:")+e;c.parentNode.insertBefore(b,c);b.onreadystatechange=function(){"complete"==this.readyState&& a()};b.onload=a}};this._initialize=function(){var a=this;googletag.cmd.push(function(){angular.forEach(d,function(a,f){g[f]=googletag.defineSlot.apply(null,a).addService(googletag.pubads());c[f]&&g[f].defineSizeMapping(c[f]);var e=a.getSlotTargeting();e&&angular.forEach(e,function(a,b){g[f].setTargeting(a.id,a.value)})});angular.forEach(m,function(a,f){googletag.pubads().setTargeting(f,a)});n&&googletag.pubads().collapseEmptyDivs();h&&googletag.pubads().setCentering(!0);p&&googletag.pubads().enableSingleRequest(); googletag.enableServices();googletag.pubads().addEventListener("slotRenderEnded",a._slotRenderEnded)})};this._slotRenderEnded=function(a){var b=d[a.slot.getSlotId().getDomId()].renderCallback;"function"===typeof b&&b(a)};this._refreshInterval=function(){return q};this.setRefreshInterval=function(a){q=a;return this};this.defineSlot=function(){var a=arguments;a.getSize=function(){return this[1]};a.getSlotTargeting=function(){return this[3]?this[3]:!1};a.setRenderCallback=function(a){this.renderCallback= a};d[arguments[2]]=a;return this};this.defineSizeMapping=function(a){c[a]||(c[a]=[]);this.addSize=function(b,f){c[a].push([b,f]);return this};return this};this.setEnabled=function(a){l=a};this.setPageTargeting=function(a,b){m[a]=b};this.collapseEmptyDivs=function(){n=!0};this.setCentering=function(a){h=a};this.setSingleRequest=function(a){p=a};var k=this;this.$get=["$q","$window","$interval",function(a,b,f){var c=a.defer();k._createTag(function(){try{k._initialize(),null!==k._refreshInterval()&&f(function(){googletag.cmd.push(function(){b.googletag.pubads().refresh()})}, k._refreshInterval()),c.resolve()}catch(a){c.reject(a)}});return{getAdSize:function(a){return c.promise.then(function(){if(angular.isUndefined(d[a]))throw"Slot "+a+" has not been defined. Define it using DoubleClickProvider.defineSlot().";return d[a][1]})},getSlot:function(a){return c.promise.then(function(){if(angular.isUndefined(d[a]))throw"Slot "+a+" has not been defined. Define it using DoubleClickProvider.defineSlot().";return d[a]})},runAd:function(a){googletag.cmd.push(function(){b.googletag.display(a)})}, refreshAds:function(){var a=[];angular.forEach(arguments,function(b){a.push(g[b])});googletag.cmd.push(function(){b.googletag.pubads().refresh(a)})}}}]}]).directive("ngDfpAdContainer",function(){return{restrict:"A",controller:["$element",function(e){this.$$setVisible=function(d,g){d?"visibility"===g?e.css("visibility","visible"):e.show():"visibility"===g?e.css("visibility","hidden"):e.hide()}}]}}).directive("ngDfpAd",["$timeout","$parse","$interval","DoubleClick",function(e,d,g,c){return{restrict:"A", template:'<div id="{{adId}}"></div>',require:"?^ngDfpAdContainer",scope:{adId:"@ngDfpAd",refresh:"@ngDfpAdRefresh",interval:"@ngDfpAdRefreshInterval",timeout:"@ngDfpAdRefreshTimeout"},replace:!0,link:function(d,l,m,n){d.$watch("adId",function(h){l.html("");var p=null,k=null;c.getSlot(h).then(function(a){var b=a.getSize();l.css("width",b[0]).css("height",b[1]);e(function(){c.runAd(h)});n&&a.setRenderCallback(function(){angular.isDefined(m.ngDfpAdHideWhenEmpty)&&(0===l.find("iframe:not([id*=hidden])").map(function(){return this.contentWindow.document}).find("body").children().length? n.$$setVisible(!1,m.ngDfpAdHideWhenEmpty):n.$$setVisible(!0,m.ngDfpAdHideWhenEmpty))});d.$watch("refresh",function(a){angular.isUndefined(a)||c.refreshAds(h)});d.$watch("interval",function(a){angular.isUndefined(a)||(p=g(function(){c.refreshAds(h)},d.interval))});d.$watch("timeout",function(a){angular.isUndefined(a)||(k=e(function(){c.refreshAds(h)},d.timeout))});d.$on("$destroy",function(){g.cancel(p);e.cancel(k);k=p=null})})})}}}]);
var loginStrategy = require('./classic-login'); var jwtStrategy = require('./jwt.js'); var User = require('../models/user'); module.exports = function(passport) { // Passport needs to be able to serialize and deserialize users to support persistent login sessions passport.serializeUser(function(user, done) { done(null, user._id); }); passport.deserializeUser(function(id, done) { User.findById(id, function(err, user) { done(err, user); }); }); //clasic login from the login form loginStrategy(passport); jwtStrategy(passport); //TODO: Social Networks signups, logins }
"use strict" var keyboardHelpVis = true; function setKeyboardHelpVis(show){ keyboardHelpVis = show; document.getElementById('showKeyboardHelp').style.display = show ? 'none' : ''; document.getElementById('keyboardHelp').style.display = show ? '' : 'none'; } var qCubeKeys = { profileName: 'QCube', helpDivId: 'qCubeKeys', settingId: 'setKeysQCube', keyDownKeys: { /*space*/ 32:function(){if(cube.isSolved() || confirm("scramble?")) cube.scramble();}, /*ESC*/ 27:function(){if(cube.isSolved() || confirm("reset?")) cube.init();}, /*4*/ 52:function(){cube.setDepth(cube.focusedDepth + 1);}, /*3*/ 51:function(){cube.setDepth(cube.focusedDepth - 1);}, /*z*/ 90:function(){cube.setWidth(cube.turnWidth - 1);}, /*x*/ 88:function(){cube.setWidth(cube.turnWidth + 1);}, /*d*/ 68:function(){cube.rotateL(cube.DIRS.CW);}, /*e*/ 69:function(){cube.rotateL(cube.DIRS.CCW);}, /*i*/ 73:function(){cube.rotateR(cube.DIRS.CW);}, /*k*/ 75:function(){cube.rotateR(cube.DIRS.CCW);}, /*j*/ 74:function(){cube.rotateU(cube.DIRS.CW);}, /*f*/ 70:function(){cube.rotateU(cube.DIRS.CCW);}, /*h*/ 72:function(){cube.rotateF(cube.DIRS.CW);}, /*g*/ 71:function(){cube.rotateF(cube.DIRS.CCW);}, /*s*/ 83:function(){cube.rotateD(cube.DIRS.CW);}, /*l*/ 76:function(){cube.rotateD(cube.DIRS.CCW);}, /*o*/ 79:function(){cube.rotateB(cube.DIRS.CW);}, /*w*/ 87:function(){cube.rotateB(cube.DIRS.CCW);}, /*y*/ 89:function(){cube.rotateFullUp();}, /*n*/ 78:function(){cube.rotateFullDown();}, /*a*/ 65:function(){cube.rotateFullRight();}, /*p*/ 80:function(){cube.rotateFullCW();}, /*q*/ 81:function(){cube.rotateFullCCW();}, }, keyPressKeys: { /*+*/ 43:function(){if(cube.isSolved() || confirm("increase size?")) cube.setSize(cube.size+1);}, /*=*/ 61:function(){if(cube.isSolved() || confirm("increase size?")) cube.setSize(cube.size+1);}, /*-*/ 45:function(){if(cube.isSolved() || confirm("reduce size?")) cube.setSize(cube.size-1);}, /*;*/ 59:function(){cube.rotateFullLeft();}, } } var ad8Keys = { profileName: 'AD8Keys', helpDivId: 'ad8Keys', settingId: 'setKeysAD8', keyDownKeys: { /*space*/32:function(){if(cube.isSolved() || confirm("scramble?")) cube.scramble();}, /*ESC*/ 27:function(){if(cube.isSolved() || confirm("reset?")) cube.init();}, /*d*/ 68:function(){cube.rotateL(cube.DIRS.CW);}, /*e*/ 69:function(){cube.rotateL(cube.DIRS.CCW);}, /*i*/ 73:function(){cube.rotateR(cube.DIRS.CW);}, /*k*/ 75:function(){cube.rotateR(cube.DIRS.CCW);}, /*f*/ 70:function(){cube.rotateU(cube.DIRS.CW);}, /*j*/ 74:function(){cube.rotateU(cube.DIRS.CCW);}, /*h*/ 72:function(){cube.rotateF(cube.DIRS.CW);}, /*g*/ 71:function(){cube.rotateF(cube.DIRS.CCW);}, /*l*/ 76:function(){cube.rotateD(cube.DIRS.CW);}, /*s*/ 83:function(){cube.rotateD(cube.DIRS.CCW);}, /*w*/ 87:function(){cube.rotateB(cube.DIRS.CW);}, /*o*/ 79:function(){cube.rotateB(cube.DIRS.CCW);}, /*y*/ 89:function(){cube.rotateFullUp();}, /*n*/ 78:function(){cube.rotateFullDown();}, /*a*/ 65:function(){cube.rotateFullLeft();}, /*p*/ 80:function(){cube.rotateFullCW();}, /*q*/ 81:function(){cube.rotateFullCCW();}, }, keyPressKeys: { /*+*/ 43:function(){if(cube.isSolved() || confirm("increase size?")) cube.setSize(cube.size+1);}, /*=*/ 61:function(){if(cube.isSolved() || confirm("increase size?")) cube.setSize(cube.size+1);}, /*-*/ 45:function(){if(cube.isSolved() || confirm("reduce size?")) cube.setSize(cube.size-1);}, /*;*/ 59:function(){cube.rotateFullRight();}, /*1*/ 49:function(){cube.setDepth(1);}, /*2*/ 50:function(){cube.setDepth(2);}, /*3*/ 51:function(){cube.setDepth(3);}, /*4*/ 52:function(){cube.setDepth(4);}, /*5*/ 53:function(){cube.setDepth(5);}, /*6*/ 54:function(){cube.setDepth(6);}, /*7*/ 55:function(){cube.setDepth(7);}, /*8*/ 56:function(){cube.setDepth(8);}, /*9*/ 57:function(){cube.setDepth(9);}, /*!*/ 33:function(){cube.setWidth(1);}, /*@*/ 64:function(){cube.setWidth(2);}, /*#*/ 35:function(){cube.setWidth(3);}, /*$*/ 36:function(){cube.setWidth(4);}, /*%*/ 37:function(){cube.setWidth(5);}, /*^*/ 94:function(){cube.setWidth(6);}, /*&*/ 38:function(){cube.setWidth(7);}, /***/ 42:function(){cube.setWidth(8);}, /*(*/ 40:function(){cube.setWidth(9);}, /*z*/ 122:function(){cube.setDepth(cube.focusedDepth - 1);}, /*x*/ 120:function(){cube.setDepth(cube.focusedDepth + 1);}, /*Z*/ 90:function(){cube.setWidth(cube.turnWidth - 1);}, /*X*/ 88:function(){cube.setWidth(cube.turnWidth + 1);}, } } var sideNameKeys = { profileName: 'SideName', helpDivId: 'sideNameKeys', settingId: 'setKeysSideName', keyDownKeys: { /*ESC*/ 27: function(){if(cube.isSolved() || confirm("reset?")) cube.init();}, /*LEFT*/ 37: function(){cube.rotateFullLeft();}, /*UP*/ 38: function(){cube.rotateFullUp();}, /*RIGHT*/39: function(){cube.rotateFullRight();}, /*DOWN*/ 40: function(){cube.rotateFullDown();}, }, keyPressKeys: { /*f*/ 102:function(){cube.rotateF(cube.DIRS.CW);}, /*F*/ 70: function(){cube.rotateF(cube.DIRS.CCW);}, /*b*/ 98: function(){cube.rotateB(cube.DIRS.CW);}, /*B*/ 66: function(){cube.rotateB(cube.DIRS.CCW);}, /*u*/ 117:function(){cube.rotateU(cube.DIRS.CW);}, /*U*/ 85: function(){cube.rotateU(cube.DIRS.CCW);}, /*d*/ 100:function(){cube.rotateD(cube.DIRS.CW);}, /*D*/ 68: function(){cube.rotateD(cube.DIRS.CCW);}, /*l*/ 108:function(){cube.rotateL(cube.DIRS.CW);}, /*L*/ 76: function(){cube.rotateL(cube.DIRS.CCW);}, /*r*/ 114:function(){cube.rotateR(cube.DIRS.CW);}, /*R*/ 82: function(){cube.rotateR(cube.DIRS.CCW);}, /*1*/ 49: function(){cube.setDepth(1);}, /*2*/ 50: function(){cube.setDepth(2);}, /*3*/ 51: function(){cube.setDepth(3);}, /*4*/ 52: function(){cube.setDepth(4);}, /*5*/ 53: function(){cube.setDepth(5);}, /*6*/ 54: function(){cube.setDepth(6);}, /*7*/ 55: function(){cube.setDepth(7);}, /*8*/ 56: function(){cube.setDepth(8);}, /*9*/ 57: function(){cube.setDepth(9);}, /*s*/ 115: function(){if(cube.isSolved() || confirm("scramble?")) cube.scramble();}, /*+*/ 43: function(){if(cube.isSolved() || confirm("increase size?")) cube.setSize(cube.size+1);}, /*-*/ 45: function(){if(cube.isSolved() || confirm("reduce size?")) cube.setSize(cube.size-1);}, /*z*/ 122: function(){cube.setDepth(cube.focusedDepth + 1);}, /*x*/ 120: function(){cube.setDepth(cube.focusedDepth - 1);}, /*Z*/ 90: function(){cube.setWidth(cube.turnWidth - 1);}, /*X*/ 88: function(){cube.setWidth(cube.turnWidth + 1);}, /*!*/ 33: function(){cube.setWidth(1);}, /*@*/ 64: function(){cube.setWidth(2);}, /*#*/ 35: function(){cube.setWidth(3);}, /*$*/ 36: function(){cube.setWidth(4);}, /*%*/ 37: function(){cube.setWidth(5);}, /*^*/ 94: function(){cube.setWidth(6);}, /*&*/ 38: function(){cube.setWidth(7);}, /***/ 42: function(){cube.setWidth(8);}, /*(*/ 40: function(){cube.setWidth(9);}, /*<*/ 60: function(){cube.rotateFullCCW();}, /*>*/ 62: function(){cube.rotateFullCW();} } } var keyProfiles = { 'SideName': sideNameKeys, 'QCube': qCubeKeys, 'AD8Keys': ad8Keys } var keyProfile = qCubeKeys; var ignoreKeys = false; function handleKey(e, dict){ if(!ignoreKeys){ e = e ? e : window.event; var kc = e.keyCode ? e.keyCode : e.which; if(dict[kc]) dict[kc](); } } function setKeyProfile(prof){ document.getElementById(keyProfile.helpDivId).style.display = 'none'; keyProfile = prof; document.getElementById(keyProfile.helpDivId).style.display = ''; }
const cp = require('./lib/app.js'); cp('lib', 'copy');
describe('directive', function() { var element , compiled , $timeout , bodyElm , $q , $compile , $controller , $controllerProvider , $rootScope , $scope , spyEvt , _mkController beforeEach(function() { angular .module('srph.infinite-scroll.test', []) .config(function(_$controllerProvider_) { $controllerProvider = _$controllerProvider_ }); module('srph.infinite-scroll', 'srph.infinite-scroll.test'); inject(function(_$compile_, _$q_, _$timeout_, _$controller_, _$rootScope_) { $q = _$q_; $compile = _$compile_; $timeout = _$timeout_; $controller = _$controller_; $rootScope = _$rootScope_; $scope = $rootScope.$new(); _mkController = function(controller) { $controllerProvider.register('TestController', controller || function($scope) { $scope.callback = angular.noop; }); }; }); bodyElm = angular.element('html, body'); bodyElm.height(750); }); // YOLO it('should pass', function() { expect(true).toBe(true); }); describe('scroll handler / infinite scroll', function() { describe('halt execution', function() { it('should halt when disabled', function() { _mkController(); var controller = $controller('TestController', { $scope: $scope }); element = _mkElm({ disabled: true }); // spyOn($scope, 'callback'); scroll(element); // expect($scope.callback).toHaveBeenCalled(); $timeout.flush() }); it('should not halt callback when scope.disabled is undefined', function() { element = _mkElm(); scroll(element); }); it('should not halt callback when scope.disabled is false', function() { element = _mkElm(); scroll(element); }); it('should halt when promise is not null', function() { element = _mkElm(); }); }); describe('trigger when the scroll reaches the bottom + threshold', function() { describe('trigger', function() { it('should trigger for window'); it('should trigger for element', function() { element = _mkElm({ container: true }); compiled = compile(element); scroll(compiled); }); }); it('should execute callback i qn <throttle-ms> (e.g, 500ms)', function() { }); it('should assign promise to null only after the callback is finished (testing async)', function() { }); }); }); function _mkElm(options) { options = options || {}; var callback = options.callback; var disabled = options.disabled; var throttle = options.throttle; var immediate = options.immediate; var container = options.container; var threshold = options.threshold; var children = options.children; return angular.element([ '<div ', 'srph-infinite-scroll="callback()"', 'style="height: 500px; overflow: scroll"; width: 100%;', disabled !== undefined ? 'disabled="' + disabled + '"' : '', throttle !== undefined ? 'throttle="' + throttle + '"' : '', immediate !== undefined ? 'immediate="' + immediate + '"' : '', container !== undefined ? 'container="' + container + '"' : '', threshold !== undefined ? 'threshold="' + threshold + '"' : '', '>', children, '</div>' ].join(' ')); } function scroll(e, t) { expect( e.scrollTop() ).toBe(0); var bottom = e.prop('scrollHeight'); var height = e.height(); var s = Math.abs((bottom - height <= 0 ? bottom : bottom - height)) - (t || 0); e.scrollTop( s ); e.scroll(); e.triggerHandler('scroll'); expect( e.scrollTop() ).toBe(s); } function compile(e) { var c = $compile( e )($scope); $scope.$digest(); return c; } });
import React from 'react' export default class Certificate extends React.Component { render() { let classes = `List__item List__item--${this.props.status}` let buttonText = { 'connected': 'Disconnect', 'disconnected': 'Connect' }[this.props.status] return ( <li className={classes}> {this.props.name} <button className='Button'> {buttonText} </button> </li> ) } }
'use strict'; module.exports.definition = { set: function (v) { this.setProperty('-webkit-border-end-width', v); }, get: function () { return this.getPropertyValue('-webkit-border-end-width'); }, enumerable: true, configurable: true };
// Commands: // bocbot pug bomb - Bomb this channel with 3 pugs // bocbot pug bomb # - Bomb this channel with the specified number of pugs var _ = require('underscore'); module.exports = function(robot){ robot.pugbomb = { pugmeUrl: 'http://pugme.herokuapp.com/bomb?count=', pugBombLikelihood: 2, // Odds of pugbomb happening (rand() % this_number) pugBombReplies: [ 'Take your {{number}} pugs elsewhere.', 'Nope. Nobody needs to see that many pugs.', 'Why do you think we all need to see {{number}} pugs?', '{{number}} pugs... {{number}} PUGS?? Absolutely not.', 'http://i.imgur.com/cUJd5aO.jpg' ], doBomb: function(response, numPugs){ response.http(robot.pugbomb.pugmeUrl + numPugs).get()(function(err, res, body){ if (!!err){ response.reply('There was an error getting your pugs.'); robot.errors.log(err); return; } var pugs = JSON.parse(body).pugs, responses = []; _.each(pugs, function(pug){ responses.push(response.send(pug)); }); return responses; }); }, denyBomb: function(response, numPugs){ var index = Math.floor(Math.random() * robot.pugbomb.pugBombReplies.length), reply = robot.pugbomb.pugBombReplies[index].replace(/{{number}}/g, numPugs); response.reply(reply); } }; robot.respond(/pug bomb( (\d+))?/i, function(res){ var number = res.match[2] || 3; // if (robot.auth.isAdmin(res.message.user) || robot.auth.hasRole(res.message.user, robot.roles.pugBomber)){ // User has full pugbomb permissons return robot.pugbomb.doBomb(res, number); // } // else if (robot.auth.hasRole(res.message.user, robot.roles.limitedPugBomber)){ // User has limited pugbomb permissions // if (robot.util.random(robot.pugbomb.pugBombLikelihood) === 0) // return robot.pugbomb.doBomb(res, number); // else // return robot.pugbomb.denyBomb(res, number); // } // else{ // User has no pugbomb permissions // return robot.pugbomb.denyBomb(res, number); // } }); }
const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const User = require('./../../models/user'); const login = (req, res, next) => { User.findOne( { email: req.body.email }, (err, user) => { if (err) { return res.status(500).json({ message: 'An error occured', error: err }); } if (!user) { return res.status(401).json({ message: 'Login failed', error: { message: 'Invalid credentials' } }); } if (!bcrypt.compareSync(req.body.password, user.password)) { return res.status(401).json({ message: 'Login failed', error: { message: 'Invalid credentials' } }); } res.status(200).json({ message: 'Successfully logged in', token: generateToken(user), userId: user._id }); } ); }; const generateToken = user => { // TODO: write skey generation return jwt.sign( { user: user }, 'skey', { expiresIn: 7200 } ); }; module.exports = login;
angular.module('ngNuxeoQueryPart') .provider('NuxeoQueryMixin', ['QueryProvider', function (QueryProvider) { QueryProvider.addQueryPartProvider('NuxeoQueryMixin'); this.$get = ['nuxeoUtils', function (utils) { var QueryPart = function () { /** * Excludes some document facets from search query * @param mixin, Array of excluded mixin * @returns {*} */ this.excludeMixin = function (mixin) { this.options.excludeMixinTypes = mixin; return this; }; /** * Includes some document facets from search query * @param mixin, Array of excluded mixin * @returns {QueryPart} */ this.withMixin = function (mixin) { this.options.mixin = mixin; return this; }; }; // Don't provide default behaviour // QueryPart.defaultOptions = { excludeMixinTypes: ['Folderish', 'HiddenInNavigation'] }; QueryPart.getPart = function (options) { // Exclusion var criterias = ''; var excl = options.excludeMixinTypes; if (angular.isArray(excl) && excl.length) { criterias += 'ecm:mixinType NOT IN (\'' + excl.join('\',\'') + '\')'; } else if (angular.isString(excl) && excl.length) { criterias += 'ecm:mixinType <> \'' + excl + '\''; } // Inclusion : Transform if Object => Array var incl = utils.objToArray(options.mixin); if (angular.isArray(incl) && incl.length) { criterias += 'ecm:mixinType IN (\'' + incl.join('\',\'') + '\')'; } else if (angular.isString(incl) && incl.length) { criterias += 'ecm:mixinType = \'' + incl + '\''; } return criterias; }; return QueryPart; }]; }]);
import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import { Card, CardActions, CardHeader, CardText } from 'material-ui/Card'; import RaisedButton from 'material-ui/RaisedButton'; import ActionHome from 'material-ui/svg-icons/action/home'; const GithubBox = props => ( <div> <Card> <CardHeader title={props.data.get('name')} subtitle={props.userId} avatar={props.data.get('avatar_url')} /> <CardText> Followers : {props.data.get('followers')} </CardText> <CardText> Following : {props.data.get('following')} </CardText> <CardActions> <Link to="/"> <RaisedButton label="Back" icon={<ActionHome />} secondary /> </Link> </CardActions> </Card> </div> ); GithubBox.propTypes = { data: PropTypes.object, userId: PropTypes.string, }; export default GithubBox;
var SubmitB = React.createClass({displayName: "SubmitB", getInitialState: function(){ return{value: '', text: false, para: '', position: []}; }, handleClick : function(e){ this.setState({value: this.refs['a'].state.text, text: this.refs['b'].state.text, para: this.refs['c'].state.value, position: this.refs['d'].state.position }, function () { console.log(this.state.value); console.log(this.state.text); console.log(this.state.para); console.log(this.state.position); }); }, render : function(){ var value = this.state.value; var text = this.state.text; var para = this.state.para; var position = this.state.position; return ( React.createElement("div", null, React.createElement(TextImage, {ref: "b", value: text}), React.createElement(TextV, {ref: "c", value: para}), React.createElement(FontSize, {ref: "a", value: value}), React.createElement(Imagepos, {ref: "d", value: position}), React.createElement("button", {onClick: this.handleClick, id: "button"}, "Submit") ) ); } }); var Imagepos = React.createClass({displayName: "Imagepos", getInitialState: function(){ return {position: this.props.value, clicks: 0}; }, handleChange: function(event){ var OFFSET_X = 450; var OFFSET_Y = 60; var pos_x = event.clientX?(event.clientX):event.pageX; var pos_y = event.clientY?(event.clientY):event.pageY; if(this.state.clicks == 0){ this.setState({clicks: this.state.clicks + 1 , position: [pos_x-OFFSET_X, pos_y-OFFSET_Y]}, function(){ console.log(this.state.position); }); } else if(this.state.clicks == 1){ this.setState({clicks: this.state.clicks + 1 , position: [this.state.position[0], this.state.position[1], pos_x-OFFSET_X, pos_y-OFFSET_Y]}, function(){ console.log(this.state.position); }); } else{ document.getElementById("pointer_div").onclick = function() { return false; } ; } }, render:function(){ return( React.createElement("form", {name: "pointform", method: "post"}, React.createElement("div", {id: "pointer_div", onClick: this.handleChange}, React.createElement("img", {src: "test.png", id: "cross"}) ) ) ); } }); var TextV = React.createClass({displayName: "TextV", getInitialState: function(){ return {value: this.props.value}; }, handleChange : function(e){ this.setState({value: e.target.value}); }, render: function () { var value = this.state.value; return(React.createElement("div", {className: "form-group", id: "textV"}, React.createElement("label", {className: "col-sm-1 control-label"}, "Text"), React.createElement("div", {className: "col-sm-4"}, React.createElement("textarea", {className: "form-control", rows: "10", id: "focusedInput", onChange: this.handleChange, type: "text", value: this.state.value}) ) ) ); } }); var TextImage = React.createClass({displayName: "TextImage", getInitialState: function(){ return {text: this.props.value}; }, itsText: function(e){ this.setState({text: true}); }, itsImage: function(e){ this.setState({text: false}); }, render: function(){ return( React.createElement("div", {className: "radio", id: "TextOrImage"}, React.createElement("label", null, React.createElement("input", {type: "radio", name: "optradio", onChange: this.itsText}), "Text"), React.createElement("label", null, React.createElement("input", {type: "radio", name: "optradio", onChange: this.itsImage}), "Image") ) ); } }); var FontSize = React.createClass({displayName: "FontSize", getInitialState: function(){ return {text: this.props.value}; }, handleChange : function(e){ this.setState({text: e.target.value}); }, render: function () { return(React.createElement("div", {className: "form-group", id: "fontSize"}, React.createElement("label", {className: "col-sm-1 control-label"}, "FontSize"), React.createElement("div", {className: "col-sm-1"}, React.createElement("textarea", {className: "form-control", rows: "1", id: "focusedInput", onChange: this.handleChange, type: "text", value: this.text}) ) ) ); } }); React.render(React.createElement(Imagepos, null) , document.getElementById('fontSize'));
#!/usr/bin/env node /** * this script is just a temporary solution to deal with the issue of npm outputting the npm * shrinkwrap file in an unstable manner. * * See: https://github.com/npm/npm/issues/3581 */ var _ = require('lodash'); var sorted = require('sorted-object'); var fs = require('fs'); function cleanModule(module, name) { // keep `from` and `resolve` properties for git dependencies, delete otherwise if (!(module.resolved && module.resolved.match(/^git:\/\//))) { delete module.from; delete module.resolved; } if (name === 'chokidar') { if (module.version === '0.8.1') { delete module.dependencies; } else if ( module.version !== '0.8.2') { throw new Error("Unfamiliar chokidar version (v" + module.version + ") , please check status of https://github.com/paulmillr/chokidar/pull/106"); } } _.forEach(module.dependencies, function(mod, name) { cleanModule(mod, name); }); } console.log('Reading npm-shrinkwrap.json'); var shrinkwrap = require('./../npm-shrinkwrap.json'); console.log('Cleaning shrinkwrap object'); cleanModule(shrinkwrap, shrinkwrap.name); console.log('Writing cleaned npm-shrinkwrap.json'); fs.writeFileSync('./npm-shrinkwrap.json', JSON.stringify(sorted(shrinkwrap), null, 2) + "\n");
'use strict'; module.exports = function(app) { var users = require('../../app/controllers/users.server.controller'); var filmes = require('../../app/controllers/filmes.server.controller'); // Filmes Routes app.route('/filmes') .get(filmes.list) .post(users.requiresLogin, filmes.create); //Filmes List app.route('/filmes/listar') .get(filmes.listar) app.route('/filmes/:filmeId') .get(filmes.read) .put(users.requiresLogin, filmes.hasAuthorization, filmes.update) .delete(users.requiresLogin, filmes.hasAuthorization, filmes.delete); // Finish by binding the Filme middleware app.param('filmeId', filmes.filmeByID); };
modules.define('spec', ['functions'], function(provide, functions) { describe('functions', function() { describe('isFunction', function() { it('should returns true for function', function() { functions.isFunction(function() {}).should.be.equal(true); functions.isFunction(new Function()).should.be.equal(true); }); it('should return false for non-functions', function() { functions.isFunction().should.be.equal(false); functions.isFunction(5).should.be.equal(false); functions.isFunction({}).should.be.equal(false); functions.isFunction('').should.be.equal(false); functions.isFunction([]).should.be.equal(false); functions.isFunction(null).should.be.equal(false); functions.isFunction(new function() {}).should.be.equal(false); }); }); describe('noop', function() { it('should be a function', function() { functions.isFunction(functions.noop).should.be.true; }); }); }); provide(); });
var webpack = require('webpack') module.exports = { entry: [ // 'webpack-dev-server/client?http://localhost:2018', // 'webpack/hot/only-dev-server', './src/main.js' ], output: { filename: 'bundle.js', path: __dirname + '/dist', publicPath: 'http://localhost:2018/static' }, plugins: [ new webpack.NoErrorsPlugin(), new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), new webpack.DefinePlugin({ 'process.env': { // This has effect on the react lib size 'NODE_ENV': JSON.stringify('production'), } }), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, sourceMap: false }), new webpack.optimize.OccurrenceOrderPlugin(), new webpack.optimize.DedupePlugin() ], module: { loaders: [ { test: /\.js$/ , exclude: /node_modules/, loaders: ['babel?presets[]=es2015,presets[]=react'] }, { test: /\.jsx$/ , exclude: /node_modules/, loaders: ['babel?presets[]=es2015,presets[]=react'] }, { test: /\.css$/, loader: 'style!css' }, { test: /\.json$/, loaders: ['json'] } ] } }
var helper = require("../../../helper"); // var Manager = require("../../../src/etl/fact-purchasing-etl-manager"); var Manager = require("../../../../src/etl/purchasing/fact-pembelian"); var instanceManager = null; var should = require("should"); var sqlHelper = require("../../../sql-helper"); before("#00. connect db", function (done) { Promise.all([helper, sqlHelper]) .then((result) => { var db = result[0]; var sql = result[1]; db.getDb().then((db) => { instanceManager = new Manager(db, { username: "unit-test" }, sql); done(); }) .catch((e) => { done(e); }) }); }); it("#01. should success when create etl fact-purchasing", function (done) { instanceManager.run() .then((a) => { console.log(a); done(); }) .catch((e) => { console.log(e); done(e); }); }); it("#02. should success when transforming data", function (done) { var data = [ { purchaseOrder: { _deleted: false, _createdDate: new Date(), purchaseOrderExternal: { date: new Date(1970, 1, 1) }, items: [ { fulfillments: [ { deliveryOrderDate: new Date() } ] } ] }, purchaseRequest: { _deleted: false, category: { name: "" }, date: new Date(1970, 1, 1) } }, { purchaseOrder: { _deleted: false, _createdDate: new Date(), purchaseOrderExternal: { date: new Date() }, items: [ { fulfillments: [ { deliveryOrderDate: new Date() } ] } ] }, purchaseRequest: { category: { name: "BAHAN BAKU" }, date: new Date() } }, { _deleted: true, purchaseOrder: { _createdDate: new Date("2017-03-29T16:13:51+07:00"), purchaseOrderExternal: { date: new Date("2017-04-16T16:14:08+07:00") }, items: [ { fulfillments: [ { deliveryOrderDate: new Date("2017-05-29T16:14:08+07:00") } ] } ] }, purchaseRequest: { _deleted: false, category: { name: "BUKAN BAHAN BAKU" }, date: new Date("2017-04-08T16:14:08+07:00") } }, { _deleted: true, purchaseOrder: { _createdDate: new Date("2017-03-29T16:13:51+07:00"), purchaseOrderExternal: { date: new Date("2017-04-16T16:14:08+07:00") }, items: [ { fulfillments: [ { deliveryOrderDate: new Date("2017-06-29T16:14:08+07:00") } ] } ] }, purchaseRequest: { _deleted: false, category: { name: "BUKAN BAHAN BAKU" }, date: new Date("2017-04-08T16:14:08+07:00") } }, { _deleted: true, purchaseOrder: { _createdDate: new Date("2017-03-29T16:13:51+07:00"), purchaseOrderExternal: { date: new Date("2017-04-16T16:14:08+07:00") }, items: [ { fulfillments: [ ] } ] }, purchaseRequest: { _deleted: false, category: { name: "BUKAN BAHAN BAKU" }, date: new Date("2017-04-08T16:14:08+07:00") } }, { purchaseOrder: null, purchaseRequest: { _deleted: false, category: { name: "BUKAN BAHAN BAKU" }, date: new Date("2017-04-08T16:14:08+07:00"), items: [ ] } } ]; instanceManager.transform(data) .then(() => { done(); }) .catch((e) => { done(e); }); }); it("#03. should success when extracting PR from PO", function (done) { var data = [ { purchaseRequest: {} } ]; instanceManager.getPRFromPO(data) .then(() => { done(); }) .catch((e) => { done(e); }); }); it("#04. should success when joining PR to PO", function (done) { var data = []; instanceManager.joinPurchaseOrder(data) .then(() => { done(); }) .catch((e) => { done(e); }); }); it("#05. should success when remove duplicate data", function (done) { var arr = [{ no: {} }, { no: {} }]; instanceManager.removeDuplicates(arr) .then((a) => { done(); }) .catch((e) => { done(e); }); }); // it("#06. should error when load empty data", function (done) { // instanceManager.load({}) // .then(id => { // done("should error when create with empty data"); // }) // .catch((e) => { // try { // done(); // } // catch (ex) { // done(ex); // } // }); // }); it("#07. should error when insert empty data", function (done) { instanceManager.insertQuery(this.sql, "") .then((id) => { done("should error when create with empty data"); }) .catch((e) => { try { done(); } catch (ex) { done(ex); } }); });
var structtesting_1_1internal_1_1_matcher_tuple_3_01_1_1testing_1_1tuple_3_01_a1_00_01_a2_00_01_a3_00_01_a4_01_4_01_4 = [ [ "type", "structtesting_1_1internal_1_1_matcher_tuple_3_01_1_1testing_1_1tuple_3_01_a1_00_01_a2_00_01_a3_00_01_a4_01_4_01_4.html#afa578cadfc6b4725920b115d4f7633df", null ] ];
/* * * CONFIGURATION VARIABLES * * */ var disqus_shortname = 'mywork-aci'; /* * * DON'T EDIT BELOW THIS LINE * * */ (function() { var s = document.createElement('script'); s.async = true; s.type = 'text/javascript'; s.src = 'http://' + disqus_shortname + '.disqus.com/count.js'; (document.getElementsByTagName('HEAD')[0] || document.getElementsByTagName('BODY')[0]).appendChild(s); }());
PERT.Project = class Project { /** * @param {String} name * @param {DataStore} config */ constructor(name, config) { this.name = name; this.config = Project.migrate(config); // Setup project UI PERT.ui('area').innerHTML = '<div class="project-area"></div>'; PERT.ui('menu-contents').classList.add('menu-contents-project-loaded'); const configData = this.configData; const projectMenu = PERT.ui('menu-contents-project'); const project = PERT.template('ProjectTemplate'); projectMenu.innerHTML = ''; projectMenu.appendChild(project); this.dates = project.querySelectorAll('.project-dates input'); this.dates[0].value = configData.start; this.dates[1].value = configData.end; const timezone = project.querySelector('.project-timezone'); timezone.value = configData.timezone; if (this.isStarted) { project.classList.add('project-started'); } // Date change handlers this.dates.forEach((node, index) => { const name = index ? 'end' : 'start'; node.addEventListener('change', e => { configData[name] = e.target.value; this.recalculateDateConstraints(); }); }); // Timezone change handler timezone.addEventListener('change', e => { configData.timezone = parseInt(e.target.options[e.target.selectedIndex].value); this.recalculateDateAdvancement(); }); // Generate project resources for (const id in configData.resources) { this.createResourceInputs(id); } this.createResourceInputs(); // Update the last accessed project timestamp this.configData.stats.accessedAt = Date.now(); this.save(); // Register UI button handlers project.querySelector('.project-save').addEventListener('click', () => this.save()); project.querySelector('.project-export').addEventListener('click', () => this.export()); project.querySelector('.project-rename').addEventListener('click', () => this.rename()); project.querySelector('.project-delete').addEventListener('click', () => this.delete()); project.querySelector('.project-start').addEventListener('click', () => this.start()); project.querySelector('.project-changes').addEventListener('click', () => this.generateRequirementChanges()); project.querySelector('.project-add-node').addEventListener('click', () => this.addNode()); // Register pre-HTML5 drag and drop and stats hover handlers const projectArea = PERT.ui('area').querySelector('.project-area'); // Scrolls the project area when dragging close to the browser edge const dragScroll = e => { const activate = 30; if (e.clientX < activate) { projectArea.scrollLeft -= Math.min(e.clientX, projectArea.scrollLeft); } else if (window.innerWidth - e.clientX < activate) { projectArea.scrollLeft += window.innerWidth - e.clientX; } else if (e.clientY < activate) { projectArea.scrollTop -= Math.min(e.clientY, projectArea.scrollTop); } else if (window.innerHeight - e.clientY < activate) { projectArea.scrollTop += window.innerHeight - e.clientY; } }; projectArea.addEventListener('mousemove', e => { if (this.moveNode) { dragScroll(e); this.moveNode.drag(e.clientX + projectArea.scrollLeft, e.clientY + projectArea.scrollTop); } else { let nodeId = null; // Recursively determine if the mouse is over a node let element = e.srcElement; do { if (element.classList.contains('node')) { nodeId = element.id; break; } element = element.parentElement; } while (element); // Redraw the stats only if their target is different if (nodeId !== PERT.currentStats) { PERT.currentStats = nodeId; this.redrawStats(nodeId); } } }); projectArea.addEventListener('mouseout', e => { if (e.fromElement.tagName === 'HTML') { this.moveNode = null; } }); projectArea.addEventListener('mouseup', () => this.moveNode = null); // Edge drag projectArea.addEventListener('drag', e => { // If there's a custom redraw handler, call it if (e.target.redrawEdge) { dragScroll(e); e.target.redrawEdge(e.clientX + projectArea.scrollLeft, e.clientY + projectArea.scrollTop); } }); this.nodes = {}; PERT.currentStats = null; } /** * The plain object representation of the project's configuration DataStore. * @returns {Object} */ get configData() { return this.config.getData(); } /** * Whether or not the project has been started. * @returns {Boolean} */ get isStarted() { return this.config.has('original'); } /** * Whether or not the project's and all nodes' start and end dates have * been set. * @returns {Boolean} */ get hasAllDates() { const config = this.configData; let hasAllDates = !!config.start && !!config.end; for (const key in config.nodes) { hasAllDates = hasAllDates && !!config.nodes[key].start && !!config.nodes[key].end; } return hasAllDates; } /** * Commits any changes made to the project. */ save() { if (this.isStarted && !this.hasAllDates) { alert('Started projects must have their dates and all their nodes\' start and end dates set to be saved.'); return; } this.config.get('stats').modifiedAt = Date.now(); this.config.commit(); } /** * Opens the project rename dialog and renames the project. */ rename() { const newName = PERT.Dashboard.getNewProjectName(true); if (newName !== null) { PERT.config.reset(); PERT.config.set(newName, this.configData); PERT.config.unset(this.name); PERT.config.commit(); PERT.Dashboard.redrawProjectsSelector(); PERT.Dashboard.loadProject(newName); } } /** * Opens the project delete dialog and deletes the project. */ delete() { if (confirm('Are you sure you want to delete the current project? This action cannot be undone.')) { PERT.Dashboard.deleteProject(this.name); } } /** * Opens the project start dialog and starts the project, preserving an * immutable copy of the current state. */ start() { if (this.isStarted) { alert('The project has already been started.'); return; } const config = this.configData; if (!this.hasAllDates) { alert('Please set the project\'s and all nodes\' start and end dates before starting the project.'); return; } if (confirm('Are you sure you want to start the current project? Once started, all future modifications will \ become a part of the requirement changes report.')) { this.config.set('original', { resources: this.config.deepCopy(config.resources), nodes: this.config.deepCopy(config.nodes), edges: this.config.deepCopy(config.edges), start: config.start, end: config.end }); this.recalculateDateAdvancement(); } } /** * Exports the project to a file. */ export() { // Prepare the project configuration, so it can be loaded as a base64 // encoded string, so that it can be used as a link's href const json = JSON.stringify(this.configData); const blob = new Blob([json], {type: 'application/json'}); const reader = new FileReader(); reader.addEventListener('load', e => { // Create a download link and automatically invoke it const link = document.createElement('a'); link.download = `${this.name}.pert`; link.href = e.target.result; link.click(); }); reader.readAsDataURL(blob); } /** * Opens the node add dialog and creates a new node. */ addNode() { let name, promptText = ''; for (;;) { promptText += 'Please enter a name for the new milestone:'; name = prompt(promptText, name); if (name === null) { return; } else if (name === '') { promptText = 'The new milestone name cannot be empty.\n'; } else { break; } } const nodes = this.config.ns('nodes'); // Make sure the new node ID does not overlap with a deleted node if the // project is started. const unset = []; let id; do { id = nodes.findFreeKey('n'); nodes.set(id, {}); unset.push(id); // Skip original node IDs } while (this.isStarted && id in this.configData.original.nodes); // Clean up unset.slice(0, -1).forEach(id => nodes.unset(id)); this.nodes[id] = new PERT.Node(id, nodes.ns(id), name); this.recalculateDateConstraints(); } /** * Draws all nodes, edges and stats. */ drawElements() { const nodes = this.config.ns('nodes'); const edges = this.config.get('edges'); for (const id of nodes.keys()) { this.nodes[id] = new PERT.Node(id, nodes.ns(id)); } for (const id in edges) { this.nodes[edges[id].from].connect(id, this.nodes[edges[id].to]); } this.redrawStats(); this.recalculateDateConstraints(); // Recalculate date advancement on the day following const tomorrow = this.getDate(); tomorrow.setDate(tomorrow.getDate() + 1); const interval = setInterval(() => { // Stop interval if the project has been unloaded if (PERT.currentProject !== this) { clearInterval(interval); } if (tomorrow <= this.getDate()) { // Bump next update to the day following tomorrow.setDate(tomorrow.getDate() + 1); this.recalculateDateAdvancement(); } }, 50); } /** * Removes the supplied node from the project. * @param {String} id */ deleteNode(id) { delete this.nodes[id]; this.config.ns('nodes').unset(id); this.recalculateDateConstraints(); this.recalculateResourceConstraints(); } /** * Creates the inputs for provided project resource. * @param {String} [id] */ createResourceInputs(id) { // If no ID has been supplied, create a new placeholder resource if (typeof id !== 'string') { const resources = this.config.ns('resources'); // Make sure the new resource ID does not overlap with a deleted // resource if the project is started. const unset = []; do { id = resources.findFreeKey('r'); resources.set(id, {}); unset.push(id); // Skip original resource IDs } while (this.isStarted && id in this.configData.original.resources); // Clean up unset.forEach(id => resources.unset(id)); } const config = this.config.ns('resources').getData(); const resource = PERT.template('ResourceTemplate'); // Pre-fill the inputs const inputs = resource.querySelectorAll('input'); inputs[0].value = config[id] ? config[id].name : ''; inputs[0].addEventListener('change', e => this.updateResource(id, e.target)); inputs[1].value = config[id] ? config[id].amount : ''; inputs[1].addEventListener('change', e => this.updateResource(id, e.target)); inputs[2].value = config[id] ? config[id].concurrency : ''; inputs[2].addEventListener('change', e => this.updateResource(id, e.target)); PERT.ui('menu-contents-project').querySelector('.project-resources').appendChild(resource); } /** * Handles any project resource changes. * @param {String} id * @param {HTMLElement} element */ updateResource(id, element) { const resources = this.config.ns('resources'); const type = element.name; let value = element.value; // All fields that do not represent a name, should be a positive float if (type !== 'name') { value = Math.max(0, parseFloat(value) || 0); } // If the changed resource was a placeholder, register it as a new // resource, and create a new placeholder if (!resources.has(id)) { resources.set(id, {name: null, amount: null, concurrency: null}); this.createResourceInputs(); } // If the resource name was deleted, delete the resource if (type === 'name' && value === '') { if (confirm('Are you sure you want to delete this resource?')) { resources.unset(id); element.parentNode.parentNode.removeChild(element.parentNode); } else { element.value = resources.get(id)[type]; } } else { element.value = resources.get(id)[type] = value; } // Update all node resource fields for (const id in this.nodes) { this.nodes[id].update(); } } /** * Recalculates and sets the minimum and maximum values for all project and * node dates. */ recalculateDateConstraints() { // Reset the project date constraints Object.assign(this.dates[0], this.dates[1], {min: '', max: ''}); // Reset all nodes' date constraints and find the left and rightmost // nodes const left = [], right = []; for (const nodeId in this.nodes) { const node = this.nodes[nodeId]; Object.assign(node.dateInputs[0], node.dateInputs[1], {min: '', max: ''}); if (!node.getNeighbours(true).length) { left.push(node); } if (!node.getNeighbours().length) { right.push(node); } } // Recalculate all node date constraints left.forEach(node => node.updateDateConstraints(false, this.dates[0].value)); right.forEach(node => node.updateDateConstraints(true, this.dates[1].value)); // Recalculate the project's date constraints // Set the maximum project start date to be the earliest node start time left.forEach(node => { const value = node.dateInputs[0].value || node.dateInputs[1].value || node.dateInputs[1].max; if (!this.dates[0].max || (value && this.dates[0].max > value)) { this.dates[0].max = value; } }); // Set the minimum project end date to be the latest node end time right.forEach(node => { const value = node.dateInputs[1].value || node.dateInputs[0].value || node.dateInputs[0].min; if (!this.dates[1].min || (value && this.dates[1].min < value)) { this.dates[1].min = value; } }); this.recalculateResourceConstraints(); this.recalculateDateAdvancement(); } /** * Recalculate all resource constraints. */ recalculateResourceConstraints() { // Order nodes by date const nodes = this.config.get('nodes'); const nodesOrdered = this .config .ns('nodes') .keys() .sort((a, b) => (nodes[a].start || nodes[a].end) > (nodes[b].start || nodes[b].end) ? 1 : -1); const resources = this.config.get('resources'); // Copy resource amounts and concurrency information const resourcesLeft = {}, concurrencies = {}; for (const resourceId in resources) { resourcesLeft[resourceId] = resources[resourceId].amount; concurrencies[resourceId] = resources[resourceId].concurrency; } // Collect all milestone start and end events, and determine if there // are enough resources to complete each milestone const events = []; for (const nodeId of nodesOrdered) { const node = nodes[nodeId]; if (!(nodeId in this.nodes)) { continue; } const nodeElement = this.nodes[nodeId].node; const resourceCells = nodeElement.querySelectorAll('.node-resources td'); // Remove any previous indication of insufficient resources nodeElement.classList.remove('red'); for (const resourceId in node.resources) { if (!(resourceId in resources)) { continue; } // Deduct the required resource amount from the global available resourcesLeft[resourceId] -= node.resources[resourceId]; // Find the input node offset for the resource name (index) and // value(index + 1) const index = Object.keys(node.resources).indexOf(resourceId) * 2; // If the milestone requires the resource and there is none // available, mark the node and resource inputs as insufficient if (node.resources[resourceId] > 0 && resourcesLeft[resourceId] < 0) { resourceCells[index].classList.add('red'); resourceCells[index + 1].classList.add('red'); nodeElement.classList.add('red'); resourceCells[index].title = resourceCells[index + 1].title = 'Insufficient resources'; } else { // Remove any previous indication of insufficient resources resourceCells[index].classList.remove('red'); resourceCells[index + 1].classList.remove('red'); resourceCells[index].title = resourceCells[index + 1].title = ''; } // Collect milestone start and end events if (resources[resourceId].concurrency && node.resources[resourceId] > 0) { const dates = this.nodes[nodeId].dateInputs; events.push({nodeId, resourceId, start: true, time: dates[0].value || dates[1].min}); events.push({nodeId, resourceId, start: false, time: dates[1].value || dates[0].max || 'z'}); } } } // Sort events by date, priority and level events.sort((a, b) => { if (a.time !== b.time) { return a.time > b.time ? 1 : -1; } if (a.start !== b.start) { return a.start ? 1 : -1; } if (nodes[a.nodeId].critical !== nodes[b.nodeId].critical) { return nodes[a.nodeId].critical ? -1 : 1; } return this.nodes[a.nodeId].level() > this.nodes[b.nodeId].level() ? 1 : -1; }).forEach(({nodeId, resourceId, start}) => { // Add or subtract a concurrency point based on whether the event // starts or ends concurrencies[resourceId] += start ? -1 : 1; // If the event is starting, but there are no concurrency points // available, mark the node and resource inputs as insufficient if (concurrencies[resourceId] < 0 && start) { const node = nodes[nodeId]; const nodeElement = document.getElementById(nodeId); const resourceCells = nodeElement.querySelectorAll('.node-resources td'); // Find the input node offset for the resource name (index) and // value(index + 1) const index = Object.keys(node.resources).indexOf(resourceId) * 2; resourceCells[index].classList.add('red'); resourceCells[index+1].classList.add('red'); nodeElement.classList.add('red'); if (resourceCells[index].title) { resourceCells[index].title = resourceCells[index + 1].title += ' and concurrency'; } else { resourceCells[index].title = resourceCells[index + 1].title = 'Insufficient concurrency'; } } }); } /** * Calculate node colors for started projects. */ recalculateDateAdvancement() { if (!this.isStarted) { return; } // Get today's date without the time component const now = this.getDate(); for (const nodeId in this.nodes) { const node = this.nodes[nodeId].node; node.classList.remove('node-past'); node.classList.remove('node-upcoming'); node.classList.remove('node-current'); const dates = this.nodes[nodeId].dateInputs; const start = this.getDate(dates[0].value); const end = this.getDate(dates[1].value); if (now > end) { node.classList.add('node-past'); } else if (now < start) { node.classList.add('node-upcoming'); } else { node.classList.add('node-current'); } } } /** * Calculates the resources cost until a provided date. * @param {String} date * @returns {Object} */ costUntil(date) { let resourcesSpent = {}; for (const nodeId in this.nodes) { if (this.nodes[nodeId].configData.from > date) { continue; } resourcesSpent = PERT.sumObjects(resourcesSpent, this.nodes[nodeId].cost()); } return resourcesSpent; } /** * Redraws the cumulative resource cost statistics for the supplied node or * until the project end. * @param {String} [nodeId] */ redrawStats(nodeId) { const stats = nodeId ? this.nodes[nodeId].cost(true) : this.costUntil(this.config.get('end')); const resources = this.config.get('resources'); const statArea = PERT.ui('menu-contents-project').querySelector('.project-stats'); const rows = []; if (nodeId) { const node = this.nodes[nodeId]; const nodes = [node, ...node.getNeighbours(true, true)]; const until = node.config.get('end') || node.dateInputs[1].min; let from = ''; for (const node of nodes) { const min = node.config.get('start') || node.dateInputs[0].max; if (!from || from > min) { from = min; } } rows.push(['Name', node.config.get('name')]); if (from) { rows.push(['From', from]); } if (until) { rows.push(['Until', until]); } if (from && until) { rows.push(['Duration', `${Math.round((this.getDate(until) - this.getDate(from)) / 86400000)} days`]); } rows.push(['Milestones', nodes.length]); } else { const until = this.config.get('end') || this.dates[1].min; let from = this.config.get('start') || this.dates[0].max; for (const key in this.nodes) { const min = this.nodes[key].config.get('start') || this.nodes[key].dateInputs[0].max; if (!from || from > min) { from = min; } } rows.push(['Name', 'Whole project']); if (from) { rows.push(['From', from]); } if (until) { rows.push(['Until', until]); } if (from && until) { rows.push(['Duration', `${(this.getDate(until) - this.getDate(from)) / 86400000} days`]); } rows.push(['Milestones', Object.keys(this.nodes).length]); } for (const key in stats) { rows.push([resources[key].name, stats[key]]); } statArea.innerHTML = ''; rows.forEach(row => { const rowElement = document.createElement('tr'); row.map(text => { const td = document.createElement('td'); td.innerText = text; return td; }).forEach(td => rowElement.appendChild(td)); statArea.appendChild(rowElement); }); } /** * Redraws all requirement changes since the project was started. */ generateRequirementChanges() { if (!this.isStarted) { return; } const config = this.configData; const now = this.getDate(); const output = { project: [], resources: [], nodes: {} }; // Project dates const projectStartOffset = (this.getDate(config.start) - this.getDate(config.original.start)) / 86400000; const projectEndOffset = (this.getDate(config.end) - this.getDate(config.original.end)) / 86400000; const projectDuration = projectEndOffset - projectStartOffset; const projectOffset = projectDuration === 0 ? projectStartOffset : 0; if (projectOffset) { output.project.push(`Shifted ${projectOffset > 0 ? 'forward' : 'back'} by ${Math.abs(projectOffset)} days`); } else { if (projectStartOffset !== 0) { const text = `${Math.abs(projectStartOffset)} days`; if (now >= this.getDate(config.start)) { output.project.push(`Started ${text} ${projectStartOffset > 0 ? 'late' : 'ahead of time'}`); } else { output.project.push(`Start shifted ${projectStartOffset > 0 ? 'forward' : 'back'} by ${text}`); } } if (projectEndOffset !== 0) { const text = `${Math.abs(projectEndOffset)} days`; if (now >= this.getDate(config.end)) { output.project.push(`Finished ${text} ${projectEndOffset > 0 ? 'late' : 'ahead of time'}`); } else { output.project.push(`End shifted ${projectEndOffset > 0 ? 'forward' : 'back'} by ${text}`); } } } if (projectDuration !== 0) { const text = `${Math.abs(projectDuration)} days`; if (now >= this.getDate(config.end)) { output.project.push(`Completed ${text} ${projectDuration > 0 ? 'late' : 'ahead of time'}`); } else { output.project.push(`Duration ${projectDuration > 0 ? 'in' : 'de'}creased by ${text}`); } } // Project resources for (const key in config.original.resources) { const original = config.original.resources[key]; if (!(key in config.resources)) { output.resources.push(`'${original.name}' deleted`); continue; } const current = config.resources[key]; const name = original.name; if (original.name !== name) { output.resources.push(`'${name}' renamed to '${current.name}'`); } const a = current.amount - original.amount; if (a !== 0) { output.resources.push(`'${name}' amount ${a > 0 ? 'in' : 'de'}creased by ${Math.abs(a)}'`); } const b = current.concurrency - original.concurrency; if (b !== 0) { if (!current.concurrency) { output.resources.push(`'${name}' concurrency constraint removed`); } else if (!original.concurrency) { output.resources.push(`'${name}' concurrency set to ${current.concurrency}`); } else { output.resources.push(`'${name}' concurrency ${b > 0 ? 'in' : 'de'}creased by ${Math.abs(b)}'`); } } } for (const key in config.resources) { if (!(key in config.original.resources)) { output.resources.push(`'${config.resources[key].name}' added`); } } // Nodes const resourceDiff = {}; const nodes = config.nodes; const originalNodes = config.original.nodes; for (const key in nodes) { output.nodes[key] = []; if (!(key in originalNodes)) { output.nodes[key].push('Created'); for (const rKey in nodes[key].resources) { if (!(rKey in config.original.resources) || !nodes[key].resources[rKey]) { continue; } if (rKey in resourceDiff) { resourceDiff[rKey] += nodes[key].resources[rKey]; } else { resourceDiff[rKey] = nodes[key].resources[rKey]; } } } } for (const key in originalNodes) { const original = originalNodes[key]; if (!(key in nodes)) { output.nodes[key] = ['Deleted']; for (const rKey in originalNodes[key].resources) { if (!(rKey in config.resources) || !originalNodes[key].resources[rKey]) { continue; } if (rKey in resourceDiff) { resourceDiff[rKey] -= originalNodes[key].resources[rKey]; } else { resourceDiff[rKey] = -originalNodes[key].resources[rKey]; } } continue; } const current = nodes[key]; const name = original.name; if (current.name !== name) { output.nodes[key].push(`Renamed to '${current.name}'`); } if (original.critical !== current.critical) { output.nodes[key].push(`Set ${current.critical ? 'critical' : 'not critical'}`); } const start = (this.getDate(current.start) - this.getDate(original.start)) / 86400000; const end = (this.getDate(current.end) - this.getDate(original.end)) / 86400000; const duration = end - start; const offset = duration === 0 ? start : 0; if (offset) { const text = `${Math.abs(offset)} days`; output.nodes[key].push(`Shifted ${offset > 0 ? 'forward' : 'back'} by ${text}`); } else { if (start !== 0) { const text = `${Math.abs(start)} days`; if (now >= this.getDate(current.start)) { output.nodes[key].push(`Started ${text} ${start > 0 ? 'late' : 'ahead of time'}`); } else { output.nodes[key].push(`Start shifted ${start > 0 ? 'forward' : 'back'} by ${text}`); } } if (end !== 0) { const text = `${Math.abs(end)} days`; if (now >= this.getDate(current.end)) { output.nodes[key].push(`Finished ${text} ${end > 0 ? 'late' : 'ahead of time'}`); } else { output.nodes[key].push(`'End shifted ${end > 0 ? 'forward' : 'back'} by ${text}`); } } } if (duration !== 0) { const text = `${Math.abs(duration)} days`; if (now >= this.getDate(current.end)) { output.nodes[key].push(`Completed ${text} ${duration > 0 ? 'late' : 'ahead of time'}`); } else { output.nodes[key].push(`Duration ${duration > 0 ? 'in' : 'de'}creased by ${text}`); } } for (const rKey in current.resources) { if (rKey in original.resources && current.resources[rKey] !== original.resources[rKey]) { const text = `resource '${config.resources[rKey].name}'`; const diff = current.resources[rKey] - original.resources[rKey]; resourceDiff[rKey] = rKey in resourceDiff ? resourceDiff[rKey] + diff : diff; if (now >= this.getDate(current.end)) { output.nodes[key].push(`'Took ${Math.abs(diff)} ${diff > 0 ? 'more' : 'less'} of ${text}`); } else { output.nodes[key].push(`${diff > 0 ? 'In' : 'De'}creased ${text} by ${Math.abs(diff)}`); } } } } // Total resources for (const key in resourceDiff) { const diff = resourceDiff[key]; const name = config.resources[key].name; output.project.push(`Total for '${name}' ${diff > 0 ? 'in' : 'de'}creased by ${Math.abs(diff)}`); } // Edges const findEdge = (x, c) => Object.keys(c).findIndex(k => c[k].from === x.from && c[k].to === x.to) !== -1; for (const key in config.original.edges) { const edge = config.original.edges[key]; if (findEdge(edge, config.edges) || !(edge.from in nodes) || !(edge.to in nodes)) { continue; } output.nodes[edge.from].push(`Connection to '${nodes[edge.to].name}' severed`); } for (const key in config.edges) { const edge = config.edges[key]; if (findEdge(edge, config.original.edges) || !(edge.from in originalNodes) || !(edge.to in originalNodes)) { continue; } output.nodes[edge.from].push(`Connected to '${nodes[edge.to].name}'`); } // Update requirement changes const popup = PERT.template('PopupTemplate'); const report = PERT.template('ReportTemplate'); const okText = `Everything ${now >= this.getDate(config.end) ? 'went' : 'is going'} according to plan`; report.querySelector('h1').innerText = this.name; report.querySelector('.project-report-project').innerText = output.project.join('\n') || okText; report.querySelector('.project-report-resources').innerText = output.resources.join('\n') || okText; const nodesReport = report.querySelector('.project-report-nodes'); let changed = false; for (const key in output.nodes) { if (!output.nodes[key].length) { continue; } changed = true; const h3 = document.createElement('h3'); h3.innerHTML = key in config.original.nodes ? config.original.nodes[key].name : config.nodes[key].name; const p = document.createElement('p'); p.innerHTML = output.nodes[key].join('\n'); nodesReport.appendChild(h3); nodesReport.appendChild(p); } if (!changed) { nodesReport.innerText = okText; } popup.querySelector('.popup-content').appendChild(report); popup.querySelector('.popup-background').addEventListener('click', () => popup.parentNode.removeChild(popup)); document.body.appendChild(popup); } /** * Automatically migrates the provided configuration to the latest version. * @param {DataStore} config * @returns {DataStore} */ static migrate(config) { switch (config.get('version')) { case PERT.version: // Nothing to do here break; case 1: config.set('timezone', 0); config.set('version', PERT.version); break; default: // Default configuration for new projects Object.assign(config.getData(), { resources: {}, nodes: {}, edges: {}, stats: { accessedAt: null, modifiedAt: null, createdAt: Date.now() }, start: '', end: '', timezone: 0, version: PERT.version }); } return config; } /** * A wrapper around PERT.getDate(), that injects the project's timezone into * the arguments. * @param {String} [from=''] * @param {Boolean} [time=false] * @returns {Date} */ getDate(from, time) { return PERT.getDate(this.config.get('timezone'), from, time); } };
var userData = require("../userData.json"); var status = require("../status.json"); exports.getLoginData = function(req, res) { res.json(userData['loginData']); }; exports.login = function(req, res) { var username = req.query.username; var password = req.query.password; var arr = userData["loginData"]; var validLogin = false; var userType, name, image, friends, courses; for(var i=0;i<arr.length;i++) { var obj = arr[i]; var uname, pw, type, nam, img, fr, crs; for(var key in obj) { var attrName = key; var attrValue = obj[key]; if(attrName == "username") { uname=attrValue; } if(attrName == "password") { pw=attrValue; } if(attrName == "type") { type=attrValue; } if(attrName == "name") { nam=attrValue; } if(attrName == "image") { img=attrValue; } if(attrName == "friends") { fr=attrValue; } if(attrName == "courses") { crs=attrValue; } } if(uname == username && pw == password) { validLogin=true; userType=type; name=nam; image=img; courses=crs; friends=fr; } } if(validLogin) { status["loginStatus"]["loggedIn"]="true"; status["loginStatus"]["name"]=name; status["loginStatus"]["username"]=username; status["loginStatus"]["userType"]=userType; status["loginStatus"]["image"]=image; status["loginStatus"]["friends"]=friends; status["loginStatus"]["courses"]=courses; status["loginStatus"]["questionNumber"]=0; status["loginStatus"]["score"]=0; status["loginStatus"]["totalScore"]=0; status["loginStatus"]["opponentScore"]=0; if(userType=="student") { res.redirect('/student'); } if(userType=="instructor") { res.redirect('/instructor'); } } else { status["loginStatus"]["loggedIn"]="false"; status["loginStatus"]["name"]=""; status["loginStatus"]["username"]=""; status["loginStatus"]["userType"]=""; status["loginStatus"]["image"]=""; status["loginStatus"]["friends"]=[]; status["loginStatus"]["courses"]=[]; status["loginStatus"]["currentCourseID"]=""; status["loginStatus"]["currentCourseName"]=""; status["loginStatus"]["action"]=""; status["loginStatus"]["questionNumber"]=0; status["loginStatus"]["score"]=0; status["loginStatus"]["totalScore"]=0; status["loginStatus"]["opponentScore"]=0; res.redirect('/'); } /*data["friends"].push({name: req.query.name, description: req.query.description, imageURL: 'http://lorempixel.com/400/400/people'});*/ };
module.exports = { entry: './frontend/App.jsx', output: { path: __dirname + '/src/main/resources/public/js', filename: 'core.js' }, resolve: { extensions: ['*', '.js', '.jsx'] }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /(node_modules|bower_components)/, use: ['babel-loader'] } ] } };
module.exports = { enforceOptions : { _name : '严格选项', bitwise : { def : true, note : '禁止使用位运算符[]' }, camelcase : { def : true, note : '强制所有变量使用驼峰或UPPER_CASE命名风格' }, curly : { def : true, note : '循环或条件区块不能省略花括号' }, eqeqeq : { def : true, note : '必须使用全等(===或!==)' }, es3 : { def : true, note : '代码遵循的ECMAScript3规范' }, es5 : { def : true, note : '代码遵循ECMAScript5.1规范' }, forin : { def : true, note : '需要过滤对象继承属性,使用hasOwnProperty' }, freeze : { def : true, note : '禁止复写原生对象(如Array, Date)的原型' }, funcscope : { def : true, note : '当变量定义在区块内部,而在外部被访问时,不发出警告' }, globalstrict : { def : true, note : '在全局严格模式下,不发出警告' }, immed : { def : true, note : '需要用括号包裹立即调用函数' }, iterator : { def : true, note : '使用`__iterator__`属性时,不发出警告' }, latedef : { def : false, note : '变量定义之前禁止使用' }, newcap : { def : true, note : '构造函数名首字母必须大写' }, noarg : { def : true, note : '禁止使用`arguments.caller`和`arguments.callee`' }, nocomma : { def : true, note : '禁止使用逗号运算符' }, noempty : { def : true, note : '警告出现的空代码块' }, nonbsp : { def : true, note : '警告使用特殊的字符' }, nonew : { def : true, note : '禁止将构造函数当成普通函数使用' }, notypeof : { def : true, note : '使用无效的typeof运算符时,不发出警告' }, // // shadow // singleGroups undef : { def : true, note : '禁止使用不在全局变量列表中的未定义的变量' }, unused : { def : true, note : '禁止定义变量却不使用' } }, relaxOptions : { _name : '宽松选项', asi : { def : true, note : '允许省略分号' }, boss : { def : true, note : '允许在if/for/while语句中使用赋值' }, debug : { def : true, note : '允许debugger语句' }, eqnull : { def : true, note : '允许`===null`比较' }, esnext : { def : true, note : '允许ECMAScript6规范' }, evil : { def : true, note : '允许使用eval' }, expr : { def : true, note : '允许应该出现赋值或函数调用的地方使用表达式' }, lastsemic : { def : true, note : '允许单行控制块省略分号' }, laxbreak : { def : true, note : '允许不安全的行中断(与laxcomma配合使用)' }, laxcomma : { def : true, note : '允许逗号开头的编码样式' }, loopfunc : { def : true, note : '允许循环中定义函数' }, multistr : { def : true, note : '允许多行字符串' }, noyield : { def : true, note : '允许发生器中没有yield语句' }, plusplus : { def : true, note : '禁止使用++和–-' }, proto : { def : true, note : '允许使用__proto__' }, scripturl : { def : true, note : '允许使用scripturl,像这样`javascript:...`' }, strict : { def : true, note : '强制使用ES5的严格模式' }, sub : { def : true, note : '允许类似person[\'name\']的用法' }, supernew : { def : true, note : '允许`new function() {…}`和`new Object;`' }, validthis : { def : true, note : '允许严格模式下在非构造函数中使用this' }, withstmt : { def : true, note : '允许使用with语句' } }, inputOptions : { _name : '设定选项', globals : { note : '预设全局变量(多个之间逗号分割)', def : '' }, indent : { note : '代码缩进宽度', def : '4' }, quotmark : { note : '代码统一引号(double/single/false)', def : 'single' } } };
/** * @Author : Stanislav Kabin <[email protected]> * @GitHub : https://github.com/in-the-beam/lib-appjs-v4 * @License : MIT */ jQuery( function () { /****************************************************************************************************************** * ALERTS *****************************************************************************************************************/ jQuery( '#alert_danger' ).click( function ( e ) { e.preventDefault(); window.App.alert.show( { type : 'danger', title : 'Custom title', content: 'Custom message', events : { show : function () { console.log( 'LOCAL show' ); }, shown: function ( this_id ) { console.log( 'LOCAL shown', this_id ); } } } ); return false; } ); jQuery( '#alert_warning' ).click( function ( e ) { e.preventDefault(); window.App.alert.show( { type : 'warning', content: 'Custom message', events : { show : function () { console.log( 'LOCAL show' ); }, shown: function ( this_id ) { console.log( 'LOCAL shown', this_id ); } } } ); } ); jQuery( '#alert_success' ).click( function ( e ) { e.preventDefault(); window.App.alert.show( { type : 'success', title : 'Custom title', content: 'Custom message', events : { show : function () { console.log( 'LOCAL show' ); }, shown: function ( this_id ) { console.log( 'LOCAL shown', this_id ); } } } ); } ); jQuery( '#alert_info' ).click( function ( e ) { e.preventDefault(); window.App.alert.show( { type : 'info', title : 'Custom title', content: 'Custom message', events : { show : function () { console.log( 'LOCAL show' ); }, shown: function ( this_id ) { console.log( 'LOCAL shown', this_id ); } } } ); } ); jQuery( '#alert_default' ).click( function ( e ) { e.preventDefault(); window.App.alert.show( { type : 'default', icon : 'fa fa-user-circle-o', title : 'Complex demo', content: 'This demo contains a custom icon, title and have a callback on click', events : { dismissAlert: function () { console.log( 'onetime dismissAlert' ); // DO NOT USE stopPropagation or preventDefault HERE window.App.alert.show( { type : 'success', content: 'You clicked "Complex demo" Alert<br />This is infinite alert :)', icon : 'fa fa-check-circle' } ); }, show : function () { console.log( 'LOCAL show' ); }, shown : function ( this_id ) { console.log( 'LOCAL shown', this_id ); } } } ); } ); jQuery( '#alert_ndismiss' ).click( function ( e ) { e.preventDefault(); window.App.alert.show( { type : 'success', content : 'This is non-dismissable alert with a long text', dismissable: false, closebutton: true } ); } ); /****************************************************************************************************************** * DIALOGS *****************************************************************************************************************/ jQuery( '#dialog_1' ).click( function ( e ) { e.preventDefault(); let dialogId = window.App.dialog.show( { title : 'Simple dialog with default behaviour', size : 'lg', content: 'Simple Dialog in 4 lines!<p class="code">window.App.dialog.show( {\n' + '\ttitle : [ String | HTML | jQuery Object ],\n' + '\tcontent: [ String | HTML | jQuery Object ]\n' + '} );</p>' } ); } ); jQuery( '#dialog_2' ).click( function ( e ) { e.preventDefault(); let dialogId = window.App.dialog.show( { title : 'Custom button with default behaviour', content: '<p>OK button have an default end-behaviour (forced to dismiss an dialog)</p>', buttons: { ok: window.App.dialog.buttons().button( { title : 'OK, click Me!', // title dismissable: true, // force to dismiss dialog on click this button css : 'btn-danger', // css class for button icon : 'fa fa-check fa-lg', // custom icon for button callback : function () // what to do when clicked - callback { window.App.alert.show( { type : 'success', content: 'You just clicked "OK, click Me!" button' } ); } } ) } } ); } ); jQuery( '#dialog_3' ).click( function ( e ) { e.preventDefault(); let dialogId = window.App.dialog.show( { title : 'Combine default and custom button with own behaviour', content: '<p>Button cancel have a default behaviour ( close an dialog )</p><p>OK button have a custom behavior (call Alert) with default end-behaviour (forced to dismiss an dialog)</p>', size : 'lg', // lg|large|sm|small|undefined buttons: { cancel: window.App.dialog.buttons().cancel(), ok : window.App.dialog.buttons().button( { title : 'OK, click Me!', // title dismissable: false, // force to dismiss dialog on click this button css : 'btn-danger', // css class for button icon : 'fa fa-check fa-lg', // custom icon for button callback : function () // what to do when clicked - callback { window.App.alert.show( { type : 'error', content: 'You just clicked "OK, click Me!" button' } ); } } ) } } ); } ); jQuery( '#dialog_4' ).click( function ( e ) { e.preventDefault(); let dialogId = window.App.dialog.show( { title : 'Complex dialog', content: '<p>Dialog uses an Request extension to get content from the backend.</p><p>OK button will send form data to the backend and show via Alerts returned result.</p>', size : 'lg', // lg|large|sm|small|undefined buttons: { ok: window.App.dialog.buttons().button( { title : 'OK, send data!', // title css : 'btn-danger', // css class for button icon : 'fa fa-envelope', // custom icon for button callback: function () // what to do when clicked - callback { /** * @param request_status - request status * @param request_result - returned json data from backend */ let request_callback = function ( request_status, request_result ) { // if all good if ( request_status === true ) { window.App.alert.show( { type : 'success', content: 'You just send data.<br />And backend result is:<br /><strong>' + (request_result.data !== undefined ? request_result.data : 'no data') + '</strong>' } ); } else { window.App.alert.show( { type : 'danger', content: 'You just send data.<br />Error has occur. See console for details' } ); console.dir( 'ERROR:', request_result ); } }; window.App.request.send( { a: 1, b: 'c' }, request_callback, 'src/demo_dialog_4.json' ); } } ) } } ); } ); jQuery( '#dialog_5' ).click( function ( e ) { e.preventDefault(); let dialogId = window.App.dialog.show( { title : 'This is initial Title', content: '<p>This is initial content</p>', size : 'lg', // lg|large|sm|small|undefined events : { shown: function () { setTimeout( function () { window.App.dialog.hookSetTitle( 'new Title' ); window.App.dialog.hookSetContent( 'after 3 seconds we call hook to change the title and content' ); }, 3000 ); } } } ); } ); /****************************************************************************************************************** * REQUESTS *****************************************************************************************************************/ let request_callback_demo = function ( request_status, request_result ) { if ( request_status === true ) { switch ( request_result.status ) { case true: console.log( '========================================' ); console.log( 'APPLICATION LAYERS:' ); console.log( ' SERVER STATUS:', request_status ); console.log( ' BACKEND STATUS:', request_result.status, '(returned status inside response: request_result.status)' ); console.log( 'DATA:' ); console.log( request_result ); console.log( '========================================' ); break; case false: console.error( '========================================' ); console.error( 'APPLICATION LAYERS:' ); console.error( ' SERVER STATUS:', request_status ); console.error( ' BACKEND STATUS:', request_result.status, '(returned status inside response: request_result.status)' ); console.error( 'DATA:' ); console.error( request_result ); console.error( '========================================' ); break; default: console.error( '========================================' ); console.error( 'ERROR', 'WRONG RESPONSE (format {"status":boolean,"data":mixed})' ); console.error( '========================================' ); } } else { console.error( 'STATUS:', request_status, 'ERROR:', request_result ); } }; jQuery( '#request_1' ).click( function ( e ) { e.preventDefault(); window.App.request.send( { a: 1, b: 'c' }, request_callback_demo, 'src/demo_request_1.json' ); } ); jQuery( '#request_2' ).click( function ( e ) { e.preventDefault(); window.App.request.send( { a: 1, b: 'c' }, request_callback_demo, 'src/demo_request_2.json' ); } ); jQuery( '#request_3' ).click( function ( e ) { e.preventDefault(); window.App.request.send( { a: 1, b: 'c' }, request_callback_demo, 'src/demo_request_3.json' ); } ); jQuery( '#request_4' ).click( function ( e ) { e.preventDefault(); window.App.request.send( { a: 1, b: 'c' }, request_callback_demo, 'src/demo_request_4.json' ); } ); jQuery( '#request_5' ).click( function ( e ) { e.preventDefault(); window.App.request.send( { a: 1, b: 'c' }, request_callback_demo, 'src/demo_request_5.json' ); } ); } );
// The WEBSOCKET server and port the bot should connect to. // Most of the time this isn't the same as the URL, check the `Request URL` of // the websocket. // If you really don't know how to do this... Run `node getserver.js URL`. // Fill in the URL of the client where `URL` is. // For example: `node getserver.js http://example-server.psim.us/` exports.server = 'lotus.kota.moe'; exports.port = 80; // This is the server id. // To know this one, you should check where the AJAX call 'goes' to when you // log in. // For example, on the Smogon server, it will say somewhere in the URL // ~~showdown, meaning that the server id is 'showdown'. // If you really don't know how to check this... run the said script above. exports.serverid = 'eos'; // The nick and password to log in with // If no password is required, leave pass empty exports.nick = 'Feather Bot'; exports.pass = 'milkdrink'; // The rooms that should be joined. // Joining Smogon's Showdown's Lobby is not allowed. exports.rooms = ['feather league']; // Any private rooms that should be joined. // Private rooms will be moderated differently (since /warn doesn't work in them). // The bot will also avoid leaking the private rooms through .seen exports.privaterooms = ['']; // The character text should start with to be seen as a command. // Note that using / and ! might be 'dangerous' since these are used in // Showdown itself. // Using only alphanumeric characters and spaces is not allowed. exports.commandcharacter = '#'; // The default rank is the minimum rank that can use a command in a room when // no rank is specified in settings.json exports.defaultrank = '+'; // Whether this file should be watched for changes or not. // If you change this option, the server has to be restarted in order for it to // take effect. exports.watchconfig = true; // Secondary websocket protocols should be defined here, however, Showdown // doesn't support that yet, so it's best to leave this empty. exports.secprotocols = []; // What should be logged? // 0 = error, ok, info, debug, recv, send // 1 = error, ok, info, debug, cmdr, send // 2 = error, ok, info, debug (recommended for development) // 3 = error, ok, info (recommended for production) // 4 = error, ok // 5 = error exports.debuglevel = 3; // Users who can use all commands regardless of their rank. Be very cautious // with this, especially on servers other than main. exports.excepts = []; // Whitelisted users are those who the bot will not enforce moderation for. exports.whitelist = ['Thimo', 'Feather Overseer', 'Feather Pharrell', 'Feather Suspense', 'Feather Thimo', 'Feather Bot']; // Add a link to the help for the bot here. When there is a link here, .help and .guide // will link to it. exports.botguide = 'http://pastebin.com/dHSXtU08'; // This allows the bot to act as an automated moderator. If enabled, the bot will // mute users who send 6 lines or more in 6 or fewer seconds for 7 minutes. NOTE: THIS IS // BY NO MEANS A PERFECT MODERATOR OR SCRIPT. It is a bot and so cannot think for itself or // exercise moderator discretion. In addition, it currently uses a very simple method of // determining who to mute and so may miss people who should be muted, or mute those who // shouldn't. Use with caution. exports.allowmute = true; // The punishment values system allows you to customise how you want the bot to deal with // rulebreakers. Spamming has a points value of 2, all caps has a points value of 1, etc. exports.punishvals = { 1: 'warn', 2: 'mute', 3: 'hourmute', 4: 'roomban', 5: 'ban' };
const gulp = require('gulp'); const {src, tmp} = require('./helper/dir'); const gulpLoadPlugins = require('gulp-load-plugins'); const $ = gulpLoadPlugins(); // Copy unoptimized images in dev mode const imagecopy = () => gulp.src(src('img/**/*', '!img/icons/**/*.svg')) .pipe(gulp.dest(tmp('img'))) .pipe($.size({title: 'imageCopy'})); // Optimize images const imagemin = () => gulp.src(src('img/**/*', '!img/icons/**/*.svg')) .pipe($.cache($.imagemin())) .pipe(gulp.dest(tmp('img'))) .pipe($.size({title: 'imagemin'})); // Generate SVG sprite const svgstore = () => gulp.src(src('img/icons/**/*.svg')) .pipe($.imagemin([$.imagemin.svgo({ plugins: [ {removeViewBox: false}, {removeUselessStrokeAndFill: false}, {cleanupIDs: false} ] })])) .pipe($.svgstore()) .pipe(gulp.dest(tmp('img'))) .pipe($.size({title: 'svgstore'})); module.exports = { imagecopy, imagemin, svgstore };
import React from 'react'; import PropTypes from 'prop-types'; import { hot } from 'react-hot-loader'; import { ConnectedRouter } from 'react-router-redux'; import routes from './routes'; import './styles/base.less'; const AppHost = ({ history }) => <ConnectedRouter history={history}>{routes}</ConnectedRouter>; AppHost.propTypes = { history: PropTypes.shape().isRequired, }; export default hot(module)(AppHost);
const Utils = require('../utils'); const {HooParser} = require('../grammar/HooParser'); const HooDefs = require('../hoodefs'); const PrimaryExprHandler = require('./primaryexprhandler'); let FuncCallHandler = {}; FuncCallHandler.handleFunctionCallExpression = function(node) { if(Utils.handleException(node)) { return; } let ast = {}; ast.kind = HooDefs.expression.EXPR_FUNC_CALL; ast.reference = node.children[0].getText(); ast.arguments = []; if(2 < node.children.length) { let args = node.children[2]; if(!(args instanceof HooParser.Func_argsContext)) { throw new Error('Invalid function invokation.'); } for(let index = 0; index < args.children.length; index++) { if(0 != (index % 2)) { continue; } let arg = args.children[index]; if(!(arg instanceof HooParser.Func_argContext)) { throw new Error('Invalid function argument.'); } let expression = arg.children[0]; if(!(expression instanceof HooParser.ExpressionContext)) { throw new Error('Function argument must be an expression.'); } let rawexpr = expression.children[0]; if(rawexpr instanceof HooParser.Primay_expressionContext) { let pexpr = PrimaryExprHandler.handlePrimaryExpression(rawexpr); if(pexpr) { ast.arguments.push(pexpr); } } } } return ast; }; FuncCallHandler.handleFunctionCallStatement = function(node) { if(Utils.handleException(node)) { return; } if(node.children[0] instanceof HooParser.Expr_func_callContext) { let ast = {}; ast.kind = HooDefs.statement.STMT_FUNC_CALL; ast.expression = FuncCallHandler.handleFunctionCallExpression(node.children[0]); return ast; } else { throw new Error('Invalid function call statement.'); } } module.exports = FuncCallHandler;
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router, Route, Redirect, IndexRoute, browserHistory } from 'react-router'; require('./css/main.css'); require('../../node_modules/quill/dist/quill.snow.css'); require('sweetalert/dist/sweetalert.css'); import store from './store/store'; import App from './components/App'; import UserApp from './components/UserApp'; import Post from './components/Post'; import NewsPage from './components/NewsPage'; import SinglePostPage from './components/SinglePostPage'; //Editors access import Feed from './components/Feed'; import ListFeeds from './components/ListFeeds'; //Admin access import AdminPage from './components/AdminPage'; const AppRoute = () => ( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={App}> <Route component={UserApp}> <IndexRoute component={NewsPage}/> <Route path="news/:postId" component={SinglePostPage} /> <Route path="news/:postId/edit" component={Post} onEnter={requireAuth}/> <Route path="post" component={Post} onEnter={requireAuth}/> </Route> <Route path="feeds" component={ListFeeds} onEnter={requireAuth}/> <Route path="feed" component={Feed} onEnter={requireAuth}/> <Route path="feed/:feedId/edit" component={Feed} onEnter={requireAuth}/> <Route path="admin" component={AdminPage} onEnter={requireAuth}/> <Redirect from="*" to="/" /> </Route> </Router> </Provider> ); function requireAuth(nextState, replace) { if (!store.getState().signedIn) { replace({ pathname: '/', state: { nextPathname: nextState.location.pathname } }); } } ReactDOM.render(<AppRoute/>, document.getElementById('root'));
(function($) { /* * Simulate drag of a JQuery UI sortable list * Repository: https://github.com/mattheworiordan/jquery.simulate.drag-sortable.js * Author: http://mattheworiordan.com * * options are: * - move: move item up (positive) or down (negative) by Integer amount * - dropOn: move item to a new linked list, move option now represents position in the new list (zero indexed) * - handle: selector for the draggable handle element (optional) * - listItem: selector to limit which sibling items can be used for reordering * - placeHolder: if a placeholder is used during dragging, we need to consider it's height * - tolerance: (optional) number of pixels to overlap by instead of the default 50% of the element height * */ $.fn.simulateDragSortable = function(options) { // build main options before element iteration var opts = $.extend({}, $.fn.simulateDragSortable.defaults, options); applyDrag = function(options) { // allow for a drag handle if item is not draggable var that = this, options = options || opts, // default to plugin opts unless options explicitly provided handle = options.handle ? $(this).find(options.handle)[0] : $(this)[0], listItem = options.listItem, placeHolder = options.placeHolder, sibling = $(this), moveCounter = Math.floor(options.move), direction = moveCounter > 0 ? 'down' : 'up', moveVerticalAmount = 0, initialVerticalPosition = 0, extraDrag = !isNaN(parseInt(options.tolerance, 10)) ? function() { return Number(options.tolerance); } : function(obj) { return ($(obj).outerHeight() / 2) + 5; }, dragPastBy = 0, // represents the additional amount one drags past an element and bounce back dropOn = options.dropOn ? $(options.dropOn) : false, center = findCenter(handle), x = Math.floor(center.x), y = Math.floor(center.y), mouseUpAfter = (opts.debug ? 2500 : 10); if (dropOn) { if (dropOn.length === 0) { if (console && console.log) { console.log('simulate.drag-sortable.js ERROR: Drop on target could not be found'); console.log(options.dropOn); } return; } sibling = dropOn.find('>*:last'); moveCounter = -(dropOn.find('>*').length + 1) + (moveCounter + 1); // calculate length of list after this move, use moveCounter as a positive index position in list to reverse back up if (dropOn.offset().top - $(this).offset().top < 0) { // moving to a list above this list, so move to just above top of last item (tried moving to top but JQuery UI wouldn't bite) initialVerticalPosition = sibling.offset().top - $(this).offset().top - extraDrag(this); } else { // moving to a list below this list, so move to bottom and work up (JQuery UI does not trigger new list below unless you move past top item first) initialVerticalPosition = sibling.offset().top - $(this).offset().top - $(this).height(); } } else if (moveCounter === 0) { if (console && console.log) { console.log('simulate.drag-sortable.js WARNING: Drag with move set to zero has no effect'); } return; } else { while (moveCounter !== 0) { if (direction === 'down') { if (sibling.next(listItem).length) { sibling = sibling.next(listItem); moveVerticalAmount += sibling.outerHeight(); } moveCounter -= 1; } else { if (sibling.prev(listItem).length) { sibling = sibling.prev(listItem); moveVerticalAmount -= sibling.outerHeight(); } moveCounter += 1; } } } dispatchEvent(handle, 'mousedown', createEvent('mousedown', handle, { clientX: x, clientY: y })); // simulate drag start dispatchEvent(document, 'mousemove', createEvent('mousemove', document, { clientX: x+1, clientY: y+1 })); if (dropOn) { // jump to top or bottom of new list but do it in increments so that JQuery UI registers the drag events slideUpTo(x, y, initialVerticalPosition); // reset y position to top or bottom of list and move from there y += initialVerticalPosition; // now call regular shift/down in a list options = jQuery.extend(options, { move: moveCounter }); delete options.dropOn; // add some delays to allow JQuery UI to catch up setTimeout(function() { dispatchEvent(document, 'mousemove', createEvent('mousemove', document, { clientX: x, clientY: y })); }, 5); setTimeout(function() { dispatchEvent(handle, 'mouseup', createEvent('mouseup', handle, { clientX: x, clientY: y })); setTimeout(function() { if (options.move) { applyDrag.call(that, options); } }, 5); }, mouseUpAfter); // stop execution as applyDrag has been called again return; } // Sortable is using a fixed height placeholder meaning items jump up and down as you drag variable height items into fixed height placeholder placeHolder = placeHolder && $(this).parent().find(placeHolder); if (!placeHolder && (direction === 'down')) { // need to move at least as far as this item and or the last sibling if ($(this).outerHeight() > $(sibling).outerHeight()) { moveVerticalAmount += $(this).outerHeight() - $(sibling).outerHeight(); } moveVerticalAmount += extraDrag(sibling); dragPastBy += extraDrag(sibling); } else if (direction === 'up') { // move a little extra to ensure item clips into next position moveVerticalAmount -= Math.max(extraDrag(this), 5); } else if (direction === 'down') { // moving down with a place holder if (placeHolder.height() < $(this).height()) { moveVerticalAmount += Math.max(placeHolder.height(), 5); } else { moveVerticalAmount += extraDrag(sibling); } } if (sibling[0] !== $(this)[0]) { // step through so that the UI controller can determine when to show the placeHolder slideUpTo(x, y, moveVerticalAmount, dragPastBy); } else { if (window.console) { console.log('simulate.drag-sortable.js WARNING: Could not move as at top or bottom already'); } } setTimeout(function() { dispatchEvent(document, 'mousemove', createEvent('mousemove', document, { clientX: x, clientY: y + moveVerticalAmount })); }, 5); setTimeout(function() { dispatchEvent(handle, 'mouseup', createEvent('mouseup', handle, { clientX: x, clientY: y + moveVerticalAmount })); }, mouseUpAfter); }; // iterate and move each matched element return this.each(applyDrag); }; // fire mouse events, go half way, then the next half, so small mouse movements near target and big at the start function slideUpTo(x, y, targetOffset, goPastBy) { var moveBy, offset; if (!goPastBy) { goPastBy = 0; } if ((targetOffset < 0) && (goPastBy > 0)) { goPastBy = -goPastBy; } // ensure go past is in the direction as often passed in from object height so always positive // go forwards including goPastBy for (offset = 0; Math.abs(offset) + 1 < Math.abs(targetOffset + goPastBy); offset += ((targetOffset + goPastBy - offset)/2) ) { dispatchEvent(document, 'mousemove', createEvent('mousemove', document, { clientX: x, clientY: y + Math.ceil(offset) })); } offset = targetOffset + goPastBy; dispatchEvent(document, 'mousemove', createEvent('mousemove', document, { clientX: x, clientY: y + offset })); // now bounce back for (; Math.abs(offset) - 1 >= Math.abs(targetOffset); offset += ((targetOffset - offset)/2) ) { dispatchEvent(document, 'mousemove', createEvent('mousemove', document, { clientX: x, clientY: y + Math.ceil(offset) })); } dispatchEvent(document, 'mousemove', createEvent('mousemove', document, { clientX: x, clientY: y + targetOffset })); } function createEvent(type, target, options) { var evt; var e = $.extend({ target: target, preventDefault: function() { }, stopImmediatePropagation: function() { }, stopPropagation: function() { }, isPropagationStopped: function() { return true; }, isImmediatePropagationStopped: function() { return true; }, isDefaultPrevented: function() { return true; }, bubbles: true, cancelable: (type != "mousemove"), view: window, detail: 0, screenX: 0, screenY: 0, clientX: 0, clientY: 0, ctrlKey: false, altKey: false, shiftKey: false, metaKey: false, button: 0, relatedTarget: undefined }, options || {}); if ($.isFunction(document.createEvent)) { evt = document.createEvent("MouseEvents"); evt.initMouseEvent(type, e.bubbles, e.cancelable, e.view, e.detail, e.screenX, e.screenY, e.clientX, e.clientY, e.ctrlKey, e.altKey, e.shiftKey, e.metaKey, e.button, e.relatedTarget || document.body.parentNode); } else if (document.createEventObject) { evt = document.createEventObject(); $.extend(evt, e); evt.button = { 0:1, 1:4, 2:2 }[evt.button] || evt.button; } return evt; } function dispatchEvent(el, type, evt) { if (el.dispatchEvent) { el.dispatchEvent(evt); } else if (el.fireEvent) { el.fireEvent('on' + type, evt); } return evt; } function findCenter(el) { var elm = $(el), o = elm.offset(); return { x: o.left + elm.outerWidth() / 2, y: o.top + elm.outerHeight() / 2 }; } // // plugin defaults // $.fn.simulateDragSortable.defaults = { move: 0 }; })(jQuery);
var Members = function(elem) { this.elem = elem; this.memberList = {}; this.numMembers = 0; }; Members.prototype.list = function() { return this.memberList; } Members.prototype.length = function() { console.log("Number of members: " + String(this.numMembers)); return this.numMembers; } Members.prototype.addMembers = function(members) { for (var ndx = 0; ndx < members.length; ndx++) { this.addMember(members[ndx]); } } Members.prototype.addMember = function(member) { console.log("Adding a new member."); if (this.memberList[member.id]) { return; } this.numMembers = this.numMembers + 1; this.memberList[member.id] = member; this.createHTML(); }; Members.prototype.removeMember = function(id) { console.log("Removing member with id: " + id); if (this.memberList[id]) { delete this.memberList[id]; this.numMembers = this.numMembers - 1; this.createHTML(); } }; Members.prototype.createHTML = function() { console.log("Rendering members HTML"); var elem = this.elem; elem.empty(); $.each(this.memberList, function(ndx, member) { var memberHTML = '<span class="selected-member" data-member-id="' + member.id + '">' + '<button class="btn btn-default" style="margin: 3px;" onclick="mem.removeMember(' + member.id + ');">' + member.value + '</button>' + '</span>' + '<br />'; elem.append(memberHTML); }); };
import Ember from 'ember'; export default Ember.Route.extend({ model: function(params) { return this.store.find('person', { name: params.person_name}) .then(function(persons) { return persons.get('firstObject'); }); } });
const path = require('path'); module.exports = { entry: './src/index.js', output: { path: path.join(__dirname, 'dist'), filename: 'bundle.js' }, devtool: 'source-map', devServer: { port: 80, publicPath: '/dist/' } };
import Ember from 'ember'; var $ = Ember.$; export default Ember.Controller.extend({ needs: ['flash'], flashBinding: 'controllers.flash', defaultTitle: "Classroom", init: function() { this.setDefaultTitle(); return this.createLinkElement(); }, setDefaultTitle: function() { return this.set('title', this.get('defaultTitle')); }, titleDidChange: (function() { return document.title = this.get('title'); }).observes('title'), createLinkElement: function() { this.set('linkElement', $("<link rel='stylesheet' class='theme-link'></link>")); return $('head').append(this.get('linkElement')); }, setThemeUrl: function(url) { return this.get('linkElement').attr('href', url); } });
/******************************/ /* DATA TASKS /******************************/ const gulp = require('gulp'); const replace = require('gulp-replace'); const runSequence = require('run-sequence'); var replaceRegexp = /tmp\/semantic-ui-modified/g; var replaceWith = 'lib/semantic-ui'; gulp.task('data:definitions-json', function() { return gulp.src(info.semantic.dest.allDefinitionsFiles) .pipe(require('gulp-filelist')('definitions.json')) .pipe(replace(replaceRegexp, replaceWith)) .pipe(gulp.dest('./tmp/data')); }); gulp.task('data:themes-json', function() { return gulp.src(info.semantic.dest.allThemesFiles) .pipe(require('gulp-filelist')('themes.json')) .pipe(replace(replaceRegexp, replaceWith)) .pipe(gulp.dest('./tmp/data')); }); gulp.task('data:sites-json', function() { return gulp.src(info.semantic.dest.allSitesFiles) .pipe(require('gulp-filelist')('sites.json')) .pipe(replace(replaceRegexp, replaceWith)) .pipe(gulp.dest('./tmp/data')); }); gulp.task('data', function(callback) { var tasks = [ 'data:definitions-json', 'data:themes-json', 'data:sites-json', callback ]; runSequence.apply(this, tasks); });
define(['lib/stapes', 'lib/tinycolor', 'utils/Tools'], function (Stapes, Tinycolor, tools) { 'use strict'; var timer; function showMessageField (text, type) { var dom, wrapper; dom = document.querySelector('.work .msg'); if (!dom) { dom = document.createElement('div'); dom.classList.add('msg'); dom.classList.add(type); wrapper = document.createElement('div'); wrapper.classList.add('wrapper_msg'); wrapper.classList.add('invisible'); wrapper.appendChild(dom); document.querySelector('.work').appendChild(wrapper); setTimeout(function () { wrapper.classList.remove('invisible'); }, 0); } if (!dom.classList.contains(type)) { dom.className = 'msg'; dom.classList.add(type); } dom.innerHTML = text; if (timer) { clearTimeout(timer); } timer = setTimeout(function () { var error = document.querySelector('.work .wrapper_msg'); if (error) { error.parentNode.removeChild(error); } }, 1600); } return Stapes.subclass(/** @lends MainView.prototype*/{ pointer: null, colorpicker: null, slider: null, sliderinput: null, cpradius: 0, cpcenter: 0, drag: false, color: null, brightness: 1.0, inputbox: null, /** * @class MainView * @construct * @fires barClick * @fires colorChange */ constructor: function () { this.pointer = document.querySelector('#colorpicker #pointer'); this.colorpicker = document.querySelector('#colorpicker #colorwheelbg'); this.slider = document.querySelector('.slider'); this.sliderinput = document.querySelector('.slider input'); this.inputbox = document.querySelector('#color input.value'); this.cpradius = this.colorpicker.offsetWidth / 2; this.cpcenter = this.colorpicker.offsetLeft + this.cpradius; this.bindEventHandlers(); window.dispatchEvent(new Event('resize')); }, /** * @private */ bindEventHandlers: function () { var cptouchrect; window.addEventListener('resize', function () { var attrW, attrH, side, w = this.colorpicker.parentNode.clientWidth, h = this.colorpicker.parentNode.clientHeight; attrW = this.colorpicker.getAttribute('width'); attrH = this.colorpicker.getAttribute('height'); side = attrW === 'auto' ? attrH : attrW; if (w > h) { if (attrH !== side) { this.colorpicker.setAttribute('height', side); this.colorpicker.setAttribute('width', 'auto'); } } else if (attrW !== side){ this.colorpicker.setAttribute('height', 'auto'); this.colorpicker.setAttribute('width', side); } this.cpradius = this.colorpicker.offsetWidth / 2; this.cpcenter = this.colorpicker.offsetLeft + this.cpradius; if (this.color) { this.updatePointer(); } }.bind(this)); window.addClickHandler(document.querySelector('.footer'), function (event) { this.emit('barClick', event.target.parentNode.dataset.area); }.bind(this)); this.sliderinput.addEventListener('input', function (event) { this.leaveInput(); this.brightness = parseFloat(event.target.value); this.updateInput(); this.fireColorEvent(); }.bind(this), false); this.inputbox.addEventListener('input', function (event) { var bright, rgb = new Tinycolor(event.target.value).toRgb(); if (rgb.r === 0 && rgb.g === 0 && rgb.b === 0) { this.brightness = 0; this.color = new Tinycolor({r: 0xff, g: 0xff, b: 0xff}); } else { bright = Math.max(rgb.r, rgb.g, rgb.b) / 256; rgb.r = Math.round(rgb.r / bright); rgb.g = Math.round(rgb.g / bright); rgb.b = Math.round(rgb.b / bright); this.brightness = bright; this.color = new Tinycolor(rgb); } this.fireColorEvent(); this.updatePointer(); this.updateSlider(); }.bind(this), false); this.inputbox.addEventListener('keydown', function (event) { switch (event.keyCode) { case 8: case 9: case 16: case 37: case 38: case 46: break; default: { if (event.target.value.length >= 6 && (event.target.selectionEnd - event.target.selectionStart) === 0) { event.preventDefault(); event.stopPropagation(); } else if (event.keyCode < 48 || event.keyCode > 71) { event.preventDefault(); event.stopPropagation(); } } } }); cptouchrect = document.querySelector('#colorpicker .touchrect'); window.addPointerDownHandler(cptouchrect, function (event) { this.leaveInput(); this.drag = true; this.handleEvent(event); }.bind(this)); window.addPointerMoveHandler(cptouchrect, function (event) { if (this.drag) { this.handleEvent(event); } }.bind(this)); window.addPointerUpHandler(cptouchrect, function () { this.drag = false; }.bind(this)); window.addClickHandler(document.querySelector('#clear_button'), function () { this.emit('clear'); }.bind(this)); window.addClickHandler(document.querySelector('#clearall_button'), function () { this.emit('clearall'); }.bind(this)); }, /** * @private * @param event */ handleEvent: function (event) { var point, x, y; if (event.touches) { x = event.touches[0].clientX; y = event.touches[0].clientY; } else { x = event.clientX; y = event.clientY; } point = this.getCirclePoint(x, y); this.color = this.getColorFromPoint(point); this.updatePointer(); this.updateSlider(); this.updateInput(); this.fireColorEvent(); }, /** * @private * @param {number} x * @param {number} y * @returns {{x: number, y: number}} */ getCirclePoint: function (x, y) { var p = {x: x, y: y}, c = { x: this.colorpicker.offsetLeft + this.cpradius, y: this.colorpicker.offsetTop + this.cpradius }, n; n = Math.sqrt(Math.pow((x - c.x), 2) + Math.pow((y - c.y), 2)); if (n > this.cpradius) { p.x = (c.x) + this.cpradius * ((x - c.x) / n); p.y = (c.y) + this.cpradius * ((y - c.y) / n); } return p; }, /** * @private * @param {{x: number, y: number}} p * @returns {Tinycolor} */ getColorFromPoint: function (p) { var h, t, s, x, y; x = p.x - this.colorpicker.offsetLeft - this.cpradius; y = this.cpradius - p.y + this.colorpicker.offsetTop; t = Math.atan2(y, x); h = (t * (180 / Math.PI) + 360) % 360; s = Math.min(Math.sqrt(x * x + y * y) / this.cpradius, 1); return new Tinycolor({h: h, s: s, v: 1}); }, /** * @private * @param color * @returns {{x: number, y: number}} */ getPointFromColor: function (color) { var t, x, y, p = {}; t = color.h * (Math.PI / 180); y = Math.sin(t) * this.cpradius * color.s; x = Math.cos(t) * this.cpradius * color.s; p.x = Math.round(x + this.colorpicker.offsetLeft + this.cpradius); p.y = Math.round(this.cpradius - y + this.colorpicker.offsetTop); return p; }, /** * @private */ fireColorEvent: function () { var rgb = this.color.toRgb(); rgb.r = Math.round(rgb.r * this.brightness); rgb.g = Math.round(rgb.g * this.brightness); rgb.b = Math.round(rgb.b * this.brightness); this.emit('colorChange', rgb); }, /** * * @param rgb */ setColor: function (rgb) { var bright; if (rgb.r === 0 && rgb.g === 0 && rgb.b === 0) { this.brightness = 0; this.color = new Tinycolor({r: 0xff, g: 0xff, b: 0xff}); } else { bright = Math.max(rgb.r, rgb.g, rgb.b) / 256; rgb.r = Math.round(rgb.r / bright); rgb.g = Math.round(rgb.g / bright); rgb.b = Math.round(rgb.b / bright); this.brightness = bright; this.color = new Tinycolor(rgb); } this.updatePointer(); this.updateSlider(); this.updateInput(); }, /** * @private */ updateSlider: function () { this.sliderinput.value = this.brightness; this.slider.style.backgroundImage = '-webkit-linear-gradient(left, #000000 0%, ' + this.color.toHexString() + ' 100%)'; }, /** * @private */ updatePointer: function () { var point = this.getPointFromColor(this.color.toHsv()); this.pointer.style.left = (point.x - this.pointer.offsetWidth / 2) + 'px'; this.pointer.style.top = (point.y - this.pointer.offsetHeight / 2) + 'px'; this.pointer.style.backgroundColor = this.color.toHexString(); }, /** * @private */ updateInput: function () { var rgb = this.color.toRgb(); rgb.r = Math.round(rgb.r * this.brightness); rgb.g = Math.round(rgb.g * this.brightness); rgb.b = Math.round(rgb.b * this.brightness); this.inputbox.value = tools.b2hexstr(rgb.r) + tools.b2hexstr(rgb.g) + tools.b2hexstr(rgb.b); }, /** * Scroll to the specific tab content * @param {string} id - Id of the tab to scroll to */ scrollToArea: function (id) { var area, index; document.querySelector('.footer .selected').classList.remove('selected'); document.querySelector('.footer .button[data-area =' + id + ']').classList.add('selected'); area = document.getElementById(id); index = area.offsetLeft / area.clientWidth; area.parentNode.style.left = -index * 100 + '%'; }, /** * Shows a status message * @param {string} message - Text to show */ showStatus: function (message) { showMessageField(message, 'status'); }, /** * Shows the error text * @param {string} error - Error message */ showError: function (error) { showMessageField(error, 'error'); }, /** * @private */ leaveInput: function () { this.inputbox.blur(); } }); });
Hoodie.extend(function(hoodie) { hoodie.goodreads = {}; hoodie.goodreads.getinfo = hoodie.task('goodreadsgetinfo').start; });
import fs from 'fs'; import Boom from 'boom'; import path from 'path'; import Router from 'koa-router'; import logger from '../logger'; import checkRole from '../middleware/checkRole'; import checkAccess from '../middleware/checkAccess'; import checkAuthentication from '../middleware/checkAuthentication'; import filterRequestByAccess from '../middleware/filterRequestByAccess'; const defaultAccessControl = { authenticated: false, check: true, filter: true, }; /** * This will setup the modules defined and setup their routing. * * @param {object} app */ export default (app) => { logger.debug('[Module] Setting up'); // get all files in the directory const filesInDir = fs.readdirSync(__dirname); // then find all the directories const directories = filesInDir.filter((dir) => fs.statSync(path.join(__dirname, dir)).isDirectory()); directories.forEach((dir) => { logger.debug(`[Module][${dir}] Setting up module`); const { routes, baseUrl, paramResolver, middleware = [] } = require(path.join(__dirname, dir, '/router.js')); const instance = new Router({ prefix: baseUrl }); instance.use(...middleware); // filter routes and just get ones marked as active (default is true) const activeRoutes = routes.filter(({ active = true }) => active); activeRoutes.forEach((config) => { const { route, method, handler, middleware: routeMiddleware = [], afterMiddleware: afterRouteMiddleware = [], } = config; const accessControl = { ...defaultAccessControl, ...config.accessControl, }; const methods = Array.isArray(method) ? method : [method]; const shouldCheck = accessControl.check && accessControl.resource; const shouldFilter = accessControl.filter && accessControl.resource; const paramResolverMiddleware = paramResolver; const accessControlCheckAuthenticationMiddleware = accessControl.authenticated && checkAuthentication; const accessControlCheckRoleMiddleware = accessControl.role && checkRole(accessControl.role); const accessControlCheckMiddleware = shouldCheck && checkAccess(accessControl); const accessControlPreFilterMiddleware = shouldFilter && filterRequestByAccess; methods.forEach((httpMethod) => { logger.debug(`[Module][${dir}][${httpMethod.toUpperCase()} ${baseUrl}${route}] Setting up route`); const middlewareToRun = [ accessControlCheckAuthenticationMiddleware, accessControlCheckRoleMiddleware, accessControlCheckMiddleware, paramResolverMiddleware, ...routeMiddleware, accessControlPreFilterMiddleware, async (ctx, next) => { await handler(ctx, next); return next(); }, ...afterRouteMiddleware, ].filter(Boolean); instance[httpMethod](route, ...middlewareToRun); }); }); app.use(instance.routes()); app.use( instance.allowedMethods({ throw: true, notImplemented: () => Boom.notImplemented(), methodNotAllowed: () => Boom.methodNotAllowed(), }) ); }); logger.debug('[Module] Finished setting up'); };
'use strict' var Boom = require('boom') module.exports = { auth: { strategy: 'jwt', scope: ['individual'] }, jsonp: 'callback', handler (request, reply) { global.ABIBAO.services.domain.execute('query', 'authentificationGlobalInformationsQuery', request.auth.credentials) .then(function (user) { reply(user) }) .catch(function (error) { reply(Boom.badRequest(error)) }) } }
/** * 校验工具集 * @author Brian Li * @email [email protected] * @version 0.0.2.1 * @note * 此工具集被src\mixins\InputWidget.js使用 */ define(function (require) { return { /** * 校验配置工厂。如果传入字符串,尝试用JSON.parse将字符串转成对象,否则什么都不做。 * @interface validationFactory * @param {Object|String} validations 校验配置 * @return {Object} 校验机对象 */ validationFactory: function (validations) { if (typeof validations !== 'string') return validations || {}; var result = {}; try { result = JSON.parse(validations); } catch (e) { console.error(e); } return result; }, /** * 检查input组件的外层表单实例上有没有某个方法 * @interface isCallbackExist * @param {ReactComponent} me Input类型组件,这种类型的组件引入的InputWidget mixin * @param {String} callback 方法名称 * @return {Boolean} 检查结果,input组件外层没有form或input组件没有配置name属性或form中没有命为callback的方法,都返回false */ isCallbackExist: function (me, callback) { var name = me.props.name; var form = me.context.___form___; if ( typeof name !== 'string' || name.length === 0 || typeof form !== 'object' || typeof form[callback] !== 'function' ) { return false; } return true; }, /** * 校验准则工厂 * @interface rulesFactory * @param {ReactComponent} me Input类型组件 * @param {String|Array.<String>} rules 校验名称集 * @return {Array.<String>} 校验机中存在的校验准则序列,rules中存在但组件校验机中不存在的准则名称将被过滤 */ rulesFactory: function (me, rules) { var result = []; var validations = me.___validations___; if (typeof rules === 'string') { rules = [rules]; } if (rules instanceof Array) { for (var i = 0; i < rules.length; i++) { var rule = rules[i]; if (validations.hasOwnProperty(rule)) result.push(rule); } } else { for (var key in validations) { if (validations.hasOwnProperty(key)) result.push(key); } } return result; } }; });
require( [ "jquery", "hbs!./templates/index_template", "hbs!./templates/login_template", "bacon", "lodash", "flot", "flot-resize" ], function($, indexT, loginT) { var rawData = [] var includedIndexByStartDay = [] var includedIndexByPace = [] var excludedIndexByStartDay = [] var excludedIndexByPace = [] doPlot() var restHR = 50 inputValue($('#rest_hr')).debounce(500).onValue(function(val) { restHR = val reCalculateData() }) var maxPace = 6.25 inputValue($('#slowest')).debounce(500).onValue(function(val) { maxPace = val reCalculateData() }) var minHR = 100 inputValue($('#hr_min')).debounce(500).onValue(function(val) { minHR = val reCalculateData() }) var maxHR = 100 inputValue($('#hr_max')).debounce(500).onValue(function(val) { maxHR = val reCalculateData() }) var userE = getJsonE('/rest/user') userE.onValue(function() { var dataE = Bacon.fromArray([1,2,3,4,5,6,7,8,9,10]) .flatMap(function(page) { return Bacon.retry({ source: function() { return getJsonE('/rest/runs/' + page) }, retries: 5 }) }) .flatMap(function(runs) { return Bacon.fromArray(runs) }) .flatMap(function(run_id) { return Bacon.retry({ source: function() { return getJsonE('/rest/laps/' + run_id) }, retries: 5 }) }) .flatMap(function(laps) { return Bacon.fromArray(laps) }) dataE .onValue(function(lap) { rawData.push(lap) }) dataE.throttle(250).onValue(function() { reCalculateData() }) dataE.take(1).onValue(function() { $('#header').html('<h4>Etenem&auml; v0.1</h4>') }) dataE.onError(function(e) { $('#header').html('<h4>Etenem&auml; v0.1 - virhe, pahoittelut! Yrit&auml; my&ouml;hemmin uudelleen</h4>') console.log('error: ' + JSON.stringify(e)) }) }) userE.onError(function(e) { $('#header').html('<h4>Etenem&auml; v0.1 - kirjaudu sis&auml;&auml;n</h4>') $('#login').empty().append(loginT()) }) function reCalculateData() { lapsInRange = _.filter(rawData, lapDataInRanges) lapsOutOfRange = _.filter(rawData, lapDataNotInRanges) includedIndexByStartDay = _.map(lapsInRange, calcIndexByStartDay) includedIndexByPace = _.map(lapsInRange, calcIndexByPacePair) excludedIndexByStartDay = _.map(lapsOutOfRange, calcIndexByStartDay) excludedIndexByPace = _.map(lapsOutOfRange, calcIndexByPacePair) doPlot() function calcIndexByPacePair(lap) { return [pace(lap), lap.distance / (lap.elapsed_time * (lap.average_heartrate - restHR))] } function calcIndexByStartDay(lap) { return [lap.start_time, lap.distance / (lap.elapsed_time * (lap.average_heartrate - restHR))] } function lapDataInRanges(lap) { return pace(lap) <= maxPace && lap.average_heartrate >= minHR && lap.average_heartrate <= maxHR } function lapDataNotInRanges(lap) { return !lapDataInRanges(lap) } function pace(lap) { return lap.distance > 0.0 ? (lap.elapsed_time / lap.distance) * 1000 : 0 } } function inputValue($input) { function value() { return $input.val() } return $input.asEventStream("input change").map(value).toProperty(value()) } function getJsonE(url) { return Bacon.fromPromise($.ajax({url: url, dataType: 'json', timeout: 10000})) } function doPlot() { function cross(ctx, x, y, radius, shadow) { var size = radius * Math.sqrt(Math.PI) / 2; ctx.moveTo(x - size, y - size); ctx.lineTo(x + size, y + size); ctx.moveTo(x - size, y + size); ctx.lineTo(x + size, y - size); } function doPlotHistory() { $.plot($("#historyplot"), [ {color: "rgb(200, 200, 200)", data: excludedIndexByStartDay}, {color: "rgb(255, 000, 000)", data: includedIndexByStartDay} ], { yaxis: { max: 5, min: 0 }, xaxis: { minTickSize: 1 }, series: { points: { show: true, symbol: cross } } }) } function doPlotPaceVsIndex() { $.plot($('#pacevsindexplot'), [ {color: "rgb(200, 200, 200)", data: excludedIndexByPace}, {color: "rgb(255, 000, 000)", data: includedIndexByPace} ], { yaxis: { max: 5, min: 0 }, xaxis: { min: 1.75, max: maxPace, minTickSize: 0.25 }, series: { points: { show: true, symbol: cross } } }) } doPlotPaceVsIndex() doPlotHistory() } } )
$(document).ready(function() { var context_select = $('#rule_context_id')[0]; if(context_select){ $(context_select).change(function(){ var context_id = $('#rule_context_id')[0].value; var request = $.ajax({ url: BASE_URL + "/contexts/" + context_id + "/variables" , type: "GET", dataType: "html" }); request.done(function(msg) { $("#available_variables").html( msg ); }); }); if(context_select.value){ $(context_select).change(); } } });
version https://git-lfs.github.com/spec/v1 oid sha256:b5098e3da4636aa63a715190fa65c3867ea3f773a8bdcff7d9c09e9d6bdc0ebf size 6770
joo.classLoader.prepare("package flash.errors",/* {*/ /** * An EOFError exception is thrown when you attempt to read past the end of the available data. For example, an EOFError is thrown when one of the read methods in the IDataInput interface is called and there is insufficient data to satisfy the read request. * <p><a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/errors/EOFError.html#includeExamplesSummary">View the examples</a></p> * @see flash.utils.ByteArray * @see flash.utils.IDataInput * @see flash.net.Socket * @see flash.net.URLStream * @see http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7ecc.html Working with the debugger versions of Flash runtimes * @see http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7ece.html Comparing the Error classes * @see http://help.adobe.com/en_US/as3/dev/WS5b3ccc516d4fbf351e63e3d118a9b90204-7eb1.html flash.error package Error classes * */ "public dynamic class EOFError extends flash.errors.IOError",3,function($$private){;return[ /** * Creates a new EOFError object. * @param message A string associated with the error object. * */ "public function EOFError",function EOFError$(message/*:String = ""*/) {if(arguments.length<1){message = "";} flash.errors.IOError.call(this,message); }, ];},[],["flash.errors.IOError"], "0.8.0", "0.9.6" );
joo.classLoader.prepare("package flash.text",/* {*/ /** * The CSMSettings class contains properties for use with the <code>TextRenderer.setAdvancedAntiAliasingTable()</code> method to provide continuous stroke modulation (CSM). CSM is the continuous modulation of both stroke weight and edge sharpness. * @see TextRenderer#setAdvancedAntiAliasingTable() * */ "public final class CSMSettings",1,function($$private){;return[ /** * The size, in pixels, for which the settings apply. * <p>The <code>advancedAntiAliasingTable</code> array passed to the <code>setAdvancedAntiAliasingTable()</code> method can contain multiple entries that specify CSM settings for different font sizes. Using this property, you can specify the font size to which the other settings apply.</p> * @see TextRenderer#setAdvancedAntiAliasingTable() * */ "public var",{ fontSize/*:Number*/:NaN}, /** * The inside cutoff value, above which densities are set to a maximum density value (such as 255). * @see TextRenderer#setAdvancedAntiAliasingTable() * */ "public var",{ insideCutoff/*:Number*/:NaN}, /** * The outside cutoff value, below which densities are set to zero. * @see TextRenderer#setAdvancedAntiAliasingTable() * */ "public var",{ outsideCutoff/*:Number*/:NaN}, /** * Creates a new CSMSettings object which stores stroke values for custom anti-aliasing settings. * @param fontSize The size, in pixels, for which the settings apply. * @param insideCutoff The inside cutoff value, above which densities are set to a maximum density value (such as 255). * @param outsideCutoff The outside cutoff value, below which densities are set to zero. * */ "public function CSMSettings",function CSMSettings$(fontSize/*:Number*/, insideCutoff/*:Number*/, outsideCutoff/*:Number*/) { throw new Error('not implemented'); // TODO: implement! }, ];},[],["Error"], "0.8.0", "0.9.6" );
/** * Copyright 2018-present Tuan Le. * * Licensed under the MIT License. * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *------------------------------------------------------------------------ * * @module TapeTestRunnerComposite * @description - A tape test runner composite for test agent. * * @author Tuan Le ([email protected]) * * @flow */ 'use strict'; // eslint-disable-line import testRunner from 'tape'; import { ENV, isFunction, isSchema, log } from '../../utils/common-util'; import Composite from '../../../src/composite'; export default Composite({ template: { /** * @description - Initialized and check that factory is valid for this composite. * * @method $initTapeTestRunnerComposite * @return void */ $initTapeTestRunnerComposite () { const tAgent = this; if (ENV.DEVELOPMENT) { if (!isSchema({ name: `string`, type: `string`, addUnitTest: `function` }).of(tAgent) || tAgent.type !== `test-agent`) { log(`error`, `TapeTestRunnerComposite.$init - Test agent is invalid. Cannot apply composite.`); } } }, /** * @description - Perform unit testing... * * @method verify * @param {string} description * @param {function} tester * @return void */ verify (description = ``, tester) { const tAgent = this; if (ENV.DEVELOPMENT) { if (!isFunction(tester)) { log(`error`, `TapeTestRunnerComposite.verify - Input tester function is invalid.`); } } tAgent.addUnitTest((end) => { if (ENV.DEVELOPMENT) { if (!isFunction(end)) { log(`error`, `TapeTestRunnerComposite.verify - Input unit test end function is invalid.`); } } testRunner(description, ((assert) => { tester(assert, end); })); }); } } });
apiready = function(){ var header = document.querySelector('#header'); $api.fixStatusBar(header); getbingpic(); }; function getbingpic(){ var connectionType = api.connectionType; api.imageCache({ url: 'https://img.1cf.co/bing.png', thumbnail:true }, function(ret, err){ if( ret.status='true' ){ var bingpic = ret.url; document.getElementById("bingpic").innerHTML = "<img src=\"" + bingpic + "\" style=\"width:100%;\"></img>"; //document.getElementById("bingpicinfo").innerHTML = "加载中......"; }else{ ; } }); if(connectionType != 'none'){ api.ajax({ url: 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN', method: 'post' },function(ret, err){ if (ret) { var bingpicinfo = ret.images[0].copyright; document.getElementById("bingpicinfo").innerHTML = bingpicinfo; } else { document.getElementById("bingpic").innerHTML = "<img src=\"" + "../image/bing.png" + "\" style=\"width:100%;\"></img>"; } }); } } function info(){ var connectionType = api.connectionType; if(connectionType != 'none'){ api.ajax({ url: 'http://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mkt=zh-CN', method: 'post' },function(ret, err){ if (ret) { var bingpicinfo = ret.images[0].copyright; api.alert({ title: '今日必应™美图', msg: bingpicinfo + "\n\n必应™美图所有图片版权均归属原作者所有。", }); } else { api.alert({ title: '今日必应™美图', msg: "必应™美图所有图片版权均归属原作者所有。", }); } }); }else{ api.alert({ title: '今日必应™美图', msg: "必应™美图所有图片版权均归属原作者所有。", }); } } function personal(){ api.alert({ title: '个人中心', msg: "建设中......", }); }
var expect = require('expect.js'); var smarketComponent = require('../smarketcomponent'); describe('smarket-component', function() { it('normal usage', function() { }); });
var data = {about: {}};
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.returnExports = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * @file Cross-browser array-like slicer. * @version 1.1.0 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module array-like-slice-x */ 'use strict'; var toObject = _dereq_('to-object-x'); var toInteger = _dereq_('to-integer-x'); var toLength = _dereq_('to-length-x'); var isUndefined = _dereq_('validate.io-undefined'); var splitIfBoxedBug = _dereq_('split-if-boxed-bug-x'); var setRelative = function _setRelative(value, length) { return value < 0 ? Math.max(length + value, 0) : Math.min(value, length); }; /** * The slice() method returns a shallow copy of a portion of an array into a new * array object selected from begin to end (end not included). The original * array will not be modified. * * @param {!Object} argsObject - The `arguments` to slice. * @param {number} [start] - Zero-based index at which to begin extraction. * A negative index can be used, indicating an offset from the end of the * sequence. slice(-2) extracts the last two elements in the sequence. * If begin is undefined, slice begins from index 0. * @param {number} [end] - Zero-based index before which to end extraction. * Slice extracts up to but not including end. For example, slice([0,1,2,3,4],1,4) * extracts the second element through the fourth element (elements indexed * 1, 2, and 3). * A negative index can be used, indicating an offset from the end of the * sequence. slice(2,-1) extracts the third element through the second-to-last * element in the sequence. * If end is omitted, slice extracts through the end of the sequence (arr.length). * If end is greater than the length of the sequence, slice extracts through * the end of the sequence (arr.length). * @returns {Array} A new array containing the extracted elements. * @example * var arrayLikeSlice = require('array-like-slice-x'); * var args = (function () { return arguments; * }('Banana', 'Orange', 'Lemon', 'Apple', 'Mango')); * * var citrus = arrayLikeSlice(args, 1, 3); * * // args contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] * // citrus contains ['Orange','Lemon'] */ module.exports = function slice(arrayLike, start, end) { var iterable = splitIfBoxedBug(toObject(arrayLike)); var length = toLength(iterable.length); var k = setRelative(toInteger(start), length); var relativeEnd = isUndefined(end) ? length : toInteger(end); var finalEnd = setRelative(relativeEnd, length); var val = []; val.length = Math.max(finalEnd - k, 0); var next = 0; while (k < finalEnd) { if (k in iterable) { val[next] = iterable[k]; } next += 1; k += 1; } return val; }; },{"split-if-boxed-bug-x":19,"to-integer-x":20,"to-length-x":21,"to-object-x":23,"validate.io-undefined":30}],2:[function(_dereq_,module,exports){ /** * @file Check support of by-index access of string characters. * @version 1.0.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module has-boxed-string-x */ 'use strict'; var boxedString = Object('a'); /** * Check failure of by-index access of string characters (IE < 9) * and failure of `0 in boxedString` (Rhino). * * `true` if no failure; otherwise `false`. * * @type boolean */ module.exports = boxedString[0] === 'a' && (0 in boxedString); },{}],3:[function(_dereq_,module,exports){ /** * @file Tests if ES6 Symbol is supported. * @version 1.4.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module has-symbol-support-x */ 'use strict'; /** * Indicates if `Symbol`exists and creates the correct type. * `true`, if it exists and creates the correct type, otherwise `false`. * * @type boolean */ module.exports = typeof Symbol === 'function' && typeof Symbol('') === 'symbol'; },{}],4:[function(_dereq_,module,exports){ /** * @file Tests if ES6 @@toStringTag is supported. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-@@tostringtag|26.3.1 @@toStringTag} * @version 1.4.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module has-to-string-tag-x */ 'use strict'; /** * Indicates if `Symbol.toStringTag`exists and is the correct type. * `true`, if it exists and is the correct type, otherwise `false`. * * @type boolean */ module.exports = _dereq_('has-symbol-support-x') && typeof Symbol.toStringTag === 'symbol'; },{"has-symbol-support-x":3}],5:[function(_dereq_,module,exports){ 'use strict'; var getDay = Date.prototype.getDay; var tryDateObject = function tryDateObject(value) { try { getDay.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var dateClass = '[object Date]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isDateObject(value) { if (typeof value !== 'object' || value === null) { return false; } return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; }; },{}],6:[function(_dereq_,module,exports){ /** * @file ES6-compliant shim for Number.isFinite. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-number.isfinite|20.1.2.2 Number.isFinite ( number )} * @version 3.0.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module is-finite-x */ 'use strict'; var numberIsNaN = _dereq_('is-nan-x'); var inf = 1 / 0; var negInf = 1 / -0; /** * This method determines whether the passed value is a finite number. * * @param {*} number - The value to be tested for finiteness. * @returns {boolean} A Boolean indicating whether or not the given value is a finite number. * @example * var numIsFinite = require('is-finite-x'); * * numIsFinite(Infinity); // false * numIsFinite(NaN); // false * numIsFinite(-Infinity); // false * * numIsFinite(0); // true * numIsFinite(2e64); // true * * numIsFinite('0'); // false, would've been true with * // global isFinite('0') * numIsFinite(null); // false, would've been true with */ module.exports = function isFinite(number) { return typeof number === 'number' && numberIsNaN(number) === false && number !== inf && number !== negInf; }; },{"is-nan-x":8}],7:[function(_dereq_,module,exports){ /** * @file Determine whether a given value is a function object. * @version 3.1.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module is-function-x */ 'use strict'; var fToString = Function.prototype.toString; var toStringTag = _dereq_('to-string-tag-x'); var hasToStringTag = _dereq_('has-to-string-tag-x'); var isPrimitive = _dereq_('is-primitive'); var normalise = _dereq_('normalize-space-x'); var deComment = _dereq_('replace-comments-x'); var funcTag = '[object Function]'; var genTag = '[object GeneratorFunction]'; var asyncTag = '[object AsyncFunction]'; var hasNativeClass = true; try { // eslint-disable-next-line no-new-func Function('"use strict"; return class My {};')(); } catch (ignore) { hasNativeClass = false; } var ctrRx = /^class /; var isES6ClassFn = function isES6ClassFunc(value) { try { return ctrRx.test(normalise(deComment(fToString.call(value), ' '))); } catch (ignore) {} // not a function return false; }; /** * Checks if `value` is classified as a `Function` object. * * @private * @param {*} value - The value to check. * @param {boolean} allowClass - Whether to filter ES6 classes. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. */ var tryFuncToString = function funcToString(value, allowClass) { try { if (hasNativeClass && allowClass === false && isES6ClassFn(value)) { return false; } fToString.call(value); return true; } catch (ignore) {} return false; }; /** * Checks if `value` is classified as a `Function` object. * * @param {*} value - The value to check. * @param {boolean} [allowClass=false] - Whether to filter ES6 classes. * @returns {boolean} Returns `true` if `value` is correctly classified, * else `false`. * @example * var isFunction = require('is-function-x'); * * isFunction(); // false * isFunction(Number.MIN_VALUE); // false * isFunction('abc'); // false * isFunction(true); // false * isFunction({ name: 'abc' }); // false * isFunction(function () {}); // true * isFunction(new Function ()); // true * isFunction(function* test1() {}); // true * isFunction(function test2(a, b) {}); // true * isFunction(async function test3() {}); // true * isFunction(class Test {}); // false * isFunction(class Test {}, true); // true * isFunction((x, y) => {return this;}); // true */ module.exports = function isFunction(value) { if (isPrimitive(value)) { return false; } var allowClass = arguments.length > 0 ? Boolean(arguments[1]) : false; if (hasToStringTag) { return tryFuncToString(value, allowClass); } if (hasNativeClass && allowClass === false && isES6ClassFn(value)) { return false; } var strTag = toStringTag(value); return strTag === funcTag || strTag === genTag || strTag === asyncTag; }; },{"has-to-string-tag-x":4,"is-primitive":10,"normalize-space-x":16,"replace-comments-x":17,"to-string-tag-x":25}],8:[function(_dereq_,module,exports){ /** * @file ES6-compliant shim for Number.isNaN - the global isNaN returns false positives. * @version 1.0.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module is-nan-x */ 'use strict'; /** * This method determines whether the passed value is NaN and its type is * `Number`. It is a more robust version of the original, global isNaN(). * * @param {*} value - The value to be tested for NaN. * @returns {boolean} `true` if the given value is NaN and its type is Number; * otherwise, `false`. * @example * var numberIsNaN = require('is-nan-x'); * * numberIsNaN(NaN); // true * numberIsNaN(Number.NaN); // true * numberIsNaN(0 / 0); // true * * // e.g. these would have been true with global isNaN() * numberIsNaN('NaN'); // false * numberIsNaN(undefined); // false * numberIsNaN({}); // false * numberIsNaN('blabla'); // false * * // These all return false * numberIsNaN(true); * numberIsNaN(null); * numberIsNaN(37); * numberIsNaN('37'); * numberIsNaN('37.37'); * numberIsNaN(''); * numberIsNaN(' '); */ module.exports = function isNaN(value) { return value !== value; }; },{}],9:[function(_dereq_,module,exports){ /** * @file Checks if `value` is `null` or `undefined`. * @version 1.4.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module is-nil-x */ 'use strict'; var isUndefined = _dereq_('validate.io-undefined'); var isNull = _dereq_('lodash.isnull'); /** * Checks if `value` is `null` or `undefined`. * * @param {*} value - The value to check. * @returns {boolean} Returns `true` if `value` is nullish, else `false`. * @example * var isNil = require('is-nil-x'); * * isNil(null); // => true * isNil(void 0); // => true * isNil(NaN); // => false */ module.exports = function isNil(value) { return isNull(value) || isUndefined(value); }; },{"lodash.isnull":13,"validate.io-undefined":30}],10:[function(_dereq_,module,exports){ /*! * is-primitive <https://github.com/jonschlinkert/is-primitive> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ 'use strict'; // see http://jsperf.com/testing-value-is-primitive/7 module.exports = function isPrimitive(value) { return value == null || (typeof value !== 'function' && typeof value !== 'object'); }; },{}],11:[function(_dereq_,module,exports){ 'use strict'; var strValue = String.prototype.valueOf; var tryStringObject = function tryStringObject(value) { try { strValue.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var strClass = '[object String]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isString(value) { if (typeof value === 'string') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass; }; },{}],12:[function(_dereq_,module,exports){ 'use strict'; var toStr = Object.prototype.toString; var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; if (hasSymbols) { var symToStr = Symbol.prototype.toString; var symStringRegex = /^Symbol\(.*\)$/; var isSymbolObject = function isSymbolObject(value) { if (typeof value.valueOf() !== 'symbol') { return false; } return symStringRegex.test(symToStr.call(value)); }; module.exports = function isSymbol(value) { if (typeof value === 'symbol') { return true; } if (toStr.call(value) !== '[object Symbol]') { return false; } try { return isSymbolObject(value); } catch (e) { return false; } }; } else { module.exports = function isSymbol(value) { // this environment does not support Symbols. return false; }; } },{}],13:[function(_dereq_,module,exports){ /** * lodash 3.0.0 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.7.0 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Checks if `value` is `null`. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `null`, else `false`. * @example * * _.isNull(null); * // => true * * _.isNull(void 0); * // => false */ function isNull(value) { return value === null; } module.exports = isNull; },{}],14:[function(_dereq_,module,exports){ /** * @file ES6-compliant shim for Math.sign. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-math.sign|20.2.2.29 Math.sign(x)} * @version 2.1.0 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module math-sign-x */ 'use strict'; var toNumber = _dereq_('to-number-x'); var numberIsNaN = _dereq_('is-nan-x'); /** * This method returns the sign of a number, indicating whether the number is positive, * negative or zero. * * @param {*} x - A number. * @returns {number} A number representing the sign of the given argument. If the argument * is a positive number, negative number, positive zero or negative zero, the function will * return 1, -1, 0 or -0 respectively. Otherwise, NaN is returned. * @example * var mathSign = require('math-sign-x'); * * mathSign(3); // 1 * mathSign(-3); // -1 * mathSign('-3'); // -1 * mathSign(0); // 0 * mathSign(-0); // -0 * mathSign(NaN); // NaN * mathSign('foo'); // NaN * mathSign(); // NaN */ module.exports = function sign(x) { var n = toNumber(x); if (n === 0 || numberIsNaN(n)) { return n; } return n > 0 ? 1 : -1; }; },{"is-nan-x":8,"to-number-x":22}],15:[function(_dereq_,module,exports){ 'use strict'; module.exports = 9007199254740991; },{}],16:[function(_dereq_,module,exports){ /** * @file Trims and replaces sequences of whitespace characters by a single space. * @version 1.3.3 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module normalize-space-x */ 'use strict'; var trim = _dereq_('trim-x'); var reNormalize = new RegExp('[' + _dereq_('white-space-x').string + ']+', 'g'); /** * This method strips leading and trailing white-space from a string, * replaces sequences of whitespace characters by a single space, * and returns the resulting string. * * @param {string} string - The string to be normalized. * @returns {string} The normalized string. * @example * var normalizeSpace = require('normalize-space-x'); * * normalizeSpace(' \t\na \t\nb \t\n') === 'a b'; // true */ module.exports = function normalizeSpace(string) { return trim(string).replace(reNormalize, ' '); }; },{"trim-x":29,"white-space-x":31}],17:[function(_dereq_,module,exports){ /** * @file Replace the comments in a string. * @version 1.0.3 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module replace-comments-x */ 'use strict'; var isString = _dereq_('is-string'); var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; /** * This method replaces comments in a string. * * @param {string} string - The string to be stripped. * @param {string} [replacement] - The string to be used as a replacement. * @returns {string} The new string with the comments replaced. * @example * var replaceComments = require('replace-comments-x'); * * replaceComments(test;/* test * /, ''), // 'test;' * replaceComments(test; // test, ''), // 'test;' */ module.exports = function replaceComments(string) { var replacement = arguments.length > 1 && isString(arguments[1]) ? arguments[1] : ''; return isString(string) ? string.replace(STRIP_COMMENTS, replacement) : ''; }; },{"is-string":11}],18:[function(_dereq_,module,exports){ /** * @file ES6-compliant shim for RequireObjectCoercible. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-requireobjectcoercible|7.2.1 RequireObjectCoercible ( argument )} * @version 1.4.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module require-object-coercible-x */ 'use strict'; var isNil = _dereq_('is-nil-x'); /** * The abstract operation RequireObjectCoercible throws an error if argument * is a value that cannot be converted to an Object using ToObject. * * @param {*} value - The `value` to check. * @throws {TypeError} If `value` is a `null` or `undefined`. * @returns {string} The `value`. * @example * var RequireObjectCoercible = require('require-object-coercible-x'); * * RequireObjectCoercible(); // TypeError * RequireObjectCoercible(null); // TypeError * RequireObjectCoercible('abc'); // 'abc' * RequireObjectCoercible(true); // true * RequireObjectCoercible(Symbol('foo')); // Symbol('foo') */ module.exports = function RequireObjectCoercible(value) { if (isNil(value)) { throw new TypeError('Cannot call method on ' + value); } return value; }; },{"is-nil-x":9}],19:[function(_dereq_,module,exports){ /** * @file Tests if a value is a string with the boxed bug; splits to an array. * @version 1.0.0 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module split-if-boxed-bug-x */ 'use strict'; var splitString = _dereq_('has-boxed-string-x') === false; var strSplit; var isString; if (splitString) { strSplit = String.prototype.split; isString = _dereq_('is-string'); } /** * This method tests if a value is a string with the boxed bug; splits to an * array for iteration; otherwise returns the original value. * * @param {*} value - The value to be tested. * @returns {*} An array or characters if value was a string with the boxed bug; * otherwise the value. * @example * var splitIfBoxedBug = require('split-if-boxed-bug-x'); * * // No boxed bug * splitIfBoxedBug('abc'); // 'abc' * * // Boxed bug * splitIfBoxedBug('abc'); // ['a', 'b', 'c'] */ module.exports = function splitIfBoxedBug(value) { return splitString && isString(value) ? strSplit.call(value, '') : value; }; },{"has-boxed-string-x":2,"is-string":11}],20:[function(_dereq_,module,exports){ /** * @file ToInteger converts 'argument' to an integral numeric value. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-tointeger|7.1.4 ToInteger ( argument )} * @version 2.1.0 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module to-integer-x */ 'use strict'; var toNumber = _dereq_('to-number-x'); var numberIsNaN = _dereq_('is-nan-x'); var numberIsFinite = _dereq_('is-finite-x'); var mathSign = _dereq_('math-sign-x'); /** * Converts `value` to an integer. * * @param {*} value - The value to convert. * @returns {number} Returns the converted integer. * * @example * var toInteger = require('to-integer-x'); * toInteger(3); // 3 * toInteger(Number.MIN_VALUE); // 0 * toInteger(Infinity); // 1.7976931348623157e+308 * toInteger('3'); // 3 */ module.exports = function toInteger(value) { var number = toNumber(value); if (numberIsNaN(number)) { return 0; } if (number === 0 || numberIsFinite(number) === false) { return number; } return mathSign(number) * Math.floor(Math.abs(number)); }; },{"is-finite-x":6,"is-nan-x":8,"math-sign-x":14,"to-number-x":22}],21:[function(_dereq_,module,exports){ /** * @file ES6-compliant shim for ToLength. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-tolength|7.1.15 ToLength ( argument )} * @version 2.1.0 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module to-length-x */ 'use strict'; var toInteger = _dereq_('to-integer-x'); var MAX_SAFE_INTEGER = _dereq_('max-safe-integer'); /** * Converts `value` to an integer suitable for use as the length of an * array-like object. * * @param {*} value - The value to convert. * @returns {number} Returns the converted integer. * @example * var toLength = require('to-length-x'); * toLength(3); // 3 * toLength(Number.MIN_VALUE); // 0 * toLength(Infinity); // Number.MAX_SAFE_INTEGER * toLength('3'); // 3 */ module.exports = function toLength(value) { var len = toInteger(value); // includes converting -0 to +0 if (len <= 0) { return 0; } if (len > MAX_SAFE_INTEGER) { return MAX_SAFE_INTEGER; } return len; }; },{"max-safe-integer":15,"to-integer-x":20}],22:[function(_dereq_,module,exports){ /** * @file Converts argument to a value of type Number. * @version 1.1.0 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module to-number-x */ 'use strict'; var toPrimitive = _dereq_('to-primitive-x'); var trim = _dereq_('trim-x'); var pStrSlice = String.prototype.slice; var binaryRegex = /^0b[01]+$/i; // Note that in IE 8, RegExp.prototype.test doesn't seem to exist: ie, "test" is an own property of regexes. wtf. var test = binaryRegex.test; var isBinary = function _isBinary(value) { return test.call(binaryRegex, value); }; var octalRegex = /^0o[0-7]+$/i; var isOctal = function _isOctal(value) { return test.call(octalRegex, value); }; var nonWS = [ '\u0085', '\u200b', '\ufffe' ].join(''); var nonWSregex = new RegExp('[' + nonWS + ']', 'g'); var hasNonWS = function _hasNonWS(value) { return test.call(nonWSregex, value); }; var invalidHexLiteral = /^[-+]0x[0-9a-f]+$/i; var isInvalidHexLiteral = function _isInvalidHexLiteral(value) { return test.call(invalidHexLiteral, value); }; var $toNumber = function toNumber(argument) { var value = toPrimitive(argument, Number); if (typeof value === 'symbol') { throw new TypeError('Cannot convert a Symbol value to a number'); } if (typeof value === 'string') { if (isBinary(value)) { return $toNumber(parseInt(pStrSlice.call(value, 2), 2)); } if (isOctal(value)) { return $toNumber(parseInt(pStrSlice.call(value, 2), 8)); } if (hasNonWS(value) || isInvalidHexLiteral(value)) { return NaN; } var trimmed = trim(value); if (trimmed !== value) { return $toNumber(trimmed); } } return Number(value); }; /** * This method converts argument to a value of type Number. * @param {*} argument The argument to convert to a number. * @throws {TypeError} If argument is a Symbol. * @return {*} The argument converted to a number. * @example * var toNumber = require('to-number-x'); * * toNumber('1'); // 1 * toNumber(null); // 0 * toNumber(true); // 1 */ module.exports = $toNumber; },{"to-primitive-x":24,"trim-x":29}],23:[function(_dereq_,module,exports){ /** * @file ES6-compliant shim for ToObject. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-toobject|7.1.13 ToObject ( argument )} * @version 1.4.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module to-object-x */ 'use strict'; var requireObjectCoercible = _dereq_('require-object-coercible-x'); /** * The abstract operation ToObject converts argument to a value of * type Object. * * @param {*} value - The `value` to convert. * @throws {TypeError} If `value` is a `null` or `undefined`. * @returns {!Object} The `value` converted to an object. * @example * var ToObject = require('to-object-x'); * * ToObject(); // TypeError * ToObject(null); // TypeError * ToObject('abc'); // Object('abc') * ToObject(true); // Object(true) * ToObject(Symbol('foo')); // Object(Symbol('foo')) */ module.exports = function toObject(value) { return Object(requireObjectCoercible(value)); }; },{"require-object-coercible-x":18}],24:[function(_dereq_,module,exports){ /** * @file Converts a JavaScript object to a primitive value. * @version 1.0.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module to-primitive-x */ 'use strict'; var hasSymbols = _dereq_('has-symbol-support-x'); var isPrimitive = _dereq_('is-primitive'); var isDate = _dereq_('is-date-object'); var isSymbol = _dereq_('is-symbol'); var isFunction = _dereq_('is-function-x'); var requireObjectCoercible = _dereq_('require-object-coercible-x'); var isNil = _dereq_('is-nil-x'); var isUndefined = _dereq_('validate.io-undefined'); var symToPrimitive = hasSymbols && Symbol.toPrimitive; var symValueOf = hasSymbols && Symbol.prototype.valueOf; var toStringOrder = ['toString', 'valueOf']; var toNumberOrder = ['valueOf', 'toString']; var orderLength = 2; var ordinaryToPrimitive = function _ordinaryToPrimitive(O, hint) { requireObjectCoercible(O); if (typeof hint !== 'string' || (hint !== 'number' && hint !== 'string')) { throw new TypeError('hint must be "string" or "number"'); } var methodNames = hint === 'string' ? toStringOrder : toNumberOrder; var method; var result; for (var i = 0; i < orderLength; i += 1) { method = O[methodNames[i]]; if (isFunction(method)) { result = method.call(O); if (isPrimitive(result)) { return result; } } } throw new TypeError('No default value'); }; var getMethod = function _getMethod(O, P) { var func = O[P]; if (isNil(func) === false) { if (isFunction(func) === false) { throw new TypeError(func + ' returned for property ' + P + ' of object ' + O + ' is not a function'); } return func; } return void 0; }; // http://www.ecma-international.org/ecma-262/6.0/#sec-toprimitive /** * This method converts a JavaScript object to a primitive value. * Note: When toPrimitive is called with no hint, then it generally behaves as * if the hint were Number. However, objects may over-ride this behaviour by * defining a @@toPrimitive method. Of the objects defined in this specification * only Date objects (see 20.3.4.45) and Symbol objects (see 19.4.3.4) over-ride * the default ToPrimitive behaviour. Date objects treat no hint as if the hint * were String. * * @param {*} input - The input to convert. * @param {constructor} [prefferedtype] - The preffered type (String or Number). * @throws {TypeError} If unable to convert input to a primitive. * @returns {string|number} The converted input as a primitive. * @example * var toPrimitive = require('to-primitive-x'); * * var date = new Date(0); * toPrimitive(date)); // Thu Jan 01 1970 01:00:00 GMT+0100 (CET) * toPrimitive(date, String)); // Thu Jan 01 1970 01:00:00 GMT+0100 (CET) * toPrimitive(date, Number)); // 0 */ module.exports = function toPrimitive(input, preferredType) { if (isPrimitive(input)) { return input; } var hint = 'default'; if (arguments.length > 1) { if (preferredType === String) { hint = 'string'; } else if (preferredType === Number) { hint = 'number'; } } var exoticToPrim; if (hasSymbols) { if (symToPrimitive) { exoticToPrim = getMethod(input, symToPrimitive); } else if (isSymbol(input)) { exoticToPrim = symValueOf; } } if (isUndefined(exoticToPrim) === false) { var result = exoticToPrim.call(input, hint); if (isPrimitive(result)) { return result; } throw new TypeError('unable to convert exotic object to primitive'); } if (hint === 'default' && (isDate(input) || isSymbol(input))) { hint = 'string'; } return ordinaryToPrimitive(input, hint === 'default' ? 'number' : hint); }; },{"has-symbol-support-x":3,"is-date-object":5,"is-function-x":7,"is-nil-x":9,"is-primitive":10,"is-symbol":12,"require-object-coercible-x":18,"validate.io-undefined":30}],25:[function(_dereq_,module,exports){ /** * @file Get an object's ES6 @@toStringTag. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring|19.1.3.6 Object.prototype.toString ( )} * @version 1.4.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module to-string-tag-x */ 'use strict'; var isNull = _dereq_('lodash.isnull'); var isUndefined = _dereq_('validate.io-undefined'); var toStr = Object.prototype.toString; /** * The `toStringTag` method returns "[object type]", where type is the * object type. * * @param {*} value - The object of which to get the object type string. * @returns {string} The object type string. * @example * var toStringTag = require('to-string-tag-x'); * * var o = new Object(); * toStringTag(o); // returns '[object Object]' */ module.exports = function toStringTag(value) { if (isNull(value)) { return '[object Null]'; } if (isUndefined(value)) { return '[object Undefined]'; } return toStr.call(value); }; },{"lodash.isnull":13,"validate.io-undefined":30}],26:[function(_dereq_,module,exports){ /** * @file ES6-compliant shim for ToString. * @see {@link http://www.ecma-international.org/ecma-262/6.0/#sec-tostring|7.1.12 ToString ( argument )} * @version 1.4.1 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module to-string-x */ 'use strict'; var isSymbol = _dereq_('is-symbol'); /** * The abstract operation ToString converts argument to a value of type String. * * @param {*} value - The value to convert to a string. * @throws {TypeError} If `value` is a Symbol. * @returns {string} The converted value. * @example * var $toString = require('to-string-x'); * * $toString(); // 'undefined' * $toString(null); // 'null' * $toString('abc'); // 'abc' * $toString(true); // 'true' * $toString(Symbol('foo')); // TypeError * $toString(Symbol.iterator); // TypeError * $toString(Object(Symbol.iterator)); // TypeError */ module.exports = function ToString(value) { if (isSymbol(value)) { throw new TypeError('Cannot convert a Symbol value to a string'); } return String(value); }; },{"is-symbol":12}],27:[function(_dereq_,module,exports){ /** * @file This method removes whitespace from the left end of a string. * @version 1.3.5 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module trim-left-x */ 'use strict'; var $toString = _dereq_('to-string-x'); var reLeft = new RegExp('^[' + _dereq_('white-space-x').string + ']+'); /** * This method removes whitespace from the left end of a string. * * @param {string} string - The string to trim the left end whitespace from. * @returns {undefined|string} The left trimmed string. * @example * var trimLeft = require('trim-left-x'); * * trimLeft(' \t\na \t\n') === 'a \t\n'; // true */ module.exports = function trimLeft(string) { return $toString(string).replace(reLeft, ''); }; },{"to-string-x":26,"white-space-x":31}],28:[function(_dereq_,module,exports){ /** * @file This method removes whitespace from the right end of a string. * @version 1.3.3 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module trim-right-x */ 'use strict'; var $toString = _dereq_('to-string-x'); var reRight = new RegExp('[' + _dereq_('white-space-x').string + ']+$'); /** * This method removes whitespace from the right end of a string. * * @param {string} string - The string to trim the right end whitespace from. * @returns {undefined|string} The right trimmed string. * @example * var trimRight = require('trim-right-x'); * * trimRight(' \t\na \t\n') === ' \t\na'; // true */ module.exports = function trimRight(string) { return $toString(string).replace(reRight, ''); }; },{"to-string-x":26,"white-space-x":31}],29:[function(_dereq_,module,exports){ /** * @file This method removes whitespace from the left and right end of a string. * @version 1.0.3 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module trim-x */ 'use strict'; var trimLeft = _dereq_('trim-left-x'); var trimRight = _dereq_('trim-right-x'); /** * This method removes whitespace from the left and right end of a string. * * @param {string} string - The string to trim the whitespace from. * @returns {undefined|string} The trimmed string. * @example * var trim = require('trim-x'); * * trim(' \t\na \t\n') === 'a'; // true */ module.exports = function trim(string) { return trimLeft(trimRight(string)); }; },{"trim-left-x":27,"trim-right-x":28}],30:[function(_dereq_,module,exports){ /** * * VALIDATE: undefined * * * DESCRIPTION: * - Validates if a value is undefined. * * * NOTES: * [1] * * * TODO: * [1] * * * LICENSE: * MIT * * Copyright (c) 2014. Athan Reines. * * * AUTHOR: * Athan Reines. [email protected]. 2014. * */ 'use strict'; /** * FUNCTION: isUndefined( value ) * Validates if a value is undefined. * * @param {*} value - value to be validated * @returns {Boolean} boolean indicating whether value is undefined */ function isUndefined( value ) { return value === void 0; } // end FUNCTION isUndefined() // EXPORTS // module.exports = isUndefined; },{}],31:[function(_dereq_,module,exports){ /** * @file List of ECMAScript5 white space characters. * @version 2.0.3 * @author Xotic750 <[email protected]> * @copyright Xotic750 * @license {@link <https://opensource.org/licenses/MIT> MIT} * @module white-space-x */ 'use strict'; /** * An array of the ES5 whitespace char codes, string, and their descriptions. * * @name list * @type Array.<Object> * @example * var whiteSpace = require('white-space-x'); * whiteSpaces.list.foreach(function (item) { * console.log(lib.description, item.code, item.string); * }); */ var list = [ { code: 0x0009, description: 'Tab', string: '\u0009' }, { code: 0x000a, description: 'Line Feed', string: '\u000a' }, { code: 0x000b, description: 'Vertical Tab', string: '\u000b' }, { code: 0x000c, description: 'Form Feed', string: '\u000c' }, { code: 0x000d, description: 'Carriage Return', string: '\u000d' }, { code: 0x0020, description: 'Space', string: '\u0020' }, /* { code: 0x0085, description: 'Next line - Not ES5 whitespace', string: '\u0085' } */ { code: 0x00a0, description: 'No-break space', string: '\u00a0' }, { code: 0x1680, description: 'Ogham space mark', string: '\u1680' }, { code: 0x180e, description: 'Mongolian vowel separator', string: '\u180e' }, { code: 0x2000, description: 'En quad', string: '\u2000' }, { code: 0x2001, description: 'Em quad', string: '\u2001' }, { code: 0x2002, description: 'En space', string: '\u2002' }, { code: 0x2003, description: 'Em space', string: '\u2003' }, { code: 0x2004, description: 'Three-per-em space', string: '\u2004' }, { code: 0x2005, description: 'Four-per-em space', string: '\u2005' }, { code: 0x2006, description: 'Six-per-em space', string: '\u2006' }, { code: 0x2007, description: 'Figure space', string: '\u2007' }, { code: 0x2008, description: 'Punctuation space', string: '\u2008' }, { code: 0x2009, description: 'Thin space', string: '\u2009' }, { code: 0x200a, description: 'Hair space', string: '\u200a' }, /* { code: 0x200b, description: 'Zero width space - Not ES5 whitespace', string: '\u200b' }, */ { code: 0x2028, description: 'Line separator', string: '\u2028' }, { code: 0x2029, description: 'Paragraph separator', string: '\u2029' }, { code: 0x202f, description: 'Narrow no-break space', string: '\u202f' }, { code: 0x205f, description: 'Medium mathematical space', string: '\u205f' }, { code: 0x3000, description: 'Ideographic space', string: '\u3000' }, { code: 0xfeff, description: 'Byte Order Mark', string: '\ufeff' } ]; var string = ''; var length = list.length; for (var i = 0; i < length; i += 1) { string += list[i].string; } /** * A string of the ES5 whitespace characters. * * @name string * @type string * @example * var whiteSpace = require('white-space-x'); * var characters = [ * '\u0009', * '\u000a', * '\u000b', * '\u000c', * '\u000d', * '\u0020', * '\u00a0', * '\u1680', * '\u180e', * '\u2000', * '\u2001', * '\u2002', * '\u2003', * '\u2004', * '\u2005', * '\u2006', * '\u2007', * '\u2008', * '\u2009', * '\u200a', * '\u2028', * '\u2029', * '\u202f', * '\u205f', * '\u3000', * '\ufeff' * ]; * var ws = characters.join(''); * var re1 = new RegExp('^[' + whiteSpace.string + ']+$)'); * re1.test(ws); // true */ module.exports = { list: list, string: string }; },{}]},{},[1])(1) });
import Tab from '../../src/tab' /** Test helpers */ import { getFixture, clearFixture, jQueryMock } from '../helpers/fixture' describe('Tab', () => { let fixtureEl beforeAll(() => { fixtureEl = getFixture() }) afterEach(() => { clearFixture() }) describe('VERSION', () => { it('should return plugin version', () => { expect(Tab.VERSION).toEqual(jasmine.any(String)) }) }) describe('constructor', () => { it('should take care of element either passed as a CSS selector or DOM element', () => { fixtureEl.innerHTML = [ '<ul class="nav"><li><a href="#home" role="tab">Home</a></li></ul>', '<ul><li id="home"></li></ul>' ].join('') const tabEl = fixtureEl.querySelector('[href="#home"]') const tabBySelector = new Tab('[href="#home"]') const tabByElement = new Tab(tabEl) expect(tabBySelector._element).toEqual(tabEl) expect(tabByElement._element).toEqual(tabEl) }) }) describe('show', () => { it('should activate element by tab id (using buttons, the preferred semantic way)', done => { fixtureEl.innerHTML = [ '<ul class="nav" role="tablist">', ' <li><button type="button" data-bs-target="#home" role="tab">Home</button></li>', ' <li><button type="button" id="triggerProfile" data-bs-target="#profile" role="tab">Profile</button></li>', '</ul>', '<ul>', ' <li id="home" role="tabpanel"></li>', ' <li id="profile" role="tabpanel"></li>', '</ul>' ].join('') const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') const tab = new Tab(profileTriggerEl) profileTriggerEl.addEventListener('shown.bs.tab', () => { expect(fixtureEl.querySelector('#profile').classList.contains('active')).toEqual(true) expect(profileTriggerEl.getAttribute('aria-selected')).toEqual('true') done() }) tab.show() }) it('should activate element by tab id (using links for tabs - not ideal, but still supported)', done => { fixtureEl.innerHTML = [ '<ul class="nav" role="tablist">', ' <li><a href="#home" role="tab">Home</a></li>', ' <li><a id="triggerProfile" href="#profile" role="tab">Profile</a></li>', '</ul>', '<ul>', ' <li id="home" role="tabpanel"></li>', ' <li id="profile" role="tabpanel"></li>', '</ul>' ].join('') const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') const tab = new Tab(profileTriggerEl) profileTriggerEl.addEventListener('shown.bs.tab', () => { expect(fixtureEl.querySelector('#profile').classList.contains('active')).toEqual(true) expect(profileTriggerEl.getAttribute('aria-selected')).toEqual('true') done() }) tab.show() }) it('should activate element by tab id in ordered list', done => { fixtureEl.innerHTML = [ '<ol class="nav nav-pills">', ' <li><button type="button" data-bs-target="#home" role="tab">Home</button></li>', ' <li><button type="button" id="triggerProfile" href="#profile" role="tab">Profile</button></li>', '</ol>', '<ol>', ' <li id="home" role="tabpanel"></li>', ' <li id="profile" role="tabpanel"></li>', '</ol>' ].join('') const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') const tab = new Tab(profileTriggerEl) profileTriggerEl.addEventListener('shown.bs.tab', () => { expect(fixtureEl.querySelector('#profile').classList.contains('active')).toEqual(true) done() }) tab.show() }) it('should activate element by tab id in nav list', done => { fixtureEl.innerHTML = [ '<nav class="nav">', ' <button type="button" data-bs-target="#home" role="tab">Home</button>', ' <button type="button" id="triggerProfile" data-bs-target="#profile" role="tab">Profile</a>', '</nav>', '<div><div id="home" role="tabpanel"></div><div id="profile" role="tabpanel"></div></div>' ].join('') const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') const tab = new Tab(profileTriggerEl) profileTriggerEl.addEventListener('shown.bs.tab', () => { expect(fixtureEl.querySelector('#profile').classList.contains('active')).toEqual(true) done() }) tab.show() }) it('should activate element by tab id in list group', done => { fixtureEl.innerHTML = [ '<div class="list-group" role="tablist">', ' <button type="button" data-bs-target="#home" role="tab">Home</button>', ' <button type="button" id="triggerProfile" data-bs-target="#profile" role="tab">Profile</button>', '</div>', '<div><div id="home" role="tabpanel"></div><div id="profile" role="tabpanel"></div></div>' ].join('') const profileTriggerEl = fixtureEl.querySelector('#triggerProfile') const tab = new Tab(profileTriggerEl) profileTriggerEl.addEventListener('shown.bs.tab', () => { expect(fixtureEl.querySelector('#profile').classList.contains('active')).toEqual(true) done() }) tab.show() }) it('should not fire shown when show is prevented', done => { fixtureEl.innerHTML = '<div class="nav"></div>' const navEl = fixtureEl.querySelector('div') const tab = new Tab(navEl) const expectDone = () => { setTimeout(() => { expect().nothing() done() }, 30) } navEl.addEventListener('show.bs.tab', ev => { ev.preventDefault() expectDone() }) navEl.addEventListener('shown.bs.tab', () => { throw new Error('should not trigger shown event') }) tab.show() }) it('should not fire shown when tab is already active', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation"><button type="button" data-bs-target="#home" class="nav-link active" role="tab" aria-selected="true">Home</button></li>', ' <li class="nav-item" role="presentation"><button type="button" data-bs-target="#profile" class="nav-link" role="tab">Profile</button></li>', '</ul>', '<div class="tab-content">', ' <div class="tab-pane active" id="home" role="tabpanel"></div>', ' <div class="tab-pane" id="profile" role="tabpanel"></div>', '</div>' ].join('') const triggerActive = fixtureEl.querySelector('button.active') const tab = new Tab(triggerActive) triggerActive.addEventListener('shown.bs.tab', () => { throw new Error('should not trigger shown event') }) tab.show() setTimeout(() => { expect().nothing() done() }, 30) }) it('should not fire shown when tab has disabled attribute', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation"><button type="button" data-bs-target="#home" class="nav-link active" role="tab" aria-selected="true">Home</button></li>', ' <li class="nav-item" role="presentation"><button type="button" data-bs-target="#profile" class="nav-link" disabled role="tab">Profile</button></li>', '</ul>', '<div class="tab-content">', ' <div class="tab-pane active" id="home" role="tabpanel"></div>', ' <div class="tab-pane" id="profile" role="tabpanel"></div>', '</div>' ].join('') const triggerDisabled = fixtureEl.querySelector('button[disabled]') const tab = new Tab(triggerDisabled) triggerDisabled.addEventListener('shown.bs.tab', () => { throw new Error('should not trigger shown event') }) tab.show() setTimeout(() => { expect().nothing() done() }, 30) }) it('should not fire shown when tab has disabled class', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation"><a href="#home" class="nav-link active" role="tab" aria-selected="true">Home</a></li>', ' <li class="nav-item" role="presentation"><a href="#profile" class="nav-link disabled" role="tab">Profile</a></li>', '</ul>', '<div class="tab-content">', ' <div class="tab-pane active" id="home" role="tabpanel"></div>', ' <div class="tab-pane" id="profile" role="tabpanel"></div>', '</div>' ].join('') const triggerDisabled = fixtureEl.querySelector('a.disabled') const tab = new Tab(triggerDisabled) triggerDisabled.addEventListener('shown.bs.tab', () => { throw new Error('should not trigger shown event') }) tab.show() setTimeout(() => { expect().nothing() done() }, 30) }) it('show and shown events should reference correct relatedTarget', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation"><button type="button" data-bs-target="#home" class="nav-link active" role="tab" aria-selected="true">Home</button></li>', ' <li class="nav-item" role="presentation"><button type="button" id="triggerProfile" data-bs-target="#profile" class="nav-link" role="tab">Profile</button></li>', '</ul>', '<div class="tab-content">', ' <div class="tab-pane active" id="home" role="tabpanel"></div>', ' <div class="tab-pane" id="profile" role="tabpanel"></div>', '</div>' ].join('') const secondTabTrigger = fixtureEl.querySelector('#triggerProfile') const secondTab = new Tab(secondTabTrigger) secondTabTrigger.addEventListener('show.bs.tab', ev => { expect(ev.relatedTarget.getAttribute('data-bs-target')).toEqual('#home') }) secondTabTrigger.addEventListener('shown.bs.tab', ev => { expect(ev.relatedTarget.getAttribute('data-bs-target')).toEqual('#home') expect(secondTabTrigger.getAttribute('aria-selected')).toEqual('true') expect(fixtureEl.querySelector('button:not(.active)').getAttribute('aria-selected')).toEqual('false') done() }) secondTab.show() }) it('should fire hide and hidden events', done => { fixtureEl.innerHTML = [ '<ul class="nav" role="tablist">', ' <li><button type="button" data-bs-target="#home" role="tab">Home</button></li>', ' <li><button type="button" data-bs-target="#profile">Profile</button></li>', '</ul>' ].join('') const triggerList = fixtureEl.querySelectorAll('button') const firstTab = new Tab(triggerList[0]) const secondTab = new Tab(triggerList[1]) let hideCalled = false triggerList[0].addEventListener('shown.bs.tab', () => { secondTab.show() }) triggerList[0].addEventListener('hide.bs.tab', ev => { hideCalled = true expect(ev.relatedTarget.getAttribute('data-bs-target')).toEqual('#profile') }) triggerList[0].addEventListener('hidden.bs.tab', ev => { expect(hideCalled).toEqual(true) expect(ev.relatedTarget.getAttribute('data-bs-target')).toEqual('#profile') done() }) firstTab.show() }) it('should not fire hidden when hide is prevented', done => { fixtureEl.innerHTML = [ '<ul class="nav" role="tablist">', ' <li><button type="button" data-bs-target="#home" role="tab">Home</button></li>', ' <li><button type="button" data-bs-target="#profile" role="tab">Profile</button></li>', '</ul>' ].join('') const triggerList = fixtureEl.querySelectorAll('button') const firstTab = new Tab(triggerList[0]) const secondTab = new Tab(triggerList[1]) const expectDone = () => { setTimeout(() => { expect().nothing() done() }, 30) } triggerList[0].addEventListener('shown.bs.tab', () => { secondTab.show() }) triggerList[0].addEventListener('hide.bs.tab', ev => { ev.preventDefault() expectDone() }) triggerList[0].addEventListener('hidden.bs.tab', () => { throw new Error('should not trigger hidden') }) firstTab.show() }) it('should handle removed tabs', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation">', ' <a class="nav-link nav-tab" href="#profile" role="tab" data-bs-toggle="tab">', ' <button class="btn-close" aria-label="Close"></button>', ' </a>', ' </li>', ' <li class="nav-item" role="presentation">', ' <a id="secondNav" class="nav-link nav-tab" href="#buzz" role="tab" data-bs-toggle="tab">', ' <button class="btn-close" aria-label="Close"></button>', ' </a>', ' </li>', ' <li class="nav-item" role="presentation">', ' <a class="nav-link nav-tab" href="#references" role="tab" data-bs-toggle="tab">', ' <button id="btnClose" class="btn-close" aria-label="Close"></button>', ' </a>', ' </li>', '</ul>', '<div class="tab-content">', ' <div role="tabpanel" class="tab-pane fade show active" id="profile">test 1</div>', ' <div role="tabpanel" class="tab-pane fade" id="buzz">test 2</div>', ' <div role="tabpanel" class="tab-pane fade" id="references">test 3</div>', '</div>' ].join('') const secondNavEl = fixtureEl.querySelector('#secondNav') const btnCloseEl = fixtureEl.querySelector('#btnClose') const secondNavTab = new Tab(secondNavEl) secondNavEl.addEventListener('shown.bs.tab', () => { expect(fixtureEl.querySelectorAll('.nav-tab').length).toEqual(2) done() }) btnCloseEl.addEventListener('click', () => { const linkEl = btnCloseEl.parentNode const liEl = linkEl.parentNode const tabId = linkEl.getAttribute('href') const tabIdEl = fixtureEl.querySelector(tabId) liEl.parentNode.removeChild(liEl) tabIdEl.parentNode.removeChild(tabIdEl) secondNavTab.show() }) btnCloseEl.click() }) }) describe('dispose', () => { it('should dispose a tab', () => { fixtureEl.innerHTML = '<div></div>' const el = fixtureEl.querySelector('div') const tab = new Tab(fixtureEl.querySelector('div')) expect(Tab.getInstance(el)).not.toBeNull() tab.dispose() expect(Tab.getInstance(el)).toBeNull() }) }) describe('jQueryInterface', () => { it('should create a tab', () => { fixtureEl.innerHTML = '<div></div>' const div = fixtureEl.querySelector('div') jQueryMock.fn.tab = Tab.jQueryInterface jQueryMock.elements = [div] jQueryMock.fn.tab.call(jQueryMock) expect(Tab.getInstance(div)).toBeDefined() }) it('should not re create a tab', () => { fixtureEl.innerHTML = '<div></div>' const div = fixtureEl.querySelector('div') const tab = new Tab(div) jQueryMock.fn.tab = Tab.jQueryInterface jQueryMock.elements = [div] jQueryMock.fn.tab.call(jQueryMock) expect(Tab.getInstance(div)).toEqual(tab) }) it('should call a tab method', () => { fixtureEl.innerHTML = '<div></div>' const div = fixtureEl.querySelector('div') const tab = new Tab(div) spyOn(tab, 'show') jQueryMock.fn.tab = Tab.jQueryInterface jQueryMock.elements = [div] jQueryMock.fn.tab.call(jQueryMock, 'show') expect(Tab.getInstance(div)).toEqual(tab) expect(tab.show).toHaveBeenCalled() }) it('should throw error on undefined method', () => { fixtureEl.innerHTML = '<div></div>' const div = fixtureEl.querySelector('div') const action = 'undefinedMethod' jQueryMock.fn.tab = Tab.jQueryInterface jQueryMock.elements = [div] expect(() => { jQueryMock.fn.tab.call(jQueryMock, action) }).toThrowError(TypeError, `No method named "${action}"`) }) }) describe('getInstance', () => { it('should return null if there is no instance', () => { expect(Tab.getInstance(fixtureEl)).toEqual(null) }) it('should return this instance', () => { fixtureEl.innerHTML = '<div></div>' const divEl = fixtureEl.querySelector('div') const tab = new Tab(divEl) expect(Tab.getInstance(divEl)).toEqual(tab) expect(Tab.getInstance(divEl)).toBeInstanceOf(Tab) }) }) describe('data-api', () => { it('should create dynamically a tab', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation"><button type="button" data-bs-target="#home" class="nav-link active" role="tab" aria-selected="true">Home</button></li>', ' <li class="nav-item" role="presentation"><button type="button" id="triggerProfile" data-bs-toggle="tab" data-bs-target="#profile" class="nav-link" role="tab">Profile</button></li>', '</ul>', '<div class="tab-content">', ' <div class="tab-pane active" id="home" role="tabpanel"></div>', ' <div class="tab-pane" id="profile" role="tabpanel"></div>', '</div>' ].join('') const secondTabTrigger = fixtureEl.querySelector('#triggerProfile') secondTabTrigger.addEventListener('shown.bs.tab', () => { expect(secondTabTrigger.classList.contains('active')).toEqual(true) expect(fixtureEl.querySelector('#profile').classList.contains('active')).toEqual(true) done() }) secondTabTrigger.click() }) it('selected tab should deactivate previous selected link in dropdown', () => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs">', ' <li class="nav-item"><a class="nav-link" href="#home" data-bs-toggle="tab">Home</a></li>', ' <li class="nav-item"><a class="nav-link" href="#profile" data-bs-toggle="tab">Profile</a></li>', ' <li class="nav-item dropdown">', ' <a class="nav-link dropdown-toggle active" data-bs-toggle="dropdown" href="#">Dropdown</a>', ' <div class="dropdown-menu">', ' <a class="dropdown-item active" href="#dropdown1" id="dropdown1-tab" data-bs-toggle="tab">@fat</a>', ' <a class="dropdown-item" href="#dropdown2" id="dropdown2-tab" data-bs-toggle="tab">@mdo</a>', ' </div>', ' </li>', '</ul>' ].join('') const firstLiLinkEl = fixtureEl.querySelector('li:first-child a') firstLiLinkEl.click() expect(firstLiLinkEl.classList.contains('active')).toEqual(true) expect(fixtureEl.querySelector('li:last-child a').classList.contains('active')).toEqual(false) expect(fixtureEl.querySelector('li:last-child .dropdown-menu a:first-child').classList.contains('active')).toEqual(false) }) it('should handle nested tabs', done => { fixtureEl.innerHTML = [ '<nav class="nav nav-tabs" role="tablist">', ' <button type="button" id="tab1" data-bs-target="#x-tab1" class="nav-link" data-bs-toggle="tab" role="tab" aria-controls="x-tab1">Tab 1</button>', ' <button type="button" data-bs-target="#x-tab2" class="nav-link active" data-bs-toggle="tab" role="tab" aria-controls="x-tab2" aria-selected="true">Tab 2</button>', ' <button type="button" data-bs-target="#x-tab3" class="nav-link" data-bs-toggle="tab" role="tab" aria-controls="x-tab3">Tab 3</button>', '</nav>', '<div class="tab-content">', ' <div class="tab-pane" id="x-tab1" role="tabpanel">', ' <nav class="nav nav-tabs" role="tablist">', ' <button type="button" data-bs-target="#nested-tab1" class="nav-link active" data-bs-toggle="tab" role="tab" aria-controls="x-tab1" aria-selected="true">Nested Tab 1</button>', ' <button type="button" id="tabNested2" data-bs-target="#nested-tab2" class="nav-link" data-bs-toggle="tab" role="tab" aria-controls="x-profile">Nested Tab2</button>', ' </nav>', ' <div class="tab-content">', ' <div class="tab-pane active" id="nested-tab1" role="tabpanel">Nested Tab1 Content</div>', ' <div class="tab-pane" id="nested-tab2" role="tabpanel">Nested Tab2 Content</div>', ' </div>', ' </div>', ' <div class="tab-pane active" id="x-tab2" role="tabpanel">Tab2 Content</div>', ' <div class="tab-pane" id="x-tab3" role="tabpanel">Tab3 Content</div>', '</div>' ].join('') const tab1El = fixtureEl.querySelector('#tab1') const tabNested2El = fixtureEl.querySelector('#tabNested2') const xTab1El = fixtureEl.querySelector('#x-tab1') tabNested2El.addEventListener('shown.bs.tab', () => { expect(xTab1El.classList.contains('active')).toEqual(true) done() }) tab1El.addEventListener('shown.bs.tab', () => { expect(xTab1El.classList.contains('active')).toEqual(true) tabNested2El.click() }) tab1El.click() }) it('should not remove fade class if no active pane is present', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation"><button type="button" id="tab-home" data-bs-target="#home" class="nav-link" data-bs-toggle="tab" role="tab">Home</button></li>', ' <li class="nav-item" role="presentation"><button type="button" id="tab-profile" data-bs-target="#profile" class="nav-link" data-bs-toggle="tab" role="tab">Profile</button></li>', '</ul>', '<div class="tab-content">', ' <div class="tab-pane fade" id="home" role="tabpanel"></div>', ' <div class="tab-pane fade" id="profile" role="tabpanel"></div>', '</div>' ].join('') const triggerTabProfileEl = fixtureEl.querySelector('#tab-profile') const triggerTabHomeEl = fixtureEl.querySelector('#tab-home') const tabProfileEl = fixtureEl.querySelector('#profile') const tabHomeEl = fixtureEl.querySelector('#home') triggerTabProfileEl.addEventListener('shown.bs.tab', () => { expect(tabProfileEl.classList.contains('fade')).toEqual(true) expect(tabProfileEl.classList.contains('show')).toEqual(true) triggerTabHomeEl.addEventListener('shown.bs.tab', () => { expect(tabProfileEl.classList.contains('fade')).toEqual(true) expect(tabProfileEl.classList.contains('show')).toEqual(false) expect(tabHomeEl.classList.contains('fade')).toEqual(true) expect(tabHomeEl.classList.contains('show')).toEqual(true) done() }) triggerTabHomeEl.click() }) triggerTabProfileEl.click() }) it('should not add show class to tab panes if there is no `.fade` class', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation">', ' <button type="button" class="nav-link nav-tab" data-bs-target="#home" role="tab" data-bs-toggle="tab">Home</button>', ' </li>', ' <li class="nav-item" role="presentation">', ' <button type="button" id="secondNav" class="nav-link nav-tab" data-bs-target="#profile" role="tab" data-bs-toggle="tab">Profile</button>', ' </li>', '</ul>', '<div class="tab-content">', ' <div role="tabpanel" class="tab-pane" id="home">test 1</div>', ' <div role="tabpanel" class="tab-pane" id="profile">test 2</div>', '</div>' ].join('') const secondNavEl = fixtureEl.querySelector('#secondNav') secondNavEl.addEventListener('shown.bs.tab', () => { expect(fixtureEl.querySelectorAll('.show').length).toEqual(0) done() }) secondNavEl.click() }) it('should add show class to tab panes if there is a `.fade` class', done => { fixtureEl.innerHTML = [ '<ul class="nav nav-tabs" role="tablist">', ' <li class="nav-item" role="presentation">', ' <button type="button" class="nav-link nav-tab" data-bs-target="#home" role="tab" data-bs-toggle="tab">Home</button>', ' </li>', ' <li class="nav-item" role="presentation">', ' <button type="button" id="secondNav" class="nav-link nav-tab" data-bs-target="#profile" role="tab" data-bs-toggle="tab">Profile</button>', ' </li>', '</ul>', '<div class="tab-content">', ' <div role="tabpanel" class="tab-pane fade" id="home">test 1</div>', ' <div role="tabpanel" class="tab-pane fade" id="profile">test 2</div>', '</div>' ].join('') const secondNavEl = fixtureEl.querySelector('#secondNav') secondNavEl.addEventListener('shown.bs.tab', () => { expect(fixtureEl.querySelectorAll('.show').length).toEqual(1) done() }) secondNavEl.click() }) }) })
let Products = require('../models/product'); const ResError = require('./util').ResError; let User = require('../models/user'); let fs = require('fs'); const xss = require('xss'); const tokenForUser = require('./util').tokenForUser; const registrationSchema = require('../validation/validation_schemas.js') exports.delete = function (req,res, next){ req.body.email && (req.body.email = xss(req.body.email)); User.findOneAndRemove( { email: req.body.email }) .exec() .then(function(user){ return res.send({success: true}) }) .catch(function(err){ console.log(err) return res.status(500).json({ errMsg: "Invalid Form Data"}); }); } exports.post_detail = function (req,res){ req.body.accessRight && (req.body.accessRight = xss(req.body.accessRight)); req.body.email && (req.body.email = xss(req.body.email)); req.body.password && (req.body.password = xss(req.body.password)); req.body.username && (req.body.username = xss(req.body.username)); let nUser = req.user; if (req.body.accessRight !== undefined && (!req.user._doc || !req.user._doc.accessRight || req.user._doc.accessRight < 8)){ return res.status(401).json({ errMsg: "Unauthorized"}); } if( req.file && req.file.filename){ fs.unlink(`./public/${nUser.profile.picture.trim().replace(/^\/api\//,'')}`, (err) => { err&&console.log(err);}); nUser.profile.picture = '/api/img/users/'+ req.file.filename; } req.body.accessRight && (nUser.accessRight = req.body.accessRight); req.body.email && (nUser.email = req.body.email); req.body.password && (nUser.password = req.body.password); req.body.username && (nUser.profile.username = req.body.username); req.body.data && (nUser.data = req.body.data); req.checkBody(registrationSchema); req.getValidationResult().then(function(result) { if (!result.isEmpty()) { throw new ResError({status: 400, errMsg: result.array().reduce((prev, next) => prev + `. ${next.msg}`, "") }); } return nUser.save(); }) .then( function (user){ let retUser = {}; retUser.details = Object.assign({}, user._doc); delete retUser.details._id; delete retUser.details.__v; delete retUser.details.password; retUser.token = tokenForUser(user); return res.json(retUser); }) .catch(function(err){ if (err.status) { return res.status(err.status).send({errMsg: err.errMsg});} return res.status(500).json({ errMsg:"Invalid Data" }); }); } exports.post_rate = function (req,res){ req.body.rate && (req.body.rate = xss(req.body.rate)); req.params.id && (req.params.id = xss(req.params.id)); if (req.body.rate === undefined ){ return res.status(500).json({ errMsg: "Plase Provide Rating Number"}); } if (req.params.id === undefined ){ return res.status(500).json({ errMsg: "Plase Provide Product ID"}); } let id = req.params.id, rate= req.body.rate, nUser = req.user, addVoteCount = 0, oldUserStar = 0, nRate = undefined; nUser.rate = nUser.rate || []; nUser.data.rate.forEach(function (rate) { (rate.productId === id) && (nRate = rate); }); oldUserStar = (nRate && nRate.rate) || 0; if (!nRate){ nRate = {productId : id}; addVoteCount++; nUser.data.rate.push(nRate); nRate = undefined; } let ret = {user_data:{}, product_stars:{}}; Products.ProductModel.findOne({_id: req.params.id}) .exec() .then( function (details){ details.stars = details.stars || {totalStars:0, voteCount:0}; details.stars.totalStars = details.stars.totalStars || 0; details.stars.voteCount = details.stars.voteCount || 0; details.stars.totalStars += (rate - oldUserStar); details.stars.voteCount += addVoteCount; return details.save(); }) .then( function (details){ ret.product_stars = details.stars; nRate = nRate || nUser.data.rate[nUser.data.rate.length - 1]; nRate.cat = details.cat; nRate.rate = rate; return User.findByIdAndUpdate(nUser._id, {data: nUser.data}, {new: true}); }) .then( function (user){ ret.token = tokenForUser(user); ret.user_data = user._doc.data; return res.json(ret); }) .catch(function(err){ console.log(err); if (err.status) { return res.status(err.status).send({errMsg: err.errMsg});} return res.status(500).json({ errMsg:err.toString() }); }); } exports.post_favorite = function (req,res){ req.body.love && (req.body.love = xss(req.body.love)); req.params.id && (req.params.id = xss(req.params.id)); if (req.body.love === undefined ){ return res.status(500).json({ errMsg: "Plase Provide Favorite Status"}); } if (req.params.id === undefined ){ return res.status(500).json({ errMsg: "Plase Provide Product ID"}); } let id = req.params.id, fav = req.body.love, nUser = req.user, oldUserfav = false, nFav = undefined; nUser.favorite = nUser.favorite || []; if (!fav) { //remove from fav nUser.data.favorite = nUser.data.favorite.filter(function (favorite) { !oldUserfav && (oldUserfav = favorite.productId === id); return favorite.productId !== id; }); } else { nUser.data.favorite.forEach(function (fav) { (fav.productId === id) && (nFav = fav); }); oldUserfav = !!nFav; if (!nFav){ nFav = { productId: id}; nUser.data.favorite.push(nFav); nFav = undefined; } } let ret = {user_data:{}, product_favorite:{}}; Products.ProductModel.findOne({_id: req.params.id}) .exec() .then( function (details){ details.favorite = details.favorite || 0; if (oldUserfav != fav) details.favorite += (fav?1:-1); details.favorite = ((details.favorite < 0 ) && 0) || details.favorite; return details.save(); }) .then( function (details){ ret.product_favorite = details.favorite; if (fav){ nFav = nFav || nUser.data.favorite[nUser.data.favorite.length - 1]; nFav.cat = fav && details.cat; } return User.findByIdAndUpdate(nUser._id, {data: nUser.data}, {new: true}); }) .then( function (user){ ret.token = tokenForUser(user); ret.user_data = user._doc.data; return res.json(ret); }) .catch(function(err){ console.log(err); if (err.status) { return res.status(err.status).send({errMsg: err.errMsg});} return res.status(500).json({ errMsg:err.toString() }); }); } exports.get_detail = function (req, res){ //user already had their email anf password auth'd let nUser = Object.assign({}, req.user._doc); delete nUser.password; delete nUser._id; delete nUser.__v; return res.json({details: nUser}); //req.user: pass by passpart by done() }
/** * Bootstrap.js by @fat & @mdo * plugins: bootstrap-transition.js, bootstrap-modal.js, bootstrap-dropdown.js, bootstrap-scrollspy.js, bootstrap-tab.js, bootstrap-affix.js, bootstrap-alert.js, bootstrap-collapse.js, bootstrap-carousel.js, bootstrap-typeahead.js * Copyright 2012 Twitter, Inc. * http://www.apache.org/licenses/LICENSE-2.0.txt */ !function (a) { a(function () { a.support.transition = function () { var a = function () { var a = document.createElement("bootstrap"), b = { WebkitTransition: "webkitTransitionEnd", MozTransition: "transitionend", OTransition: "oTransitionEnd otransitionend", transition: "transitionend" }, c; for (c in b)if (a.style[c] !== undefined)return b[c] }(); return a && {end: a} }() }) }(window.jQuery), !function (a) { var b = function (b, c) { this.options = c, this.$element = a(b).delegate('[data-dismiss="modal"]', "click.dismiss.modal", a.proxy(this.hide, this)), this.options.remote && this.$element.find(".modal-body").load(this.options.remote) }; b.prototype = { constructor: b, toggle: function () { return this[this.isShown ? "hide" : "show"]() }, show: function () { var b = this, c = a.Event("show"); this.$element.trigger(c); if (this.isShown || c.isDefaultPrevented())return; this.isShown = !0, this.escape(), this.backdrop(function () { var c = a.support.transition && b.$element.hasClass("fade"); b.$element.parent().length || b.$element.appendTo(document.body), b.$element.show(), c && b.$element[0].offsetWidth, b.$element.addClass("in").attr("aria-hidden", !1), b.enforceFocus(), c ? b.$element.one(a.support.transition.end, function () { b.$element.focus().trigger("shown") }) : b.$element.focus().trigger("shown") }) }, hide: function (b) { b && b.preventDefault(); var c = this; b = a.Event("hide"), this.$element.trigger(b); if (!this.isShown || b.isDefaultPrevented())return; this.isShown = !1, this.escape(), a(document).off("focusin.modal"), this.$element.removeClass("in").attr("aria-hidden", !0), a.support.transition && this.$element.hasClass("fade") ? this.hideWithTransition() : this.hideModal() }, enforceFocus: function () { var b = this; a(document).on("focusin.modal", function (a) { b.$element[0] !== a.target && !b.$element.has(a.target).length && b.$element.focus() }) }, escape: function () { var a = this; this.isShown && this.options.keyboard ? this.$element.on("keyup.dismiss.modal", function (b) { b.which == 27 && a.hide() }) : this.isShown || this.$element.off("keyup.dismiss.modal") }, hideWithTransition: function () { var b = this, c = setTimeout(function () { b.$element.off(a.support.transition.end), b.hideModal() }, 500); this.$element.one(a.support.transition.end, function () { clearTimeout(c), b.hideModal() }) }, hideModal: function (a) { this.$element.hide().trigger("hidden"), this.backdrop() }, removeBackdrop: function () { this.$backdrop.remove(), this.$backdrop = null }, backdrop: function (b) { var c = this, d = this.$element.hasClass("fade") ? "fade" : ""; if (this.isShown && this.options.backdrop) { var e = a.support.transition && d; this.$backdrop = a('<div class="modal-backdrop ' + d + '" />').appendTo(document.body), this.$backdrop.click(this.options.backdrop == "static" ? a.proxy(this.$element[0].focus, this.$element[0]) : a.proxy(this.hide, this)), e && this.$backdrop[0].offsetWidth, this.$backdrop.addClass("in"), e ? this.$backdrop.one(a.support.transition.end, b) : b() } else!this.isShown && this.$backdrop ? (this.$backdrop.removeClass("in"), a.support.transition && this.$element.hasClass("fade") ? this.$backdrop.one(a.support.transition.end, a.proxy(this.removeBackdrop, this)) : this.removeBackdrop()) : b && b() } }; var c = a.fn.modal; a.fn.modal = function (c) { return this.each(function () { var d = a(this), e = d.data("modal"), f = a.extend({}, a.fn.modal.defaults, d.data(), typeof c == "object" && c); e || d.data("modal", e = new b(this, f)), typeof c == "string" ? e[c]() : f.show && e.show() }) }, a.fn.modal.defaults = { backdrop: !0, keyboard: !0, show: !0 }, a.fn.modal.Constructor = b, a.fn.modal.noConflict = function () { return a.fn.modal = c, this }, a(document).on("click.modal.data-api", '[data-toggle="modal"]', function (b) { var c = a(this), d = c.attr("href"), e = a(c.attr("data-target") || d && d.replace(/.*(?=#[^\s]+$)/, "")), f = e.data("modal") ? "toggle" : a.extend({remote: !/#/.test(d) && d}, e.data(), c.data()); b.preventDefault(), e.modal(f).one("hide", function () { c.focus() }) }) }(window.jQuery), !function (a) { function d() { a(b).each(function () { e(a(this)).removeClass("open") }) } function e(b) { var c = b.attr("data-target"), d; return c || (c = b.attr("href"), c = c && /#/.test(c) && c.replace(/.*(?=#[^\s]*$)/, "")), d = a(c), d.length || (d = b.parent()), d } var b = "[data-toggle=dropdown]", c = function (b) { var c = a(b).on("click.dropdown.data-api", this.toggle); a("html").on("click.dropdown.data-api", function () { c.parent().removeClass("open") }) }; c.prototype = { constructor: c, toggle: function (b) { var c = a(this), f, g; if (c.is(".disabled, :disabled"))return; return f = e(c), g = f.hasClass("open"), d(), g || f.toggleClass("open"), c.focus(), !1 }, keydown: function (b) { var c, d, f, g, h, i; if (!/(38|40|27)/.test(b.keyCode))return; c = a(this), b.preventDefault(), b.stopPropagation(); if (c.is(".disabled, :disabled"))return; g = e(c), h = g.hasClass("open"); if (!h || h && b.keyCode == 27)return c.click(); d = a("[role=menu] li:not(.divider):visible a", g); if (!d.length)return; i = d.index(d.filter(":focus")), b.keyCode == 38 && i > 0 && i--, b.keyCode == 40 && i < d.length - 1 && i++, ~i || (i = 0), d.eq(i).focus() } }; var f = a.fn.dropdown; a.fn.dropdown = function (b) { return this.each(function () { var d = a(this), e = d.data("dropdown"); e || d.data("dropdown", e = new c(this)), typeof b == "string" && e[b].call(d) }) }, a.fn.dropdown.Constructor = c, a.fn.dropdown.noConflict = function () { return a.fn.dropdown = f, this }, a(document).on("click.dropdown.data-api touchstart.dropdown.data-api", d).on("click.dropdown touchstart.dropdown.data-api", ".dropdown form", function (a) { a.stopPropagation() }).on("touchstart.dropdown.data-api", ".dropdown-menu", function (a) { a.stopPropagation() }).on("click.dropdown.data-api touchstart.dropdown.data-api", b, c.prototype.toggle).on("keydown.dropdown.data-api touchstart.dropdown.data-api", b + ", [role=menu]", c.prototype.keydown) }(window.jQuery), !function (a) { function b(b, c) { var d = a.proxy(this.process, this), e = a(b).is("body") ? a(window) : a(b), f; this.options = a.extend({}, a.fn.scrollspy.defaults, c), this.$scrollElement = e.on("scroll.scroll-spy.data-api", d), this.selector = (this.options.target || (f = a(b).attr("href")) && f.replace(/.*(?=#[^\s]+$)/, "") || "") + " .nav li > a", this.$body = a("body"), this.refresh(), this.process() } b.prototype = { constructor: b, refresh: function () { var b = this, c; this.offsets = a([]), this.targets = a([]), c = this.$body.find(this.selector).map(function () { var c = a(this), d = c.data("target") || c.attr("href"), e = /^#\w/.test(d) && a(d); return e && e.length && [[e.position().top + b.$scrollElement.scrollTop(), d]] || null }).sort(function (a, b) { return a[0] - b[0] }).each(function () { b.offsets.push(this[0]), b.targets.push(this[1]) }) }, process: function () { var a = this.$scrollElement.scrollTop() + this.options.offset, b = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight, c = b - this.$scrollElement.height(), d = this.offsets, e = this.targets, f = this.activeTarget, g; if (a >= c)return f != (g = e.last()[0]) && this.activate(g); for (g = d.length; g--;)f != e[g] && a >= d[g] && (!d[g + 1] || a <= d[g + 1]) && this.activate(e[g]) }, activate: function (b) { var c, d; this.activeTarget = b, a(this.selector).parent(".active").removeClass("active"), d = this.selector + '[data-target="' + b + '"],' + this.selector + '[href="' + b + '"]', c = a(d).parent("li").addClass("active"), c.parent(".dropdown-menu").length && (c = c.closest("li.dropdown").addClass("active")), c.trigger("activate") } }; var c = a.fn.scrollspy; a.fn.scrollspy = function (c) { return this.each(function () { var d = a(this), e = d.data("scrollspy"), f = typeof c == "object" && c; e || d.data("scrollspy", e = new b(this, f)), typeof c == "string" && e[c]() }) }, a.fn.scrollspy.Constructor = b, a.fn.scrollspy.defaults = {offset: 10}, a.fn.scrollspy.noConflict = function () { return a.fn.scrollspy = c, this }, a(window).on("load", function () { a('[data-spy="scroll"]').each(function () { var b = a(this); b.scrollspy(b.data()) }) }) }(window.jQuery), !function (a) { var b = function (b) { this.element = a(b) }; b.prototype = { constructor: b, show: function () { var b = this.element, c = b.closest("ul:not(.dropdown-menu)"), d = b.attr("data-target"), e, f, g; d || (d = b.attr("href"), d = d && d.replace(/.*(?=#[^\s]*$)/, "")); if (b.parent("li").hasClass("active"))return; e = c.find(".active:last a")[0], g = a.Event("show", {relatedTarget: e}), b.trigger(g); if (g.isDefaultPrevented())return; f = a(d), this.activate(b.parent("li"), c), this.activate(f, f.parent(), function () { b.trigger({type: "shown", relatedTarget: e}) }) }, activate: function (b, c, d) { function g() { e.removeClass("active").find("> .dropdown-menu > .active").removeClass("active"), b.addClass("active"), f ? (b[0].offsetWidth, b.addClass("in")) : b.removeClass("fade"), b.parent(".dropdown-menu") && b.closest("li.dropdown").addClass("active"), d && d() } var e = c.find("> .active"), f = d && a.support.transition && e.hasClass("fade"); f ? e.one(a.support.transition.end, g) : g(), e.removeClass("in") } }; var c = a.fn.tab; a.fn.tab = function (c) { return this.each(function () { var d = a(this), e = d.data("tab"); e || d.data("tab", e = new b(this)), typeof c == "string" && e[c]() }) }, a.fn.tab.Constructor = b, a.fn.tab.noConflict = function () { return a.fn.tab = c, this }, a(document).on("click.tab.data-api", '[data-toggle="tab"], [data-toggle="pill"]', function (b) { b.preventDefault(), a(this).tab("show") }) }(window.jQuery), !function (a) { var b = function (b, c) { this.options = a.extend({}, a.fn.affix.defaults, c), this.$window = a(window).on("scroll.affix.data-api", a.proxy(this.checkPosition, this)).on("click.affix.data-api", a.proxy(function () { setTimeout(a.proxy(this.checkPosition, this), 1) }, this)), this.$element = a(b), this.checkPosition() }; b.prototype.checkPosition = function () { if (!this.$element.is(":visible"))return; var b = a(document).height(), c = this.$window.scrollTop(), d = this.$element.offset(), e = this.options.offset, f = e.bottom, g = e.top, h = "affix affix-top affix-bottom", i; typeof e != "object" && (f = g = e), typeof g == "function" && (g = e.top()), typeof f == "function" && (f = e.bottom()), i = this.unpin != null && c + this.unpin <= d.top ? !1 : f != null && d.top + this.$element.height() >= b - f ? "bottom" : g != null && c <= g ? "top" : !1; if (this.affixed === i)return; this.affixed = i, this.unpin = i == "bottom" ? d.top - c : null, this.$element.removeClass(h).addClass("affix" + (i ? "-" + i : "")) }; var c = a.fn.affix; a.fn.affix = function (c) { return this.each(function () { var d = a(this), e = d.data("affix"), f = typeof c == "object" && c; e || d.data("affix", e = new b(this, f)), typeof c == "string" && e[c]() }) }, a.fn.affix.Constructor = b, a.fn.affix.defaults = {offset: 0}, a.fn.affix.noConflict = function () { return a.fn.affix = c, this }, a(window).on("load", function () { a('[data-spy="affix"]').each(function () { var b = a(this), c = b.data(); c.offset = c.offset || {}, c.offsetBottom && (c.offset.bottom = c.offsetBottom), c.offsetTop && (c.offset.top = c.offsetTop), b.affix(c) }) }) }(window.jQuery), !function (a) { var b = '[data-dismiss="alert"]', c = function (c) { a(c).on("click", b, this.close) }; c.prototype.close = function (b) { function f() { e.trigger("closed").remove() } var c = a(this), d = c.attr("data-target"), e; d || (d = c.attr("href"), d = d && d.replace(/.*(?=#[^\s]*$)/, "")), e = a(d), b && b.preventDefault(), e.length || (e = c.hasClass("alert") ? c : c.parent()), e.trigger(b = a.Event("close")); if (b.isDefaultPrevented())return; e.removeClass("in"), a.support.transition && e.hasClass("fade") ? e.on(a.support.transition.end, f) : f() }; var d = a.fn.alert; a.fn.alert = function (b) { return this.each(function () { var d = a(this), e = d.data("alert"); e || d.data("alert", e = new c(this)), typeof b == "string" && e[b].call(d) }) }, a.fn.alert.Constructor = c, a.fn.alert.noConflict = function () { return a.fn.alert = d, this }, a(document).on("click.alert.data-api", b, c.prototype.close) }(window.jQuery), !function (a) { var b = function (b, c) { this.$element = a(b), this.options = a.extend({}, a.fn.collapse.defaults, c), this.options.parent && (this.$parent = a(this.options.parent)), this.options.toggle && this.toggle() }; b.prototype = { constructor: b, dimension: function () { var a = this.$element.hasClass("width"); return a ? "width" : "height" }, show: function () { var b, c, d, e; if (this.transitioning)return; b = this.dimension(), c = a.camelCase(["scroll", b].join("-")), d = this.$parent && this.$parent.find("> .accordion-group > .in"); if (d && d.length) { e = d.data("collapse"); if (e && e.transitioning)return; d.collapse("hide"), e || d.data("collapse", null) } this.$element[b](0), this.transition("addClass", a.Event("show"), "shown"), a.support.transition && this.$element[b](this.$element[0][c]) }, hide: function () { var b; if (this.transitioning)return; b = this.dimension(), this.reset(this.$element[b]()), this.transition("removeClass", a.Event("hide"), "hidden"), this.$element[b](0) }, reset: function (a) { var b = this.dimension(); return this.$element.removeClass("collapse")[b](a || "auto")[0].offsetWidth, this.$element[a !== null ? "addClass" : "removeClass"]("collapse"), this }, transition: function (b, c, d) { var e = this, f = function () { c.type == "show" && e.reset(), e.transitioning = 0, e.$element.trigger(d) }; this.$element.trigger(c); if (c.isDefaultPrevented())return; this.transitioning = 1, this.$element[b]("in"), a.support.transition && this.$element.hasClass("collapse") ? this.$element.one(a.support.transition.end, f) : f() }, toggle: function () { this[this.$element.hasClass("in") ? "hide" : "show"]() } }; var c = a.fn.collapse; a.fn.collapse = function (c) { return this.each(function () { var d = a(this), e = d.data("collapse"), f = typeof c == "object" && c; e || d.data("collapse", e = new b(this, f)), typeof c == "string" && e[c]() }) }, a.fn.collapse.defaults = {toggle: !0}, a.fn.collapse.Constructor = b, a.fn.collapse.noConflict = function () { return a.fn.collapse = c, this }, a(document).on("click.collapse.data-api", "[data-toggle=collapse]", function (b) { var c = a(this), d, e = c.attr("data-target") || b.preventDefault() || (d = c.attr("href")) && d.replace(/.*(?=#[^\s]+$)/, ""), f = a(e).data("collapse") ? "toggle" : c.data(); c[a(e).hasClass("in") ? "addClass" : "removeClass"]("collapsed"), a(e).collapse(f) }) }(window.jQuery), !function (a) { var b = function (b, c) { this.$element = a(b), this.options = c, this.options.pause == "hover" && this.$element.on("mouseenter", a.proxy(this.pause, this)).on("mouseleave", a.proxy(this.cycle, this)) }; b.prototype = { cycle: function (b) { return b || (this.paused = !1), this.options.interval && !this.paused && (this.interval = setInterval(a.proxy(this.next, this), this.options.interval)), this }, to: function (b) { var c = this.$element.find(".item.active"), d = c.parent().children(), e = d.index(c), f = this; if (b > d.length - 1 || b < 0)return; return this.sliding ? this.$element.one("slid", function () { f.to(b) }) : e == b ? this.pause().cycle() : this.slide(b > e ? "next" : "prev", a(d[b])) }, pause: function (b) { return b || (this.paused = !0), this.$element.find(".next, .prev").length && a.support.transition.end && (this.$element.trigger(a.support.transition.end), this.cycle()), clearInterval(this.interval), this.interval = null, this }, next: function () { if (this.sliding)return; return this.slide("next") }, prev: function () { if (this.sliding)return; return this.slide("prev") }, slide: function (b, c) { var d = this.$element.find(".item.active"), e = c || d[b](), f = this.interval, g = b == "next" ? "left" : "right", h = b == "next" ? "first" : "last", i = this, j; this.sliding = !0, f && this.pause(), e = e.length ? e : this.$element.find(".item")[h](), j = a.Event("slide", {relatedTarget: e[0]}); if (e.hasClass("active"))return; if (a.support.transition && this.$element.hasClass("slide")) { this.$element.trigger(j); if (j.isDefaultPrevented())return; e.addClass(b), e[0].offsetWidth, d.addClass(g), e.addClass(g), this.$element.one(a.support.transition.end, function () { e.removeClass([b, g].join(" ")).addClass("active"), d.removeClass(["active", g].join(" ")), i.sliding = !1, setTimeout(function () { i.$element.trigger("slid") }, 0) }) } else { this.$element.trigger(j); if (j.isDefaultPrevented())return; d.removeClass("active"), e.addClass("active"), this.sliding = !1, this.$element.trigger("slid") } return f && this.cycle(), this } }; var c = a.fn.carousel; a.fn.carousel = function (c) { return this.each(function () { var d = a(this), e = d.data("carousel"), f = a.extend({}, a.fn.carousel.defaults, typeof c == "object" && c), g = typeof c == "string" ? c : f.slide; e || d.data("carousel", e = new b(this, f)), typeof c == "number" ? e.to(c) : g ? e[g]() : f.interval && e.cycle() }) }, a.fn.carousel.defaults = { interval: 5e3, pause: "hover" }, a.fn.carousel.Constructor = b, a.fn.carousel.noConflict = function () { return a.fn.carousel = c, this }, a(document).on("click.carousel.data-api", "[data-slide]", function (b) { var c = a(this), d, e = a(c.attr("data-target") || (d = c.attr("href")) && d.replace(/.*(?=#[^\s]+$)/, "")), f = a.extend({}, e.data(), c.data()); e.carousel(f), b.preventDefault() }) }(window.jQuery), !function (a) { var b = function (b, c) { this.$element = a(b), this.options = a.extend({}, a.fn.typeahead.defaults, c), this.matcher = this.options.matcher || this.matcher, this.sorter = this.options.sorter || this.sorter, this.highlighter = this.options.highlighter || this.highlighter, this.updater = this.options.updater || this.updater, this.source = this.options.source, this.$menu = a(this.options.menu), this.shown = !1, this.listen() }; b.prototype = { constructor: b, select: function () { var a = this.$menu.find(".active").attr("data-value"); return this.$element.val(this.updater(a)).change(), this.hide() }, updater: function (a) { return a }, show: function () { var b = a.extend({}, this.$element.position(), {height: this.$element[0].offsetHeight}); return this.$menu.insertAfter(this.$element).css({ top: b.top + b.height, left: b.left }).show(), this.shown = !0, this }, hide: function () { return this.$menu.hide(), this.shown = !1, this }, lookup: function (b) { var c; return this.query = this.$element.val(), !this.query || this.query.length < this.options.minLength ? this.shown ? this.hide() : this : (c = a.isFunction(this.source) ? this.source(this.query, a.proxy(this.process, this)) : this.source, c ? this.process(c) : this) }, process: function (b) { var c = this; return b = a.grep(b, function (a) { return c.matcher(a) }), b = this.sorter(b), b.length ? this.render(b.slice(0, this.options.items)).show() : this.shown ? this.hide() : this }, matcher: function (a) { return ~a.toLowerCase().indexOf(this.query.toLowerCase()) }, sorter: function (a) { var b = [], c = [], d = [], e; while (e = a.shift())e.toLowerCase().indexOf(this.query.toLowerCase()) ? ~e.indexOf(this.query) ? c.push(e) : d.push(e) : b.push(e); return b.concat(c, d) }, highlighter: function (a) { var b = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); return a.replace(new RegExp("(" + b + ")", "ig"), function (a, b) { return "<strong>" + b + "</strong>" }) }, render: function (b) { var c = this; return b = a(b).map(function (b, d) { return b = a(c.options.item).attr("data-value", d), b.find("a").html(c.highlighter(d)), b[0] }), b.first().addClass("active"), this.$menu.html(b), this }, next: function (b) { var c = this.$menu.find(".active").removeClass("active"), d = c.next(); d.length || (d = a(this.$menu.find("li")[0])), d.addClass("active") }, prev: function (a) { var b = this.$menu.find(".active").removeClass("active"), c = b.prev(); c.length || (c = this.$menu.find("li").last()), c.addClass("active") }, listen: function () { this.$element.on("blur", a.proxy(this.blur, this)).on("keypress", a.proxy(this.keypress, this)).on("keyup", a.proxy(this.keyup, this)), this.eventSupported("keydown") && this.$element.on("keydown", a.proxy(this.keydown, this)), this.$menu.on("click", a.proxy(this.click, this)).on("mouseenter", "li", a.proxy(this.mouseenter, this)) }, eventSupported: function (a) { var b = a in this.$element; return b || (this.$element.setAttribute(a, "return;"), b = typeof this.$element[a] == "function"), b }, move: function (a) { if (!this.shown)return; switch (a.keyCode) { case 9: case 13: case 27: a.preventDefault(); break; case 38: a.preventDefault(), this.prev(); break; case 40: a.preventDefault(), this.next() } a.stopPropagation() }, keydown: function (b) { this.suppressKeyPressRepeat = ~a.inArray(b.keyCode, [40, 38, 9, 13, 27]), this.move(b) }, keypress: function (a) { if (this.suppressKeyPressRepeat)return; this.move(a) }, keyup: function (a) { switch (a.keyCode) { case 40: case 38: case 16: case 17: case 18: break; case 9: case 13: if (!this.shown)return; this.select(); break; case 27: if (!this.shown)return; this.hide(); break; default: this.lookup() } a.stopPropagation(), a.preventDefault() }, blur: function (a) { var b = this; setTimeout(function () { b.hide() }, 150) }, click: function (a) { a.stopPropagation(), a.preventDefault(), this.select() }, mouseenter: function (b) { this.$menu.find(".active").removeClass("active"), a(b.currentTarget).addClass("active") } }; var c = a.fn.typeahead; a.fn.typeahead = function (c) { return this.each(function () { var d = a(this), e = d.data("typeahead"), f = typeof c == "object" && c; e || d.data("typeahead", e = new b(this, f)), typeof c == "string" && e[c]() }) }, a.fn.typeahead.defaults = { source: [], items: 8, menu: '<ul class="typeahead dropdown-menu"></ul>', item: '<li><a href="#"></a></li>', minLength: 1 }, a.fn.typeahead.Constructor = b, a.fn.typeahead.noConflict = function () { return a.fn.typeahead = c, this }, a(document).on("focus.typeahead.data-api", '[data-provide="typeahead"]', function (b) { var c = a(this); if (c.data("typeahead"))return; b.preventDefault(), c.typeahead(c.data()) }) }(window.jQuery)
'use strict'; module.exports = { up: function (migration, DataTypes) { return migration.changeColumn('User', 'signature', { type: DataTypes.STRING, allowNull: false, defaultValue: 'Signature', }); }, down: function () {}, };
/** * @author Ross Lehr <[email protected]> * @copyright 2014 Ross Lehr */ /** * Holds all of the code for the game States Preloader * * @class Game.State.Preloader */ (function() { /** * Creates Preloader state of the game * * @method Game.Preloader * @param {game} Reference to the current game */ Game.State.Preloader = function(game) { /** * A reference to the currently running Game. * * @property game * @type {Object} */ this.game = game; /** * A reference to the nonsenseLogo * * @property nonsenseLogo * @type {Phaser.Sprite} */ this.nonsenseLogo = null; /** * A reference to the preloadBar * * @property preloadBar * @type {Phaser.Sprite} */ this.preloadBar = null; }; /** * Preloads all images needed for this level * Using my preloadItems array to load items. * * @method preload */ Game.State.Preloader.prototype.preload = function() { //Load the game logo this.nonsenseLogo = this.game.add.sprite(0, 0, 'nonsenseLogo'); this.nonsenseLogo.x = (this.game.width / 2) - (this.nonsenseLogo.width / 2); this.nonsenseLogo.y = (this.game.height / 2) - (this.nonsenseLogo.height); //load the loader bar this.preloadBar = this.game.add.sprite(0, 0, 'preloaderBar'); this.preloadBar.x = this.nonsenseLogo.x; this.preloadBar.y = this.nonsenseLogo.y + this.nonsenseLogo.height; this.load.setPreloadSprite(this.preloadBar); //load all items in Game.preloadItems array for (count = 0; count < Game.preloadItems.length; count++) { //Get the type of item in the preloader array switch (Game.preloadItems[count].type) { case "json": this.game.load.json(Game.preloadItems[count].name, Game.preloadItems[count].path); break; case "image": this.game.load.image(Game.preloadItems[count].name, Game.preloadItems[count].path); break; case "spriteSheet": this.game.load.spritesheet(Game.preloadItems[count].name, Game.preloadItems[count].path, Game.preloadItems[count].width, Game.preloadItems[count].height, Game.preloadItems[count].frameCount); break; case "audio": this.game.load.audio(Game.preloadItems[count].name, Game.preloadItems[count].path); break; case "font": this.game.load.bitmapFont(Game.preloadItems[count].name, Game.preloadItems[count].path, Game.preloadItems[count].xml); break; case "atlas": this.game.load.atlasXML(Game.preloadItems[count].name, Game.preloadItems[count].path, Game.preloadItems[count].xml); break; case "text": this.game.load.text(Game.preloadItems[count].name, Game.preloadItems[count].path); break; case "tilemap": this.game.load.tilemap(Game.preloadItems[count].name, Game.preloadItems[count].path, null, Phaser.Tilemap.TILED_JSON); break; case "jsonHash": this.game.load.atlasJSONHash(Game.preloadItems[count].name, Game.preloadItems[count].image, Game.preloadItems[count].jsonData); break; } } }; /** * Create everything for the game * * @method create */ Game.State.Preloader.prototype.create = function() { //Once the load has finished we disable the crop because we're going to sit in the update loop for a short while as the music decodes this.preloadBar.cropEnabled = false; }; /** * Start the mainMenu state * * @method update */ Game.State.Preloader.prototype.update = function() { this.state.start('MainMenu'); }; })();
// Copyright 2014, Yahoo! Inc. // Copyrights licensed under the Mit License. See the accompanying LICENSE file for terms. var Base = require('preceptor-core').Base; var utils = require('preceptor-core').utils; var _ = require('underscore'); var path = require('path'); var fs = require('fs'); var defaultOptions = require('./defaults/clientOptions'); /** * @class AbstractClient * @extends Base * * @property {object} _options * @property {*} _instance */ var AbstractClient = Base.extend( /** * Web-driver client constructor * * @param {object} options * @constructor */ function (options) { this.__super(); this._options = utils.deepExtend({}, [ defaultOptions, options || {} ]); this._instance = null; this.initialize(); }, { /** * Initializes the instance * * @method initialize */ initialize: function () { // Make sure the configuration has the correct structure this.validate(); // Augment options with outside data this.augment(); }, /** * Validates the data given * * @method validate */ validate: function () { if (!_.isObject(this.getOptions())) { throw new Error('The options parameter is not an object.'); } if (!_.isObject(this.getConfiguration())) { throw new Error('The "configuration" parameter is not an object.'); } if (!_.isString(this.getType())) { throw new Error('The "type" parameter is not a string.'); } if (!_.isObject(this.getCapabilities())) { throw new Error('The "capabilities" parameter is not an object.'); } if (!_.isString(this.getUrl())) { throw new Error('The "url" parameter is not a string.'); } }, /** * Augments the data with default values * * @method augment */ augment: function () { // Nothing yet }, /** * Gets the client-driver instance * * @method getInstance * @return {*} */ getInstance: function () { return this._instance; }, /** * Gets the options * * @method getOptions * @return {object} */ getOptions: function () { return this._options; }, /** * Gets the type of server * * @method getType * @return {string} */ getType: function () { return this.getOptions().type; }, /** * Gets the url of the server * * @method getUrl * @return {string} */ getUrl: function () { return this.getOptions().url; }, /** * Sets the url of the server * * @method setUrl * @param {string} url */ setUrl: function (url) { this.getOptions().url = url; }, /** * Gets the capabilities * * @method getCapabilities * @return {object} */ getCapabilities: function () { return this.getOptions().capabilities; }, /** * Gets the server configuration * * @method getConfiguration * @return {object} */ getConfiguration: function () { return this.getOptions().configuration; }, /** * Starts the client * * @method start * @return {Promise} */ start: function () { throw new Error('Unimplemented web-driver client function "start".'); }, /** * Stops the client * * @method stop * @return {Promise} */ stop: function () { throw new Error('Unimplemented web-driver client function "stop".'); }, /** * Load the coverage through the Selenium client * * @method loadCoverage * @param {string} coverageVar * @return {Promise} With {object} */ loadCoverage: function (coverageVar) { return Promise.resolve({}); }, /** * Retrieves the coverage script for gather coverage data * * @method _coverageScript * @return {string} * @private */ _coverageScript: function () { return fs.readFileSync(path.join(__dirname, 'scripts', 'coverage.js')).toString('utf-8'); } }, { /** * @property TYPE * @type {string} * @static */ TYPE: 'AbstractClient' }); module.exports = AbstractClient;
/* @flow */ import React, { PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { actions as botActions } from '../../redux/modules/bots'; import GameList from 'components/GameList'; import BotWebsiteLink from 'components/BotWebsiteLink'; import BotWinPercent from 'components/BotWinPercent'; import Loading from 'components/Loading'; import styles from './BotDetailView.scss'; // import GameList from 'components/GameList'; // We can use Flow (http://flowtype.org/) to type our component's props // and state. For convenience we've included both regular propTypes and // Flow types, but if you want to try just using Flow you'll want to // disable the eslint rule `react/prop-types`. // NOTE: You can run `npm run flow:check` to check for any errors in your // code, or `npm i -g flow-bin` to have access to the binary globally. // Sorry Windows users :(. // type Props = {}; // We avoid using the `@connect` decorator on the class definition so // that we can export the undecorated component for testing. // See: http://rackt.github.io/redux/docs/recipes/WritingTests.html export class BotDetailView extends React.Component { // props: Props; static propTypes = { botActions: PropTypes.object.isRequired, currentBot: PropTypes.object.isRequired, params: PropTypes.object.isRequired, }; componentWillReceiveProps = (nextProps) => { if (this.props.params.id !== nextProps.params.id) { this.props.botActions.clearBotDetail(); this.props.botActions.getBotDetail(nextProps.params.id); this.props.botActions.listGamesForBot(nextProps.params.id); } } componentDidMount = () => { this.props.botActions.getBotDetail(this.props.params.id); this.props.botActions.listGamesForBot(this.props.params.id); } componentWillUnmount = () => { this.props.botActions.clearBotDetail(); } render () { if (this.props.currentBot === undefined) { return <Loading />; } let bot = this.props.currentBot; const gamesPlayed = bot.gamesPlayed; const gamesWon = bot.gamesWon; const gamesDrawn = bot.gamesDrawn; const currentScore = bot.currentScore; const renderGamesList = () => { if (bot.games) { return ( <GameList games={bot.games} contextBot={bot} /> ); } else { return ( <Loading /> ); } }; return ( <div> <div className={styles.headingContainer}> <h1 className={styles.botHeading}>{bot.name} <span className={styles.titleVersion}>({bot.version})</span></h1> <div className={styles.playContainer}> <h1> <BotWinPercent currentScore={currentScore} gamesPlayed={gamesPlayed} /> </h1> <div className={styles.playSummary}> Played: {gamesPlayed}, Won: {gamesWon}, Drawn: {gamesDrawn} </div> </div> </div> <div className={styles.subHeadingContainer}> by {bot.user.name}, written in {bot.programmingLanguage} </div> <p className={styles.description}>{bot.description}</p> <BotWebsiteLink website={bot.website} /> <div className={styles.gamesContainer}> <h2>Games</h2> {renderGamesList()} </div> </div> ); } } const mapStateToProps = (state) => ({ currentBot: state.bots.currentBot, }); const mapDisptachToProps = (dispatch) => { return { botActions: bindActionCreators(botActions, dispatch), }; }; export default connect(mapStateToProps, mapDisptachToProps)(BotDetailView);
$(document).ready(function() { /* code here */ }); $(function() { var changeHandler = function(){ var fs = window.fullScreenApi.isFullScreen(); console.log("f" + (fs ? 'yes' : 'no' )); if (fs) { //alert("In fullscreen, I should do something here"); //Disable right click $(this).bind("contextmenu", function(e) { e.preventDefault(); }); //Disable F12 document.onkeydown = function (event) { event = (event || window.event); if (event.keyCode == 123) { //alert('No F-keys'); return false; } } document.onmousedown = function (event) { event = (event || window.event); if (event.keyCode == 123) { //alert('No F-keys'); return false; } } document.onkeydown = function (event) { event = (event || window.event); if (event.keyCode == 123) { //alert('No F-keys'); return false; } } //Disable Shift key $(this).keydown(function(event) { if(event.shiftKey) { //alert('You have pressed Shift Key.'); event.preventDefault(); } }); //window.location. = "/online-test.php" //window.history.pushState("object or string", "Title", "/online-test.php"); window.History.pushState({urlPath:'/online-test.php'},"",'/online-test.php') } else { alert("NOT In fullscreen, Cheating!!"); //window.location="http://www.google.com" } } document.addEventListener("fullscreenchange", changeHandler, false); document.addEventListener("webkitfullscreenchange", changeHandler, false); document.addEventListener("mozfullscreenchange", changeHandler, false); }); function fullscreen(){ $('#digital_download').html('Downloading...'); // Show "Downloading..." // Do an ajax request $.ajax({ url: "/online-registration.php" }).done(function(data) { // data what is sent back by the php page $('#digital_download').html(data); // display data }); var docElm = document.documentElement; if (docElm.requestFullscreen) { docElm.requestFullscreen(); } else if (docElm.mozRequestFullScreen) { docElm.mozRequestFullScreen(); } else if (docElm.webkitRequestFullScreen) { docElm.webkitRequestFullScreen(); } }
/** * @file 事件观察器 * @author mengke01([email protected]) * * modify from : * https://github.com/ecomfe/moye/blob/master/src/ui/lib.js */ /** * 事件功能 * * @namespace */ const observe = { /** * 添加事件绑定 * * @public * @param {string=} type 事件类型 * @param {Function} listener 要添加绑定的监听器 * @return {this} */ on(type, listener) { if (typeof type === 'function') { listener = type; type = '*'; } this._listeners = this._listeners || {}; let listeners = this._listeners[type] || []; if (listeners.indexOf(listener) < 0) { listener.$type = type; listeners.push(listener); } this._listeners[type] = listeners; return this; }, /** * 添加单次事件绑定 * * @public * @param {string=} type 事件类型 * @param {Function} listener 要添加绑定的监听器 * @return {this} */ once(type, listener) { let onceFn = function (e) { listener.call(this, e); this.un(type, listener); }; this.on(type, onceFn); return this; }, /** * 解除事件绑定 * * @public * @param {string=} type 事件类型 * @param {Function=} listener 要解除绑定的监听器 * @return {this} */ un(type, listener) { if (typeof type === 'function') { listener = type; type = '*'; } else if (typeof type === 'undefined') { delete this._listeners; this._listeners = {}; return this; } this._listeners = this._listeners || {}; let listeners = this._listeners[type]; if (listeners) { if (listener) { let index = listeners.indexOf(listener); if (~index) { delete listeners[index]; } } else { listeners.length = 0; delete this._listeners[type]; } } return this; }, /** * 触发指定事件 * * @public * @param {string} type 事件类型 * @param {Object} args 透传的事件数据对象 * @return {this} */ fire(type, args) { this._listeners = this._listeners || {}; let listeners = this._listeners[type]; if (listeners) { let me = this; listeners.forEach( function (listener) { args = args || {}; args.type = type; listener.call(me, args); } ); } if (type !== '*') { this.fire('*', args); } return this; } }; /** * 观察器对象 * * @type {Object} */ export default { /** * 混入一个对象 * * @param {Object} object 对象 * @return {Object} 混入后的对象 */ mixin(object) { if (undefined === object) { return object; } return Object.assign(object, observe); } };
'use strict'; module.exports = { up: function (queryInterface, Sequelize) { return queryInterface.createTable('Quizzes', {id: { type: Sequelize.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true, unique: true }, question: {type: Sequelize.STRING, validate: {notEmpty: {msg: "Falta Pregunta"}}}, answer: {type: Sequelize.STRING, validate: {notEmpty: {msg: "Falta Respuesta"}}}, createdAt: {type: Sequelize.DATE, allowNull: false}, updatedAt: {type: Sequelize.DATE, allowNull: false} }, { sync: {force: true} } ); }, down: function (queryInterface, Sequelize) { return queryInterface.dropTable('Quizzes'); } };
'use strict'; // Karma configuration // Generated on Tue Sep 10 2013 18:12:14 GMT+0200 (CEST) var files = require('./../files.conf.js'); var conf = require('./karma.shared.conf.js'); module.exports = function(config) { conf.files = files.testFilesBuild; conf.browserStack = { username: process.env.BROWSER_STACK_USERNAME, accessKey: process.env.BROWSER_STACK_ACCESS_KEY, project: process.env.TRAVIS_REPO_SLUG || 'stimuli@local', build: process.env.TRAVIS_BUILD_NUMBER, startTunnel: true, retryLimit: 5, timeout: 600 }; conf.captureTimeout = 90000; // 1 min 30 conf.logLevel = config.LOG_DEBUG; conf.reportSlowerThan = 30000; conf.disconnectTolerance = 5; conf.autoWatch = false; conf.singleRun = true; conf.disableCompression = true; conf.serverPort = 9876; conf.serverHost = '127.0.0.1'; conf.clientHost = '127.0.0.1'; conf.clientPort = 8080; conf.transports = ['xhr-polling']; conf.customLaunchers = { BS_FIREFOX: { base: 'BrowserStack', browser: 'firefox', browser_version: '24.0', os: 'Windows', os_version: 'XP' }, BS_CHROME: { base: 'BrowserStack', browser: 'chrome', browser_version: '29.0', os: 'Windows', os_version: 'XP' }, BS_IE8: { base: 'BrowserStack', browser: 'ie', browser_version: '8.0', os: 'Windows', os_version: 'XP' }, BS_IE9: { base: 'BrowserStack', browser: 'ie', browser_version: '9.0', os: 'Windows', os_version: '7' }, BS_IE10: { base: 'BrowserStack', browser: 'ie', browser_version: '10.0', os: 'Windows', os_version: '8' }, BS_IE11: { base: 'BrowserStack', browser: 'ie', browser_version: '11.0', os: 'Windows', os_version: '7' }, BS_SAFARI51: { base: 'BrowserStack', browser: 'safari', browser_version: '5.1', os: 'OS X', os_version: 'Snow Leopard' }, BS_SAFARI6: { base: 'BrowserStack', browser: 'safari', browser_version: '6.0', os: 'OS X', os_version: 'Mountain Lion' }, BS_OPERA16: { base: 'BrowserStack', os: 'OS X', browser: 'opera', os_version: 'Mountain Lion', browser_version: '16.0' }, BS_ANDROID_4: { base: 'BrowserStack', os: 'android', device: 'Samsung Galaxy Nexus', browser: 'Android Browser', os_version: '4.0', browser_version: null }, BS_ANDROID_41: { base: 'BrowserStack', os: 'android', device: 'Samsung Galaxy Note II', browser: 'Android Browser', os_version: '4.1', browser_version: null }, BS_ANDROID_42: { base: 'BrowserStack', os: 'android', device: 'LG Nexus 4', browser: 'Android Browser', os_version: '4.2', browser_version: null }, BS_IOS_7: { base: 'BrowserStack', os: 'ios', device: 'iPhone 5S', browser: 'Mobile Safari', os_version: '7.0', browser_version: null } }; config.set(conf); };
import React from 'react'; import PropTypes from 'prop-types'; import Editor from '../Editor'; import Step from '../Step'; import './content.css'; const Content = ({ steps, active, addStep, onEditorChange, onEditorSave, onStepChange, onStepDelete, onStepNameChange }) => ( <div className="content"> <div className="side-panel"> {steps && steps.map((step, i) => ( <Step active={i === active} name={step.name} key={step.id} onClick={onStepChange} onDelete={onStepDelete} onNameChange={onStepNameChange} index={i} /> ))} <div className="add-step" onClick={addStep}>+</div> </div> <div className="editor-container"> <Editor onChange={onEditorChange} editorState={steps[active].editorState} /> <div className="editor-save" onClick={onEditorSave}>Save</div> </div> </div> ); Content.propTypes = { steps: PropTypes.arrayOf(PropTypes.shape({ name: PropTypes.string.isRequired })).isRequired, active: PropTypes.number.isRequired, addStep: PropTypes.func.isRequired }; export default Content;
const PATH = require('path') const FS = require('fs-extra') const dirtree = require('directory-tree') const chalk = require('chalk') module.exports = function generateMvvcConfig(rootFolderPath, boilerplateMvvcConfigPath) { return Promise.resolve( new Promise((resolve, reject) => { const path = PATH.resolve(rootFolderPath, './mvvc.config.js') // generate file if (!dirtree(path)) { FS.copySync(boilerplateMvvcConfigPath, path) console.log(chalk.bold.green(`"mvvc.config.js" was created!`), `(${path})`) resolve() } else { console.log(chalk.bold.red(`mvvc.config.js is alread exsited, please remove it mutually! (${path})`)) } }) ) }
(function() { 'use strict'; angular .module('minotaur') .directive('uploadMe', uploadMe) .directive('uploadMe2', uploadMe2) .directive('uploadMe3', uploadMe3); /** @ngInject */ function uploadMe() { var directive = { restrict: 'A', link: function (scope, elem, attrs) { var reader = new FileReader(); reader.onload = function (e) { scope.image = e.target.result; scope.$apply(); } elem.on('change', function() { reader.readAsDataURL(elem[0].files[0]); scope.file = elem[0].files[0]; }); } }; return directive; } function uploadMe2() { var directive = { restrict: 'A', link: function (scope, elem, attrs) { var reader2 = new FileReader(); reader2.onload = function (e) { scope.image2 = e.target.result; scope.$apply(); } elem.on('change', function() { reader2.readAsDataURL(elem[0].files[0]); scope.file2 = elem[0].files[0]; }); } }; return directive; } function uploadMe3() { var directive = { restrict: 'A', link: function (scope, elem, attrs) { var reader3 = new FileReader(); reader3.onload = function (e) { scope.image3 = e.target.result; scope.$apply(); } elem.on('change', function() { reader3.readAsDataURL(elem[0].files[0]); scope.file3 = elem[0].files[0]; }); } }; return directive; } })();
var $$FSR = { 'enabled': true, 'frames': false, 'sessionreplay': true, 'auto': true, 'encode': true, 'version': '18.1.3', 'files': '/foresee/', // The 'swf_files' attribute needs to be set when foresee_transport.swf is not located at 'files' //'swf_files': '/some/other/location/' 'id': 'ZdykBhX9f5FYknEDsngaKg==', 'definition': 'foresee_surveydef.js', 'swf': { 'fileName': 'foresee_transport.swf', 'scriptAccess': 'always' }, 'worker': 'foresee_worker.js', 'embedded': false, 'replay_id': 'cancer.gov', 'site_id': 'cancer.gov', 'attach': false, 'renderer': 'W3C', // or "ASRECORDED" 'layout': 'CENTERFIXED', // or "LEFTFIXED" or "LEFTSTRETCH" or "CENTERSTRETCH" 'triggerDelay': 0, 'heartbeat': true, 'enableAMD': false, 'pools': [{ 'path': '.', 'sp': 100 // CHANGE ONLY WHEN INCLUDING SESSION REPLAY }], 'sites': [{ 'path': /\w+-?\w+\.(com|org|edu|gov|net|co\.uk)/ }, { 'path': '.', 'domain': 'default' }], 'storageOption': 'cookie', 'nameBackup': window.name, 'iframeHrefs': ["frameWorker.html"], 'acceptableorigins': [] }; $$FSR.FSRCONFIG = {}; (function (config) { var FSR, supports_amd = !! config.enableAMD && typeof(_4c.global["define"]) === 'function' && !! _4c.global["define"]["amd"]; if (!supports_amd) FSR = window.FSR; else FSR = {}; /* * ForeSee Survey Def(s) */ FSR.surveydefs = [{ name: 'nci-spanish', invite: { when: 'onentry', //dual language dialogs: [{ reverseButtons: false, headline: "Welcome to the National Cancer Institute Web site.", blurb: "<br>We Need Your Help!<p>During your visit to our Web site today, you may be asked to participate in a survey about your experience with the site.<p>Your comments will help us to make the site more useful. We appreciate the opportunity to hear from you.<br><br>", noticeAboutSurvey: "Are you willing to participate in our survey?<br>", attribution: "This survey is conducted by an independent company ForeSee, on behalf of the site you are visiting.", closeInviteButtonText: "Click to close.", declineButton: "No", acceptButton: "Yes", locales: { "en": { locale: "en" }, "sp": { locale: "sp" } } }, { reverseButtons: false, headline: "Welcome to the National Cancer Institute Web site.", blurb: "We Need Your Help!<br><br>During your visit to our Web site today, you may be asked to participate in a survey about your experience with the site.<br><br>Your comments will help us to make the site more useful. We appreciate the opportunity to hear from you.", noticeAboutSurvey: "Are you willing to participate in our survey?", attribution: "This survey is conducted by an independent company ForeSee, on behalf of the site you are visiting.", closeInviteButtonText: "Click to close.", declineButton: "No", acceptButton: "Yes", locales: { "en": { headline: "Gracias por visitar el sitio web en español del Instituto Nacional del Cáncer.", blurb: "¡Necesitamos su ayuda!<p>Su opinión es muy importante.<p>Durante su visita a nuestro sitio web hoy, posiblemente le pediremos que participe en una encuesta sobre su visita. Sus comentarios nos ayudarán a mejorar nuestro sitio.", noticeAboutSurvey: "Por favor, haga clic en Sí para compartir su opinión con nosotros.", attribution: "Esta encuesta se realiza a través de una empresa independiente, ForeSee, en nombre del sitio que usted está visitando.", closeInviteButtonText: "Haga clic para cerrar.", declineButton: "No Gracias", acceptButton: "Sí", locale: "sp" }, "sp": { headline: "Gracias por visitar el sitio web en español del Instituto Nacional del Cáncer.", blurb: "¡Necesitamos su ayuda!<p>Su opinión es muy importante.<p>Durante su visita a nuestro sitio web hoy, posiblemente le pediremos que participe en una encuesta sobre su visita. Sus comentarios nos ayudarán a mejorar nuestro sitio.", noticeAboutSurvey: "Por favor, haga clic en Sí para compartir su opinión con nosotros.", attribution: "Esta encuesta se realiza a través de una empresa independiente, ForeSee, en nombre del sitio que usted está visitando.", closeInviteButtonText: "Haga clic para cerrar.", declineButton: "No Gracias", acceptButton: "Sí", } } }] }, lock: 1, pop: { when: 'later' }, criteria: { sp: 100, lf: 2 }, include: { urls: ['/espanol', '/diccionario', 'lang=spanish'] } }, { name: 'nci-main', invite: { when: 'onentry' }, pop: { when: 'later' }, criteria: { sp: 10, lf: 2 }, lock: 1, links: { cancel: [{ tag: 'a', attribute: 'href', patterns: ['xlivehelp'] }] }, include: { urls: ['.'] } }]; /* * ForeSee Properties */ FSR.properties = { repeatdays: 60, repeatoverride: false, altcookie: {}, language: { locale: 'en' }, exclude: {}, ignoreWindowTopCheck: false, ipexclude: 'fsr$ip', mobileHeartbeat: { delay: 60, /*mobile on exit heartbeat delay seconds*/ max: 3600 /*mobile on exit heartbeat max run time seconds*/ }, invite: { // For no site logo, comment this line: siteLogo: "sitelogo.gif", //alt text fore site logo img siteLogoAlt: "", /* Desktop */ dialogs: [ [{ reverseButtons: false, headline: "Welcome to the National Cancer Institute Web site.", blurb: "We Need Your Help!<p>During your visit to our Web site today, you may be asked to participate in a survey about your experience with the site.<p>Your comments will help us to make the site more useful. We appreciate the opportunity to hear from you.", noticeAboutSurvey: "Are you willing to participate in our survey?", attribution: "This survey is conducted by an independent company ForeSee, on behalf of the site you are visiting.", closeInviteButtonText: "Click to close.", declineButton: "No", acceptButton: "Yes", error: "Error", warnLaunch: "this will launch a new window" }] ], exclude: { urls: [/ncicancerbulletin/gi, /resultscancerbulletin.aspx/gi, /cb[a-zA-Z0-9-\.]*\.aspx/gi], referrers: [], userAgents: [], browsers: [], cookies: [], variables: [] }, include: { local: ['.'] }, delay: 0, timeout: 0, hideOnClick: false, hideCloseButton: false, css: 'foresee_dhtml.css', hide: [], hideFlash: false, type: 'dhtml', /* desktop */ // url: 'invite.html' /* mobile */ url: 'invite-mobile.html', back: 'url' //SurveyMutex: 'SurveyMutex' }, tracker: { width: '690', height: '415', // Timeout is the normal between-page timeout timeout: 10, // Fast timeout is when we think there's a good chance we've closed the browser fasttimeout: 4, adjust: true, alert: { enabled: true, message: 'The survey is now available.', locales: [{ locale: 'en', message: 'The survey is now available.' }, { locale: 'sp', message: 'Su encuesta se encuentra ahora disponible.' }] }, url: 'tracker.html', locales: [{ locale: 'en', url: 'tracker.html' }, { locale: 'sp', url: 'tracker_sp.html' }] }, survey: { width: 690, height: 600 }, qualifier: { footer: '<div id=\"fsrcontainer\"><div style=\"float:left;width:80%;font-size:8pt;text-align:left;line-height:12px;\">This survey is conducted by an independent company ForeSee,<br>on behalf of the site you are visiting.</div><div style=\"float:right;font-size:8pt;\"><a target="_blank" title="Validate TRUSTe privacy certification" href="//privacy-policy.truste.com/click-with-confidence/ctv/en/www.foreseeresults.com/seal_m"><img border=\"0\" src=\"{%baseHref%}truste.png\" alt=\"Validate TRUSTe Privacy Certification\"></a></div></div>', width: '690', height: '500', bgcolor: '#333', opacity: 0.7, x: 'center', y: 'center', delay: 0, buttons: { accept: 'Continue' }, hideOnClick: false, css: 'foresee_dhtml.css', url: 'qualifying.html' }, cancel: { url: 'cancel.html', width: '690', height: '400' }, pop: { what: 'survey', after: 'leaving-site', pu: false, tracker: true }, meta: { referrer: true, terms: true, ref_url: true, url: true, url_params: false, user_agent: false, entry: false, entry_params: false }, events: { enabled: true, id: true, codes: { purchase: 800, items: 801, dollars: 802, followup: 803, information: 804, content: 805 }, pd: 7, custom: {} }, previous: false, analytics: { google_local: false, google_remote: false }, cpps: {}, mode: 'hybrid' }; if (supports_amd) { define(function () { return FSR }); } })($$FSR);
/** * 应用入口 */ import 'core-js/modules/es6.promise' import 'regenerator-runtime/runtime' import Vue from 'vue' {{#fastclick}} import FastClick from 'fastclick' {{/fastclick}} {{#baobabui}} import BaobabUI from 'baobab-ui' import 'baobab-ui/lib/baobab-ui.css' {{/baobabui}} import App from 'views/login' {{#sentry}} /** * 使用 https://sentry.io 收集应用异常 */ // import Raven from 'raven-js' // import RavenVue from 'raven-js/plugins/vue' // // if (process.env.NODE_ENV === 'production') { // Raven // .config('', { // release: window.__CONFIG__.version // }) // .addPlugin(RavenVue, Vue).install() // } {{/sentry}} {{#fastclick}} // 解决移动端 300ms 点击延迟问题 FastClick.attach(document.body) {{/fastclick}} {{#baobabui}} Vue.use(BaobabUI) {{/baobabui}} window.app = new Vue({ el: '#app', ...App })
'use strict'; var _ = require("lodash"); var template = function (inputvar) { var mytemplate = "Hello <%= name %> (logins: <%= login.length %>)"; return _.template(mytemplate)(inputvar); }; module.exports = template;
define(function() { $("#personalInfo").hide(); $(".show-hide-link").on('click', function(event) { $("#personalInfo").toggle(); $("#contactSubmitBtn").toggle(); return false; }); });
// @flow import { connect } from 'react-redux'; import Posts from '../components/Posts'; import { type State } from '~/store/state'; const mapDispatchToProps = {}; const mapStateToProps = (state: State) => ({ data: (state.posts || {}).data, }); export default connect(mapStateToProps, mapDispatchToProps)(Posts);
import $ from "jquery"; class Requester { get(url, headers) { var promise = new Promise(function(resolve, reject) { $.ajax({ url, method: "GET", headers, contentType: "application/json", success(response) { resolve(response); }, error(err) { reject(err); } }); }); return promise; } post(url, headers, data) { var promise = new Promise(function(resolve, reject) { $.ajax({ url, method: "POST", headers, data: JSON.stringify(data), contentType: "application/json", success: function(data) { resolve(data); }, error: function(err) { reject(err); }, }); }); return promise; } put(url, headers, data) { var promise = new Promise(function(resolve, reject) { $.ajax({ url, method: "PUT", headers, data: JSON.stringify(data), contentType: "application/json", success: function(data) { resolve(data); }, error: function(err) { reject(err); }, }); }); return promise; } } let requester = new Requester(); export { requester };
var test = require('tape'), argosy = require('argosy'), hansa = require('..') test('connect/disconnect', function (t) { t.plan(8) var service1 = argosy(), service2 = argosy(), service3 = argosy(), league = hansa() var svcPattern = { help: argosy.pattern.match.defined } service1.accept(svcPattern) service2.accept(svcPattern) service3.accept(svcPattern) league.connect([service1, service2, service3], function (err) { t.false(err, 'should not supply err') t.equal(league.patterns.length, 1, 'league exposes 1 pattern before disconnect') t.equal(league.providersOfPattern(svcPattern).length, 3, 'with 3 providers before disconnect') league.connect(service1, function () { t.equal(league.patterns.length, 1, 'league exposes 1 pattern after attempting double-connect') t.equal(league.providersOfPattern(svcPattern).length, 3, 'with 3 providers after attempting double-connect') league.disconnect(service1, function () { t.equal(league.providersOfPattern(svcPattern).length, 2, 'with 2 providers after 1st disconnect') league.disconnect([service2, service3], function () { t.equal(league.patterns.length, 0, 'with 0 patterns after 2nd and 3rd disconnect') league.disconnect(service3, function (value) { t.equal(value, null, 'disconnecting a second time resolves with null value') }) }) }) }) }) })
"use strict"; /** * Keyboard input handling. An instance of Keyboard is available as {@link Splat.Game#keyboard}. * @constructor * @param {module:KeyMap} keymap A map of keycodes to descriptive key names. */ function Keyboard(keyMap) { /** * The current key states. * @member {object} * @private */ this.keys = {}; var self = this; for (var kc in keyMap) { if (keyMap.hasOwnProperty(kc)) { this.keys[keyMap[kc]] = 0; } } window.addEventListener("keydown", function(event) { event.preventDefault(); if (keyMap.hasOwnProperty(event.keyCode)) { if (self.keys[keyMap[event.keyCode]] === 0) { self.keys[keyMap[event.keyCode]] = 2; } return false; } }); window.addEventListener("keyup", function(event) { event.preventDefault(); if (keyMap.hasOwnProperty(event.keyCode)) { self.keys[keyMap[event.keyCode]] = 0; return false; } }); } /** * Test if a key is currently pressed. * @param {string} name The name of the key to test * @returns {boolean} */ Keyboard.prototype.isPressed = function(name) { return this.keys[name] >= 1; }; /** * Test if a key is currently pressed, also making it look like the key was unpressed. * This makes is so multiple successive calls will not return true unless the key was repressed. * @param {string} name The name of the key to test * @returns {boolean} */ Keyboard.prototype.consumePressed = function(name) { var p = this.keys[name] === 2; if (p) { this.keys[name] = 1; } return p; }; module.exports = Keyboard;
import Vue from 'vue'; import VueAnalytics from 'vue-analytics'; /** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ // const files = require.context('./', true, /\.vue$/i); // files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default)); Vue.component('alert', require('./components/_controls/Alert.vue').default); Vue.component('loading-overlay', require('./components/_controls/LoadingOverlay.vue').default); Vue.component('overview-1sty', require('./components/pages/Overview1stY.vue').default); Vue.component('overview-2ndy', require('./components/pages/Overview2ndY.vue').default); Vue.component('pagination', require('./components/_controls/Pagination.vue').default); Vue.component('sidebar-nav', require('./components/SidebarNav.vue').default); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ const router = require('./router').default; const store = require('./store').default; // Enable Google Analytics. Vue.use(VueAnalytics, { id: 'UA-110515281-1', router, }); let app; store.dispatch('auth/getSession').then(() => { // Create the app. app = new Vue(Vue.util.extend({ el: '#app', router: router, store: store, }, require('./components/App.vue').default)); }); // Create a global event bus. const eventBus = new Vue(); export { app, eventBus, };
//================================================ //CORE class //================================================ var core = {}; init(); function init() { function def(arg, val) { return typeof arg !== 'undefined' ? arg : val; } if (def(corep.js_show_errors, false)) window.onerror = function (msg, url, linenumber) { alert('JS ERROR\n' + msg); }; $(document).ready(function () { //Success,Info,Warning,Error toastr.options = { "closeButton": false, "debug": false, "newestOnTop": true, "progressBar": false, "positionClass": "toast-top-right", "preventDuplicates": false, "onclick": null, "showDuration": "300", "hideDuration": "1000", "timeOut": "5000", "extendedTimeOut": "1000", "showEasing": "swing", "hideEasing": "linear", "showMethod": "fadeIn", "hideMethod": "fadeOut" }; if (def(corep.js_show_errors, false)) window.onerror = function (msg, url, linenumber) { var t = 'Error message: ' + msg; toastr["error"]("JavaScript", t); }; }); var util = { dump: function (obj) { var out = ''; for (var i in obj) { out += i + ": " + obj[i] + "\n"; } return out; }, reject: function (data, yesMessage, noMessage) { if (data.result === 'ok') toastr['success'](def(yesMessage, data.message)); else toastr['error'](def(noMessage, data.message)); } }; //------------------------------------------ //Sidebar //------------------------------------------ var sidebar = { isNoBackBtn: false, //functions init: function () { var $dynamicBody = $('#dynamicBody'); $('.sidebar a', $dynamicBody).click(function () { core.sidebar.click(this); }).attr('onclick', 'return false;'); if (window.location.hash !== '') this.nav(window.location.hash); $('[data-toggle=offcanvas]', $dynamicBody).click(function () { $('.row-offcanvas', $dynamicBody).toggleClass('active'); window.scrollTo(0, 0); }); $('[data-spy=affix]', $dynamicBody).affix('checkPosition'); }, nav: function (link) { this.isNoBackBtn = true; window.location.hash = link; //set link $('.row-offcanvas.active').removeClass('active'); $('.sidebar a.active').removeClass('active'); $('.sidebar a[href="' + link + '"]').addClass('active'); //set view var n = $('.vis-blocks' + link); var c = $('.vis-blocks.active'); if (c.attr('id') === n.attr('id')) return; c.removeClass('active'); n.addClass('active'); window.scrollTo(0, 0); }, click: function (sender) { var href = $(sender).attr('href'); //hide sidebar this.nav(href); return false; } }; //------------------------------------------ //Navbar //------------------------------------------ var topnav = { //var inited: false, //functions init: function () { if (this.inited) return; $('.navbar .navbar-nav li a:not(.noajax)').click(function () { if ($(this).attr('href') !== '') { core.topnav.click(this); $(this).attr('onclick', 'return false;'); return false; } }); // $(window).resize(function(){ // core.topnav.move_hr_toActive(); // }); this.inited = true; // this.move_hr_toActive(); }, click: function (sender) { var $navbar = $('.navbar .navbar-nav'); var link = $(sender).attr('href'); core.load(link.toString().trimSlash()); if(!$(sender).hasClass('notab')) this.move_hr(sender); }, update: function () { var $navbar = $('.navbar .navbar-nav'); var link = core.uri(0); if (link.toLowerCase() === 'admin') { var d = core.uri(1); link = core.uri(0) + '/' + d; //(!d?'/':d); } $('li', $navbar).removeClass('active'); var $a = $('li a[href="/' + link + '"]', $navbar); $a.parent().addClass('active'); $('.get-title').html($a.text()); }, move_hr: function(obj){ $(function(){ //alert(typeof(obj) == 'undefined'); //console.log(obj); var tt = $('#topnav_underline'); var x = $(obj).offset().left; var w = $(obj).width(); var pl = parseInt($(obj).css('padding-left')); var pp = 4; x = x+pl-pp; w = w+pp*2; tt.css({left:x, width:w}); $('.collapse').collapse('hide'); }); }, move_hr_toActive: function(){ var p1 = $('.navbar .navbar-nav li.active'); this.move_hr(p1); } }; //------------------------------------------ //News //------------------------------------------ var news = { delete: function (id, callback, _confirm) { _confirm = def(confirm, true); if (_confirm) if (!confirm('Вы уверены что хотите удалить?')) return; if (def(id, -1) === -1) return; core.api('editor', { id: id, action: 'delete' }, function (data) { core.news.reject(data, 'Удалено', 'Ошибка при удалении'); callback(data); }); }, reject: function (data, yesMessage, noMessage) { if (data.result === 'ok') toastr['success']('Редактор', yesMessage); else toastr['error']('Редактор', noMessage); } }; var images = { previewUpdate: function () { $('img.preview').each(function () { var link = $(this).attr('src'); var j = link.split('/'); var index = $.inArray('thumbs', j); if (index > -1) j[index] = 'files'; link = j.join('/'); $(this).click(function () { // alert(link); $modal = $("#imgpreview"); // $('.modal-body',$modal).html('<img src="'+link+'"/>'); $('.img01', $modal).attr('src', link); $modal.modal(); }); }); } }; //------------------------------------------ //Core function //------------------------------------------ core.load = function (pageName) { //dynamicBody // $('#dynamicBody').html('...'); $('.navbar .loader').show(); $.ajax({ url: '/' + pageName.trimSlash(), type: 'POST', data: { ajax: true }, success: function (data) { $('.navbar .loader').hide(); $('#dynamicBody').html(data); // $('#dynamicBody').html($('body',data).html()); window.history.pushState("", document.title, "/" + pageName); core.topnav.update(); core.sidebar.init(); core.images.previewUpdate(); }, error: function () { $('.navbar .loader').hide(); $('#dynamicBody').html('<h2>Ошибка передачи данных</h2>'); } }); }; core.nav = function (uri) { window.location = uri; }; core.uri = function (index) { var path = window.location.pathname; var pp = path.trimSlash().split('/'); if (index < pp.length) return pp[index]; else return false; }; core.pushLocation = function (add) { window.history.pushState("Details", "Title", window.location + "/" + add); }; core.logout = function () { this.api('admin', { action: 'ajax_logout' }, function (data) { if (data.result === 'ok') core.nav('/'); }, true); }; core.api = function (controller, postdata, callback, reject) { postdata.ajax = true; $.post('/api/' + controller, postdata, function (data) { if (data.sys !== undefined) { if (data.sys['phper'] !== undefined) { var dump = core.util.dump(data.sys['phper']); toastr['error'](dump.replace('\n', '<br>'), 'PHP Error:'); } if (data.sys['sqler'] !== undefined) { var dump3 = core.util.dump(data.sys['sqler']); toastr['error'](dump3.replace('\n', '<br>'), 'SQL Error:'); } if (data.sys['apiInclude'] !== undefined) { var dump2 = core.util.dump(data.sys['apiInclude']); toastr['error'](dump2.replace('\n', '<br>'), 'API Error:'); } } if (def(reject, false)) core.util.reject(data.data); callback(data.data); }, 'json'); }; //append core.sidebar = sidebar; core.topnav = topnav; core.news = news; core.util = util; core.images = images; //back btn fix window.onpopstate = function () { if (core.sidebar.isNoBackBtn) { core.sidebar.isNoBackBtn = false; return; } core.sidebar.nav(location.hash); return false; }; } //core end //================================================ //PROTOTYPE //================================================ String.prototype.trimSlash = function () { return this.replace(/^\/|\/$/g, ""); }; String.prototype.format = function () { var formatted = this; for (var i = 0; i < arguments.length; i++) { var regexp = new RegExp('\\{' + i + '\\}', 'gi'); formatted = formatted.replace(regexp, arguments[i]); } return formatted; }; $.fn.hasAttr = function (name) { return this.attr(name) !== undefined; }; Object.size = function (obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; ////////////////////////////////////////////////////////////////////// function def() { for (var i = 0; i < arguments.length; i++) { if ((arguments[i] === null) || (typeof (arguments[i]) === 'undefined')) return false; } return true; } function defkey(obj,k) { return obj.hasOwnProperty(k); } ////////////////////////////////////////////////////////////////////// //Obj 'd'; coming d.record.InsertDateTime 2016-10-02T000:00:00:000 function recordInsertDateToStr(d) { var t; if (d.record.InsertDateTime == undefined) t = d.record.DateTimeInsert.split('T')[0].split('-'); else t = d.record.InsertDateTime.split('T')[0].split('-'); return "{0}-{1}-{2}".format(t[2], t[1], t[0]); } function DT_str_deprecated(d, str) { if (d.record[str] == undefined) return '-'; var dt = d.record[str].split('T'); var t = dt[0].split('-'); try { var tt = dt[1].split('.')[0].split(':'); return "{0}-{1}-{2} {3}:{4}:{5}".format(t[2], t[1], t[0], tt[0], tt[1], tt[2]); } catch (ex) { }; return "{0}-{1}-{2}".format(t[2], t[1], t[0]); } function DT_str(d, str) { if (d.record[str] == undefined) return '-'; var date = new Date(d.record[str]); //var dt = localtime.split('T'); //var t = dt[0].split('-'); //try { // var tt = dt[1].split('.')[0].split(':'); // return "{0}-{1}-{2} {3}:{4}:{5}".format(t[2], t[1], t[0], tt[0], tt[1], tt[2]); //} catch (ex) { }; //return "{0}-{1}-{2}".format(t[2], t[1], t[0]); var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds var firstDate = date; var secondDate = new Date(); var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay))); var dts; if (diffDays < 1) dts = "сегодня в" else if (diffDays < 2) dts = "вчера в" else dts = date.getDate() + "-" + date.getMonth() + "-" + date.getFullYear(); var dth = (date + "").split(" ")[4]; var r = dts + " " + dth; return r; } function q(selector) { return document.querySelector(selector); } function qa(selector) { return document.querySelectorAll(selector); } function getRandomInt(min, max) { if (!max) return Math.floor(Math.random() * (min)); else return Math.floor(Math.random() * (max - min)) + min; }
define({ "addTaskTip": "向微件添加一个或多个过滤器,并针对每个过滤器配置参数。", "enableMapFilter": "从地图中移除预设图层过滤器。", "newFilter": "新建过滤器", "filterExpression": "过滤器表达式", "layerDefaultSymbolTip": "使用图层的默认符号", "uploadImage": "上传图像", "selectLayerTip": "请选择图层。", "setTitleTip": "请设置标题。" });
/* global OC */ var _paq = _paq || []; (function() { "use strict"; var options; try { options = JSON.parse('%OPTIONS%'); } catch (err) {} if (!options || !options.url || !options.siteId) { return; } if (options.url[options.url.length - 1] !== '/') { options.url += '/'; } var app = null; var path = window.location.pathname; var pathParts = path.match(/(?:index\.php\/)?apps\/([a-z0-9]+)\/?/i) || path.match(/(?:index\.php\/)?([a-z0-9]+)(\/([a-z0-9]+))?/i) || []; if (pathParts.length >= 2) { app = pathParts[1]; if (app === 's') { // rewrite app name app = 'share'; var shareValue = $('input[name="filename"]').val(); if (shareValue) { shareValue = pathParts[3] + ' (' + shareValue + ')'; // save share id + share name in slot 3 _paq.push(['setCustomVariable', '3', 'ShareNodes', shareValue, 'page']); } else { shareValue = pathParts[3]; } // save share id in slot 2 _paq.push(['setCustomVariable', '2', 'Shares', pathParts[3], 'page']); } // save app name in slot 1 _paq.push(['setCustomVariable', '1', 'App', app, 'page']); } if (OC && OC.currentUser && options.trackUser) { // set user id _paq.push(['setUserId', OC.currentUser]); } if (options.trackDir === 'on' || options.trackDir === true) { // track file browsing $('#app-content').delegate('>div', 'afterChangeDirectory', function() { // update title and url for next page view _paq.push(['setDocumentTitle', document.title]); _paq.push(['setCustomUrl', window.location.href]); _paq.push(['trackPageView']); }); } // set piwik options _paq.push(['setTrackerUrl', options.url + 'piwik.php']); _paq.push(['setSiteId', options.siteId]); if (app !== 'files' || options.trackDir !== 'on') { // track page view _paq.push(['trackPageView']); } if (typeof Piwik === 'undefined') { // load piwik library var d = document, g = d.createElement('script'), s = d.getElementsByTagName('script')[0]; g.type = 'text/javascript'; g.async = true; g.defer = true; g.src = options.url + 'piwik.js'; s.parentNode.insertBefore(g, s); } }());
import Vue from 'vue' Vue.filter('total', (num) => { return num && num > 10000 ? parseFloat(num / 10000).toFixed(1) + '万' : num })