code
stringlengths
2
1.05M
(function () { 'use strict'; angular.module('about.module') .constant('appName', 'App Name') // version x.y.z // Where: // x = main version number, 1-~. // y = feature number, 0-9. Increase this number if the change contains new features with or without bug fixes. // z = hotfix number, 0-~. Increase this number if the change only contains bug fixes. .constant('version', 'Version 0.0.1') .constant('copyright', 'Copyright jdtibbs 2014'); })();
import Audio from './audio'; import Battle from './battle'; import Input from './input'; import Screen from './screen'; import Title from './title'; export default class Game { constructor() { this.screen = new Screen(); this.input = new Input(); Audio.play(); this.currentState = new Title(); } start() { setInterval(this.update.bind(this), 1000 / 30); } update() { this.currentState.update(this); requestAnimationFrame(() => this.draw()); if (this.input.hasKey(84)) { this.input.handleKey(84); Audio.isPlaying ? Audio.stop() : Audio.play(); } } draw() { this.screen.reset(); this.currentState.draw(this.screen); this.screen.finish(); } startBattle() { this.currentState = new Battle(this); } }
/** * Created by Chris on 29-11-13. */ !function($){ function Emitter() { this.callbacks = {}; } Emitter.prototype.on = function(event, callback){ if(!(event in this.callbacks)) this.callbacks[event] = $.Callbacks(); this.callbacks[event].add(callback); return this; }; Emitter.prototype.removeListener = function(event, callback){ if(event in this.callbacks){ this.callbacks[event].remove.apply(this.callbacks[event], Array.prototype.slice.call(arguments, 1)); } return this; }; Emitter.prototype.once = function(event, callback){ var self = this; var _once = function(){ callback(); self.removeListener(event, arguments.callee); }; return this.on(event, _once); }; Emitter.prototype.trigger = function(event, data){ if(event in this.callbacks){ this.callbacks[event].fireWith(this, Array.prototype.slice.call(arguments, 1)); } return this; }; function Client(){ Emitter.apply(this, arguments); var self = this; var ws = null; var openPromise = $.Deferred(); var reconnectTimer = null; this.connect = function(url, autoReconnect){ try { ws = new WebSocket(url); }catch(error){ console.log("Cannot create WebSocket instance"); return openPromise; } ws.addEventListener('open', function () { openPromise.resolveWith(self); self.trigger("open", arguments); }); ws.addEventListener('close', function () { openPromise.resolveWith(self); self.trigger("close", arguments); }); ws.addEventListener('error', function () { openPromise.rejectWith(self); self.trigger("error", arguments); }); ws.addEventListener('message', function (event) { self.trigger("message", [event.data]); }); if (autoReconnect && !reconnectTimer) { reconnectTimer = setInterval( function () { if (ws.readyState != WebSocket.OPEN) self.connect(url); }, 5000 ); } return openPromise; }; this.whenConnected = function(callback, context){ this.on("open", function(){callback.call(context);}); if(ws && ws.readyState == WebSocket.OPEN){ callback.call(context); } }; this.send = function(data){ return ws.send(data); }; this.close = function(){ return ws.close.apply(ws, arguments); }; }; Client.prototype = new Emitter; Client.prototype.constructor = Client; function Room (client, transport, name){ Emitter.apply(this, arguments); this.subscribed = true; this.name = name; this.transport = transport; this.client = client; } Room.prototype = new Emitter; Room.prototype.constructor = Room; Room.prototype.on = function(event, callback){ // Subscribe if we haven't done that yet if(!this.subscribed){ throw Error("Not subscribed to room " + this.name); } Emitter.prototype.on.apply(this, arguments); return this; }; Room.prototype.emit = function(event, data){ this.transport.emit(this.name, event, data); return this; }; Room.prototype.subscribe = function(){ var self = this; this.subscribed = true; this.client.whenConnected(function(){ console.log("Subscribing to room " + self.name); self.transport.emit(self.name, "subscribe"); }); return this; }; function EventTransport (client){ Emitter.apply(this, arguments); var self = this; var rooms = {}; var previousTag = 0; var generateTag = function(){ previousTag += 1; return "client-"+previousTag; }; var sendObj = function(obj){ client.send(JSON.stringify(obj)); }; var addReply = function(obj){ obj.reply = function(data){ var msg = { tag: obj.tag, data: obj.data, event: obj.event, room: obj.room }; sendObj(msg); }; }; client.on("message", function(message){ var messageObj = JSON.parse(message); addReply(messageObj); self.trigger(messageObj.event, messageObj); if('room' in messageObj){ self.room(messageObj.room).trigger(messageObj.event, messageObj); } }); this.room = function(name){ if(!(name in rooms)) rooms[name] = new Room(client, this, name); return rooms[name]; }; this.emit = function(room, event, args){ var msg = { room: room, tag: generateTag(), event: event, data: args }; sendObj(msg); return this; }; }; EventTransport.prototype = new Emitter; EventTransport.prototype.constructor = EventTransport; window.Phpws = { Client: Client, RemoteEvents: EventTransport }; }(window.jQuery);
/* eslint-disable no-console, no-shadow */ import path from 'path'; import webpack from 'webpack'; import express from 'express'; import WebpackDevServer from 'webpack-dev-server'; import chalk from 'chalk'; import webpackConfig from '../webpack.config'; import config from './config/environment'; // Launch Relay by using webpack.config.js const relayServer = new WebpackDevServer(webpack(webpackConfig), { contentBase: '/build/', stats: { colors: true }, hot: true, historyApiFallback: true }); // Serve static resources relayServer.use('/', express.static(path.join(__dirname, '../build'))); relayServer.listen(config.port, () => console.log(chalk.green(`Relay is listening on port ${config.port}`)));
var Participant = BaseModel.extend({ url: 'participant/', idAttribute: 'date', defaults: { topic: '', description: '', date: '29-02-2000', time_start: '18:00', time_end: '24:00' } }); var ParticipantCollection = BaseCollection.extend({ model: Event, url: 'participant/' });
var _ = require('lodash'); var analyticsManager = require('./analyticsManager'); var apiServer = require('./apiServer'); var config = require('./config'); var logger = require('./logger')(__filename); var analyticsSocket; apiServer.on('sockets_listening', function(){ analyticsSocket = apiServer.io.of('/analytics'); analyticsManager.subscribe('', function(data, channel){ var topic = channel.namespace; analyticsSocket.emit(topic, data); }); }); apiServer.get({ path: "/analytics/reports/:period", name: "getReports" }, function(req, res){ var periodName = req.params.period; var reports; var reportIds = [ 'event:client:fileViewed', 'event:client:indigoLinked', 'event:client:pageLoaded', 'event:server:bytesProcessed', 'event:server:fileProcessed', 'event:server:scanTime', 'event:server:scanVelocity' ]; analyticsManager.getReportsByPeriod(periodName) .then(function(reports_){ reports = reports_; }) .then(function(){ _(reportIds).each(function(reportId){ if(!_.some(reports, function(report){ return report._id === (reportId+'_'+periodName); })){ reports.push(analyticsManager.getEmptyReport(reportId, periodName)); } }); }) .then(function(){ res.send(reports); }) .fail(function(err){ res.contentType = 'text'; if(err.indexOf('Invalid report period') === 0){ res.send(404, err); } else { res.send(500, err); } }); }); apiServer.post({ path: /\/analytics\/event\/([\w:]+)(?:\/([\w\d\.]+))?/, name: "notifyEvent" }, function(req, res){ var topic = req.params[0]; var value = req.params[1]; var data = (typeof value !== 'undefined') ? { value: value } : undefined; analyticsManager.publish(topic, data); res.send(204); });
'use strict'; angular.module('pdb.version', [ 'pdb.version.interpolate-filter', 'pdb.version.version-directive' ]) .value('version', '0.1');
import React from 'react'; import { storiesOf } from '@storybook/react'; import { host } from 'storybook-host'; import { ThemeProvider } from 'styled-components'; import CloseIcon from '../index'; const customTheme = { closeFontSize: '1.75rem', closeFontWeight: 700, closeColor: 'red', closeTextShadow: '0 1px 0 blue' }; export default storiesOf('CloseIcon', module) .addDecorator( host({ align: 'center' }) ) .add('Default', () => <CloseIcon />) .add('With custom theme', () => ( <ThemeProvider theme={customTheme}> <CloseIcon /> </ThemeProvider> ));
'use strict'; var through = require('through2'); var contents = require('file-contents'); var dest = require('dest'); var loader = require('..'); /** * Example usage */ var src = loader(function (options) { return through.obj(function (file, enc, cb) { console.log('file.path', file.path); this.push(file); return cb(); }); }); src('*.js') .pipe(src('*.js')) .pipe(src('fixtures/*.txt')) .pipe(src('fixtures/*.md')) .pipe(contents()) .pipe(through.obj(function (file, enc, cb) { // console.log(file); this.push(file); return cb(); })) .on('error', console.error) .on('data', function (file) { console.log(file.path); }) .on('end', function () { console.log('example done'); });
/*globals changeCase */ import _ from 'underscore'; const URL = Npm.require('url'); const QueryString = Npm.require('querystring'); class Providers { constructor() { this.providers = []; } static getConsumerUrl(provider, url) { const urlObj = URL.parse(provider.endPoint, true); urlObj.query['url'] = url; delete urlObj.search; return URL.format(urlObj); } registerProvider(provider) { return this.providers.push(provider); } getProviders() { return this.providers; } getProviderForUrl(url) { return _.find(this.providers, function(provider) { const candidate = _.find(provider.urls, function(re) { return re.test(url); }); return candidate != null; }); } } const providers = new Providers(); providers.registerProvider({ urls: [new RegExp('https?://soundcloud.com/\\S+')], endPoint: 'https://soundcloud.com/oembed?format=json&maxheight=150' }); providers.registerProvider({ urls: [new RegExp('https?://vimeo.com/[^/]+'), new RegExp('https?://vimeo.com/channels/[^/]+/[^/]+'), new RegExp('https://vimeo.com/groups/[^/]+/videos/[^/]+')], endPoint: 'https://vimeo.com/api/oembed.json?maxheight=200' }); providers.registerProvider({ urls: [new RegExp('https?://www.youtube.com/\\S+'), new RegExp('https?://youtu.be/\\S+')], endPoint: 'https://www.youtube.com/oembed?maxheight=200' }); providers.registerProvider({ urls: [new RegExp('https?://www.rdio.com/\\S+'), new RegExp('https?://rd.io/\\S+')], endPoint: 'https://www.rdio.com/api/oembed/?format=json&maxheight=150' }); providers.registerProvider({ urls: [new RegExp('https?://www.slideshare.net/[^/]+/[^/]+')], endPoint: 'https://www.slideshare.net/api/oembed/2?format=json&maxheight=200' }); providers.registerProvider({ urls: [new RegExp('https?://www.dailymotion.com/video/\\S+')], endPoint: 'https://www.dailymotion.com/services/oembed?maxheight=200' }); RocketChat.oembed = {}; RocketChat.oembed.providers = providers; RocketChat.callbacks.add('oembed:beforeGetUrlContent', function(data) { if (data.parsedUrl != null) { const url = URL.format(data.parsedUrl); const provider = providers.getProviderForUrl(url); if (provider != null) { let consumerUrl = Providers.getConsumerUrl(provider, url); consumerUrl = URL.parse(consumerUrl, true); _.extend(data.parsedUrl, consumerUrl); data.urlObj.port = consumerUrl.port; data.urlObj.hostname = consumerUrl.hostname; data.urlObj.pathname = consumerUrl.pathname; data.urlObj.query = consumerUrl.query; delete data.urlObj.search; delete data.urlObj.host; } } return data; }, RocketChat.callbacks.priority.MEDIUM, 'oembed-providers-before'); RocketChat.callbacks.add('oembed:afterParseContent', function(data) { if (data.parsedUrl && data.parsedUrl.query) { let queryString = data.parsedUrl.query; if (_.isString(data.parsedUrl.query)) { queryString = QueryString.parse(data.parsedUrl.query); } if (queryString.url != null) { const url = queryString.url; const provider = providers.getProviderForUrl(url); if (provider != null) { if (data.content && data.content.body) { try { const metas = JSON.parse(data.content.body); _.each(metas, function(value, key) { if (_.isString(value)) { return data.meta[changeCase.camelCase(`oembed_${ key }`)] = value; } }); data.meta['oembedUrl'] = url; } catch (error) { console.log(error); } } } } } return data; }, RocketChat.callbacks.priority.MEDIUM, 'oembed-providers-after');
/** * The MIT License (MIT) * Copyright (c) 2017-present Dmitry Soshnikov <dmitry.soshnikov@gmail.com> */ const parser = require('..'); function re(regexp) { return parser.parse(regexp.toString()); } describe('basic', () => { it('char', () => { expect(re(/a/)).toEqual({ type: 'RegExp', body: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, flags: '', }); }); it('parens char', () => { expect(re(/\(\)/)).toEqual({ type: 'RegExp', body: { type: 'Alternative', expressions: [ { type: 'Char', value: '(', symbol: '(', kind: 'simple', escaped: true, codePoint: '('.codePointAt(0), }, { type: 'Char', value: ')', symbol: ')', kind: 'simple', escaped: true, codePoint: ')'.codePointAt(0), }, ], }, flags: '', }); }); it('disjunction', () => { expect(re(/a|b/)).toEqual({ type: 'RegExp', body: { type: 'Disjunction', left: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, right: { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 'b'.codePointAt(0), }, }, flags: '', }); }); it('alternative', () => { expect(re(/ab/)).toEqual({ type: 'RegExp', body: { type: 'Alternative', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 'b'.codePointAt(0), }, ], }, flags: '', }); }); it('character class', () => { expect(re(/[a-z\d]/i)).toEqual({ type: 'RegExp', body: { type: 'CharacterClass', expressions: [ { type: 'ClassRange', from: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, to: { type: 'Char', value: 'z', symbol: 'z', kind: 'simple', codePoint: 'z'.codePointAt(0), }, }, { type: 'Char', value: '\\d', kind: 'meta', codePoint: NaN, }, ], }, flags: 'i', }); expect(re(/[a\-z]/u)).toEqual({ type: 'RegExp', body: { type: 'CharacterClass', expressions: [ { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, { type: 'Char', value: '-', symbol: '-', kind: 'simple', escaped: true, codePoint: '-'.codePointAt(0), }, { type: 'Char', value: 'z', symbol: 'z', kind: 'simple', codePoint: 'z'.codePointAt(0), }, ], }, flags: 'u', }); }); it('empty class', () => { /*eslint no-empty-character-class:0*/ expect(re(/[]/)).toEqual({ type: 'RegExp', body: { type: 'CharacterClass', expressions: [], }, flags: '', }); expect(re(/[^]/)).toEqual({ type: 'RegExp', body: { type: 'CharacterClass', negative: true, expressions: [], }, flags: '', }); }); it('character class with punctuation symbols', () => { expect(re('/[!"#$%&\'()*+,./:;<=>?@^_`{|}~-]/')).toEqual({ type: 'RegExp', body: { type: 'CharacterClass', expressions: [ { type: 'Char', kind: 'simple', value: '!', symbol: '!', codePoint: '!'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '"', symbol: '"', codePoint: '"'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '#', symbol: '#', codePoint: '#'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '$', symbol: '$', codePoint: '$'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '%', symbol: '%', codePoint: '%'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '&', symbol: '&', codePoint: '&'.codePointAt(0), }, { type: 'Char', kind: 'simple', // prettier-ignore value: '\'', // prettier-ignore symbol: '\'', // prettier-ignore codePoint: '\''.codePointAt(0) }, { type: 'Char', kind: 'simple', value: '(', symbol: '(', codePoint: '('.codePointAt(0), }, { type: 'Char', kind: 'simple', value: ')', symbol: ')', codePoint: ')'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '*', symbol: '*', codePoint: '*'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '+', symbol: '+', codePoint: '+'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: ',', symbol: ',', codePoint: ','.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '.', symbol: '.', codePoint: '.'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '/', symbol: '/', codePoint: '/'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: ':', symbol: ':', codePoint: ':'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: ';', symbol: ';', codePoint: ';'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '<', symbol: '<', codePoint: '<'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '=', symbol: '=', codePoint: '='.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '>', symbol: '>', codePoint: '>'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '?', symbol: '?', codePoint: '?'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '@', symbol: '@', codePoint: '@'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '^', symbol: '^', codePoint: '^'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '_', symbol: '_', codePoint: '_'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '`', symbol: '`', codePoint: '`'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '{', symbol: '{', codePoint: '{'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '|', symbol: '|', codePoint: '|'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '}', symbol: '}', codePoint: '}'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '~', symbol: '~', codePoint: '~'.codePointAt(0), }, { type: 'Char', kind: 'simple', value: '-', symbol: '-', codePoint: '-'.codePointAt(0), }, ], }, flags: '', }); }); it('named capturing group duplicate', () => { expect(() => parser.parse('/(?<foo>)(?<foo>)/')).toThrowError( new SyntaxError(`Duplicate of the named group "foo".`) ); }); it('allow named capturing group duplicate', () => { expect(() => parser.parse('/(?<foo>)(?<foo>)/', {allowGroupNameDuplicates: true}) ).not.toThrow(); }); it('named unicode name', () => { expect(() => parser.parse('/(?<\\u{41}\\u0042>)/')).toThrowError( new SyntaxError( `invalid group Unicode name "\\u{41}\\u0042", use \`u\` flag.` ) ); expect(() => parser.parse('/(?<A>)\\k<\\u{41}>/')).toThrowError( new SyntaxError(`invalid group Unicode name "\\u{41}", use \`u\` flag.`) ); expect(() => parser.parse('/(?<\\u{41}>)/u')).not.toThrow(); expect(() => parser.parse('/(?<A>)\\k<\\u{41}>/u')).not.toThrow(); }); it('capturing group numbers', () => { expect(re('/(?:)(a)(?:)(?<name>b)/')).toEqual({ type: 'RegExp', body: { type: 'Alternative', expressions: [ { type: 'Group', capturing: false, expression: null, }, { type: 'Group', capturing: true, number: 1, expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, { type: 'Group', capturing: false, expression: null, }, { type: 'Group', capturing: true, name: 'name', nameRaw: 'name', number: 2, expression: { type: 'Char', value: 'b', symbol: 'b', kind: 'simple', codePoint: 'b'.codePointAt(0), }, }, ], }, flags: '', }); }); it('empty group', () => { expect(re(/()/)).toEqual({ type: 'RegExp', body: { type: 'Group', capturing: true, number: 1, expression: null, }, flags: '', }); // Not using `re` helper here because named groups are not yet implemented. expect(parser.parse('/(?<foo>)/')).toEqual({ type: 'RegExp', body: { type: 'Group', capturing: true, name: 'foo', nameRaw: 'foo', number: 1, expression: null, }, flags: '', }); expect(re(/(?:)/)).toEqual({ type: 'RegExp', body: { type: 'Group', capturing: false, expression: null, }, flags: '', }); }); it('non-empty group', () => { expect(re(/(a)/)).toEqual({ type: 'RegExp', body: { type: 'Group', capturing: true, number: 1, expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, flags: '', }); // Not using `re` helper here because named groups are not yet implemented. expect(parser.parse('/(?<foo>a)/')).toEqual({ type: 'RegExp', body: { type: 'Group', name: 'foo', nameRaw: 'foo', capturing: true, number: 1, expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, flags: '', }); expect(re(/(?:a)/)).toEqual({ type: 'RegExp', body: { type: 'Group', capturing: false, expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, flags: '', }); }); it('empty LA assertion', () => { expect(re(/(?=)/)).toEqual({ type: 'RegExp', body: { type: 'Assertion', kind: 'Lookahead', assertion: null, }, flags: '', }); expect(re(/(?!)/)).toEqual({ type: 'RegExp', body: { type: 'Assertion', kind: 'Lookahead', negative: true, assertion: null, }, flags: '', }); }); it('non-empty LA assertion', () => { expect(re(/(?=a)/)).toEqual({ type: 'RegExp', body: { type: 'Assertion', kind: 'Lookahead', assertion: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, flags: '', }); expect(re(/(?!a)/)).toEqual({ type: 'RegExp', body: { type: 'Assertion', kind: 'Lookahead', negative: true, assertion: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, flags: '', }); }); it('empty LB assertion', () => { // Not using `re` helper here because lookbehind // assertions are not yet implemented in JS. expect(parser.parse('/(?<=)/')).toEqual({ type: 'RegExp', body: { type: 'Assertion', kind: 'Lookbehind', assertion: null, }, flags: '', }); expect(parser.parse('/(?<!)/')).toEqual({ type: 'RegExp', body: { type: 'Assertion', kind: 'Lookbehind', negative: true, assertion: null, }, flags: '', }); }); it('non-empty LB assertion', () => { // Not using `re` helper here because lookbehind // assertions are not yet implemented in JS. expect(re('/(?<=a)/')).toEqual({ type: 'RegExp', body: { type: 'Assertion', kind: 'Lookbehind', assertion: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, flags: '', }); expect(parser.parse('/(?<!a)/')).toEqual({ type: 'RegExp', body: { type: 'Assertion', kind: 'Lookbehind', negative: true, assertion: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, flags: '', }); }); it('numeric backreference', () => { expect(re(/(a)\1\2/)).toEqual({ type: 'RegExp', body: { type: 'Alternative', expressions: [ { type: 'Group', capturing: true, number: 1, expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, { type: 'Backreference', kind: 'number', number: 1, reference: 1, }, { type: 'Char', value: '\\2', kind: 'decimal', symbol: String.fromCodePoint(2), codePoint: 2, }, ], }, flags: '', }); }); it('named backreference', () => { // Not using `re` helper here because named groups are not yet implemented expect(parser.parse('/(?<x>y)\\k<x>\\k<z>/')).toEqual({ type: 'RegExp', body: { type: 'Alternative', expressions: [ { type: 'Group', capturing: true, number: 1, name: 'x', nameRaw: 'x', expression: { type: 'Char', value: 'y', symbol: 'y', kind: 'simple', codePoint: 'y'.codePointAt(0), }, }, { type: 'Backreference', kind: 'name', number: 1, reference: 'x', referenceRaw: 'x', }, { type: 'Char', value: 'k', symbol: 'k', kind: 'simple', escaped: true, codePoint: 'k'.codePointAt(0), }, { type: 'Char', value: '<', symbol: '<', kind: 'simple', codePoint: '<'.codePointAt(0), }, { type: 'Char', value: 'z', symbol: 'z', kind: 'simple', codePoint: 'z'.codePointAt(0), }, { type: 'Char', value: '>', symbol: '>', kind: 'simple', codePoint: '>'.codePointAt(0), }, ], }, flags: '', }); }); it('non-backreferences', () => { expect(re(/(?:a)\1\k<z>/)).toEqual({ type: 'RegExp', body: { type: 'Alternative', expressions: [ { type: 'Group', capturing: false, expression: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, }, { type: 'Char', value: '\\1', symbol: String.fromCodePoint(1), kind: 'decimal', codePoint: 1, }, { type: 'Char', value: 'k', symbol: 'k', kind: 'simple', escaped: true, codePoint: 'k'.codePointAt(0), }, { type: 'Char', value: '<', symbol: '<', kind: 'simple', codePoint: '<'.codePointAt(0), }, { type: 'Char', value: 'z', symbol: 'z', kind: 'simple', codePoint: 'z'.codePointAt(0), }, { type: 'Char', value: '>', symbol: '>', kind: 'simple', codePoint: '>'.codePointAt(0), }, ], }, flags: '', }); }); it('meta chars', () => { function LettersRange(start, stop) { const range = []; for ( let idx = start.charCodeAt(0), end = stop.charCodeAt(0); idx <= end; ++idx ) { range.push(String.fromCodePoint(idx)); } return range; } const metaChars = new Set([ 't', 'n', 'r', 'd', 'D', 's', 'S', 'w', 'W', 'v', 'f', ]); const azAZRange = LettersRange('a', 'z').concat(LettersRange('A', 'Z')); for (const letter of azAZRange) { const parsedChar = parser.parse(`/\\${letter}/`).body; if (metaChars.has(letter)) { expect(parsedChar.kind).toBe('meta'); } else { expect(parsedChar.kind).not.toBe('meta'); } } // Special case for [\b] - Backspace const backspace = parser.parse('/[\\b]/').body.expressions[0]; expect(backspace.kind).toBe('meta'); }); it('unicode', () => { expect(re(/\u003B/).body).toEqual({ type: 'Char', value: '\\u003B', symbol: String.fromCodePoint(0x003b), kind: 'unicode', codePoint: 0x003b, }); // Using `u` flag, 1 digit. expect(re(/\u{9}/u).body).toEqual({ type: 'Char', value: '\\u{9}', symbol: String.fromCodePoint(9), kind: 'unicode', codePoint: 9, }); // Using `u` flag, 6 digits, 10FFFF is max. expect(re(/\u{10FFFF}/u).body).toEqual({ type: 'Char', value: '\\u{10FFFF}', symbol: String.fromCodePoint(0x10ffff), kind: 'unicode', codePoint: 0x10ffff, }); // Using `u` flag, leading zeros. expect(re(/\u{000001D306}/u).body).toEqual({ type: 'Char', value: '\\u{000001D306}', symbol: String.fromCodePoint(0x000001d306), kind: 'unicode', codePoint: 0x000001d306, }); // Not using `u` flag, not parsed as a unicode code point, // but as an (escaped) `u` character repeated 1234 times. expect(re(/\u{1234}/).body).toEqual({ type: 'Repetition', expression: { type: 'Char', value: 'u', symbol: 'u', kind: 'simple', escaped: true, codePoint: 'u'.codePointAt(0), }, quantifier: { type: 'Quantifier', kind: 'Range', from: 1234, to: 1234, greedy: true, }, }); // Using `u` flag, surrogate pairs. expect(re(/\ud83d\ude80/u).body).toEqual({ type: 'Char', value: '\\ud83d\\ude80', kind: 'unicode', symbol: String.fromCodePoint(0x1f680), codePoint: 0x1f680, isSurrogatePair: true, }); // Using `u` flag, surrogate pairs in character class. expect(re(/[\ud83d\ude80]/u).body).toEqual({ type: 'CharacterClass', expressions: [ { type: 'Char', value: '\\ud83d\\ude80', kind: 'unicode', symbol: String.fromCodePoint(0x1f680), codePoint: 0x1f680, isSurrogatePair: true, }, ], }); // Not using `u` flag, surrogate pairs are treated as two characters expect(re(/\ud83d\ude80/).body).toEqual({ type: 'Alternative', expressions: [ { type: 'Char', value: '\\ud83d', kind: 'unicode', symbol: String.fromCodePoint(0xd83d), codePoint: 0xd83d, }, { type: 'Char', value: '\\ude80', kind: 'unicode', symbol: String.fromCodePoint(0xde80), codePoint: 0xde80, }, ], }); }); it('valid sorted flags', () => { expect(re(/a/gimuy)).toEqual({ type: 'RegExp', body: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, flags: 'gimuy', }); }); it('valid not sorted flags', () => { // Not using `re` helper here because `RegExp.prototype.toString` sorts flags expect(parser.parse('/a/mgyiu')).toEqual({ type: 'RegExp', body: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, flags: 'gimuy', }); }); it('hex escape', () => { expect(re(/\x33/)).toEqual({ type: 'RegExp', body: { type: 'Char', value: '\\x33', kind: 'hex', symbol: String.fromCodePoint(0x33), codePoint: 0x33, }, flags: '', }); }); it('decimal escape', () => { expect(re(/\99/)).toEqual({ type: 'RegExp', body: { type: 'Char', value: '\\99', kind: 'decimal', symbol: String.fromCodePoint(99), codePoint: 99, }, flags: '', }); }); it('dotAll (/s) flag', () => { // Not using `re` helper here because /s flag is not yet implemented expect(parser.parse('/a/s')).toEqual({ type: 'RegExp', body: { type: 'Char', value: 'a', symbol: 'a', kind: 'simple', codePoint: 'a'.codePointAt(0), }, flags: 's', }); }); it('throws error on invalid Unicode escape', () => { expect(() => parser.parse('/\\p/u')).toThrowError(SyntaxError); expect(() => parser.parse('/\\e/u')).toThrowError(SyntaxError); expect(() => parser.parse('/\\g/u')).toThrowError(SyntaxError); expect(() => parser.parse('/\\-/u')).toThrowError(SyntaxError); }); it('should not throw when identity escape is a syntax character', () => { expect(() => parser.parse('/\\./u')).not.toThrowError(); }); });
var bracers = [ { name: "Ancient Parthan Defenders", type: "Bracers", weight: 50, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, RANDOM:3 }, secondary:{ ParthanDefenders:{ min:9, max:12 }, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_102_x1_demonhunter_male.png', flavor:'These bracers were first worn in the distant past by members of the Partha Guard. Though musty from age, they retain power that has protected the city for centuries.' }, { name:"Aughild's Search", type:"Bracers", weight:0, hc:false, season:false, craft:{ rp:25,ad:72,vc:7,fs:2,db:4 }, smartLoot:[ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ RANDOM:4 }, secondary:{ RANDOM:2 }, set:'Aughild\'s Authority', image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_009_x1_demonhunter_male.png', flavor:'Aughild had fifty demands that had to be met before he would spare the lives of the nobles. Those demands are written in the wrappings of these bracers.' }, { name: "Custerian Wristguards", type: "Bracers", weight: 100, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, CritChance:null, RANDOM:2 }, secondary:{ Custerian:null, GoldFind:null }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_107_x1_demonhunter_male.png', flavor:'"In ancient times, there lived a strange race of people—the Custerians. No one knows who they were, or what they were doing, but their legacy remains beaten into the very metal of these wristguards." —Yuan, wise man of Tufnyl' }, { name:"Demon's Animus", type:"Bracers", weight:0, hc:false, season:false, craft:{ rp:25,ad:72,vc:7,fs:2,db:4 }, smartLoot:[ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ RANDOM:4 }, secondary:{ RANDOM:2 }, set:'Demon\'s Hide', image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_011_x1_demonhunter_male.png', flavor:'Sulam met an unfortunate end when he tried to harvest the flesh of a demon that was not actually dead. He was never able to complete this, the last piece of his set. Fortunately, he left the plans for its construction.' }, { name:"Drakon's Lesson", type:"Bracers", weight:100, hc:false, season:false, smartLoot: ["Crusader"], primary:{ Strength:null, CritChance:null, RANDOM:2 }, secondary:{ Drakon:{ min:150, max:200 }, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/p2_unique_bracer_110_demonhunter_male.png', flavor:'The Elder Crusader Drakon believed in precision, and trained his apprentice to strike fewer targets, but with more power. "Would you rather face ten opponents who are slightly injured? Or seven healthy opponents, who are distracted by the three corpses at your feet?"' }, { name:"Guardian's Aversion", type:"Bracers", weight:0, hc:false, season:false, craft:{ rp:25,ad:72,vc:7,fs:2,db:4 }, smartLoot:[ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ RANDOM:4 }, secondary:{ RANDOM:2 }, set:'Guardian\'s Jeopardy', image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_010_x1_demonhunter_male.png', flavor:'The enigmatic sorcerer known only as the Guardian was convinced the world would one day turn against magic users, and he prepared himself accordingly.' }, { name: "Gungdo Gear", type: "Bracers", weight: 100, hc: false, season: false, smartLoot: [ "Monk" ], primary:{ Dexterity:null, ELEMENTAL:null, RANDOM:2, }, secondary:{ Gungdo:null, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/p2_unique_bracer_006_demonhunter_male.png', flavor:'"Cover your wrists in righteousness that you may strike with the will of the gods." —Tenets of the Veradani' }, { name: "Krelm's Buff Bracers", type: "Bracers", weight: 100, hc: false, season: true, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:1, RANDOM:3 }, secondary:{ KrelmBracer:null, RANDOM:1 }, set:'Krelm\'s Buff Bulwark', image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_set_02_x1_demonhunter_male.png', flavor:'“Twas hitherto eons past from whence Krelm the Immodest didst thitherward dash forth upon the Blazing Wastes clad only in his bogodile skin belt and bracers to face the loathsome Oglak beast and slew him thence mightily with nigh but his bare hands thereupon.” -Excerpt from Stories Meant to Frighten Small Children' }, { name:"Kethyes' Splint", type:"Bracers", weight:0, hc:false, season:false, craft:{ rp:25,ad:72,vc:7,fs:2 }, smartLoot:[ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ RANDOM:4 }, secondary:{ RANDOM:2 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_001_x1_demonhunter_male.png', flavor:'"Her arrows spent and bow snapped, she advanced into a cloud of enemy spears as they fell upon her cohort, turning them aside and throwing them back in kind." —The Amazon Princess' }, { name: "Lacuni Prowlers", type: "Bracers", weight: 25, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, AttackSpeed:{ min:5, max:6 }, MoveSpeed:{ min:10, max:12 }, RANDOM:1 }, secondary:{ Thorns:null, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_005_x1_demonhunter_male.png', flavor:'The savage fierceness of the lacuni is unrivaled in all of Sanctuary.' }, { name: "Nemesis Bracers", type: "Bracers", weight: 50, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:1, RANDOM:3 }, secondary:{ Nemesis:null, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_106_x1_demonhunter_male.png', flavor:'Wear these armguards at your own risk. Only for the heartiest of adventurers.' }, { name: "Promise of Glory", type: "Bracers", weight: 50, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, CritChance:null, RANDOM:2 }, secondary:{ PromiseOfGlory:{ min:4, max:6 }, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_002_x1_demonhunter_male.png', flavor:'Lost and found again through the ages, these bracers bear the names of all who have worn them. Each one found great glory, but not all survived to reap the rewards.' }, { name:"Ranslor's Folly", type:"Bracers", weight:100, hc:false, season:true, smartLoot:[ "Wizard" ], primary:{ Intelligence:null, CritChance:null, RANDOM:2 }, secondary:{ Ranslor:null, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_108_x1_demonhunter_male.png', flavor:'Ranslor, the chief crafter to the High Vizjerei, was concerned that the power contained within these bracers would prove too much for even the most seasoned warrior, so he scoured waterfront taverns for unfortunate souls to test them. After several catastrophic failures, he was so certain he had solved the problem he tried them himself. The bracers were found by his assistant in a pile of ash.' }, { name:"Reaper's Wraps", type:"Bracers", weight:0, hc:false, season:false, smartLoot:[ "Barbarian", "Crusader", "Demon Hunter", "Monk", "Witch Doctor", "Wizard" ], primary:{ RANDOM:4 }, secondary:{ ReapersWraps:{ min:25, max:30 }, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_103_x1_demonhunter_male.png', flavor:'"The magic emanating from these bracers is strange and unknown to us. Prior to their discovery, it was thought impossible to utilize the powers that grant one health to also regenerate one\'s might. Their very existence forces us to reconsider some of our basic understandings of the nature of magic." —Archmage Valthek' }, { name: "Shackles of the Invoker", type: "Bracers", weight: 100, hc: false, season: false, smartLoot: [ "Monk", "Barbarian", "Crusader", "Witch Doctor" ], primary:{ MAIN:null, RANDOM:3 }, secondary:{ Thorns:null, RANDOM:1 }, set:'Thorns of the Invoker', image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_set_12_x1_demonhunter_male.png', flavor:'Each of these bracers is charred and scored with gouges, as if whoever once wore the armor had tried desperately to cast it off.' }, { name: "Slave Bonds", type: "Bracers", weight: 100, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, MoveSpeed:{ min:10, max:12 }, RANDOM:2 }, secondary:{ LifeAfterKill:{ min:2083, max:4251 }, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_003_104_demonhunter_male.png', flavor:'Broken chains still dangle from these heavy iron shackles.' }, { name:"Spirit Guards", type:"Bracers", weight:100, hc:false, season:true, smartLoot: [ "Monk" ], primary:{ Dexterity:null, CritChance:null, RANDOM:2 }, secondary:{ SpiritGuard:{ min:30, max:40 }, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/p2_unique_bracer_109_demonhunter_male.png', flavor:'The Patriarchs say that when the spirit waxes, the dangers of this world wane.' }, { name: "Steady Strikers", type: "Bracers", weight: 100, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, AttackSpeed:{ min:5, max:6 }, RANDOM:2 }, secondary:{ RANDOM:2 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_004_x1_demonhunter_male.png', flavor:'You need only intend to strike your target, and your hands will wield the weapon with the confidence of a seasoned veteran.' }, { name: "Strongarm Bracers", type: "Bracers", weight: 50, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, Vitality:null, CritChance:null, RANDOM:1 }, secondary:{ Strongarm:{ min:20, max:30 }, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_007_x1_demonhunter_male.png', flavor:'A warrior wearing bracers made of Skartaran metal can best monsters twice his size.' }, { name: "Trag'Oul Coils", type: "Bracers", weight: 100, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, RANDOM:3 }, secondary:{ Tragoul:{ min:45, max:60 }, RANDOM:1 }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_104_x1_demonhunter_male.png', flavor:'"The guardian shall ever maintain his eternal watch over those who serve and protect the balance." —Excerpt from the Books of Kalan' }, { name: "Warzechian Armguards", type: "Bracers", weight: 50, hc: false, season: false, smartLoot: [ "Demon Hunter", "Monk", "Barbarian", "Crusader", "Wizard", "Witch Doctor" ], primary:{ MAIN:null, CritChance:null, RANDOM:2 }, secondary:{ PickupRadius:null, Warzechian:null }, image:'//media.blizzard.com/d3/icons/items/large/unique_bracer_101_x1_demonhunter_male.png', flavor:'"After a long search through the eastern lands, the noble leaders of House Chien chose the Artoun Clan for their personal guard. These loyal protectors are easily recognized by the distinctive armguards they wear out of pride for their service." —Abd al-Hazir, The Xiansai Chronicles' } ]; module.exports = bracers;
/** Created by paper on 15/8/25. Missing Number https://leetcode.com/problems/missing-number/ Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array. For example, Given nums = [0, 1, 3] return 2. Note: Your algorithm should run in linear runtime complexity. Could you implement it using only constant extra space complexity? */ /** * @param {number[]} nums * @return {number} */ // 题目看起来nums是排序了,其实测试数据是乱序的,这不坑爹么。。。 // 还有就是 [0,1] 返回值是 2,这个也应该在example里写一下啊!!! var missingNumber = function(nums) { var len = nums.length; var sum1 = 0; var sum2 = 0; for(var i=0; i<len; i++){ sum1 += nums[i]; sum2 += i; } return len - (sum1 - sum2); };
'use strict'; var assert = require('assert'); var fs = require('fs'); var imageSize = require('image-size'); var concat = require('concat-stream'); var Pageres = require('../'); process.chdir(__dirname); before(function () { this.timeout(20000); }); it('should generate screenshots', function (cb) { var pageres = new Pageres() .src('yeoman.io', ['480x320', '1024x768', 'iphone5s']) .src('todomvc.com', ['1280x1024', '1920x1080']); pageres.run(function (err, streams) { assert(!err, err); assert.strictEqual(streams.length, 5); assert.strictEqual(streams[0].filename, 'todomvc.com-1280x1024.png'); assert.strictEqual(streams[4].filename, 'yeoman.io-320x568.png'); streams[0].once('data', function (data) { assert(data.length > 1000); cb(); }); }); }); it('should remove special characters from the URL to create a valid filename', function (cb) { var pageres = new Pageres() .src('http://www.microsoft.com/?query=pageres*|<>:"\\', ['1024x768']); pageres.run(function (err, streams) { assert(!err, err); assert.strictEqual(streams.length, 1); assert.strictEqual(streams[0].filename, 'microsoft.com!query=pageres-1024x768.png'); cb(); }); }); it('should have a `delay` option', function (cb) { var pageres = new Pageres({ delay: 2 }) .src('http://todomvc.com', ['1024x768']); pageres.run(function (err, streams) { assert(!err, err); var now = new Date(); streams[0].once('data', function () { assert((new Date()) - now > 2000); cb(); }); }); }); it('should crop image using the `crop` option', function (cb) { var pageres = new Pageres({ crop: true }) .src('http://todomvc.com', ['1024x768']); pageres.run(function (err, streams) { assert(!err, err); streams[0].pipe(concat(function (data) { var size = imageSize(data); assert.strictEqual(size.width, 1024); assert.strictEqual(size.height, 768); cb(); })); }); }); it('should support local relative files', function (cb) { var pageres = new Pageres() .src('fixture.html', ['1024x768']); pageres.run(function (err, streams) { assert(!err, err); assert.strictEqual(streams[0].filename, 'fixture.html-1024x768.png'); streams[0].once('data', function (data) { assert(data.length > 1000); cb(); }); }); }); it('should save image', function (cb) { var pageres = new Pageres() .src('http://todomvc.com', ['1024x768']) .dest(__dirname); pageres.run(function (err) { assert(!err); assert(fs.existsSync('todomvc.com-1024x768.png')); fs.unlinkSync('todomvc.com-1024x768.png'); cb(); }); });
/** * The Module that serves as an interface to access input information. * * @class InputManager * @property {boolean[]} keysPressed - An array linking the keycodes to a boolean representing if the key is pressed or not. * @property {{isDown: boolean, position: Vector}} mouse - An object giving informations about the mouse. */ class InputManager { /** * Creates an instance of InputManager. * * @param {HTMLCanvasElement} canvas */ constructor(canvas) { this.keysPressed = []; this.mouse = { isDown: false, screenPosition: Vector.zero, position: Vector.zero, scroll: 0 } this._canvas = canvas; /////////////////////////////////////// ///// ----- EVENT LISTENERS ----- ///// /////////////////////////////////////// document.addEventListener("keydown", function (e) { engine.InputManager.keysPressed[e.keyCode] = true; }); document.addEventListener("keyup", function (e) { engine.InputManager.keysPressed[e.keyCode] = false; }); canvas.addEventListener("mousemove", function (e) { engine.InputManager.mouse.screenPosition = new Vector(e.clientX, e.clientY); engine.InputManager.$RefreshWorldPosition(); }); canvas.addEventListener("mousedown", function (e) { engine.InputManager.mouse.isDown = true; }); document.addEventListener("mouseup", function (e) { engine.InputManager.mouse.isDown = false; }); canvas.addEventListener("mousewheel", function (e) { engine.InputManager.mouse.scroll = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail))); }); } $RefreshWorldPosition() { let canvas = this._canvas; let rect = canvas.getBoundingClientRect(); let tmpPos = { x: (canvas.width / canvas.scrollWidth) * (this.mouse.screenPosition.x - rect.left), y: canvas.height - (canvas.height / canvas.scrollHeight) * (this.mouse.screenPosition.y - rect.top) }; engine.InputManager.mouse.position = engine.Camera.ScreenToWorldPoint(tmpPos); } $Update() { this.mouse.scroll = 0; } }
$(() => { setGreeting(); const baseUrl = 'https://baas.kinvey.com/'; const appKey = 'kid_S1vgc01Pb'; const appSecret = '7b2ba554530d4f38bcb3c1be124ec66b'; $('#linkHome').click(() => showView('home')); $('#linkLogin').click(() => showView('login')); $('#linkRegister').click(() => showView('register')); $('#linkList').click(() => showView('books')); $('#linkCreate').click(() => showView('create')); $('#linkLogout').click(logout); $('#viewLogin').find('form').submit(login); $('#viewRegister').find('form').submit(register); $('#viewCreate').find('form').submit(createBook); $(document).on({ ajaxStart: () => $('#loadingBox').show(), ajaxStop: () => $('#loadingBox').hide() }); $('#infoBox').click((event) => $(event.target).hide()); $('#errorBox').click((event) => $(event.target).hide()); function showInfo(message) { $('#infoBox').text(message); $('#infoBox').show(); setTimeout(() => $('#infoBox').fadeOut(), 3000); } function showError(message) { $('#errorBox').text(message); $('#errorBox').show(); } function handleError(reason) { showError(reason.responseJSON.description); } // Navigation and header function showView(name) { $('section').hide(); switch (name) { case 'home': $('#viewHome').show(); break; case 'login': $('#viewLogin').show(); break; case 'register': $('#viewRegister').show(); break; case 'books': getBooks(); $('#viewBooks').show(); break; case 'create': $('#viewCreate').show(); break; case 'edit': $('#viewEdit').show(); break; case 'logout': $('#viewLogout').show(); break; } } function makeHeader(type) { if (type === 'basic') { return { 'Authorization': 'Basic ' + btoa(appKey + ':' + appSecret), 'Content-Type': 'application/json' } } else if (type === 'kinvey') { return { 'Authorization': 'Kinvey ' + localStorage.getItem('authtoken'), 'Content-Type': 'application/json' } } } // User session function setStorage(data) { localStorage.setItem('authtoken', data._kmd.authtoken); localStorage.setItem('username', data.username); localStorage.setItem('userId', data._id); $('#loggedInUser').text(`Welcome, ${data.username}!`); setGreeting(); showView('books'); } function setGreeting() { let username = localStorage.getItem('username'); if (username !== null) { $('#loggedInUser').text(`Welcome, ${username}!`); $('#linkLogin').hide(); $('#linkRegister').hide(); $('#linkList').show(); $('#linkCreate').show(); $('#linkLogout').show(); } else { $('#loggedInUser').text(''); $('#linkLogin').show(); $('#linkRegister').show(); $('#linkList').hide(); $('#linkCreate').hide(); $('#linkLogout').hide(); } } function login(e) { e.preventDefault(); let username = $('#inputUsername').val(); let password = $('#inputPassword').val(); let req = { url: baseUrl + 'user/' + appKey + '/login', method: 'POST', headers: makeHeader('basic'), data: JSON.stringify({ username: username, password: password }), success: (data) => { showInfo('Login successful'); setStorage(data); }, error: handleError }; $.ajax(req); } function register(e) { e.preventDefault(); let username = $('#inputNewUsername').val(); let password = $('#inputNewPassword').val(); let repeat = $('#inputNewPassRepeat').val(); if (username.length === 0) { showError('Username cannot be empty'); return; } if (password.length === 0) { showError('Password cannot be empty'); return; } if (password !== repeat) { showError("Passwords don't match!"); return; } let req = { url: baseUrl + 'user/' + appKey, method: 'POST', headers: makeHeader('basic'), data: JSON.stringify({ username: username, password: password }), success: (data) => { showInfo('Registration successful'); setStorage(data); }, error: handleError }; $.ajax(req); } function logout() { let req = { url: baseUrl + 'user/' + appKey + '/_logout', method: 'POST', headers: makeHeader('kinvey'), success: logoutSuccess, error: handleError }; $.ajax(req); function logoutSuccess(data) { localStorage.clear(); setGreeting(); showView('home'); } } // Catalog function getBooks() { let tbody = $('#viewBooks').find('table').find('tbody'); tbody.empty(); let req = { url: baseUrl + 'appdata/' + appKey + '/books', method: 'GET', headers: makeHeader('kinvey'), success: displayBooks, error: handleError }; $.ajax(req); function displayBooks(data) { for (let book of data) { let actions = []; if (book._acl.creator === localStorage.getItem('userId')) { actions.push($('<button>&#9998;</button>').click(() => editBook(book))); actions.push($('<button>&#10006;</button>').click(() => deleteBook(book._id))); } let row = $('<tr>'); row.append(`<td>${book.title}</td>`); row.append(`<td>${book.author}</td>`); row.append(`<td>${book.description}</td>`); row.append($('<td>').append(actions)); row.appendTo(tbody); } } } function createBook() { let title = $('#inputNewTitle').val(); let author = $('#inputNewAuthor').val(); let description = $('#inputNewDescription').val(); if (title.length === 0) { showError('Title cannot be empty'); return; } if (author.length === 0) { showError('Author cannot be empty'); return; } let req = { url: baseUrl + 'appdata/' + appKey + '/books', method: 'POST', headers: makeHeader('kinvey'), data: JSON.stringify({ title, author, description }), success: createSuccess, error: handleError }; $.ajax(req); function createSuccess(data) { $('#viewCreate').find('form').trigger('reset'); showView('books'); } } function deleteBook(id) { let req = { url: baseUrl + 'appdata/' + appKey + '/books/' + id, method: 'DELETE', headers: makeHeader('kinvey'), success: deleteSuccess, error: handleError }; $.ajax(req); function deleteSuccess(data) { showInfo('Book deleted'); showView('books'); } } function editBook(book) { showView('edit'); $('#inputTitle').val(book.title); $('#inputAuthor').val(book.author); $('#inputDescription').val(book.description); $('#viewEdit').find('form').submit(edit); function edit() { let editedBook = { title: $('#inputTitle').val(), author: $('#inputAuthor').val(), description: $('inputDescription').val() }; if (editedBook.title.length === 0) { showError('Title cannot be empty'); return; } if (editedBook.author.length === 0) { showError('Author cannot be empty'); return; } let req = { url: baseUrl + 'appdata/' + appKey + '/books/' + book._id, method: 'PUT', headers: makeHeader('kinvey'), data: JSON.stringify(editedBook), success: editSuccess, error: handleError }; $.ajax(req); function editSuccess(data) { showInfo('Book edited'); showView('books'); } } } });
module.exports = [ /////////////////////////////////////////////////// // Device Explorer how-to doc /////////////////////////////////////////////////// { "taskType": "regexReplaceTask", "filePath": "tools/DeviceExplorer/doc/how_to_use_device_explorer.md", "search": "(https\\:\\/\\/github.com\\/Azure\\/azure-iot-sdks\\/releases\\/download\\/).*(\\/SetupDeviceExplorer.msi)", "replaceString": function(versions) { return '$1' + versions['github-release'] + '$2'; } }, { "taskType": "regexReplaceTask", "filePath": "tools/DeviceExplorer/DeviceExplorer/Properties/AssemblyInfo.cs", "search": "(AssemblyInformationalVersion\\(\").*(\"\\)\\])", "replaceString": function(versions) { return '$1' + versions['device-explorer'] + '$2'; } }, /////////////////////////////////////////////////// // C SDK /////////////////////////////////////////////////// { "taskType": "regexReplaceTask", "filePath": "build/docs/Doxyfile", "search": "(PROJECT\\_NUMBER)([ ]+\\= )(.*)", "replaceString": function(versions) { return '$1' + '$2' + versions.c.device; } }, { "taskType": "regexReplaceTask", "filePath": "c/iothub_client/inc/version.h", "search": "(IOTHUB\\_SDK\\_VERSION)([ ]+)(\".*\")", "replaceString": function(versions) { return '$1' + '$2' + '"' + versions.c.device + '"'; } }, { "taskType": "regexReplaceTask", "filePath": "c/iothub_client/tests/version_unittests/version_unittests.cpp", "search": "(\\\".*\\\")([ \t]*\\,[ \t]*IOTHUB\\_SDK\\_VERSION)", "replaceString": function(versions) { return '"' + versions.c.device + '"$2'; } }, { "taskType": "xmlReplaceTask", "filePath": "c/build_all/packaging/windows/Apache.QPID.Proton.AzureIot.nuspec", "search": "//*[local-name(.)='package' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd']/*[local-name(.)='metadata' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd']/*[local-name(.)='version' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd']", "replaceString": "qpid_proton_nuget" }, { "taskType": "xmlReplaceTask", "filePath": "c/build_all/packaging/windows/Microsoft.Azure.IoTHub.AmqpTransport.nuspec", "search": "//*[local-name(.)='package' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='metadata' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='version' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']", "replaceString": "c_nuget.device" }, { "taskType": "xmlReplaceTask", "filePath": "c/build_all/packaging/windows/Eclipse.Paho-C.paho-mqtt3cs.nuspec", "search": "//*[local-name(.)='package' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd']/*[local-name(.)='metadata' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd']/*[local-name(.)='version' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2011/08/nuspec.xsd']", "replaceString": "eclipse_paho_nuget" }, { "taskType": "xmlReplaceTask", "filePath": "c/build_all/packaging/windows/Microsoft.Azure.IoTHub.Common.nuspec", "search": "//*[local-name(.)='package' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='metadata' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='version' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']", "replaceString": "c_nuget.device" }, { "taskType": "xmlReplaceTask", "filePath": "c/build_all/packaging/windows/Microsoft.Azure.IoTHub.HttpTransport.nuspec", "search": "//*[local-name(.)='package' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='metadata' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='version' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']", "replaceString": "c_nuget.device" }, { "taskType": "xmlReplaceTask", "filePath": "c/build_all/packaging/windows/Microsoft.Azure.IoTHub.IoTHubClient.nuspec", "search": "//*[local-name(.)='package' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='metadata' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='version' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']", "replaceString": "c_nuget.device" }, { "taskType": "xmlReplaceTask", "filePath": "c/build_all/packaging/windows/Microsoft.Azure.IoTHub.MqttTransport.nuspec", "search": "//*[local-name(.)='package' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='metadata' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='version' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']", "replaceString": "c_nuget.device" }, { "taskType": "xmlReplaceTask", "filePath": "c/build_all/packaging/windows/Microsoft.Azure.IoTHub.Serializer.nuspec", "search": "//*[local-name(.)='package' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='metadata' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']/*[local-name(.)='version' and namespace-uri(.)='http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd']", "replaceString": "c_nuget.device" }, /////////////////////////////////////////////////// // C# Device SDK /////////////////////////////////////////////////// { "taskType": "regexReplaceTask", "filePath": "csharp/device/Microsoft.Azure.Devices.Client/Properties/AssemblyInfo.cs", "search": "(AssemblyInformationalVersion\\(\").*(\"\\)\\])", "replaceString": function(versions) { return '$1' + versions.csharp.device + '$2'; } }, { "taskType": "regexReplaceTask", "filePath": "csharp/device/Microsoft.Azure.Devices.Client.WinRT/Properties/AssemblyInfo.cs", "search": "(AssemblyInformationalVersion\\(\").*(\"\\)\\])", "replaceString": function(versions) { return '$1' + versions.csharp.device + '$2'; } }, /////////////////////////////////////////////////// // C# Service SDK /////////////////////////////////////////////////// { "taskType": "regexReplaceTask", "filePath": "csharp/service/Microsoft.Azure.Devices/Properties/AssemblyInfo.cs", "search": "(AssemblyInformationalVersion\\(\").*(\"\\)\\])", "replaceString": function(versions) { return '$1' + versions.csharp.service + '$2'; } }, /////////////////////////////////////////////////// // Java Device SDK POM files /////////////////////////////////////////////////// { "taskType": "xmlReplaceTask", "filePath": "java/device/pom.xml", "search": "//project/version", "replaceString": "java.device" }, { "taskType": "xmlReplaceTask", "filePath": "java/device/iothub-java-client/pom.xml", "search": "//project/parent/version", "replaceString": "java.device" }, { "taskType": "multiTask", "filePath": "java/device/samples/pom.xml", "search": [ { "taskType": "xmlReplaceTask", "search": "//project/parent/version", "replaceString": "java.device" }, { "taskType": "xmlReplaceTask", "search": "//project/dependencies/dependency[groupId = 'com.microsoft.azure.iothub-java-client']/version", "replaceString": "java.device" } ] }, { "taskType": "xmlReplaceTask", "filePath": "java/device/samples/handle-messages/pom.xml", "search": "//project/parent/version", "replaceString": "java.device" }, { "taskType": "xmlReplaceTask", "filePath": "java/device/samples/send-event/pom.xml", "search": "//project/parent/version", "replaceString": "java.device" }, { "taskType": "xmlReplaceTask", "filePath": "java/device/samples/send-serialized-event/pom.xml", "search": "//project/parent/version", "replaceString": "java.device" }, /////////////////////////////////////////////////// // Java Service SDK POM files /////////////////////////////////////////////////// { "taskType": "xmlReplaceTask", "filePath": "java/service/pom.xml", "search": "//project/version", "replaceString": "java.service" }, { "taskType": "xmlReplaceTask", "filePath": "java/service/iothub-service-sdk/pom.xml", "search": "//project/version", "replaceString": "java.service" }, { "taskType": "multiTask", "filePath": "java/service/samples/pom.xml", "search": [ { "taskType": "xmlReplaceTask", "search": "//project/version", "replaceString": "java.service" }, { "taskType": "xmlReplaceTask", "search": "//project/dependencies/dependency[groupId = 'com.microsoft.azure.iothub.service.sdk']/version", "replaceString": "java.service" } ] }, { "taskType": "multiTask", "filePath": "java/service/samples/device-manager-sample/pom.xml", "search": [ { "taskType": "xmlReplaceTask", "search": "//project/version", "replaceString": "java.service" }, { "taskType": "xmlReplaceTask", "search": "//project/dependencies/dependency[groupId = 'com.microsoft.azure.iothub.service.sdk']/version", "replaceString": "java.service" } ] }, { "taskType": "multiTask", "filePath": "java/service/samples/service-client-sample/pom.xml", "search": [ { "taskType": "xmlReplaceTask", "search": "//project/version", "replaceString": "java.service" }, { "taskType": "xmlReplaceTask", "search": "//project/dependencies/dependency[groupId = 'com.microsoft.azure.iothub.service.sdk']/version", "replaceString": "java.service" } ] }, /////////////////////////////////////////////////// // Node SDK package.json files /////////////////////////////////////////////////// { "taskType": "jsonReplaceTask", "filePath": "node/common/package.json", "search": "version", "replaceString": "node.common" }, { "taskType": "multiTask", "filePath": "node/device/package.json", "search": [ { "taskType": "jsonReplaceTask", "search": "version", "replaceString": "node.device" }, { "taskType": "jsonReplaceTask", "search": "dependencies.azure-iot-common", "replaceString": "node.common" } ] }, { "taskType": "jsonReplaceTask", "filePath": "node/device/samples/package.json", "search": "dependencies.azure-iot-device", "replaceString": "node.device" }, { "taskType": "multiTask", "filePath": "node/service/package.json", "search": [ { "taskType": "jsonReplaceTask", "search": "version", "replaceString": "node.service" }, { "taskType": "jsonReplaceTask", "search": "dependencies.azure-iot-common", "replaceString": "node.common" } ] }, { "taskType": "jsonReplaceTask", "filePath": "node/service/samples/package.json", "search": "dependencies.azure-iothub", "replaceString": "node.service" }, { "taskType": "multiTask", "filePath": "tools/iothub-explorer/package.json", "search": [ { "taskType": "jsonReplaceTask", "search": "version", "replaceString": "iothub-explorer" }, { "taskType": "jsonReplaceTask", "search": "dependencies.azure-iot-common", "replaceString": "node.common" }, { "taskType": "jsonReplaceTask", "search": "dependencies.azure-iothub", "replaceString": "node.service" } ] } ];
'Use Strict'; angular.module('App').controller('loginController', function ($scope, $state,$cordovaOauth, $localStorage, $location,$http,$ionicPopup, $firebaseObject, Auth, FURL, Utils) { var ref = new Firebase(FURL); var userkey = ""; $scope.signIn = function (user) { console.log("Enviado"); if(angular.isDefined(user)){ Utils.show(); Auth.login(user) .then(function(authData) { //console.log("id del usuario:" + JSON.stringify(authData)); ref.child('profile').orderByChild("id").equalTo(authData.uid).on("child_added", function(snapshot) { console.log(snapshot.key()); userkey = snapshot.key(); var obj = $firebaseObject(ref.child('profile').child(userkey)); obj.$loaded() .then(function(data) { console.log(data === obj); // true console.log(obj.email); $localStorage.email = obj.email; $localStorage.userkey = userkey; Utils.hide(); $state.go('home'); console.log("Starter page","Home"); }) .catch(function(error) { console.error("Error:", error); }); }); }, function(err) { Utils.hide(); Utils.errMessage(err); }); } }; });
const { update, createSession } = require('../sess') describe('sess_local', () => { it('should', () => {}) // it('should send data from one side the other side through sessions', (done) => { // const a = createSession(1) // const b = createSession(1) // const data = Buffer.from('ffff0000', 'hex') // // a.bind(() => { // a.on('message', (d) => { // expect(d.toString('hex')).toBe('ffff0000') // done() // }) // // const { port } = a.address() // // b.send(data, port) // // setInterval(() => { // update(b) // update(a) // }, 20) // }) // }) })
const config = require('../config/env'); const requestHelper = require('../helpers/request'); const pathHelper = require('../helpers/path'); /** * Get pricing information for a specified list of Instruments within an Account. * @param req * @param res * @param next * @returns {Promise.<*>} */ function pricing(req, res, next) { const accountId = req.params.accountId; const apiUrl = `${config.api.url}/accounts/${accountId}/pricing`; const reqObj = requestHelper.createGetObj(apiUrl, {}); return requestHelper.createRequest(reqObj) .then(accounts => res.json(accounts)) .catch(e => next(e)); } /** * Get a stream of Account Prices starting from when the request is made. * This pricing stream does not include every single price created for the Account, * but instead will provide at most 4 prices per second (every 250 milliseconds) * for each instrument being requested. If more than one price is created for an instrument * during the 250 millisecond window, only the price in effect at the end of the window is sent. * @param req * @param res * @param next * @returns {Promise.<*>} */ function stream(req, res, next) { const parameters = { id: req.params.accountId, }; const query = { instruments: 'EUR_USD' }; const apiUrl = pathHelper.getAccountPricingStreamUrl(parameters, query); const reqObj = requestHelper.createGetObj(apiUrl, { data: {} }); return requestHelper.createGetStreamRequest(reqObj, chunk => console.log('DATA', chunk.toString()), () => console.log('END RECEIVED'), chunk => console.log('ERROR', chunk.toString())) .catch(err => console.log(err)); } module.exports = { pricing, stream };
// Generated by psc-make version 0.6.9.5 "use strict"; var Prelude = require("Prelude"); var Control_Monad_Trans = require("Control.Monad.Trans"); var Data_Monoid = require("Data.Monoid"); var Control_Monad_Eff = require("Control.Monad.Eff"); var Control_Monad_Maybe_Trans = require("Control.Monad.Maybe.Trans"); var Control_Monad_Error_Trans = require("Control.Monad.Error.Trans"); var Control_Monad_State_Trans = require("Control.Monad.State.Trans"); var Control_Monad_Writer_Trans = require("Control.Monad.Writer.Trans"); var Control_Monad_Reader_Trans = require("Control.Monad.Reader.Trans"); var Control_Monad_RWS_Trans = require("Control.Monad.RWS.Trans"); var MonadEff = function (__superclass_Prelude$dotMonad_0, liftEff) { this["__superclass_Prelude.Monad_0"] = __superclass_Prelude$dotMonad_0; this.liftEff = liftEff; }; var monadEffEff = new MonadEff(function () { return Control_Monad_Eff.monadEff; }, Prelude.id(Prelude.categoryArr)); var liftEff = function (dict) { return dict.liftEff; }; var monadEffError = function (__dict_Monad_0) { return function (__dict_MonadEff_1) { return new MonadEff(function () { return Control_Monad_Error_Trans.monadErrorT(__dict_Monad_0); }, Prelude["<<<"](Prelude.semigroupoidArr)(Control_Monad_Trans.lift(Control_Monad_Error_Trans.monadTransErrorT)(__dict_Monad_0))(liftEff(__dict_MonadEff_1))); }; }; var monadEffMaybe = function (__dict_Monad_2) { return function (__dict_MonadEff_3) { return new MonadEff(function () { return Control_Monad_Maybe_Trans.monadMaybeT(__dict_Monad_2); }, Prelude["<<<"](Prelude.semigroupoidArr)(Control_Monad_Trans.lift(Control_Monad_Maybe_Trans.monadTransMaybeT)(__dict_Monad_2))(liftEff(__dict_MonadEff_3))); }; }; var monadEffRWS = function (__dict_Monad_4) { return function (__dict_Monoid_5) { return function (__dict_MonadEff_6) { return new MonadEff(function () { return Control_Monad_RWS_Trans.monadRWST(__dict_Monad_4)(__dict_Monoid_5); }, Prelude["<<<"](Prelude.semigroupoidArr)(Control_Monad_Trans.lift(Control_Monad_RWS_Trans.monadTransRWST(__dict_Monoid_5))(__dict_Monad_4))(liftEff(__dict_MonadEff_6))); }; }; }; var monadEffReader = function (__dict_Monad_7) { return function (__dict_MonadEff_8) { return new MonadEff(function () { return Control_Monad_Reader_Trans.monadReaderT(__dict_Monad_7); }, Prelude["<<<"](Prelude.semigroupoidArr)(Control_Monad_Trans.lift(Control_Monad_Reader_Trans.monadTransReaderT)(__dict_Monad_7))(liftEff(__dict_MonadEff_8))); }; }; var monadEffState = function (__dict_Monad_9) { return function (__dict_MonadEff_10) { return new MonadEff(function () { return Control_Monad_State_Trans.monadStateT(__dict_Monad_9); }, Prelude["<<<"](Prelude.semigroupoidArr)(Control_Monad_Trans.lift(Control_Monad_State_Trans.monadTransStateT)(__dict_Monad_9))(liftEff(__dict_MonadEff_10))); }; }; var monadEffWriter = function (__dict_Monad_11) { return function (__dict_Monoid_12) { return function (__dict_MonadEff_13) { return new MonadEff(function () { return Control_Monad_Writer_Trans.monadWriterT(__dict_Monoid_12)(__dict_Monad_11); }, Prelude["<<<"](Prelude.semigroupoidArr)(Control_Monad_Trans.lift(Control_Monad_Writer_Trans.monadTransWriterT(__dict_Monoid_12))(__dict_Monad_11))(liftEff(__dict_MonadEff_13))); }; }; }; module.exports = { MonadEff: MonadEff, liftEff: liftEff, monadEffEff: monadEffEff, monadEffMaybe: monadEffMaybe, monadEffError: monadEffError, monadEffState: monadEffState, monadEffWriter: monadEffWriter, monadEffReader: monadEffReader, monadEffRWS: monadEffRWS };
dojo.declare("Main", wm.Page, { "preferredDevice": "desktop", "i18n": true, onCloseSessionByDBCall: function(inError, inMessage) { console.debug('Start Main.onCloseSessionByDBCall'); console.debug('inMessage: ' + inMessage); this.controller.showWarningOnConnect(this.getDictionaryItem(inMessage)); console.debug('End Main.onCloseSessionByDBCall'); }, onCloseSession: function() { console.debug('Start Main.onCloseSession'); this.controller.showWarningOnConnect(this.getDictionaryItem("ERROR_MSG_REGISTER_SESSION_FAILD")); console.debug('End Main.onCloseSession'); }, onCloseWarningOnStart: function() { if (app.globalData.globalDataFound()) { this.dlgWarningOnStart.hide(); this.disconnect(this.conIdByOnCloseWarningOnStart); } }, onEnableGUI: function() { try { console.debug('Start Main.onEnableGUI'); if (!this.controller.enableGUI()) { throw this.getDictionaryItem("ERROR_MSG_BY_CONTROLLER_ENABLEGUI"); } console.debug('End Main.onEnableGUI'); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".onEnableGUI() failed: " + e.toString(), e); this.templateLogoutVar.update(); } }, setGlobalData: function() { var loginUsername = this.templateUsernameVar.getValue("dataValue"); app.initGlobalData(loginUsername); }, start: function() { try { console.debug('Start Main.start'); app.dlgLoading.setParameter(this.registerSessionVar, this.lbxMain); this.controller = new MainCtrl(app, this); console.debug('End Main.start'); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".start() failed: " + e.toString(), e); } }, onStart: function(inPage) { try { console.debug('Start Main.onStart'); console.debug('End Main.onStart'); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".onStart() failed: " + e.toString(), e); } }, onShow: function() { try { console.debug('Start Main.onShow'); if (!this.controller) { dojo.publish("session-expiration"); } else {} console.debug('End Main.onShow'); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".onShow() failed: " + e.toString(), e); } }, templateUsernameVarSuccess: function(inSender, inDeprecated) { try { app.initGlobalData(inDeprecated); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".templateUsernameVarSuccess() failed: " + e.toString(), e); } }, navCallNewAddressBeforeUpdate: function(inSender, ioInput) { try { if (!app.globalData.globalDataFound()) { this.setGlobalData(); } } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".navCallNewAddressBeforeUpdate() failed: " + e.toString(), e); } }, dlgWarningOnStartClose: function(inSender, inWhy) { try { if (!app.globalData.globalDataFound()) { this.lbxMain.setDisabled(false); this.templateLogoutVar.update(); } } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".dlgWarningOnStartClose() failed: " + e.toString(), e); } }, dlgWarningOnStartButton2Click: function(inSender, inButton, inText) { try { if (!this.conIdByOnCloseWarningOnStart) { this.conIdByOnCloseWarningOnStart = this.connect(this, "onEnableGUI", this, "onCloseWarningOnStart"); } this.templateUsernameVar.update(); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".dlgWarningOnStartButton2Click() failed: " + e.toString(), e); } }, dlgWarningOnConnectClose: function(inSender, inWhy) { try { this.templateLogoutVar.update(); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".dlgWarningOnConnectClose() failed: " + e.toString(), e); } }, mnuMainAdresseClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("NewAddress", "Neuaufnahme Adresse"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainAdresseClick() failed: " + e.toString(), e); } }, mnuMainBetriebClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("NewFactory", "Neuaufnahme Betrieb"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainAdresseClick() failed: " + e.toString(), e); } }, mnuMainMitgliedClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("NewMember", "Neuaufnahme Mitglied"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainAdresseClick() failed: " + e.toString(), e); } }, /* nach diesem Aufruf wird ein weiteres OnClick-Ereignis ausgelöst, welches die SerciceVariabel für den CheckGrant-Service startet (s. Propertyeditor) */ mnuMainTabelleClick: function(inSender /*,args*/ ) { app.controller.startAdminGrantedModuleByChannel("main-add-table"); }, /* nach diesem Aufruf wird ein weiteres OnClick-Ereignis ausgelöst, welches die SerciceVariabel für den CheckGrant-Service startet (s. Propertyeditor) */ mnuMainStrukturClick: function(inSender /*,args*/ ) { app.controller.startAdminGrantedModuleByChannel("main-add-schema"); }, closeSessionVarError: function(inSender, inError) { this.controller.startErrOnCloseDlg(inError, this.getDictionaryItem("ERROR_MSG_ERROR_CLOSE_SESSION")); }, templateLogoutVarError: function(inSender, inError) { console.debug('Start Main.templateLogoutVarError'); this.controller.handleErrorByCtrl(this.getDictionaryItem("ERROR_MSG_ERROR_ON_LOGOUT"), inError); console.debug('End Main.templateLogoutVarError'); }, invalidateSessionVarError: function(inSender, inError) { console.debug('Start Main.invalidateSessionVarError'); console.error('Fehler beim Schließen einer Sitzung: ' + inError); console.debug('End Main.invalidateSessionVarError'); }, /* nach diesem Aufruf wird ein weiteres OnClick-Ereignis ausgelöst, welches die SerciceVariabel für den CheckGrant-Service startet (s. Propertyeditor) */ mnuMainMandantClick: function(inSender /*,args*/ ) { app.controller.startAdminGrantedModuleByChannel("main-add-tenant"); }, /* nach diesem Aufruf wird ein weiteres OnClick-Ereignis ausgelöst, welches die SerciceVariabel für den CheckGrant-Service startet (s. Propertyeditor) */ mnuMainBenutzerClick: function(inSender /*,args*/ ) { app.controller.startAdminGrantedModuleByChannel("main-add-user"); }, mnuMainBenutzerrolleClick: function(inSender /*,args*/ ) { app.controller.startAdminGrantedModuleByChannel("main-add-role"); }, mnuMainAkteClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("NewDossier", "Neuaufnahme Akte"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainAkteClick() failed: " + e.toString(), e); } }, mnuMainNotizenClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("NewTicket", "Neuaufnahme Notiz"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainNotizenClick() failed: " + e.toString(), e); } }, mnuMainVorgangClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("NewProcess", "Neuaufnahme Vorgang"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainVorgangClick() failed: " + e.toString(), e); } }, mnuMainImpressumClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("ShowImpressum", "Impressum und Datenschutzerkärung"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainImpressumClick() failed: " + e.toString(), e); } }, mnuMainKontaktClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("ShowContact", "Kontakt"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainKontaktClick() failed: " + e.toString(), e); } }, mnuMainUeber_die_AnwendungClick: function(inSender /*,args*/ ) { try { app.controller.showWizard("ShowAbout", "&Uuml;ber die Anwendung"); } catch (e) { this.controller.handleExceptionByCtrl(this.name + ".mnuMainUeber_die_AnwendungClick() failed: " + e.toString(), e); } }, /* nach diesem Aufruf wird ein weiteres OnClick-Ereignis ausgelöst, welches die SerciceVariabel für den CheckGrant-Service startet (s. Propertyeditor) */ mnuMainDatenblattClick: function(inSender /*,args*/) { app.controller.startAdminGrantedModuleByChannel("main-add-datasheet"); }, _end: 0 });
/* Utilities */ import marked from 'marked'; import urlObject from 'url'; import moment from 'moment'; import getSlug from 'speakingurl'; import { getSetting, registerSetting } from './settings.js'; import { Routes } from './routes.js'; import { getCollection } from './collections.js'; import set from 'lodash/set'; import get from 'lodash/get'; import isFunction from 'lodash/isFunction'; import pluralize from 'pluralize'; import { getFieldType } from './simpleSchema_utils'; import { forEachDocumentField } from './schema_utils'; import isEmpty from 'lodash/isEmpty'; registerSetting('debug', false, 'Enable debug mode (more verbose logging)'); /** * @summary The global namespace for Vulcan utils. * @namespace Telescope.utils */ export const Utils = {}; /** * @summary Convert a camelCase string to dash-separated string * @param {String} str */ Utils.camelToDash = function (str) { return str .replace(/\W+/g, '-') .replace(/([a-z\d])([A-Z])/g, '$1-$2') .toLowerCase(); }; /** * @summary Convert a camelCase string to a space-separated capitalized string * See http://stackoverflow.com/questions/4149276/javascript-camelcase-to-regular-form * @param {String} str */ Utils.camelToSpaces = function (str) { return str.replace(/([A-Z])/g, ' $1').replace(/^./, function (str) { return str.toUpperCase(); }); }; /** * @summary Convert a string to title case ('foo bar baz' to 'Foo Bar Baz') * See https://stackoverflow.com/questions/4878756/how-to-capitalize-first-letter-of-each-word-like-a-2-word-city * @param {String} str */ Utils.toTitleCase = str => str && str .toLowerCase() .split(' ') .map(s => s.charAt(0).toUpperCase() + s.substring(1)) .join(' '); /** * @summary Convert an underscore-separated string to dash-separated string * @param {String} str */ Utils.underscoreToDash = function (str) { return str.replace('_', '-'); }; /** * @summary Convert a dash separated string to camelCase. * @param {String} str */ Utils.dashToCamel = function (str) { return str.replace(/(\-[a-z])/g, function ($1) { return $1.toUpperCase().replace('-', ''); }); }; /** * @summary Convert a string to camelCase and remove spaces. * @param {String} str */ Utils.camelCaseify = function (str) { str = this.dashToCamel(str.replace(' ', '-')); str = str.slice(0, 1).toLowerCase() + str.slice(1); return str; }; /** * @summary Trim a sentence to a specified amount of words and append an ellipsis. * @param {String} s - Sentence to trim. * @param {Number} numWords - Number of words to trim sentence to. */ Utils.trimWords = function (s, numWords) { if (!s) return s; var expString = s.split(/\s+/, numWords); if (expString.length >= numWords) return expString.join(' ') + '…'; return s; }; /** * @summary Trim a block of HTML code to get a clean text excerpt * @param {String} html - HTML to trim. */ Utils.trimHTML = function (html, numWords) { var text = Utils.stripHTML(html); return Utils.trimWords(text, numWords); }; /** * @summary Capitalize a string. * @param {String} str */ export const capitalize = function (str) { return str && str.charAt(0).toUpperCase() + str.slice(1); }; Utils.capitalize = capitalize; Utils.t = function (message) { var d = new Date(); console.log( '### ' + message + ' rendered at ' + d.getHours() + ':' + d.getMinutes() + ':' + d.getSeconds() ); // eslint-disable-line }; Utils.nl2br = function (str) { var breakTag = '<br />'; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2'); }; Utils.scrollPageTo = function (selector) { $('body').scrollTop($(selector).offset().top); }; Utils.scrollIntoView = function (selector) { if (!document) return; const element = document.querySelector(selector); if (element) { element.scrollIntoView(); } }; Utils.getDateRange = function (pageNumber) { var now = moment(new Date()); var dayToDisplay = now.subtract(pageNumber - 1, 'days'); var range = {}; range.start = dayToDisplay.startOf('day').valueOf(); range.end = dayToDisplay.endOf('day').valueOf(); // console.log("after: ", dayToDisplay.startOf('day').format("dddd, MMMM Do YYYY, h:mm:ss a")); // console.log("before: ", dayToDisplay.endOf('day').format("dddd, MMMM Do YYYY, h:mm:ss a")); return range; }; ////////////////////////// // URL Helper Functions // ////////////////////////// /** * @summary Returns the user defined site URL or Meteor.absoluteUrl. Add trailing '/' if missing */ Utils.getSiteUrl = function (addSlash = true) { let url = getSetting('siteUrl', Meteor.absoluteUrl()); if (url.slice(-1) !== '/' && addSlash) { url += '/'; } return url; }; /** * @summary Returns the user defined site URL or Meteor.absoluteUrl. Remove trailing '/' if it exists */ Utils.getRootUrl = function () { let url = getSetting('siteUrl', Meteor.absoluteUrl()); if (url.slice(-1) === '/') { url = url.slice(0, -1); } return url; }; /** * @summary The global namespace for Vulcan utils. * @param {String} url - the URL to redirect */ Utils.getOutgoingUrl = function (url) { return Utils.getSiteUrl() + 'out?url=' + encodeURIComponent(url); }; Utils.slugify = function (s) { let slug = getSlug(s, { truncate: 60, }); // can't have posts with an "edit" slug if (slug === 'edit') { slug = 'edit-1'; } return slug; }; /** * @summary Given a collection and a slug, returns the same or modified slug that's unique within the collection; * It's modified by appending a dash and an integer; eg: my-slug => my-slug-1 * @param {Object} collection * @param {string} slug * @param {string} [documentId] If you are generating a slug for an existing document, pass it's _id to * avoid the slug changing * @returns {string} The slug passed in the 2nd param, but may be */ Utils.getUnusedSlug = function (collection, slug, documentId) { // test if slug is already in use for (let index = 0; index <= Number.MAX_SAFE_INTEGER; index++) { const suffix = index ? '-' + index : ''; const documentWithSlug = collection.findOne({ slug: slug + suffix }); if (!documentWithSlug || (documentId && documentWithSlug._id === documentId)) { return slug + suffix; } } }; // Different version, less calls to the db but it cannot be used until we figure out how to use async for onCreate functions // Utils.getUnusedSlug = async function (collection, slug) { // let suffix = ''; // let index = 0; // // const slugRegex = new RegExp('^' + slug + '-[0-9]+$'); // // get all the slugs matching slug or slug-123 in that collection // const results = await collection.find( { slug: { $in: [slug, slugRegex] } }, { fields: { slug: 1, _id: 0 } }); // const usedSlugs = results.map(item => item.slug); // // increment the index at the end of the slug until we find an unused one // while (usedSlugs.indexOf(slug + suffix) !== -1) { // index++; // suffix = '-' + index; // } // return slug + suffix; // }; /** * @summary This is the same as Utils.getUnusedSlug(), but takes the name of the collection instead * @param {string} collectionName * @param {string} slug * @param {string} [documentId] * @returns {string} */ Utils.getUnusedSlugByCollectionName = function (collectionName, slug, documentId) { return Utils.getUnusedSlug(getCollection(collectionName), slug, documentId); }; Utils.getShortUrl = function (post) { return post.shortUrl || post.url; }; Utils.getDomain = function (url) { try { return urlObject.parse(url).hostname.replace('www.', ''); } catch (error) { return null; } }; // add http: if missing Utils.addHttp = function (url) { try { if (url.substring(0, 5) !== 'http:' && url.substring(0, 6) !== 'https:') { url = 'http:' + url; } return url; } catch (error) { return null; } }; ///////////////////////////// // String Helper Functions // ///////////////////////////// Utils.cleanUp = function (s) { return this.stripHTML(s); }; Utils.sanitize = function (s) { return s; }; Utils.stripHTML = function (s) { return s && s.replace(/<(?:.|\n)*?>/gm, ''); }; Utils.stripMarkdown = function (s) { var htmlBody = marked(s); return Utils.stripHTML(htmlBody); }; // http://stackoverflow.com/questions/2631001/javascript-test-for-existence-of-nested-object-key Utils.checkNested = function (obj /*, level1, level2, ... levelN*/) { var args = Array.prototype.slice.call(arguments); obj = args.shift(); for (var i = 0; i < args.length; i++) { if (!obj.hasOwnProperty(args[i])) { return false; } obj = obj[args[i]]; } return true; }; Utils.log = function (s) { if (getSetting('debug', false) || process.env.NODE_ENV === 'development') { console.log(s); // eslint-disable-line } }; // see http://stackoverflow.com/questions/8051975/access-object-child-properties-using-a-dot-notation-string Utils.getNestedProperty = function (obj, desc) { var arr = desc.split('.'); while (arr.length && (obj = obj[arr.shift()])); return obj; }; // see http://stackoverflow.com/a/14058408/649299 _.mixin({ compactObject: function (object) { var clone = _.clone(object); _.each(clone, function (value, key) { /* Remove a value if: 1. it's not a boolean 2. it's not a number 3. it's undefined 4. it's an empty string 5. it's null 6. it's an empty array */ if (typeof value === 'boolean' || typeof value === 'number') { return; } if ( value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0) ) { delete clone[key]; } }); return clone; }, }); Utils.getFieldLabel = (fieldName, collection) => { const label = collection.simpleSchema()._schema[fieldName].label; const nameWithSpaces = Utils.camelToSpaces(fieldName); return label || nameWithSpaces; }; Utils.getLogoUrl = () => { const logoUrl = getSetting('logoUrl'); if (logoUrl) { const prefix = Utils.getSiteUrl().slice(0, -1); // the logo may be hosted on another website return logoUrl.indexOf('://') > -1 ? logoUrl : prefix + logoUrl; } }; Utils.findIndex = (array, predicate) => { let index = -1; let continueLoop = true; array.forEach((item, currentIndex) => { if (continueLoop && predicate(item)) { index = currentIndex; continueLoop = false; } }); return index; }; // adapted from http://stackoverflow.com/a/22072374/649299 Utils.unflatten = function (array, options, parent, level = 0, tree) { const { idProperty = '_id', parentIdProperty = 'parentId', childrenProperty = 'childrenResults', } = options; level++; tree = typeof tree !== 'undefined' ? tree : []; let children = []; if (typeof parent === 'undefined') { // if there is no parent, we're at the root level // so we return all root nodes (i.e. nodes with no parent) children = _.filter(array, node => !get(node, parentIdProperty)); } else { // if there *is* a parent, we return all its child nodes // (i.e. nodes whose parentId is equal to the parent's id.) children = _.filter(array, node => get(node, parentIdProperty) === get(parent, idProperty)); } // if we found children, we keep on iterating if (!!children.length) { if (typeof parent === 'undefined') { // if we're at the root, then the tree consist of all root nodes tree = children; } else { // else, we add the children to the parent as the "childrenResults" property set(parent, childrenProperty, children); } // we call the function on each child children.forEach(child => { child.level = level; Utils.unflatten(array, options, child, level); }); } return tree; }; // remove the telescope object from a schema and duplicate it at the root Utils.stripTelescopeNamespace = schema => { // grab the users schema keys const schemaKeys = Object.keys(schema); // remove any field beginning by telescope: .telescope, .telescope.upvotedPosts.$, ... const filteredSchemaKeys = schemaKeys.filter(key => key.slice(0, 9) !== 'telescope'); // replace the previous schema by an object based on this filteredSchemaKeys return filteredSchemaKeys.reduce((sch, key) => ({ ...sch, [key]: schema[key] }), {}); }; /** * Get the display name of a React component * @param {React Component} WrappedComponent */ Utils.getComponentDisplayName = WrappedComponent => { return WrappedComponent.displayName || WrappedComponent.name || 'Component'; }; /** * Take a collection and a list of documents, and convert all their date fields to date objects * This is necessary because Apollo doesn't support custom scalars, and stores dates as strings * @param {Object} collection * @param {Array} list */ Utils.convertDates = (collection, listOrDocument) => { // if undefined, just return if (!listOrDocument) return listOrDocument; const isArray = listOrDocument && Array.isArray(listOrDocument); if (isArray && !listOrDocument.length) return listOrDocument; const list = isArray ? listOrDocument : [listOrDocument]; const schema = collection.simpleSchema()._schema; //Nested version const convertedList = list.map((document) => { forEachDocumentField(document, schema, ({ fieldName, fieldSchema, currentPath }) => { if (fieldSchema && getFieldType(fieldSchema) === Date) { const valuePath = `${currentPath}${fieldName}`; const value = get(document, valuePath); set(document, valuePath, new Date(value)); } }); return document; }); return isArray ? convertedList : convertedList[0]; }; Utils.encodeIntlError = error => (typeof error !== 'object' ? error : JSON.stringify(error)); Utils.decodeIntlError = (error, options = { stripped: false }) => { try { // do we get the error as a string or as an error object? let strippedError = typeof error === 'string' ? error : error.message; // if the error hasn't been cleaned before (ex: it's not an error from a form) if (!options.stripped) { // strip the "GraphQL Error: message [error_code]" given by Apollo if present const graphqlPrefixIsPresent = strippedError.match(/GraphQL error: (.*)/); if (graphqlPrefixIsPresent) { strippedError = graphqlPrefixIsPresent[1]; } // strip the error code if present const errorCodeIsPresent = strippedError.match(/(.*)\[(.*)\]/); if (errorCodeIsPresent) { strippedError = errorCodeIsPresent[1]; } } // the error is an object internationalizable const parsedError = JSON.parse(strippedError); // check if the error has at least an 'id' expected by react-intl if (!parsedError.id) { console.error('[Undecodable error]', error); // eslint-disable-line return { id: 'app.something_bad_happened', value: '[undecodable error]' }; } // return the parsed error return parsedError; } catch (__) { // the error is not internationalizable return error; } }; Utils.findWhere = (array, criteria) => array.find(item => Object.keys(criteria).every(key => item[key] === criteria[key])); Utils.defineName = (o, name) => { Object.defineProperty(o, 'name', { value: name }); return o; }; Utils.getRoutePath = routeName => { return Routes[routeName] && Routes[routeName].path; }; String.prototype.replaceAll = function (search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); }; Utils.isPromise = value => isFunction(get(value, 'then')); /** * Pluralize helper with clash name prevention (adds an S) */ Utils.pluralize = (text, ...args) => { const res = pluralize(text, ...args); // avoid edge case like "people" where plural is identical to singular, leading to name clash // in resolvers if (res === text) { return res + 's'; } return res; }; Utils.singularize = pluralize.singular; Utils.removeProperty = (obj, propertyName) => { for (const prop in obj) { if (prop === propertyName) { delete obj[prop]; } else if (typeof obj[prop] === 'object') { Utils.removeProperty(obj[prop], propertyName); } } }; /** * Convert an array of field options into an allowedValues array * @param {Array} schemaFieldOptionsArray */ Utils.getSchemaFieldAllowedValues = schemaFieldOptionsArray => { if (!Array.isArray(schemaFieldOptionsArray)) { throw new Error('Utils.getAllowedValues: Expected Array'); } return schemaFieldOptionsArray.map(schemaFieldOption => schemaFieldOption.value); }; /** * type is an array due to the possibility of using SimpleSchema.oneOf * right now we support only fields with one type * @param {Object} field */ Utils.getFieldType = field => get(field, 'type.definitions.0.type'); /** * Convert an array of field names into a Mongo fields specifier * @param {Array} fieldsArray */ Utils.arrayToFields = fieldsArray => { return _.object( fieldsArray, _.map(fieldsArray, function () { return true; }) ); }; Utils.isEmptyOrUndefined = value => typeof value === 'undefined' || value === null || //value === '' || ( typeof value === 'object' && isEmpty(value) && !(value instanceof Date) && !(value instanceof RegExp) );
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var ChordOrScaleTypeConstant; (function (ChordOrScaleTypeConstant) { ChordOrScaleTypeConstant[ChordOrScaleTypeConstant["MAJOR"] = 0] = "MAJOR"; ChordOrScaleTypeConstant[ChordOrScaleTypeConstant["MINOR"] = 1] = "MINOR"; ChordOrScaleTypeConstant[ChordOrScaleTypeConstant["DOMINANT"] = 2] = "DOMINANT"; ChordOrScaleTypeConstant[ChordOrScaleTypeConstant["SYMMETRICAL"] = 3] = "SYMMETRICAL"; ChordOrScaleTypeConstant[ChordOrScaleTypeConstant["MISCELLANEOUS"] = 4] = "MISCELLANEOUS"; ChordOrScaleTypeConstant[ChordOrScaleTypeConstant["MAIN"] = 5] = "MAIN"; })(ChordOrScaleTypeConstant = exports.ChordOrScaleTypeConstant || (exports.ChordOrScaleTypeConstant = {})); //# sourceMappingURL=chordOrScaleType.constant.js.map
module.exports = { 'development': 'mongodb://localhost:27017/tipbox_development' , 'tipbox.in': 'mongodb://localhost:27017/tipbox_production' , 'tipbox.is': 'mongodb://localhost:27017/tipbox_production' };
(function ($m) { (function(proto) { if(!proto.moveLocation) { proto.moveLocation = function(id, initLoc, locs, speed, that, startLoc) { $("#inAct-" + id).text('Flying.'); // speed = vitesse du drone en m/s if(that === undefined) { that = this; } if(startLoc === undefined) { startLoc = this.getLocation(); } // var locations = proto.nearestLocation(that, initLoc, locs); var locations = locs; var endLoc = locations[0]['location']; var nextDistance = proto.getDistance(that, endLoc); var startTime = new Date(); var finalTime = Math.round(nextDistance / speed) * 1000; // t = d/v en millisecondes var interval = window.setInterval(function() { var timeElapsed = new Date() - startTime; if (timeElapsed >= finalTime) { that.setLocation(endLoc); window.clearInterval(interval, locations[0]); if(locations.length > 1) { proto.doActionAndGo(id, initLoc, locations, speed, that, endLoc); }else { $("#inAct-" + id).text('In the recharging base.'); $("#container-loading").hide("slow"); } } var timeElapsedPercent = timeElapsed / finalTime; var latitudeDistToMove = endLoc.latitude - startLoc.latitude; var longitudeDistToMove = endLoc.longitude - startLoc.longitude; that.setLocation(new $m.Location( startLoc.latitude + (timeElapsedPercent * latitudeDistToMove), startLoc.longitude + (timeElapsedPercent * longitudeDistToMove) )); }, 10); }; } if(!proto.nearestLocation) { proto.nearestLocation = function(that, initLoc, locs) { var locations = locs.slice(); var nearestKey = false; var nearest = false; var distance = Infinity; for(var i = 0; i < locations.length; i++) { if(locations[i]['location'].latitude != initLoc.latitude && locations[i]['location'].longitude != initLoc.longitude) { var currentDistance = proto.getDistance(that, locations[i]['location']); if(currentDistance < distance) { nearestKey = i; nearest = locations[i]; distance = currentDistance; } } } if(nearest != false) { var temp = locations[0]; locations[0] = nearest; locations[nearestKey] = temp; } return locations; }; } if(!proto.getDistance) { proto.getDistance = function(that, nextLocation) { var originLocation = that.getLocation(); var R = 6371000; // metres var phi1 = originLocation.latitude * Math.PI / 180; var phi2 = nextLocation.latitude * Math.PI / 180; var deltaPhi = (nextLocation.latitude-originLocation.latitude) * Math.PI / 180; var deltaLambda = (nextLocation.longitude-originLocation.longitude) * Math.PI / 180; var a = Math.sin(deltaPhi/2) * Math.sin(deltaPhi/2) + Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda/2) * Math.sin(deltaLambda/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return Math.round(R * c); }; } if(!proto.doActionAndGo) { proto.doActionAndGo = function(id, initLoc, locations, speed, that, endLoc) { switch (locations[0]['action']) { case 'photo': $("#inAct-" + id).text('Taking a photo.'); setTimeout(function() { proto.goNext(id, initLoc, locations, speed, that, endLoc); }, 1000); break; case 'sound': $("#inAct-" + id).text('Recording a sound.'); setTimeout(function() { proto.goNext(id, initLoc, locations, speed, that, endLoc); }, 2000); break; case 'video': $("#inAct-" + id).text('Recording a video.'); setTimeout(function() { proto.goNext(id, initLoc, locations, speed, that, endLoc); }, 3000); break; case 'nothing': $("#inAct-" + id).text('Nothing'); proto.goNext(id, initLoc, locations, speed, that, endLoc); break; default: $("#inAct-" + id).text('Par défaut'); } return true; }; } if(!proto.goNext) { proto.goNext = function(id, initLoc, locations, speed, that, endLoc) { locations.shift(); proto.moveLocation(id, initLoc, locations, speed, that, endLoc); }; } if(!proto.shiftPath) { proto.shiftPath = function(arr, k) { k = k % arr.length; while (k-- > 0) { var tmp = arr[0]; for (var i = 1; i < arr.length; i++) { arr[i - 1] = arr[i]; } arr[arr.length - 1] = tmp; } } } })($m.Pushpin.prototype); })(Microsoft.Maps);
/* * Make a unique id for an element, comprising of its name and random number. * Any spaces in the name will be removed. * input : element - the element to make the unique id for * return : the unique id for the element or a blank string if the input is null. */ export default function makeUniqueIdForElement(element) { if (element === null) { return ''; } const inputType = ({}).toString.call(element).match(/\s([a-zA-Z]+)/)[1].toLowerCase(); let name = 'undefinedElement'; if (inputType === 'string') { name = element; } else if (inputType === 'object') { name = element.constructor.name; } const uniqueId = `${name}-${Math.floor(Math.random() * 0xFFFF)}`; return uniqueId.replace(/[^A-Za-z0-9-]/gi, ''); }
import CategoryComponents from './category.vue'; export default CategoryComponents;
'use strict'; // Utility functions for parsing dc-* directives (dc-multitext, etc) var dbeUtil = function() { //For use inside nested anonymous functions where the value "this" can get lost var _this = this; // --- Parsing fields --- // Return the multitext's values as [{wsid: 'en', value: 'word'}, {wsid: 'de', value: 'Wort'}] // NOTE: Returns a promise. Use .then() to access the actual data. this.dcMultitextToArray = function(elem) { var inputSystemDivs = elem.all(by.repeater('tag in config.inputSystems')); return inputSystemDivs.map(function(div) { var wsidSpan = div.element(by.css('.input-group > span.wsid')), wordElem = div.element(by.css('.input-group > input')); return wsidSpan.getText().then(function(wsid) { return wordElem.getAttribute('value').then(function(word) { return { wsid: wsid, value: word, }; }); }); }); }; // Return the multitext's values as {en: 'word', de: 'Wort'} // NOTE: Returns a promise. Use .then() to access the actual data. this.dcMultitextToObject = function(elem) { return _this.dcMultitextToArray(elem).then(function(values) { var result = {}; for (var i = 0, l = values.length; i < l; i++) { result[values[i].wsid] = values[i].value; } return result; }); }; // Returns the value of the multitext's first writing system, no matter what writing system is first // NOTE: Returns a promise. Use .then() to access the actual data. this.dcMultitextToFirstValue = function(elem) { return _this.dcMultitextToArray(elem).then(function(values) { return values[0].value; }); }; this.dcOptionListToValue = function(elem) { var select = elem.element(by.css('.controls select')); return select.element(by.css('option:checked')).getText().then(function(text) { return text; }); }; // At the moment these are identical to dc-optionlist directives. // When they change, this function will need to be rewritten this.dcMultiOptionListToValue = function(elem) { return _this.dcOptionListToValue(elem); }; this.dcPicturesToObject = function(elem) { var pictures = elem.all(by.repeater('picture in pictures')); return pictures.map(function(div) { var img = div.element(by.css('img')), caption = div.element(by.css('dc-multitext')); return img.getAttribute('src').then(function(src) { return { 'fileName': src.replace(/^.*[\\\/]/, ''), 'caption': _this.dcMultitextToObject(caption) }; }); }); }; this.dcParsingFuncs = { 'multitext': { 'multitext_as_object': _this.dcMultitextToObject, 'multitext_as_array': _this.dcMultitextToArray, 'multitext_as_first_value': _this.dcMultitextToFirstValue, 'default_strategy': 'multitext_as_object' }, 'optionlist': _this.dcOptionListToValue, 'multioptionlist': _this.dcMultiOptionListToValue, 'pictures': _this.dcPicturesToObject }; this.getParser = function(elem, multitext_strategy) { multitext_strategy = multitext_strategy || _this.dcParsingFuncs.multitext.default_strategy; var switchDiv = elem.element(by.css('[data-on="config.fields[fieldName].type"] > div')); return switchDiv.getAttribute('data-ng-switch-when').then(function(fieldType) { var parser; if (fieldType == 'multitext') { parser = _this.dcParsingFuncs[fieldType][multitext_strategy]; } else { parser = _this.dcParsingFuncs[fieldType]; } return parser; }); }; this.parseDcField = function(elem, multitext_strategy) { return _this.getParser(elem, multitext_strategy).then(function(parser) { return parser(elem); }); }; this.getFields = function(searchLabel, rootElem) { if (typeof (rootElem) === "undefined") { rootElem = element(by.css('dc-entry')); } return rootElem.all(by.cssContainingText('div[data-ng-repeat="fieldName in config.fieldOrder"]', searchLabel)); }; this.getFieldValues = function(searchLabel, multitext_strategy, rootElem) { return _this.getFields(searchLabel, rootElem).map(function(fieldElem) { return _this.parseDcField(fieldElem, multitext_strategy); }); }; this.getOneField = function(searchLabel, idx, rootElem) { if (typeof (idx) === "undefined") { idx = 0; } return _this.getFields(searchLabel, rootElem).get(idx); }; this.getOneFieldValue = function(searchLabel, idx, multitext_strategy, rootElem) { return _this.getOneField(searchLabel, idx, rootElem).then(function(fieldElem) { return _this.parseDcField(fieldElem, multitext_strategy); }); }; // For convenience in writing test code, since the values in testConstants don't match the displayed values // No need to worry about localization here, since E2E tests are all run in the English-language interface this.partOfSpeechNames = { adj: 'Adjective', adv: 'Adverb', cla: 'Classifier', n: 'Noun', nprop: 'Proper Noun', num: 'Numeral', p: 'Particle', prep: 'Preposition', pro: 'Pronoun', v: 'Verb', }; // Take an abbreviation for a part of speech and return the value that will // appear in the Part of Speech dropdown (for convenience in E2E tests). this.expandPartOfSpeech = function(posAbbrev) { return _this.partOfSpeechNames[posAbbrev] + ' (' + posAbbrev + ')'; }; }; module.exports = new dbeUtil();
/* ==================================== GMapz. Yet another gmaps manager by carlos Cabo 2015. V.2.11 https://github.com/carloscabo/gmapz ==================================== */ /** * Core and general tools */ (function($, undefined) { 'use strict'; // Singleton if (typeof window.GMapz !== 'undefined') { return; } // // Module general vars // var v = '2.10', debug = false, data = { map_api_requested: false, map_api_ready: false }, pins = null, lang = '', APIKEY = ''; // // Methods // // Return uniqueID string. function getUniqueId (len, prefix) { var chars = 'abcdefghiklmnopqrstuvwxyzABCDEFGHIKLMNOPQRSTUVWXYZ'.split(''), uniqid = ''; if (!len) { len = Math.floor(Math.random() * chars.length); } for (var i = 0; i < len; i++) { uniqid += chars[Math.floor(Math.random() * chars.length)]; } if (prefix) { uniqid = prefix + uniqid; } // one last step is to check if this ID is already taken by an element before return uniqid; } // Request API function requestAPI (callback_fn) { if (!data.map_api_requested) { if (typeof callback_fn === 'undefined') { callback_fn = 'GMapz.onApiReady'; } data.map_api_requested = true; loadScript( callback_fn ); } } // Inject GM Api function loadScript (callback_fn) { if (lang === '') { lang = $('html').attr('lang') || $('html').attr('xml:lang') || 'en'; } var script = document.createElement('script'), url = 'https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places&language='+lang+'&callback='+callback_fn; if (GMapz.APIKEY !== '') { url += '&key='+GMapz.APIKEY; } script.type = 'text/javascript'; script.src = url; document.body.appendChild(script); } // Override from outside function onGoogleMapsReady() { // Do nothing } function onApiReady() { data.map_api_ready = true; if (this.debug) console.info('google.maps api loaded -> call gmapz.maps / autocomplete instances'); GMapz.onGoogleMapsReady(); // Prepare custom if any pins (we need google.maps) if(GMapz.pins) { GMapz.createCustomPins(); } // Alert each map instance $('[data-gmapz], [data-gmapz-autocomplete]').each(function(idx, el) { $(el)[0].gmapz.instanceReady(); }); } // Pin creation function createCustomPins() { var _p = $.extend(true, {}, this.pins); // Clone this.pins = {}; // Erase // Create pins for (var key in _p) { // Pins if (_p.hasOwnProperty(key) && _p[key].pin.img) { this.pins[key] = {}; // Replace .svg in IE by .png var temp_pin_img = _p[key].pin.img; if ((!!navigator.userAgent.match(/Trident/g) || !!navigator.userAgent.match(/MSIE/g)) && temp_pin_img.split('.').pop().toLowerCase() === 'svg' ) { temp_pin_img = temp_pin_img.substr(0, temp_pin_img.lastIndexOf('.')) + '.png'; } this.pins[key].pin = new google.maps.MarkerImage(temp_pin_img, // width / height new google.maps.Size(_p[key].pin.size[0], _p[key].pin.size[1]), // origin new google.maps.Point(0,0), // anchor point new google.maps.Point(_p[key].pin.anchor[0], _p[key].pin.anchor[1]) ); } } } // Given a center (cx, cy) and a corner (rx, ry) // Returns the opposite corner of rectangle function getOppositeCorner(cx, cy, rx, ry) { var x = cx + (cx - rx), y = cy + (cy - ry); return new google.maps.LatLng(x,y); } // Converts google.maps bounds object into "NW_lat, NW_lng, SE_lat, SE_lng" sting function serializeBounds (bounds) { var sw = bounds.getSouthWest(), ne = bounds.getNorthEast(); return [sw.lat(), sw.lng(), ne.lat(), ne.lng()].join(','); } // Initialize buttons to control the map(s) // Buttons may have data-gmapz-target attribute, read the doc // For functionallity function attachActionButtons () { // Generic elements but select / <a> $(document).on('click', '*[data-gmapz-target]:not(select)', function (e) { e.preventDefault(); var target = $(this).attr('data-gmapz-target'); // Get all data attributes ans send them to gmapz handler and the element $('[data-gmapz="'+target+'"]')[0].gmapz.btnAction($(this).data(), $(this)); }).on('change', 'select[data-gmapz-target]', function (e) { // <select> var target = $(this).attr('data-gmapz-target'); $('[data-gmapz="'+target+'"]')[0].gmapz.btnAction($(this).find('option:selected').data()); }); } // // Public methods / properties // window.GMapz = { onGoogleMapsReady: onGoogleMapsReady, attachActionButtons: attachActionButtons, getOppositeCorner: getOppositeCorner, createCustomPins: createCustomPins, onApiReady: onApiReady, requestAPI: requestAPI, getUniqueId: getUniqueId, debug: debug, data: data, pins: pins // Custom pins }; }(jQuery));
define([ 'dojo/store/Memory' ], function( Memory ){ return new Memory({ idProperty: 'id', data: [ {id: 'large', size: 7, text: '<span class="font-large">Large</span>'}, {id: 'normal', size: 4, text: '<span class="font-normal">Normal</span>'}, {id: 'small', size: 2, text: '<span class="font-small">Small</span>'}, {id: 'mini', size: 1, text: '<span class="font-mini">Mini</span>'} ] }); });
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'find', 'vi', { find: 'Tìm kiếm', findOptions: 'Tìm tùy chọn', findWhat: 'Tìm chuỗi:', matchCase: 'Phân biệt chữ hoa/thường', matchCyclic: 'Giống một phần', matchWord: 'Giống toàn bộ từ', notFoundMsg: 'Không tìm thấy chuỗi cần tìm.', replace: 'Thay thế', replaceAll: 'Thay thế tất cả', replaceSuccessMsg: '%1 vị trí đã được thay thế.', replaceWith: 'Thay bằng:', title: 'Tìm kiếm và thay thế' } );
import Bootstrapper from './setup/Bootstrapper'; Bootstrapper.bootstrap();
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import Player from '../components/Player'; import { removeFromQueue } from '../../track/actions'; class SideBar extends Component { constructor(props) { super(props); } render() { var style = { width: 300, float: 'right', 'height': '100%', overflow: 'auto', } console.log(this.props); return ( <div style={style}> <Player nowPlaying={this.props.trackQueue[0]} removeFromQueue={this.props.removeFromQueue} /> </div> ) } } function mapStateToProps(state) { return {trackQueue: state.trackQueue}; } function mapDispatchToProps(dispatch) { return bindActionCreators({ removeFromQueue }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(SideBar);
/* --- AUTOGENERATED FILE ----------------------------- * If you make changes to this file delete this comment. * Otherwise the file may be overwritten in the future. * --------------------------------------------------- */ const { mergeLocMatchGroups } = require('../lib/matching/utils'); const { regexMatchLocs } = require('../lib/matching/regexMatch'); const allSetSrc = { type: 'website', url: 'https://resources.allsetlearning.com/chinese/grammar/ASGP000J', name: 'AllSet Chinese Grammar Wiki', }; module.exports = { id: 'yizhi', structures: ['Subj. + 一直 + Predicate'], description: '一直 (yīzhí) literally means "straight." Used as an adverb, 一直 (yīzhí) can also be used to express that you have been doing something all along, have been continuously doing something since a certain time, or that something will continuously happen in the future.', sources: [allSetSrc], match: sentence => mergeLocMatchGroups([regexMatchLocs(sentence.text, /(一直)/)]), examples: [ { zh: '我一直在学习中文。', en: "I've been studying Chinese all along.", src: allSetSrc, }, { zh: '昨天晚上我一直在做作业。', en: 'Yesterday evening I was continuously doing homework.', src: allSetSrc, }, { zh: '老板一直很忙。', en: 'The boss is always very busy.', src: allSetSrc, }, { zh: '我一直很喜欢你。', en: "I've always liked you a lot.", src: allSetSrc, }, { zh: '爸爸一直都不抽烟。', en: 'Dad has never smoked cigarettes.', src: allSetSrc, }, { zh: '我男朋友一直在中国教英文。', en: 'My boyfriend has always been teaching English in China.', src: allSetSrc, }, { zh: '18岁以后,他一直一个人住。', en: 'Since he was 18, he has always lived alone.', src: allSetSrc, }, { zh: '你一直在这家公司工作吗?', en: 'Have you always worked in this company?', src: allSetSrc, }, { zh: '你们一直住在一起吗?', en: 'Have you always been living together?', src: allSetSrc, }, { zh: '北京的空气一直很不好。', en: 'The air in Beijing has been bad for a while.', src: allSetSrc, }, ], };
ko.computedContext = ko.dependencyDetection = (function () { var outerFrames = [], currentFrame, lastId = 0; // Return a unique ID that can be assigned to an observable for dependency tracking. // Theoretically, you could eventually overflow the number storage size, resulting // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53 // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would // take over 285 years to reach that number. // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html function getId() { return ++lastId; } function begin(options) { outerFrames.push(currentFrame); currentFrame = options; } function end() { currentFrame = outerFrames.pop(); } return { begin: begin, end: end, registerDependency: function (subscribable) { if (currentFrame) { if (!ko.isSubscribable(subscribable)) throw new Error("Only subscribable things can act as dependencies"); currentFrame.callback.call(currentFrame.callbackTarget, subscribable, subscribable._id || (subscribable._id = getId())); } }, ignore: function (callback, callbackTarget, callbackArgs) { try { begin(); return callback.apply(callbackTarget, callbackArgs || []); } finally { end(); } }, getDependenciesCount: function () { if (currentFrame) return currentFrame.computed.getDependenciesCount(); }, getDependencies: function () { if (currentFrame) return currentFrame.computed.getDependencies(); }, isInitial: function() { if (currentFrame) return currentFrame.isInitial; } }; })(); ko.exportSymbol('computedContext', ko.computedContext); ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount); ko.exportSymbol('computedContext.getDependencies', ko.computedContext.getDependencies); ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial); ko.exportSymbol('computedContext.registerDependency', ko.computedContext.registerDependency); ko.exportSymbol('ignoreDependencies', ko.ignoreDependencies = ko.dependencyDetection.ignore);
/** * Incubation stat extends egg state to draw the incubation lamp over it * TECHNICALLY this is an exercise but it shares more code with the egg class */ import { EmptyPhrasebook } from '../../text/phrasebooks/phrasebook' import AIncubate from '../../animation/incubate' import { STATS, STATES } from '../../constants' import { MAX_EGG_LEVEL, ENERGY_COST_INCUBATE } from '../../balance' import Exert from './exert' import { BABY_EMOJI, INCUBATE_VERB } from '../../text/game-text' export default class Incubate extends Exert { constructor(savedState, reps) { super(savedState, reps) this.id = STATES.EGG this.stat = STATS.EGG this.fatigueCost = ENERGY_COST_INCUBATE this.phrasebook = new EmptyPhrasebook() this.anim = new AIncubate(savedState.anim) this.idleState = STATES.BABY this.verb = INCUBATE_VERB this.emoji = BABY_EMOJI } // have to override this because this has a different stat max _doTransitionToIdle(friendo) { if (friendo.getStat(this.stat) === MAX_EGG_LEVEL) return true else if (this.reps <= 0) return true return false } _doTransitionToSleep() { return false } }
() => { const [startDate, setStartDate] = useState(new Date()); const ExampleCustomTimeInput = ({ date, value, onChange }) => ( <input value={value} onChange={(e) => onChange(e.target.value)} style={{ border: "solid 1px pink" }} /> ); return ( <DatePicker selected={startDate} onChange={(date) => setStartDate(date)} showTimeInput customTimeInput={<ExampleCustomTimeInput />} /> ); };
angular.module('labController', ['ngCookies','angular.filter']) // inject the Todo service factory into our controller .controller('mainController', ['$scope','$http','$cookies','$filter','Labs', function($scope, $http, $cookies,$filter, Labs) { $scope.formData = {}; $scope.loading = true; $scope.usercookie = $cookies.get('userid'); // GET by user ===================================================================== // when landing on the page, get all labs and show the // use the service to get all the labs var labuser = $scope.usercookie; Labs.getbyuser(labuser) .success(function(data) { $scope.labsbyuser = data; $scope.loading = false; }); // GET ===================================================================== // when landing on the page, get all labs and show them // use the service to get all the labs // Labs.get() // .success(function(data) { // $scope.labs = data; // $scope.loading = false; // }); Labs.getbyarch('Enterprise Networks') .success(function(data) { $scope.enlabs = data; $scope.loading = false; }); Labs.getbyarch('Datacenter',labuser) .success(function(data) { $scope.dclabs = data; $scope.loading = false; }); Labs.getbyarch('Collaboration',labuser) .success(function(data) { $scope.collablabs = data; $scope.loading = false; }); Labs.getbyarch('Security',labuser) .success(function(data) { $scope.seclabs = data; $scope.loading = false; }); Labs.getbyarch('Devnet',labuser) .success(function(data) { $scope.devnetlabs = data; $scope.loading = false; }); Labs.getbyarch('Meraki',labuser) .success(function(data) { $scope.merakilabs = data; $scope.loading = false; }); // CREATE ================================================================== // when submitting the add form, send the text to the node API $scope.createLab = function() { // validate the formData to make sure that something is there // if form is empty, nothing will happen if ($scope.formData.labname != undefined) { $scope.loading = true; // call the create function from our service (returns a promise object) Labs.create($scope.formData) // if successful creation, call our get function to get all the new todos .success(function(data) { $scope.loading = false; $scope.formData = {}; // clear the form so our user is ready to enter another $scope.labs = data; // assign our new list of todos }); } }; // DELETE ================================================================== // delete a lab after checking it $scope.deleteLab = function(id) { $scope.loading = true; Labs.delete(id) // if successful creation, call our get function to get all the new todos .success(function(data) { $scope.loading = false; $scope.labs = data; // assign our new list of todos }); }; // BOOK ================================================================== // BOOK a lab after checking it $scope.bookLab = function(labuser,labname) { $scope.loading = true; angular.forEach($scope.labsbyuser,function(value,index){ if(labname == value.labname){ alert('Sorry you have aleady requested that lab'); labname = 'null' } }) Labs.booklab(labuser,labname) // if successful creation, call our get function to get all the new labs .success(function(data) { $scope.loading = false; Labs.getbyuser(labuser) .success(function(data) { $scope.labsbyuser = data; Labs.getbyarch('Enterprise Networks') .success(function(data) { $scope.enlabs = data; $scope.loading = false; }); Labs.getbyarch('Datacenter') .success(function(data) { $scope.dclabs = data; $scope.loading = false; }); Labs.getbyarch('Collaboration') .success(function(data) { $scope.collablabs = data; $scope.loading = false; }); Labs.getbyarch('Security') .success(function(data) { $scope.seclabs = data; $scope.loading = false; }); Labs.getbyarch('Devnet') .success(function(data) { $scope.devnetlabs = data; $scope.loading = false; }); Labs.getbyarch('Meraki') .success(function(data) { $scope.merakilabs = data; $scope.loading = false; }); $scope.loading = false; }); }); }; }]);
#!/usr/bin/env node 'use strict'; var fs = require('fs'); var join = require('path').join; var shiny = function (name) { name = name.charAt(0).toUpperCase() + name.substring(1).toLowerCase(); name = name.replace('.jpg', ''); name = name.replace('.png', ''); name = name.replace(/-/g, ' '); name = name.replace(/ã©/g, 'é'); name = name.replace(/ã§/g, 'ç'); return name; }; var slugify = function (name) { name = name.toLowerCase(); name = name.replace(/ /g, '-'); name = name.replace(/_/g, '-'); name = name.replace(/ã©/g, 'é'); name = name.replace(/ã§/g, 'ç'); return name; }; module.exports = function (root) { var result = []; var queue = ['/']; while (queue.length) { var d = queue.shift(); fs.readdirSync(join(root, d)).sort().forEach(function (entry) { var f = join(root, d, entry); var stat = fs.statSync(f); if (stat.isDirectory() && entry != 'node_modules') { queue.push(join(d, entry)); } else { if (/.png/i.test(entry) || /.jpg/i.test(entry)) { var filename = slugify(entry); fs.renameSync(f, join(root, d, filename)); if (d == '/') { result.push({ uri: '.' + d + filename, name: shiny(entry) }); } else { result.push({ uri: '.' + d + '/' + filename, name: shiny(entry) }); } } } }); } return result; };
function Solve(args) { var fieldSizes = args[0].split(" "); var rows = parseInt(fieldSizes[0]); var cols = parseInt(fieldSizes[1]); var startPosition = args[1].split(" "); var startRow = parseInt(startPosition[0]); var startCol = parseInt(startPosition[1]); var fieldNumbers = new Array(rows); var fieldDirections = new Array(rows); var visited = new Array(rows); var value = 1; for (var row = 0; row < rows; row++) { fieldNumbers[row] = new Array(cols); fieldDirections[row] = new Array(cols); visited[row] = new Array(cols); for (var col = 0; col < cols; col++) { fieldNumbers[row][col] = value++; fieldDirections[row][col] = args[row + 2][col]; visited[row][col] = false; } } var newCoordsAddition; var sumOfNumbers = 0; var numberOfCells = 0; while (true) { sumOfNumbers += fieldNumbers[startRow][startCol]; numberOfCells++; visited[startRow][startCol] = true; newCoordsAddition = processDirection(fieldDirections[startRow][startCol]); startRow += newCoordsAddition[0]; startCol += newCoordsAddition[1]; if (!isInField(startRow, startCol, fieldNumbers)) { return "out " + sumOfNumbers; } if (visited[startRow][startCol]) { return "lost " + numberOfCells; } } } function isInField(row, col, field) { if (row < 0 || row >= field.length) { return false; } if (col < 0 || col >= field[0].length) { return false; } return true; } function processDirection(direction) { if (direction == "r") { return [0, 1]; } else if (direction == "l") { return [0, -1]; } else if (direction == "d") { return [1, 0]; } else { return [-1, 0] } }
var SkyRTC = function() { var PeerConnection = (window.PeerConnection || window.webkitPeerConnection00 || window.webkitRTCPeerConnection || window.mozRTCPeerConnection); var URL = (window.URL || window.webkitURL || window.msURL || window.oURL); var getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); var nativeRTCIceCandidate = (window.mozRTCIceCandidate || window.RTCIceCandidate); var nativeRTCSessionDescription = (window.mozRTCSessionDescription || window.RTCSessionDescription); // order is very important: "RTCSessionDescription" defined in Nighly but useless var moz = !!navigator.mozGetUserMedia; var iceServer = { "iceServers": [{ "url": "stun:stun.l.google.com:19302" }] }; var packetSize = 1000; /**********************************************************/ /* */ /* 事件处理器 */ /* */ /**********************************************************/ function EventEmitter() { this.events = {}; } //绑定事件函数 EventEmitter.prototype.on = function(eventName, callback) { this.events[eventName] = this.events[eventName] || []; this.events[eventName].push(callback); }; //触发事件函数 EventEmitter.prototype.emit = function(eventName, _) { var events = this.events[eventName], args = Array.prototype.slice.call(arguments, 1), i, m; if (!events) { return; } for (i = 0, m = events.length; i < m; i++) { events[i].apply(null, args); } }; /**********************************************************/ /* */ /* 流及信道建立部分 */ /* */ /**********************************************************/ /*******************基础部分*********************/ function skyrtc() { //本地media stream this.localMediaStream = null; //所在房间 this.room = ""; //接收文件时用于暂存接收文件 this.fileData = {}; //本地WebSocket连接 this.socket = null; //本地socket的id,由后台服务器创建 this.me = null; //保存所有与本地相连的peer connection, 键为socket id,值为PeerConnection类型 this.peerConnections = {}; //保存所有与本地连接的socket的id this.connections = []; //初始时需要构建链接的数目 this.numStreams = 0; //初始时已经连接的数目 this.initializedStreams = 0; //保存所有的data channel,键为socket id,值通过PeerConnection实例的createChannel创建 this.dataChannels = {}; //保存所有发文件的data channel及其发文件状态 this.fileChannels = {}; //保存所有接受到的文件 this.receiveFiles = {}; } //继承自事件处理器,提供绑定事件和触发事件的功能 skyrtc.prototype = new EventEmitter(); /*************************服务器连接部分***************************/ //本地连接信道,信道为websocket skyrtc.prototype.connect = function(server, room) { var socket, that = this; room = room || ""; socket = this.socket = new WebSocket(server); socket.onopen = function() { socket.send(JSON.stringify({ "eventName": "__join", "data": { "room": room } })); that.emit("socket_opened", socket); }; socket.onmessage = function(message) { var json = JSON.parse(message.data); if (json.eventName) { that.emit(json.eventName, json.data); } else { that.emit("socket_receive_message", socket, json); } }; socket.onerror = function(error) { that.emit("socket_error", error, socket); }; socket.onclose = function(data) { that.localMediaStream.close(); var pcs = that.peerConnections; for (i = pcs.length; i--;) { that.closePeerConnection(pcs[i]); } that.peerConnections = []; that.dataChannels = {}; that.fileChannels = {}; that.connections = []; that.fileData = {}; that.emit('socket_closed', socket); }; this.on('_peers', function(data) { //获取所有服务器上的 that.connections = data.connections; that.me = data.you; that.emit("get_peers", that.connections); that.emit('connected', socket); }); this.on("_ice_candidate", function(data) { var candidate = new nativeRTCIceCandidate(data); var pc = that.peerConnections[data.socketId]; pc.addIceCandidate(candidate); that.emit('get_ice_candidate', candidate); }); this.on('_new_peer', function(data) { that.connections.push(data.socketId); var pc = that.createPeerConnection(data.socketId), i, m; pc.addStream(that.localMediaStream); that.emit('new_peer', data.socketId); }); this.on('_remove_peer', function(data) { var sendId; that.closePeerConnection(that.peerConnections[data.socketId]); delete that.peerConnections[data.socketId]; delete that.dataChannels[data.socketId]; for (sendId in that.fileChannels[data.socketId]) { that.emit("send_file_error", new Error("Connection has been closed"), data.socketId, sendId, that.fileChannels[data.socketId][sendId].file); } delete that.fileChannels[data.socketId]; that.emit("remove_peer", data.socketId); }); this.on('_offer', function(data) { that.receiveOffer(data.socketId, data.sdp); that.emit("get_offer", data); }); this.on('_answer', function(data) { that.receiveAnswer(data.socketId, data.sdp); that.emit('get_answer', data); }); this.on('send_file_error', function(error, socketId, sendId, file) { that.cleanSendFile(sendId, socketId); }); this.on('receive_file_error', function(error, sendId) { that.cleanReceiveFile(sendId); }); this.on('ready', function() { that.createPeerConnections(); that.addStreams(); that.addDataChannels(); that.sendOffers(); }); }; /*************************流处理部分*******************************/ //创建本地流 skyrtc.prototype.createStream = function(options) { var that = this; options.video = !!options.video; options.audio = !!options.audio; if (getUserMedia) { this.numStreams++; getUserMedia.call(navigator, options, function(stream) { that.localMediaStream = stream; that.initializedStreams++; that.emit("stream_created", stream); if (that.initializedStreams === that.numStreams) { that.emit("ready"); } }, function(error) { that.emit("stream_create_error", error); }); } else { that.emit("stream_create_error", new Error('WebRTC is not yet supported in this browser.')); } }; //将本地流添加到所有的PeerConnection实例中 skyrtc.prototype.addStreams = function() { var i, m, stream, connection; for (connection in this.peerConnections) { this.peerConnections[connection].addStream(this.localMediaStream); } }; //将流绑定到video标签上用于输出 skyrtc.prototype.attachStream = function(stream, domId) { var element = document.getElementById(domId); if (navigator.mozGetUserMedia) { element.mozSrcObject = stream; element.play(); } else { element.src = webkitURL.createObjectURL(stream); } element.src = webkitURL.createObjectURL(stream); }; /***********************信令交换部分*******************************/ //向所有PeerConnection发送Offer类型信令 skyrtc.prototype.sendOffers = function() { var i, m, pc, that = this, pcCreateOfferCbGen = function(pc, socketId) { return function(session_desc) { pc.setLocalDescription(session_desc); that.socket.send(JSON.stringify({ "eventName": "__offer", "data": { "sdp": session_desc, "socketId": socketId } })); }; }, pcCreateOfferErrorCb = function(error) { console.log(error); }; for (i = 0, m = this.connections.length; i < m; i++) { pc = this.peerConnections[this.connections[i]]; pc.createOffer(pcCreateOfferCbGen(pc, this.connections[i]), pcCreateOfferErrorCb); } }; //接收到Offer类型信令后作为回应返回answer类型信令 skyrtc.prototype.receiveOffer = function(socketId, sdp) { var pc = this.peerConnections[socketId]; this.sendAnswer(socketId, sdp); }; //发送answer类型信令 skyrtc.prototype.sendAnswer = function(socketId, sdp) { var pc = this.peerConnections[socketId]; var that = this; pc.setRemoteDescription(new nativeRTCSessionDescription(sdp)); pc.createAnswer(function(session_desc) { pc.setLocalDescription(session_desc); that.socket.send(JSON.stringify({ "eventName": "__answer", "data": { "socketId": socketId, "sdp": session_desc } })); }, function(error) { console.log(error); }); }; //接收到answer类型信令后将对方的session描述写入PeerConnection中 skyrtc.prototype.receiveAnswer = function(socketId, sdp) { var pc = this.peerConnections[socketId]; pc.setRemoteDescription(new nativeRTCSessionDescription(sdp)); }; /***********************点对点连接部分*****************************/ //创建与其他用户连接的PeerConnections skyrtc.prototype.createPeerConnections = function() { var i, m; for (i = 0, m = this.connections.length; i < m; i++) { this.createPeerConnection(this.connections[i]); } }; //创建单个PeerConnection skyrtc.prototype.createPeerConnection = function(socketId) { var that = this; var pc = new PeerConnection(iceServer); this.peerConnections[socketId] = pc; pc.onicecandidate = function(evt) { if (evt.candidate) that.socket.send(JSON.stringify({ "eventName": "__ice_candidate", "data": { "label": evt.candidate.sdpMLineIndex, "candidate": evt.candidate.candidate, "socketId": socketId } })); that.emit("pc_get_ice_candidate", evt.candidate, socketId, pc); }; pc.onopen = function() { that.emit("pc_opened", socketId, pc); }; pc.onaddstream = function(evt) { that.emit('pc_add_stream', evt.stream, socketId, pc); }; pc.ondatachannel = function(evt) { that.addDataChannel(socketId, evt.channel); that.emit('pc_add_data_channel', evt.channel, socketId, pc); }; return pc; }; //关闭PeerConnection连接 skyrtc.prototype.closePeerConnection = function(pc) { if (!pc) return; pc.close(); }; /***********************数据通道连接部分*****************************/ //消息广播 skyrtc.prototype.broadcast = function(message) { var socketId; for (socketId in this.dataChannels) { this.sendMessage(message, socketId); } }; //发送消息方法 skyrtc.prototype.sendMessage = function(message, socketId) { if (this.dataChannels[socketId].readyState.toLowerCase() === 'open') { this.dataChannels[socketId].send(JSON.stringify({ type: "__msg", data: message })); } }; //对所有的PeerConnections创建Data channel skyrtc.prototype.addDataChannels = function() { var connection; for (connection in this.peerConnections) { this.createDataChannel(connection); } }; //对某一个PeerConnection创建Data channel skyrtc.prototype.createDataChannel = function(socketId, label) { var pc, key, channel; pc = this.peerConnections[socketId]; if (!socketId) { this.emit("data_channel_create_error", socketId, new Error("attempt to create data channel without socket id")); } if (!(pc instanceof PeerConnection)) { this.emit("data_channel_create_error", socketId, new Error("attempt to create data channel without peerConnection")); } try { channel = pc.createDataChannel(label); } catch (error) { this.emit("data_channel_create_error", socketId, error); } return this.addDataChannel(socketId, channel); }; //为Data channel绑定相应的事件回调函数 skyrtc.prototype.addDataChannel = function(socketId, channel) { var that = this; channel.onopen = function() { that.emit('data_channel_opened', channel, socketId); }; channel.onclose = function(event) { delete that.dataChannels[socketId]; that.emit('data_channel_closed', channel, socketId); }; channel.onmessage = function(message) { var json; json = JSON.parse(message.data); if (json.type === '__file') { /*that.receiveFileChunk(json);*/ that.parseFilePacket(json, socketId); } else { that.emit('data_channel_message', channel, socketId, json.data); } }; channel.onerror = function(err) { that.emit('data_channel_error', channel, socketId, err); }; this.dataChannels[socketId] = channel; return channel; }; /**********************************************************/ /* */ /* 文件传输 */ /* */ /**********************************************************/ /************************公有部分************************/ //解析Data channel上的文件类型包,来确定信令类型 skyrtc.prototype.parseFilePacket = function(json, socketId) { var signal = json.signal, that = this; if (signal === 'ask') { that.receiveFileAsk(json.sendId, json.name, json.size, socketId); } else if (signal === 'accept') { that.receiveFileAccept(json.sendId, socketId); } else if (signal === 'refuse') { that.receiveFileRefuse(json.sendId, socketId); } else if (signal === 'chunk') { that.receiveFileChunk(json.data, json.sendId, socketId, json.last, json.percent); } else if (signal === 'close') { //TODO } }; /***********************发送者部分***********************/ //通过Dtata channel向房间内所有其他用户广播文件 skyrtc.prototype.shareFile = function(dom) { var socketId, that = this; for (socketId in that.dataChannels) { that.sendFile(dom, socketId); } }; //向某一单个用户发送文件 skyrtc.prototype.sendFile = function(dom, socketId) { var that = this, file, reader, fileToSend, sendId; if (typeof dom === 'string') { dom = document.getElementById(dom); } if (!dom) { that.emit("send_file_error", new Error("Can not find dom while sending file"), socketId); return; } if (!dom.files || !dom.files[0]) { that.emit("send_file_error", new Error("No file need to be sended"), socketId); return; } file = dom.files[0]; that.fileChannels[socketId] = that.fileChannels[socketId] || {}; sendId = that.getRandomString(); fileToSend = { file: file, state: "ask" }; that.fileChannels[socketId][sendId] = fileToSend; that.sendAsk(socketId, sendId, fileToSend); that.emit("send_file", sendId, socketId, file); }; //发送多个文件的碎片 skyrtc.prototype.sendFileChunks = function() { var socketId, sendId, that = this, nextTick = false; for (socketId in that.fileChannels) { for (sendId in that.fileChannels[socketId]) { if (that.fileChannels[socketId][sendId].state === "send") { nextTick = true; that.sendFileChunk(socketId, sendId); } } } if (nextTick) { setTimeout(function() { that.sendFileChunks(); }, 10); } }; //发送某个文件的碎片 skyrtc.prototype.sendFileChunk = function(socketId, sendId) { var that = this, fileToSend = that.fileChannels[socketId][sendId], packet = { type: "__file", signal: "chunk", sendId: sendId }, channel; fileToSend.sendedPackets++; fileToSend.packetsToSend--; if (fileToSend.fileData.length > packetSize) { packet.last = false; packet.data = fileToSend.fileData.slice(0, packetSize); packet.percent = fileToSend.sendedPackets / fileToSend.allPackets * 100; that.emit("send_file_chunk", sendId, socketId, fileToSend.sendedPackets / fileToSend.allPackets * 100, fileToSend.file); } else { packet.data = fileToSend.fileData; packet.last = true; fileToSend.state = "end"; that.emit("sended_file", sendId, socketId, fileToSend.file); that.cleanSendFile(sendId, socketId); } channel = that.dataChannels[socketId]; if (!channel) { that.emit("send_file_error", new Error("Channel has been destoried"), socketId, sendId, fileToSend.file); return; } channel.send(JSON.stringify(packet)); fileToSend.fileData = fileToSend.fileData.slice(packet.data.length); }; //发送文件请求后若对方同意接受,开始传输 skyrtc.prototype.receiveFileAccept = function(sendId, socketId) { var that = this, fileToSend, reader, initSending = function(event, text) { fileToSend.state = "send"; fileToSend.fileData = event.target.result; fileToSend.sendedPackets = 0; fileToSend.packetsToSend = fileToSend.allPackets = parseInt(fileToSend.fileData.length / packetSize, 10); that.sendFileChunks(); }; fileToSend = that.fileChannels[socketId][sendId]; reader = new window.FileReader(fileToSend.file); reader.readAsDataURL(fileToSend.file); reader.onload = initSending; that.emit("send_file_accepted", sendId, socketId, that.fileChannels[socketId][sendId].file); }; //发送文件请求后若对方拒绝接受,清除掉本地的文件信息 skyrtc.prototype.receiveFileRefuse = function(sendId, socketId) { var that = this; that.fileChannels[socketId][sendId].state = "refused"; that.emit("send_file_refused", sendId, socketId, that.fileChannels[socketId][sendId].file); that.cleanSendFile(sendId, socketId); }; //清除发送文件缓存 skyrtc.prototype.cleanSendFile = function(sendId, socketId) { var that = this; delete that.fileChannels[socketId][sendId]; }; //发送文件请求 skyrtc.prototype.sendAsk = function(socketId, sendId, fileToSend) { var that = this, channel = that.dataChannels[socketId], packet; if (!channel) { that.emit("send_file_error", new Error("Channel has been closed"), socketId, sendId, fileToSend.file); } packet = { name: fileToSend.file.name, size: fileToSend.file.size, sendId: sendId, type: "__file", signal: "ask" }; channel.send(JSON.stringify(packet)); }; //获得随机字符串来生成文件发送ID skyrtc.prototype.getRandomString = function() { return (Math.random() * new Date().getTime()).toString(36).toUpperCase().replace(/\./g, '-'); }; /***********************接收者部分***********************/ //接收到文件碎片 skyrtc.prototype.receiveFileChunk = function(data, sendId, socketId, last, percent) { var that = this, fileInfo = that.receiveFiles[sendId]; if (!fileInfo.data) { fileInfo.state = "receive"; fileInfo.data = ""; } fileInfo.data = fileInfo.data || ""; fileInfo.data += data; if (last) { fileInfo.state = "end"; that.getTransferedFile(sendId); } else { that.emit("receive_file_chunk", sendId, socketId, fileInfo.name, percent); } }; //接收到所有文件碎片后将其组合成一个完整的文件并自动下载 skyrtc.prototype.getTransferedFile = function(sendId) { var that = this, fileInfo = that.receiveFiles[sendId], hyperlink = document.createElement("a"), mouseEvent = new MouseEvent('click', { view: window, bubbles: true, cancelable: true }); hyperlink.href = fileInfo.data; hyperlink.target = '_blank'; hyperlink.download = fileInfo.name || dataURL; hyperlink.dispatchEvent(mouseEvent); (window.URL || window.webkitURL).revokeObjectURL(hyperlink.href); that.emit("receive_file", sendId, fileInfo.socketId, fileInfo.name); that.cleanReceiveFile(sendId); }; //接收到发送文件请求后记录文件信息 skyrtc.prototype.receiveFileAsk = function(sendId, fileName, fileSize, socketId) { var that = this; that.receiveFiles[sendId] = { socketId: socketId, state: "ask", name: fileName, size: fileSize }; that.emit("receive_file_ask", sendId, socketId, fileName, fileSize); }; //发送同意接收文件信令 skyrtc.prototype.sendFileAccept = function(sendId) { var that = this, fileInfo = that.receiveFiles[sendId], channel = that.dataChannels[fileInfo.socketId], packet; if (!channel) { that.emit("receive_file_error", new Error("Channel has been destoried"), sendId, socketId); } packet = { type: "__file", signal: "accept", sendId: sendId }; channel.send(JSON.stringify(packet)); }; //发送拒绝接受文件信令 skyrtc.prototype.sendFileRefuse = function(sendId) { var that = this, fileInfo = that.receiveFiles[sendId], channel = that.dataChannels[fileInfo.socketId], packet; if (!channel) { that.emit("receive_file_error", new Error("Channel has been destoried"), sendId, socketId); } packet = { type: "__file", signal: "refuse", sendId: sendId }; channel.send(JSON.stringify(packet)); that.cleanReceiveFile(sendId); }; //清除接受文件缓存 skyrtc.prototype.cleanReceiveFile = function(sendId) { var that = this; delete that.receiveFiles[sendId]; }; return new skyrtc(); };
describe('controller: UserController', function() { var controller, scope, User; beforeEach(module('core')); beforeEach(module('app')); beforeEach(module('mock.user')); beforeEach(inject(function($controller, $rootScope, _User_) { scope = $rootScope.$new(); controller = $controller('UserController', { $scope: scope, User: _User_ }); User = _User_; })); describe('Is the controller defined', function() { it('should be defined', function() { expect(controller).toBeDefined(); }); }); describe('Is the scope defined', function() { it('should be defined', function() { expect(scope).toBeDefined(); }); }); describe('Does the scope have a User', function() { it('User should be on the scope', function() { expect(scope.user).toBeDefined(); }); }); describe('Does the User have expected credentials', function() { it('User should have expected credentials', function() { var userOnScope = angular.toJson(scope.user); var mockUser = angular.toJson(mockUser1); expect(userOnScope).toEqual(mockUser); }); }); describe('Should be able to set a User', function() { it('should have set the User', function() { User.set(mockUser2) var userOnScope = angular.toJson(scope.user); var mockUser = angular.toJson(mockUser2); expect(userOnScope).toEqual(mockUser); }); }); describe('Should be able to fetch a User', function() { it('should have set the fetched User', function() { User.fetch().then(function(data) { User.set(data); expect(scope.user).toEqual(mockUser3); }); }); }); });
require('babel-register'); module.exports = require('./importer');
$(function() { // Display the Popover var templatePopover = ' <div class="popover" role="tooltip">\n\ <div class="arrow"></div>\n\ <h3 class="popover-title bg-orange"></h3>\n\ <div style="height: 350px; width:280px ; overflow: auto;" class="mCustomScrollbar popover-content" data-mcs-theme="dark" data-mcs-axis="y"></div>\n\ </div>'; var content = ' <p class="text-orange"><b>Buy&Saller</b></p>\n\ <div class="list-group">\ <a href="#" class="list-group-item">\ <b>Toto:</b> Lorem ipsum dolor lorem...\ </a> \ <a href="#" class="list-group-item">\ <b>Titi:</b> Lorem ipsum dolor lorem...\ </a> \ <a href="#" class="list-group-item">\ <b>Tata:</b> Lorem ipsum dolor lorem...\ </a> \ </div>\n\ <p class="text-orange"><b>Boutiquiers de Maroua</b></p>\n\ <div class="list-group">\ <a href="#" class="list-group-item">\ <b>Toto:</b> Lorem ipsum dolor lorem...\ </a> \ <a href="#" class="list-group-item">\ <b>Titi:</b> Lorem ipsum dolor lorem...\ </a> \ <a href="#" class="list-group-item">\ <b>Tata:</b> Lorem ipsum dolor lorem...\ </a> \ <a href="#" class="list-group-item">\ <b>Toto:</b> Lorem ipsum dolor lorem...\ </a> \ <a href="#" class="list-group-item">\ <b>Titi:</b> Lorem ipsum dolor lorem...\ </a> \ <a href="#" class="list-group-item">\ <b>Tata:</b> Lorem ipsum dolor lorem...\ </a> \ </div>'; $('[data-toggle = popover]').popover({ trigger: 'focus', template: templatePopover, title: 'Discussions', content: content, placement: 'right', html: true }); // animation du message de creation de compte // $('#msg-creation-compte li').hide(); setInterval(function() { $('#msg-creation-compte li').each(function() { $(this).toggle('bounce'); }); }, 5000); });
import { Meteor } from 'meteor/meteor'; import { Accounts } from 'meteor/accounts-base'; import { check } from 'meteor/check'; Meteor.methods({ addReferrer({ code, name, url, commissionRate, cpa }) { check(code, String); check(name, Match.Optional(String)); check(url, Match.Optional(String)); check(commissionRate, Match.Optional(Number)); check(cpa, Match.Optional(Number)); if (!Roles.userIsInRole(this.userId, ['admin'])) throw new Meteor.Error(404, 'Must be admin to call this method', this.userId); return Referrers.insert({ code, name, url, commissionRate, cpa, }); }, attachReferrerToEmail({ email, code }) { check(email, String); if (!Roles.userIsInRole(this.userId, ['admin'])) throw new Meteor.Error(404, 'Must be admin to call this method', this.userId); const user = Accounts.findUserByEmail(email); if (!user) throw new Meteor.Error('error', 'Unable to find user.', email); Referrers.update({ code }, { $addToSet: { userIds: user._id, }, }, (err) => { if (!err) { Meteor.users.update({ _id: user._id }, { $set: { isAffiliate: true, }, }, () => {}); } }); }, });
const { isFunction, typeError, validateSiblings, validateChild, getLatestFromNames, loadCurrentValue, getParentData, getInitialData, saveCurrentValue } = require("../../util/ruleUtil"); const { TRANSFORM, CONTENT, DEFAULT, FUNCTION, OPTIONAL, TYPE, CAST_TO, MATCH, VALIDATE, MIN, MAX, PROPERTIES, CLEAN } = require("../../constant"); const depth = 2; const config = { properties: { userInput: { siblings: [ { name: OPTIONAL }, { name: TYPE }, { name: CAST_TO }, { name: MATCH }, { name: VALIDATE }, { name: MAX }, { name: MIN }, { name: DEFAULT }, { name: PROPERTIES }, { name: CONTENT }, ], children: { types: [FUNCTION] }, }, }, none: { body: { siblings: [ { name: PROPERTIES }, { name: OPTIONAL }, { name: VALIDATE }, { name: CONTENT }, { name: DEFAULT }, { name: CLEAN }, { name: TYPE }, ], children: { types: [FUNCTION] }, }, }, }; module.exports = { name: TRANSFORM, priority: 40, validate, execute, config, }; function execute({ rule, data }) { return new Promise(async (resolve, reject) => { loadCurrentValue(data); try { data.current.value = await rule.current.value(data.current, { parent: getParentData(data), initial: getInitialData(data) }); } catch (error) { return reject(error); } saveCurrentValue(data); resolve(true); }); } function validate({ current, parents, ruleConfig }) { const { siblings, children } = getLatestFromNames(config, parents, depth, TRANSFORM); validateSiblings({ siblings, current, parents, ruleConfig }); if (isFunction(current)) { const child = current; validateChild({ child, children, parents, current, ruleConfig }); return true; } throw typeError({ current, ruleConfig, expected: FUNCTION }); }
var readline = require('readline') var rl = readline.createInterface({ input: process.stdin, output: process.stdout }) rl.on('line', function (ln) { console.log(ln) })
'use strict'; // Declare app level module which depends on views, and components (function() { angular.module('supplementDiary', []) .controller('SupplementDiaryController', function() { this.supplements = supplements; this.categories = categories; this.displayForm = false; }) .directive('supplementCategories', function() { return { restrict: 'E', //because directive is its own element in app.html templateUrl: 'partials/supplement-categories.html', scope: { categories: '=' } }; }) .directive('supplementImages', function() { return { restrict: 'E', //because directive is its own element in app.html templateUrl: 'partials/supplement-images.html', }; }) .directive('supplementInfo', function() { return { restrict: 'E', //because directive is its own element in app.html templateUrl: 'partials/supplement-info.html', }; }) .directive('supplementReviews', function() { return { restrict: 'E', //because directive is its own element in app.html templateUrl: 'partials/supplement-reviews.html', }; }) .directive('reviewForm', function() { return { restrict: 'E', //because directive is its own element in app.html templateUrl: 'partials/review-form.html', controller: function() { this.displayForm = false; this.supplement = {}; }, controllerAs: 'reviewFormCtrl', scope: { supplements: '=', categories: '=' } }; }) /*FAKE DATABASE*/ var categories = ['fitness', 'sleep-aids', 'muscle', 'nootropic', 'memory', 'focus', 'detoxification', 'herbal', 'mood', 'energy', 'longetivity', 'antioxidants', 'adaptogens', 'hormones', 'stress']; var supplements = [{ name: 'L-Theanine', brand: 'Now Foods', dose: '200mg', asin: 'B000H7P9M0', review: 'I am very skeptical when it comes to homeopathy and supplements. Much, if not most, is purely hype, misinformation, and lies. In this case, this is the real deal. Theanine, is very useful for anyone with issues ranging from mild to annoying anxieties to sleep issues to stress during the day. This really does the job at "taking the cares away," but not like Valium does, where you can zombie out. The best way to describe it is as a nice, calming feeling. You can still get all your work done, but not worry about things, which helps keep your focus together. When it comes to sleep, this is a good way to lull you to slumber by much the same way, removing any anxieties or bothers. Well worth the try, and I always trust products from Now.', rating: 9, categories: { 'sleep-aids': true, focus: true, stress: true } }, { name: 'SAM-e', brand: 'Jarrow Formulas', dose: '200mg', asin: 'B0013OVW0O', review: "I have been on Paxil for years and others b/f but now without insurance I studied this product and tried it after a week or two I feel better than I ever have I don't feel like some say euphoric but also my feeling aren't masked over to where I feel nothing, seems so far that things that would really bother me (while taking the prescribed drugs) I am much more calm about I don't seem to have to take as much as they say you may need to. I feel this is awesome and I am so glad I made this decision. I started with a higher dose and my poor belly was not happy but when I lowered to 200 I really feel great, hope the government doesn't find out about this you probably wont be able to get it anymore LOL", rating: 8, categories: { 'mood': true, focus: true, stress: true, memory: true, energy: true } }, { name: 'Ubiquinol', brand: 'Jarrow Formulas', dose: '100mg', asin: 'B004VCOOUU', review: "I have found that CoQ10 supplementation helps maintain my general energy levels. Its not a caffeine type rush, rather a realization that you are walking more briskly and are more alert during the working day without the extreme tiredness and the end of the day or on weekends.", rating: 7, categories: { antioxidants: true, longetivity: true, stress: true, detoxification: true } }, { name: 'Tribulus Terrestris', brand: 'Optimum Nutrition', dose: '1000mg', asin: 'B00A2FZF0S', review: "Ok. I'm NOT a fan of writing reviews but because of the results i am getting this product it does deserves it. I and into physical training. My trainer told my to buy this to improve muscle mass gain by compensating my testosterone levels which because of my age are estimated to be very low compared to a 25 year old man. I am 48.", rating: 4, categories: { 'sleep-aids': true, focus: true, stress: true } }]; })();
// JavaScript Document var jasmine = require("jasmine") var app = require("../ari-geo-lab/ari-geo-lab.js"); (function(){ 'use strict'; describe("Determine the sequence of an array of numbers: ", function() { describe("Case for an empty array", function() { it("should return 0 for an empty array", function() { expect(app.aritGeo([])).toEqual(0); }); }); describe("Case for an arithmetic sequence", function() { it("should return `Arithmetic` for [2, 4, 6, 8, 10]", function() { expect(app.aritGeo([2, 4, 6, 8, 10])).toEqual('Arithmetic'); }); it("should return `Arithmetic` for [5, 11, 17, 23, 29, 35, 41]", function() { expect(app.aritGeo([5, 11, 17, 23, 29, 35, 41])).toEqual('Arithmetic'); }); it("should return `Arithmetic` for [15, 10, 5, 0, -5, -10]", function() { expect(app.aritGeo([15, 10, 5, 0, -5, -10])).toEqual('Arithmetic'); }); }); describe("Case for a geometric sequence", function() { it("should return `Geometric` for [2, 6, 18, 54, 162]", function() { expect(app.aritGeo([2, 6, 18, 54, 162])).toEqual('Geometric'); }); it("should return `Geometric` for [0.5, 3.5, 24.5, 171.5]", function() { expect(app.aritGeo([0.5, 3.5, 24.5, 171.5])).toEqual('Geometric'); }); it("should return `Geometric` for [−128, 64, −32, 16, −8]", function() { expect(app.aritGeo([-128, 64, -32, 16, -8])).toEqual('Geometric'); }); }); describe("Case for neither arithmetic nor geometric sequence", function() { it("should return -1 for [1, 2, 3, 5, 8]", function() { expect(app.aritGeo([1, 2, 3, 5, 8])).toEqual(-1); }); it("should return -1 for [1, 3, 6, 10, 15]", function() { expect(app.aritGeo([1, 3, 6, 10, 15])).toEqual(-1); }); it("should return -1 for [1, 8, 27, 64, 125]", function() { expect(app.aritGeo([1, 8, 27, 64, 125])).toEqual(-1); }); }); }); })();
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["/stdlib/markdown"],{ /***/ "../[ ] swan-js/lib/stdlib/markdown.js": /*!*********************************************!*\ !*** ../[ ] swan-js/lib/stdlib/markdown.js ***! \*********************************************/ /*! no static exports found */ /***/ (function(module, exports, __webpack_require__) { eval("const marked = __webpack_require__(/*! marked */ \"../[ ] swan-js/node_modules/marked/lib/marked.js\");\n\nexports.__apply__ = text => marked(text);\n\n\n//# sourceURL=webpack:///../%5B_%5D_swan-js/lib/stdlib/markdown.js?"); /***/ }) }]);
const baseConfig = require('./base.conf'); module.exports = function (config) { baseConfig({ set(base) { base.browsers = []; base.customLaunchers = null; base.forceJSONP = true; base.logLevel = config.LOG_DEBUG; base.transports = ['polling']; config.set(base); }, }); };
'use strict'; (function () { angular .module('dailyMummApp') .filter('fromNow', FromnowFilter); FromnowFilter.$inject = []; function FromnowFilter() { return function(date){ return moment(date).fromNow(); } } })();
export default { /** * For this example, you will need to change this url depending on * the backend you are using: * * Express: http://localhost:1337 * Sails: http://localhost:1337 * Rails: http://localhost:1337/cable */ serverUrl: 'http://localhost:1337' /** * Override to change how the websocket instance is created * that is capable of subscribing to events published by * the respective server implementation. */ // initialize: function() {}, /** * Override to change how the websocket instance establishes * a connection with the server. This method is responsible * for making sure the websocket instance connects to the * proper namespace. */ // connect: function() {}, /** * NOT IMPLEMENTED YET: In future will be called once the * connection to the server is established. */ // onConnect: function() {}, /** * Override to change how the websocket instance subscribes * to data. This method is responsible for making sure the * websocket instance is listening for events that provide * the CRUD data needed for updating the application based * on the activity of other users. */ // subscribe: function() {}, /** * NOT IMPLEMENTED YET: In future will be called once the * client starts listening for events. */ // onSubscribe: function() {}, /** Override to change how the websocket instance unsubscribes * to data. This method is responsible for making sure the * websocket instance stops listening for events. */ // unsubscribe: function() {}, /** * NOT IMPLEMENTED YET: In future will be called once the * client stops listening for events. */ // onUnsubscribe: function() {}, /** * Override if you need to modify the message before providing * it to a dispatcher. This will be the case if your messages * don't conform to the data structure the hooks use by default, * which is: * * CREATED: { verb:'created', data: {...} } * UPDATED: { verb:'updated', data: {...} } * DESTROYED: { verb:'destroyed', data: {...} } */ // parse: function(message) { // return message; // }, /** * Override if you need to change the way a message is given * to a dispatcher (or which dispatcher it is given to) */ // dispatch: function(message) { // var parsedMessage = this.parse(message); // var verb = parsedMessage.verb; // var dispatcher = this.dispatchers[verb]; // // if (dispatcher) { // dispatcher(parsedMessage); // } // } };
import React from 'react'; import { mount } from 'enzyme'; import chai, {expect} from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import { mapStateToProps, Login } from './Login'; chai.use(sinonChai); describe('<Login />', () => { it('should call onLoginClick() on button click', () => { const props = { onLoginClick: sinon.spy(), isFetching: false }; const wrapper = mount(<Login {...props} />); const loginButton = wrapper.find('button'); expect(loginButton.length).to.equal(1); loginButton.simulate('click'); expect(props.onLoginClick.calledOnce).to.equal(true); }); it('should call onLoginClick() on form submit', () => { const props = { onLoginClick: sinon.spy(), isFetching: false }; const wrapper = mount(<Login {...props} />); wrapper.simulate('submit'); expect(props.onLoginClick.calledOnce).to.equal(true); }); describe('mapStateToProps', () => { it('should return valid props', () => { const state = { auth: { isFetching: true } }; const result = mapStateToProps(state); expect(result).to.deep.equal(state.auth); }); }); });
module.exports = [{ path: '/cliente', method: 'get', callback: require('./get') }, { path: '/cliente/:cpf', method: 'get', callback: require('./getById') }, { path: '/cliente', method: 'post', callback: require('./post') }, { path: '/cliente/:cpf', method: 'put', callback: require('./update') }, { path: '/cliente/:cpf', method: 'delete', callback: require('./delete') }, { path: '/cliente/check/:atributo/:q', method: 'get', callback: require('./checkUser') } ];
import React from 'react'; export default ({ width = 35, height = 35, className, }) => ( <svg x="0px" y="0px" className={className} width={`${width}px`} height={`${height}px`} viewBox="0 0 1024 1024" > <g id="Layer_1"> <polyline fill="#FFFFFF" points="719.001,851 719.001,639.848 902,533.802 902,745.267 719.001,851" /> <polyline fill="#FFFFFF" points="302.082,643.438 122.167,539.135 122.167,747.741 302.082,852.573 302.082,643.438" /> <polyline fill="#FFFFFF" points="511.982,275.795 694.939,169.633 512.06,63 328.436,169.987 511.982,275.795" /> </g> <g id="Layer_2"> <polyline fill="none" stroke="#FFFFFF" strokeWidth="80" strokeMiterlimit="10" points="899,287.833 509,513 509,963" /> <line fill="none" stroke="#FFFFFF" strokeWidth="80" strokeMiterlimit="10" x1="122.167" y1="289" x2="511.5" y2="513" /> <polygon fill="none" stroke="#FFFFFF" strokeWidth="80" strokeMiterlimit="10" points="121,739.083 510.917,963.042 901,738.333 901,288 511,62 121,289" /> </g> </svg> );
// var token = "XXX"; // (function() { // })();
/* ************************************************************************ Googly Copyright: 2010-2011 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /* ************************************************************************ #asset(googly/*) ************************************************************************ */ /** * Unify application class */ qx.Class.define("googly.Application", { extend : unify.Application, members : { // overridden main : function() { // Call super class this.base(arguments); qx.theme.manager.Meta.getInstance().setTheme(googly.theme.Googly); // Configure application document.title = "Googly"; // Master view var MasterViewManager = new unify.view.ViewManager("master"); MasterViewManager.register(googly.view.Start, true); MasterViewManager.register(googly.view.Translate); MasterViewManager.register(googly.view.Search); MasterViewManager.register(googly.view.Weather); MasterViewManager.register(googly.view.WeatherSearch); MasterViewManager.register(unify.view.SysInfo); // Configure tab view var TabView = new unify.view.TabViewManager(MasterViewManager); TabView.register(googly.view.Start); TabView.register(googly.view.Translate); TabView.register(googly.view.Search); TabView.register(googly.view.Weather); TabView.register(unify.view.SysInfo); this.add(TabView); // Add at least one view manager to the navigation managment var Navigation = unify.view.Navigation.getInstance(); Navigation.register(MasterViewManager); Navigation.init(); } } });
window.onload = function() { var game = new Phaser.Game(800, 600, Phaser.AUTO, '', { preload: preload, create: create , update: update, render: render }); function preload () { game.load.image('background', 'game/images/background.png'); game.load.atlas('bucket', 'game/images/bucket_sprite.png', 'game/images/bucket_sprite.json'); game.load.image('glass', 'game/images/bottle.png'); game.load.image('paper', 'game/images/paper.png'); game.load.image('alu', 'game/images/can.png'); } var bucket; var garbageGroup; var cursors; var score = 0; var scoreText; var BucketType = { PAPER: 'paper', GLASS: 'glass', PLASTICS: 'plastics', ALUMINIUM: 'alu' }; var BucketKeys = { paper: null, glass: null, plastics: null, aluminium: null }; var waveIndex = 0; var waveMatrix = [ [0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] ]; function create() { game.add.sprite(0, 0, 'background'); game.physics.startSystem(Phaser.Physics.P2JS); game.physics.p2.setImpactEvents(true); game.physics.p2.defaultRestitution = 1.0; game.physics.p2.gravity.y = 100; // Turn on impact events for the world, without this we get no collision callbacks game.physics.p2.setImpactEvents(true); // game.physics.p2.restitution = 0.1; // Create our collision groups. One for the player, one for the pandas var bucketCollisionGroup = game.physics.p2.createCollisionGroup(); var garbageCollisionGroup = game.physics.p2.createCollisionGroup(); // This part is vital if you want the objects with their own collision groups to still collide with the world bounds // (which we do) - what this does is adjust the bounds to use its own collision group. // game.physics.p2.updateBoundsCollisionGroup(); game.stage.backgroundColor = '#66CCFF'; garbageGroup = game.add.group(); garbageGroup.enableBody = true; garbageGroup.physicsBodyType = Phaser.Physics.P2JS; garbageGroup.createMultiple(50, 'paper', 0, false); garbageGroup.createMultiple(50, 'glass', 0, false); garbageGroup.createMultiple(50, 'alu', 0, false); game.physics.p2.enable(garbageGroup, false); for (var i = garbageGroup.length - 1; i >= 0; i--) { //garbageGroup.getAt(i).body.collideWorldBounds = true; garbageGroup.getAt(i).body.setCollisionGroup(garbageCollisionGroup); //garbageGroup.getAt(i).body.setZeroDamping(); //garbageGroup.getAt(i).body.fixedRotation = true; garbageGroup.getAt(i).body.collides([bucketCollisionGroup]); }; bucket = game.add.sprite(300, 600, 'bucket', 'bucket_paper.png'); bucket.type = BucketType.PAPER; game.physics.p2.enable(bucket); bucket.body.setZeroDamping(); bucket.body.fixedRotation = true; bucket.body.data.gravityScale = 0; bucket.body.setCollisionGroup(bucketCollisionGroup); bucket.body.collides(garbageCollisionGroup, collisionHandler, this); cursors = game.input.keyboard.createCursorKeys(); BucketKeys.paper = game.input.keyboard.addKey(Phaser.Keyboard.ONE); BucketKeys.paper.onDown.add(setPaperBucket, this); BucketKeys.glass = game.input.keyboard.addKey(Phaser.Keyboard.TWO); BucketKeys.glass.onDown.add(setGlassBucket, this); BucketKeys.plastics = game.input.keyboard.addKey(Phaser.Keyboard.THREE); BucketKeys.plastics.onDown.add(setPlasticsBucket, this); BucketKeys.aluminium = game.input.keyboard.addKey(Phaser.Keyboard.FOUR); BucketKeys.aluminium.onDown.add(setAluminiumBucket, this); game.time.events.loop(400, throwGarbage, this); scoreText = game.add.text(16, 16, 'Score: ' + score, { font: '18px Arial', fill: '#ffffff' }); } function setPaperBucket () { bucket.type = BucketType.PAPER; bucket.frameName = 'bucket_paper.png'; } function setGlassBucket () { bucket.type = BucketType.GLASS; bucket.frameName = 'bucket_glass.png'; } function setPlasticsBucket () { bucket.type = BucketType.PLASTICS; bucket.frameName = 'bucket_plastics.png'; } function setAluminiumBucket () { bucket.type = BucketType.ALUMINIUM; bucket.frameName = 'bucket_alu.png'; } function throwGarbage() { var wave = waveMatrix[waveIndex]; for (var i = 0; i < wave.length; i++) { var garbage; var property; if(wave[i] == 0) { continue; } else if(wave[i] == 1) { property = 'paper' } else if(wave[i] == 2) { property = 'glass' } else if(wave[i] == 3) { property = 'alu' } while(!garbage || garbage.exists || garbage.key != property) { garbage = garbageGroup.next(); } garbage.frame = game.rnd.integerInRange(0,6); garbage.exists = true; delete garbage.collided; //garbage.reset(game.world.randomX, 0); garbage.reset(800/wave.length*i, 0); }; if(waveIndex < waveMatrix.length-1) { waveIndex++; } else { waveIndex = 0; } } function collisionHandler (bucket, garbage) { if (garbage.x + garbage.sprite.width*3/2 >= bucket.x && (garbage.x + garbage.sprite.width*3/2 <= bucket.x + bucket.sprite.width)) { garbage.sprite.kill(); if(!garbage.sprite.collided) { garbage.sprite.collided = true; if(bucket.sprite.type == garbage.sprite.key) { score++; bucket.sprite.frameName = 'bucket_'+bucket.sprite.type+"1.png"; } else { score--; bucket.sprite.frameName = 'bucket_'+bucket.sprite.type+".png"; } scoreText.setText("Score: " + score); } return true; } else { return false; } } function update() { bucket.body.setZeroVelocity(); bucket.body.y = 532; if (cursors.left.isDown && bucket.body.x - bucket.width/2>0) { bucket.body.moveLeft(400); } else if (cursors.right.isDown && bucket.body.x+bucket.width/2<800) { bucket.body.moveRight(400); } garbageGroup.forEachAlive(checkBounds, this); } function checkBounds(garbage) { if (garbage.y > 600) { garbage.kill(); delete garbage.collided; } } function render() { game.debug.body(bucket); } };
// todos_list_controller.js
/* # ENGINEER # I wrote this because I wanted a way for me to create server side tables with a jade file # and an object. */ /* # required modules */ (function() { var engineer, fs, jade, path, _; jade = require("jade"); _ = require("lodash"); fs = require("fs"); path = require("path"); engineer = function(opts) { this.template = path.join(__dirname, "..", "templates", "tables.jade"); this.pretty = false; if (opts != null) { _.extend(this, opts); } return this; }; engineer.prototype.make = function(opts, input, fn) { var self; if (_.isFunction(input) === true) { fn = input; input = []; } this.fields = []; if (opts != null) { _.extend(this, opts); } if (this.fields.length > 0) { this.keys = _.pluck(this.fields, "key"); this.titles = _.pluck(this.fields, "title"); delete this.fields; } else { return fn("You must pass an array of objects in your options for fields", null); } self = this; return fs.exists(self.template, function(exists) { if (exists) { return jade.renderFile(self.template, { engine: self, data: input, pretty: self.pretty }, function(err, html) { if (err != null) { return fn(err, null); } return fn(null, html); }); } else { return fn("You must provide a valid .jade file to render from", null); } }); }; module.exports = engineer; }).call(this);
var nijs = require('nijs'); var slasp = require('slasp'); exports.pkg = function(args, callback) { args.stdenv().mkDerivation ({ name : "test", buildCommand : 'echo "Hello world!" > $out' }, callback); };
/** * mixin search * * Copyright 2012 Cloud9 IDE, Inc. * * This product includes software developed by * Cloud9 IDE, Inc (http://c9.io). * * Author: Mike de Boer <info@mikedeboer.nl> **/ "use strict"; var error = require("./../../error"); var Util = require("./../../util"); var search = module.exports = { search: {} }; (function() { /** section: github * search#issues(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - q (String): Required. Search Term * - sort (String): Optional. comments, created, or updated Validation rule: ` ^(comments|created|updated)$ `. * - order (String): Optional. asc or desc Validation rule: ` ^(asc|desc)$ `. **/ this.issues = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * search#repos(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - q (String): Required. Search Term * - sort (String): Optional. stars, forks, or updated Validation rule: ` ^(stars|forks|updated)$ `. * - order (String): Optional. asc or desc Validation rule: ` ^(asc|desc)$ `. **/ this.repos = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * search#users(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - q (String): Required. Search Term * - sort (String): Optional. followers, repositories, or joined Validation rule: ` ^(followers|repositories|joined)$ `. * - order (String): Optional. asc or desc Validation rule: ` ^(asc|desc)$ `. **/ this.users = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; /** section: github * search#email(msg, callback) -> null * - msg (Object): Object that contains the parameters and their values to be sent to the server. * - callback (Function): function to call when the request is finished with an error as first argument and result data as second argument. * * ##### Params on the `msg` object: * * - headers (Object): Optional. Key/ value pair of request headers to pass along with the HTTP request. Valid headers are: 'If-Modified-Since', 'If-None-Match', 'Cookie', 'User-Agent', 'Accept', 'X-GitHub-OTP'. * - email (String): Required. Email address **/ this.email = function(msg, block, callback) { var self = this; this.client.httpSend(msg, block, function(err, res) { if (err) return self.sendError(err, null, msg, callback); var ret; try { ret = res.data && JSON.parse(res.data); } catch (ex) { if (callback) callback(new error.InternalServerError(ex.message), res); return; } if (!ret) ret = {}; if (!ret.meta) ret.meta = {}; ["x-ratelimit-limit", "x-ratelimit-remaining", "x-ratelimit-reset", "x-oauth-scopes", "link", "location", "last-modified", "etag", "status"].forEach(function(header) { if (res.headers[header]) ret.meta[header] = res.headers[header]; }); if (callback) callback(null, ret); }); }; }).call(search.search);
export function initialize(container, application) { application.inject('route', 'session', 'service:session'); application.inject('controller', 'session', 'service:session'); application.inject('service:api', 'session', 'service:session'); } export default { name: 'session-service', initialize: initialize };
/** * Native * ------ * * Extension * --------- * .addMinute() Add one or more minutes to the Date * .addHour() Add one or more hours to the Date * .addDay() Add one or more days to the Date * .addWeek() Add one or more weeks to the Date * .addMonth() Add one or more months to the Date * .addYear() Add one or more years to the Date * .before() Date is before a Date * .after() Date is after a Date * .between() Date is between 2 Dates * .diff() Returns the difference from 2 Dates **/ (function () { var Extensions = {}; Extensions.addMinute = function (n) { var dt = new Date(); dt.setTime(this.getTime() + (60e3 * (n || 1))); return dt; }; Extensions.addHour = function (n) { var dt = new Date(); dt.setTime(this.getTime() + (3600e3 * (n || 1))); return dt; }; Extensions.addDay = function (n) { var dt = new Date(); dt.setTime(this.getTime() + (86400e3 * (n || 1))); return dt; }; Extensions.addWeek = function (n) { var dt = new Date(); dt.setTime(this.getTime() + (604800e3 * (n || 1))); return dt; }; Extensions.addMonth = function (n) { var dt = new Date(); dt.setMonth(this.getMonth() + (n || 1)); return dt; }; Extensions.addYear = function (n) { var dt = new Date(); dt.setFullYear(this.getFullYear() + (n || 1)); return dt; }; Extensions.before = function (dt) { return this < dt; }; Extensions.after = function (dt) { return this > dt; }; Extensions.between = function (start, end) { return !this.before(start) && !this.after(end); }; Extensions.diff = function (dt) { return this.getTime() - dt.getTime(); }; function extendNative() { for (fun in Extensions) { if (!Date.prototype[fun]) { Object.defineProperty(Date.prototype, fun, { "value": Extensions[fun], "configurable": false, "enumerable": false, "writable": false }); } } }; if (typeof module != "undefined") { module.exports = { extendNative: extendNative }; } else { extendNative(); } })();
const { resolve } = require('path') const formidable = require('formidable') module.exports = function (req, res, next) { const form = new formidable.IncomingForm() form.uploadDir = resolve(__dirname, '../', 'uploads') let image form .on('file', function (name, file) { // make sure it is an image if (file.type === 'image/jpeg') { image = file } }) .on('error', function (err) { res.status(500).json(err) }) .on('end', function () { req.image = image next() }) form.parse(req) }
var TIP, // .on() namespace TIPNS = '.qtip-tip', // Common CSS strings MARGIN = 'margin', BORDER = 'border', COLOR = 'color', BG_COLOR = 'background-color', TRANSPARENT = 'transparent', IMPORTANT = ' !important', // Check if the browser supports <canvas/> elements HASCANVAS = !!document.createElement('canvas').getContext, // Invalid colour values used in parseColours() INVALID = /rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i; // Camel-case method, taken from jQuery source // http://code.jquery.com/jquery-1.8.0.js function camel(s) { return s.charAt(0).toUpperCase() + s.slice(1); } /* * Modified from Modernizr's testPropsAll() * http://modernizr.com/downloads/modernizr-latest.js */ var cssProps = {}, cssPrefixes = ["Webkit", "O", "Moz", "ms"]; function vendorCss(elem, prop) { var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1), props = (prop + ' ' + cssPrefixes.join(ucProp + ' ') + ucProp).split(' '), cur, val, i = 0; // If the property has already been mapped... if(cssProps[prop]) { return elem.css(cssProps[prop]); } while((cur = props[i++])) { if((val = elem.css(cur)) !== undefined) { return cssProps[prop] = cur, val; } } } // Parse a given elements CSS property into an int function intCss(elem, prop) { return Math.ceil(parseFloat(vendorCss(elem, prop))); } // VML creation (for IE only) if(!HASCANVAS) { var createVML = function(tag, props, style) { return '<qtipvml:'+tag+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(props||'')+ ' style="behavior: url(#default#VML); '+(style||'')+ '" />'; }; } // Canvas only definitions else { var PIXEL_RATIO = window.devicePixelRatio || 1, BACKING_STORE_RATIO = (function() { var context = document.createElement('canvas').getContext('2d'); return context.backingStorePixelRatio || context.webkitBackingStorePixelRatio || context.mozBackingStorePixelRatio || context.msBackingStorePixelRatio || context.oBackingStorePixelRatio || 1; }()), SCALE = PIXEL_RATIO / BACKING_STORE_RATIO; } function Tip(qtip, options) { this._ns = 'tip'; this.options = options; this.offset = options.offset; this.size = [ options.width, options.height ]; // Initialize this.init( (this.qtip = qtip) ); } $.extend(Tip.prototype, { init: function(qtip) { var context, tip; // Create tip element and prepend to the tooltip tip = this.element = qtip.elements.tip = $('<div />', { 'class': NAMESPACE+'-tip' }).prependTo(qtip.tooltip); // Create tip drawing element(s) if(HASCANVAS) { // save() as soon as we create the canvas element so FF2 doesn't bork on our first restore()! context = $('<canvas />').appendTo(this.element)[0].getContext('2d'); // Setup constant parameters context.lineJoin = 'miter'; context.miterLimit = 100000; context.save(); } else { context = createVML('shape', 'coordorigin="0,0"', 'position:absolute;'); this.element.html(context + context); // Prevent mousing down on the tip since it causes problems with .live() handling in IE due to VML qtip._bind( $('*', tip).add(tip), ['click', 'mousedown'], function(event) { event.stopPropagation(); }, this._ns); } // Bind update events qtip._bind(qtip.tooltip, 'tooltipmove', this.reposition, this._ns, this); // Create it this.create(); }, _swapDimensions: function() { this.size[0] = this.options.height; this.size[1] = this.options.width; }, _resetDimensions: function() { this.size[0] = this.options.width; this.size[1] = this.options.height; }, _useTitle: function(corner) { var titlebar = this.qtip.elements.titlebar; return titlebar && ( corner.y === TOP || (corner.y === CENTER && this.element.position().top + (this.size[1] / 2) + this.options.offset < titlebar.outerHeight(TRUE)) ); }, _parseCorner: function(corner) { var my = this.qtip.options.position.my; // Detect corner and mimic properties if(corner === FALSE || my === FALSE) { corner = FALSE; } else if(corner === TRUE) { corner = new CORNER( my.string() ); } else if(!corner.string) { corner = new CORNER(corner); corner.fixed = TRUE; } return corner; }, _parseWidth: function(corner, side, use) { var elements = this.qtip.elements, prop = BORDER + camel(side) + 'Width'; return (use ? intCss(use, prop) : ( intCss(elements.content, prop) || intCss(this._useTitle(corner) && elements.titlebar || elements.content, prop) || intCss(elements.tooltip, prop) )) || 0; }, _parseRadius: function(corner) { var elements = this.qtip.elements, prop = BORDER + camel(corner.y) + camel(corner.x) + 'Radius'; return BROWSER.ie < 9 ? 0 : intCss(this._useTitle(corner) && elements.titlebar || elements.content, prop) || intCss(elements.tooltip, prop) || 0; }, _invalidColour: function(elem, prop, compare) { var val = elem.css(prop); return !val || (compare && val === elem.css(compare)) || INVALID.test(val) ? FALSE : val; }, _parseColours: function(corner) { var elements = this.qtip.elements, tip = this.element.css('cssText', ''), borderSide = BORDER + camel(corner[ corner.precedance ]) + camel(COLOR), colorElem = this._useTitle(corner) && elements.titlebar || elements.content, css = this._invalidColour, color = []; // Attempt to detect the background colour from various elements, left-to-right precedance color[0] = css(tip, BG_COLOR) || css(colorElem, BG_COLOR) || css(elements.content, BG_COLOR) || css(elements.tooltip, BG_COLOR) || tip.css(BG_COLOR); // Attempt to detect the correct border side colour from various elements, left-to-right precedance color[1] = css(tip, borderSide, COLOR) || css(colorElem, borderSide, COLOR) || css(elements.content, borderSide, COLOR) || css(elements.tooltip, borderSide, COLOR) || elements.tooltip.css(borderSide); // Reset background and border colours $('*', tip).add(tip).css('cssText', BG_COLOR+':'+TRANSPARENT+IMPORTANT+';'+BORDER+':0'+IMPORTANT+';'); return color; }, _calculateSize: function(corner) { var y = corner.precedance === Y, width = this.options['width'], height = this.options['height'], isCenter = corner.abbrev() === 'c', base = (y ? width: height) * (isCenter ? 0.5 : 1), pow = Math.pow, round = Math.round, bigHyp, ratio, result, smallHyp = Math.sqrt( pow(base, 2) + pow(height, 2) ), hyp = [ (this.border / base) * smallHyp, (this.border / height) * smallHyp ]; hyp[2] = Math.sqrt( pow(hyp[0], 2) - pow(this.border, 2) ); hyp[3] = Math.sqrt( pow(hyp[1], 2) - pow(this.border, 2) ); bigHyp = smallHyp + hyp[2] + hyp[3] + (isCenter ? 0 : hyp[0]); ratio = bigHyp / smallHyp; result = [ round(ratio * width), round(ratio * height) ]; return y ? result : result.reverse(); }, // Tip coordinates calculator _calculateTip: function(corner, size, scale) { scale = scale || 1; size = size || this.size; var width = size[0] * scale, height = size[1] * scale, width2 = Math.ceil(width / 2), height2 = Math.ceil(height / 2), // Define tip coordinates in terms of height and width values tips = { br: [0,0, width,height, width,0], bl: [0,0, width,0, 0,height], tr: [0,height, width,0, width,height], tl: [0,0, 0,height, width,height], tc: [0,height, width2,0, width,height], bc: [0,0, width,0, width2,height], rc: [0,0, width,height2, 0,height], lc: [width,0, width,height, 0,height2] }; // Set common side shapes tips.lt = tips.br; tips.rt = tips.bl; tips.lb = tips.tr; tips.rb = tips.tl; return tips[ corner.abbrev() ]; }, // Tip coordinates drawer (canvas) _drawCoords: function(context, coords) { context.beginPath(); context.moveTo(coords[0], coords[1]); context.lineTo(coords[2], coords[3]); context.lineTo(coords[4], coords[5]); context.closePath(); }, create: function() { // Determine tip corner var c = this.corner = (HASCANVAS || BROWSER.ie) && this._parseCorner(this.options.corner); // If we have a tip corner... if( (this.enabled = !!this.corner && this.corner.abbrev() !== 'c') ) { // Cache it this.qtip.cache.corner = c.clone(); // Create it this.update(); } // Toggle tip element this.element.toggle(this.enabled); return this.corner; }, update: function(corner, position) { if(!this.enabled) { return this; } var elements = this.qtip.elements, tip = this.element, inner = tip.children(), options = this.options, curSize = this.size, mimic = options.mimic, round = Math.round, color, precedance, context, coords, bigCoords, translate, newSize, border, BACKING_STORE_RATIO; // Re-determine tip if not already set if(!corner) { corner = this.qtip.cache.corner || this.corner; } // Use corner property if we detect an invalid mimic value if(mimic === FALSE) { mimic = corner; } // Otherwise inherit mimic properties from the corner object as necessary else { mimic = new CORNER(mimic); mimic.precedance = corner.precedance; if(mimic.x === 'inherit') { mimic.x = corner.x; } else if(mimic.y === 'inherit') { mimic.y = corner.y; } else if(mimic.x === mimic.y) { mimic[ corner.precedance ] = corner[ corner.precedance ]; } } precedance = mimic.precedance; // Ensure the tip width.height are relative to the tip position if(corner.precedance === X) { this._swapDimensions(); } else { this._resetDimensions(); } // Update our colours color = this.color = this._parseColours(corner); // Detect border width, taking into account colours if(color[1] !== TRANSPARENT) { // Grab border width border = this.border = this._parseWidth(corner, corner[corner.precedance]); // If border width isn't zero, use border color as fill if it's not invalid (1.0 style tips) if(options.border && border < 1 && !INVALID.test(color[1])) { color[0] = color[1]; } // Set border width (use detected border width if options.border is true) this.border = border = options.border !== TRUE ? options.border : border; } // Border colour was invalid, set border to zero else { this.border = border = 0; } // Determine tip size newSize = this.size = this._calculateSize(corner); tip.css({ width: newSize[0], height: newSize[1], lineHeight: newSize[1]+'px' }); // Calculate tip translation if(corner.precedance === Y) { translate = [ round(mimic.x === LEFT ? border : mimic.x === RIGHT ? newSize[0] - curSize[0] - border : (newSize[0] - curSize[0]) / 2), round(mimic.y === TOP ? newSize[1] - curSize[1] : 0) ]; } else { translate = [ round(mimic.x === LEFT ? newSize[0] - curSize[0] : 0), round(mimic.y === TOP ? border : mimic.y === BOTTOM ? newSize[1] - curSize[1] - border : (newSize[1] - curSize[1]) / 2) ]; } // Canvas drawing implementation if(HASCANVAS) { // Grab canvas context and clear/save it context = inner[0].getContext('2d'); context.restore(); context.save(); context.clearRect(0,0,6000,6000); // Calculate coordinates coords = this._calculateTip(mimic, curSize, SCALE); bigCoords = this._calculateTip(mimic, this.size, SCALE); // Set the canvas size using calculated size inner.attr(WIDTH, newSize[0] * SCALE).attr(HEIGHT, newSize[1] * SCALE); inner.css(WIDTH, newSize[0]).css(HEIGHT, newSize[1]); // Draw the outer-stroke tip this._drawCoords(context, bigCoords); context.fillStyle = color[1]; context.fill(); // Draw the actual tip context.translate(translate[0] * SCALE, translate[1] * SCALE); this._drawCoords(context, coords); context.fillStyle = color[0]; context.fill(); } // VML (IE Proprietary implementation) else { // Calculate coordinates coords = this._calculateTip(mimic); // Setup coordinates string coords = 'm' + coords[0] + ',' + coords[1] + ' l' + coords[2] + ',' + coords[3] + ' ' + coords[4] + ',' + coords[5] + ' xe'; // Setup VML-specific offset for pixel-perfection translate[2] = border && /^(r|b)/i.test(corner.string()) ? BROWSER.ie === 8 ? 2 : 1 : 0; // Set initial CSS inner.css({ coordsize: (newSize[0]+border) + ' ' + (newSize[1]+border), antialias: ''+(mimic.string().indexOf(CENTER) > -1), left: translate[0] - (translate[2] * Number(precedance === X)), top: translate[1] - (translate[2] * Number(precedance === Y)), width: newSize[0] + border, height: newSize[1] + border }) .each(function(i) { var $this = $(this); // Set shape specific attributes $this[ $this.prop ? 'prop' : 'attr' ]({ coordsize: (newSize[0]+border) + ' ' + (newSize[1]+border), path: coords, fillcolor: color[0], filled: !!i, stroked: !i }) .toggle(!!(border || i)); // Check if border is enabled and add stroke element !i && $this.html( createVML( 'stroke', 'weight="'+(border*2)+'px" color="'+color[1]+'" miterlimit="1000" joinstyle="miter"' ) ); }); } // Opera bug #357 - Incorrect tip position // https://github.com/Craga89/qTip2/issues/367 window.opera && setTimeout(function() { elements.tip.css({ display: 'inline-block', visibility: 'visible' }); }, 1); // Position if needed if(position !== FALSE) { this.calculate(corner, newSize); } }, calculate: function(corner, size) { if(!this.enabled) { return FALSE; } var self = this, elements = this.qtip.elements, tip = this.element, userOffset = this.options.offset, isWidget = elements.tooltip.hasClass('ui-widget'), position = { }, precedance, corners, overlap; // Inherit corner if not provided corner = corner || this.corner; precedance = corner.precedance; // Determine which tip dimension to use for adjustment size = size || this._calculateSize(corner); // Setup corners and offset array corners = [ corner.x, corner.y ]; if(precedance === X) { corners.reverse(); } // Calculate tip position $.each(corners, function(i, side) { var b, bc, br; if(side === CENTER) { b = precedance === Y ? LEFT : TOP; position[ b ] = '50%'; position[MARGIN+'-' + b] = -Math.round(size[ precedance === Y ? 0 : 1 ] / 2) + userOffset; } else { b = self._parseWidth(corner, side, elements.tooltip); bc = self._parseWidth(corner, side, elements.content); br = self._parseRadius(corner); position[ side ] = Math.max(-self.border, i ? bc : (userOffset + (br > b ? br : -b))); } }); // Adjust for tip size position[ corner[precedance] ] -= size[ precedance === X ? 0 : 1 ]; // Set and return new position tip.css({ margin: '', top: '', bottom: '', left: '', right: '' }).css(position); return position; }, reposition: function(event, api, pos, viewport) { if(!this.enabled) { return; } var cache = api.cache, newCorner = this.corner.clone(), adjust = pos.adjusted, method = api.options.position.adjust.method.split(' '), horizontal = method[0], vertical = method[1] || method[0], shift = { left: FALSE, top: FALSE, x: 0, y: 0 }, offset, css = {}, props; function shiftflip(direction, precedance, popposite, side, opposite) { // Horizontal - Shift or flip method if(direction === SHIFT && newCorner.precedance === precedance && adjust[side] && newCorner[popposite] !== CENTER) { newCorner.precedance = newCorner.precedance === X ? Y : X; } else if(direction !== SHIFT && adjust[side]){ newCorner[precedance] = newCorner[precedance] === CENTER ? (adjust[side] > 0 ? side : opposite) : (newCorner[precedance] === side ? opposite : side); } } function shiftonly(xy, side, opposite) { if(newCorner[xy] === CENTER) { css[MARGIN+'-'+side] = shift[xy] = offset[MARGIN+'-'+side] - adjust[side]; } else { props = offset[opposite] !== undefined ? [ adjust[side], -offset[side] ] : [ -adjust[side], offset[side] ]; if( (shift[xy] = Math.max(props[0], props[1])) > props[0] ) { pos[side] -= adjust[side]; shift[side] = FALSE; } css[ offset[opposite] !== undefined ? opposite : side ] = shift[xy]; } } // If our tip position isn't fixed e.g. doesn't adjust with viewport... if(this.corner.fixed !== TRUE) { // Perform shift/flip adjustments shiftflip(horizontal, X, Y, LEFT, RIGHT); shiftflip(vertical, Y, X, TOP, BOTTOM); // Update and redraw the tip if needed (check cached details of last drawn tip) if(newCorner.string() !== cache.corner.string() || cache.cornerTop !== adjust.top || cache.cornerLeft !== adjust.left) { this.update(newCorner, FALSE); } } // Setup tip offset properties offset = this.calculate(newCorner); // Readjust offset object to make it left/top if(offset.right !== undefined) { offset.left = -offset.right; } if(offset.bottom !== undefined) { offset.top = -offset.bottom; } offset.user = this.offset; // Perform shift adjustments if(shift.left = (horizontal === SHIFT && !!adjust.left)) { shiftonly(X, LEFT, RIGHT); } if(shift.top = (vertical === SHIFT && !!adjust.top)) { shiftonly(Y, TOP, BOTTOM); } /* * If the tip is adjusted in both dimensions, or in a * direction that would cause it to be anywhere but the * outer border, hide it! */ this.element.css(css).toggle( !((shift.x && shift.y) || (newCorner.x === CENTER && shift.y) || (newCorner.y === CENTER && shift.x)) ); // Adjust position to accomodate tip dimensions pos.left -= offset.left.charAt ? offset.user : horizontal !== SHIFT || shift.top || !shift.left && !shift.top ? offset.left + this.border : 0; pos.top -= offset.top.charAt ? offset.user : vertical !== SHIFT || shift.left || !shift.left && !shift.top ? offset.top + this.border : 0; // Cache details cache.cornerLeft = adjust.left; cache.cornerTop = adjust.top; cache.corner = newCorner.clone(); }, destroy: function() { // Unbind events this.qtip._unbind(this.qtip.tooltip, this._ns); // Remove the tip element(s) if(this.qtip.elements.tip) { this.qtip.elements.tip.find('*') .remove().end().remove(); } } }); TIP = PLUGINS.tip = function(api) { return new Tip(api, api.options.style.tip); }; // Initialize tip on render TIP.initialize = 'render'; // Setup plugin sanitization options TIP.sanitize = function(options) { if(options.style && 'tip' in options.style) { var opts = options.style.tip; if(typeof opts !== 'object') { opts = options.style.tip = { corner: opts }; } if(!(/string|boolean/i).test(typeof opts.corner)) { opts.corner = TRUE; } } }; // Add new option checks for the plugin CHECKS.tip = { '^position.my|style.tip.(corner|mimic|border)$': function() { // Make sure a tip can be drawn this.create(); // Reposition the tooltip this.qtip.reposition(); }, '^style.tip.(height|width)$': function(obj) { // Re-set dimensions and redraw the tip this.size = [ obj.width, obj.height ]; this.update(); // Reposition the tooltip this.qtip.reposition(); }, '^content.title|style.(classes|widget)$': function() { this.update(); } }; // Extend original qTip defaults $.extend(TRUE, QTIP.defaults, { style: { tip: { corner: TRUE, mimic: FALSE, width: 6, height: 6, border: TRUE, offset: 0 } } });
var App = React.createClass({ getUserInfo: function(){ $.ajax({ url: '/scicuec/panel/getUserInfo', dataType: 'json', cache: true, success: function(data){ if(data['res'] === 'true'){ this.setState({usrId: data['usrId'],usrName: data['usrName'],usrFullName: data['usrFullName']}); ReactDOM.render( <Start usrFullName={this.state.usrFullName}/>, document.getElementById('main') ); this.setState({spinner:'true'}); } }.bind(this), error: function(xhr,status,err){ console.log('/scicuec/panel/logout',status,err.toString()); }.bind(this) }); }, getInitialState: function(){ return({usrId:'',usrName:'',usrFullName:'',solLoans:0,spinner:''}); }, componentDidMount: function(){ this.getUserInfo(); setInterval(this.getCurrentLoans,this.props.pollInterval); $(".dropdown-button").dropdown(); $(".button-collapse").sideNav({ edge: 'right' }); }, handleLogOut: function(){ swal({ title: '¿Estás seguro@ de querer cerrar tu sesión?', type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', cancelButtonText: 'No', confirmButtonText: 'Si, ¡quiero salir!' }).then(function() { $.ajax({ url: '/scicuec/panel/logout', dataType: 'json', cache: true, success: function(data){ if(data['res'] === 'true'){ window.location = "/scicuec/"; } }.bind(this), error: function(xhr,status,err){ console.log('/scicuec/panel/logout',status,err.toString()); }.bind(this) }); }).done(); }, render: function(){ return( <Menu usrFullName={this.state.usrFullName} logout={this.handleLogOut} spinner={this.state.spinner}/> ); } }); var Menu = React.createClass({ getInitialState: function(){ return { startBtn: 'active', loansBtn: '', invBtn: '' }; }, clearState: function(){ return { startBtn: '', loansBtn: '', invBtn: '' }; }, handleStartBtnClick: function(){ this.replaceState(this.getInitialState()); ReactDOM.render( <Start usrFullName={this.props.usrFullName}/>, document.getElementById('main') ); }, handleLoansBtnClick: function(){ this.replaceState(this.clearState); this.setState({loansBtn: 'active'}); ReactDOM.render( <Loans usrFullName={this.props.usrFullName}/>, document.getElementById('main') ); }, handleInvBtnClick: function(){ this.replaceState(this.clearState); this.setState({invBtn: 'active'}); ReactDOM.render( <Inventory url="/scicuec/panel/getItems/" usrFullName={this.props.usrFullName} pollInterval={60000}/>, document.getElementById('main') ); }, handleLogOut: function(){ this.props.logout(); }, render: function(){ return( <div> <div className="navbar-fixed"> <nav className="blue darken-4"> <div className="nav-wrapper"> <a href="#!" onClick={this.handleStartBtnClick} className="brand-logo"><img width="20%" className="responsive-img" src="../assets/img/logo.png" alt=""/> SCICUEC</a> <a href="#" data-activates="mobile" className="button-collapse right"><i className="material-icons">menu</i></a> <ul className="right hide-on-med-and-down"> <li className={this.state.startBtn}><a href="#" onClick={this.handleStartBtnClick}>Inicio</a></li> <li className={this.state.loansBtn}><a href="#" onClick={this.handleLoansBtnClick}>Préstamos</a></li> <li className={this.state.invBtn}><a href="#" onClick={this.handleInvBtnClick}>Inventario</a></li> <li><a href="#" onClick={this.handleLogOut}>Cerrar Sesión</a></li> </ul> <ul className="side-nav" id="mobile"> <li className={this.state.startBtn}><a className="waves-effect" href="#" onClick={this.handleStartBtnClick}><i className="small material-icons">view_module</i>Inicio</a></li> <li><div className="divider"></div></li> <li className={this.state.loansBtn}><a href="#" onClick={this.handleLoansBtnClick}><i className="small material-icons">assignment_id</i>Préstamos</a></li> <li><div className="divider"></div></li> <li className={this.state.invBtn}><a href="#" onClick={this.handleInvBtnClick}><i className="small material-icons">view_list</i>Inventario</a></li> <li><div className="divider"></div></li> <li><a href="#" onClick={this.handleLogOut}><i className="small material-icons">settings_power</i>Cerrar Sesión</a></li> <li><div className="divider"></div></li> </ul> </div> </nav> </div> <div hidden={this.props.spinner}> <div className="progress"> <div className="indeterminate"></div> </div> </div> </div> ); } }); var Start = React.createClass({ handleInvenClick: function(){ ReactDOM.render( <Inventory/>, document.getElementById('main') ); }, handleLoansPendClick: function(){ ReactDOM.render( <AuthSolicitation/>, document.getElementById('main') ); }, handleAlumnProfClick: function(){ ReactDOM.render( <AdminRegisterAlumn/>, document.getElementById('main') ); }, handleAdeudosClick: function(){ ReactDOM.render( <AdeudosAdmin/>, document.getElementById('main') ); }, countItems: function(){ $.ajax({ url: '/scicuec/panel/countItems/', dataType: 'json', cache: true, success: function(data){ if(data.length){ this.setState({articulosInventario:data[0].cantidad}); } }.bind(this), error: function(xhr,status,err){ console.log(this.props.url,status,err.toString()); }.bind(this) }); }, countSolicitudesEntrega: function(){ $.ajax({ url: '/scicuec/panel/countSolicitudesAlmacenEntrega/', dataType: 'json', cache: true, success: function(data){ if(data.length){ this.setState({solicitudesPendientesEntrega:data[0].cantidad}); } }.bind(this), error: function(xhr,status,err){ console.log(this.props.url,status,err.toString()); }.bind(this) }); }, countSolicitudesDevolucion: function(){ $.ajax({ url: '/scicuec/panel/countSolicitudesAlmacenDevolucion/', dataType: 'json', cache: true, success: function(data){ if(data.length){ this.setState({solicitudesPendientesDevolucion:data[0].cantidad}); } }.bind(this), error: function(xhr,status,err){ console.log(this.props.url,status,err.toString()); }.bind(this) }); }, getInitialState: function(){ return { articulosInventario:0, solicitudesPendientesEntrega:0, solicitudesPendientesDevolucion:0 }; }, componentDidMount: function(){ this.countItems(); this.countSolicitudesEntrega(); this.countSolicitudesDevolucion(); }, render: function(){ return( <main> <div className="section z-depth-3"> <div className="container"> <div className="row"> <center> <h3>Estadísticas</h3> </center> </div> </div> </div> <div className="section"> <div className="container"> <div className="row"> <div className="col s12" style={{align:"left"}}> <div className="chip"> <img src="../assets/img/user.png" alt="Current User"/> {this.props.usrFullName} </div> </div> </div> </div> </div> <div className="section"> <div className="row"> <div className="col s12 m4 l4"> <div className="card"> <div className="card-image"> <center> <h4>Artículos en Inventario</h4> </center> </div> <div className="card-content blue darken-4"> <center> <h1 style={{color:"white"}}>{this.state.articulosInventario}</h1> </center> </div> </div> </div> <div className="col s12 m4 l4"> <div className="card"> <div className="card-image"> <center> <h4>Solicitudes Pendientes de Entrega</h4> </center> </div> <div className="card-content blue darken-4"> <center> <h1 style={{color:"white"}}>{this.state.solicitudesPendientesEntrega}</h1> </center> </div> </div> </div> <div className="col s12 m4 l4"> <div className="card"> <div className="card-image"> <center> <h4>Solicitudes Pendientes de Devolución</h4> </center> </div> <div className="card-content blue darken-4"> <center> <h1 style={{color:"white"}}>{this.state.solicitudesPendientesDevolucion}</h1> </center> </div> </div> </div> </div> </div> </main> ); } }); var Loans = React.createClass({ getInitialState: function(){ return {entregaItems:[],recepcionItems:[],solicitudEntregaSearch:'',spinnerEntrega:'true',spinnerRecepcion:'true',viewEntrega:'true',viewRecepcion:'true',searchFormEntrega:'',searchFormRecepcion:'',entregaButton:'',recepcionBoton:'',spinnerBotonEntrega:'true',solicitudRecepcionSearch:'',estados:[],spinnerBotonRecepcion:'true'}; }, componentDidMount: function(){ $('select').material_select(); }, setAdeudo: function(key,e){ console.log(e.target.value); }, setEstado: function(key,e){ console.log(e.target.value); }, handleClearRecepcion: function(){ this.setState({recepcionItems:[],spinnerRecepcion:'true',viewRecepcion:'true',searchFormRecepcion:'',solicitudRecepcionSearch:''}); }, handleClearEntrega: function(){ this.setState({entregaItems:[],spinnerEntrega:'true',viewEntrega:'true',searchFormEntrega:'',solicitudEntregaSearch:''}); }, handleEntregaSubmit: function(e){ e.preventDefault(); if(this.state.solicitudEntregaSearch === ''){ swal('Error','Por favor ingresa un número de solicitud.','warning'); return; } this.setState({spinnerEntrega:''}); var data = {folio:this.state.solicitudEntregaSearch}; $.ajax({ url:'/scicuec/panel/getItemsSolicitationEntrega/', dataType: 'json', type: 'POST', data:data, success: function(data){ if(!data){ swal('Error','La solicitud aún no ha sido aprovada, fue denegada o ya fue entregada.','error'); this.setState({spinnerEntrega:'true'}); return; }else{ this.setState({entregaItems:data,spinnerEntrega:'true',viewEntrega:'',searchFormEntrega:'true'}); return; } }.bind(this), error: function(xhr,status,err){ swal('Se produjo un error',err.toString(),'error'); console.log('/scicuec/panel/getItemsSolicitation/',status,err.toString()); }.bind(this) }); }, getStates: function(){ $.ajax({ url: '/scicuec/panel/getStates/', dataType: 'json', cache: true, success: function(data){ this.setState({estados:data}); }.bind(this), error: function(xhr,status,err){ console.log(this.props.url,status,err.toString()); }.bind(this) }); }, handleRecepcionSubmit: function(e){ e.preventDefault(); if(this.state.solicitudRecepcionSearch === ''){ swal('Error','Por favor ingresa un número de solicitud.','warning'); return; } this.setState({spinnerRecepcion:''}); var data = {folio:this.state.solicitudRecepcionSearch}; this.getStates(); $.ajax({ url:'/scicuec/panel/getItemsSolicitationRecepcion/', dataType: 'json', type: 'POST', data:data, success: function(data){ if(!data){ swal('Error','La solicitud aún no ha sido entregada o ya fue recibida.','error'); this.setState({spinnerRecepcion:'true'}); return; }else{ this.setState({recepcionItems:data,spinnerRecepcion:'true',viewRecepcion:'',searchFormRecepcion:'true'}); this.state.recepcionItems.map(function(item){ item.estadoRecepcion = ''; item.adeudo = 0; item.notas = ''; }); return; } }.bind(this), error: function(xhr,status,err){ swal('Se produjo un error',err.toString(),'error'); this.setState({spinnerRecepcion:'true'}) console.log('/scicuec/panel/getItemsSolicitation/',status,err.toString()); }.bind(this) }); }, handleSolicitudEntregaChange: function(e){ let numSolicitud = e.target.value.replace(/[^0-9]/g,''); this.setState({solicitudEntregaSearch:numSolicitud}); }, handleSolicitudRecepcionChange: function(e){ let numSolicitud = e.target.value.replace(/[^0-9]/g,''); this.setState({solicitudRecepcionSearch:numSolicitud}); }, entregarMaterial: function(){ var data = [this.state.solicitudEntregaSearch]; this.state.entregaItems.map(function(item,key){ data.push(item.id); }); var elements = {data:data}; swal({ title: '¿Estás seguro?', text: "El material será asignado al usuario solicitante.", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then(function() { this.setState({entregaBoton:'true',spinnerBotonEntrega:''}); $.ajax({ url:'/scicuec/panel/entregaItems/', dataType: 'json', type: 'POST', data:elements, success: function(data){ if(data['res']){ swal({ title: 'Correcto', text: "El material se asignó correctamente.", type: 'success', confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then(function(){ this.setState({entregaBoton:'',spinnerBotonEntrega:'true'}); this.handleClearEntrega(); }.bind(this)); }else{ swal('Error','Se produjo un error, inténtalo nuevamente.','error'); this.setState({entregaBoton:'',spinnerBotonEntrega:'true'}); } }.bind(this), error: function(xhr,status,err){ swal('Se produjo un error',err.toString(),'error'); console.log('/scicuec/panel/getItemsSolicitation/',status,err.toString()); this.setState({entregaBoton:'',spinnerBotonEntrega:'true'}); }.bind(this) }); }.bind(this)).done(); }, setNotas: function(key,e){ let nota = e.target.value.trim(); this.state.recepcionItems[key].notas = nota; }, setAdeudo: function(key,e){ let adeudo = e.target.value.trim(); this.state.recepcionItems[key].adeudo = adeudo; }, setEstado: function(key,e){ let estado = e.target.value.trim(); this.state.recepcionItems[key].estadoRecepcion = estado; }, recibirItems: function(){ var incompletos = 0; var notas = 0; this.state.recepcionItems.map(function(item){ if(item.estadoRecepcion === ''){ incompletos++; } if(item.adeudo === '1' && item.notas === ''){ notas++; } }); if(incompletos){ swal('Faltan Campos','Es necesario marcar todos los elementos con su estado de devolución.','error'); return; } if(notas){ swal('Faltan Campos','Es necesario ingresar notas si el elemento se ha marcado con adeudo.','error'); return; } var data ={data:this.state.recepcionItems}; swal({ title: '¿Estás seguro?', text: "El material será recibido en el estado que has marcado, incluyendo los adeudos para el usuario.", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then(function() { this.setState({recepcionBoton:'true',spinnerBotonRecepcion:''}); $.ajax({ url:'/scicuec/panel/recepcionItems/', dataType: 'json', type: 'POST', data:data, success: function(data){ if(data['res']){ swal({ title: 'Correcto', text: "El material se recibió correctamente.", type: 'success', confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then(function(){ this.setState({recepcionBoton:'',spinnerBotonRecepcion:'true'}); this.handleClearRecepcion(); }.bind(this)); }else{ swal('Error','Se produjo un error, inténtalo nuevamente.','error'); this.setState({recepcionBoton:'',spinnerBotonRecepcion:'true'}); } }.bind(this), error: function(xhr,status,err){ swal('Se produjo un error',err.toString(),'error'); console.log('/scicuec/panel/getItemsSolicitation/',status,err.toString()); this.setState({recepcionBoton:'',spinnerBotonRecepcion:'true'}); }.bind(this) }); }.bind(this)).done(); }, render: function(){ var usuario = ''; var entregaItems = this.state.entregaItems.map(function(item){ usuario = item.nombreCompleto; return( <tr> <td>{item.nombre}</td> <td>{item.categoria}</td> <td>{item.subcategoria}</td> <td>{(!item.cod_sicop || !item.cod_economico)?item.id:"N/A"}</td> <td>{(item.cod_economico)?item.cod_economico:"N/A"}</td> <td>{(item.cod_sicop)?cod_sicop:"N/A"}</td> <td>{item.estado}</td> </tr> ); }); var estados = this.state.estados.map(function(estado){ return( <option value={estado.id}>{estado.nombre}</option> ); }.bind(this)); var recepcionItems = this.state.recepcionItems.map(function(item,key){ usuario = item.nombreCompleto; return( <tr> <td>{item.nombre}</td> <td>{item.categoria}</td> <td>{item.subcategoria}</td> <td>{(!item.cod_sicop || !item.cod_economico)?item.id:"N/A"}</td> <td>{(item.cod_economico)?item.cod_economico:"N/A"}</td> <td>{(item.cod_sicop)?cod_sicop:"N/A"}</td> <td>{item.estado}</td> <td> <select className="browser-default" onChange={() => this.setEstado(key,event)}> <option value="" disabled selected>Selecciona...</option> {estados} </select> </td> <td><input type="text" placeholder="Notas..." className="validate" onChange={() => this.setNotas(key,event)}/></td> <td> <select className="browser-default" onChange={() => this.setAdeudo(key,event)}> <option value="0" selected>No</option> <option value="1">Si</option> </select> </td> </tr> ); }.bind(this)); return( <main> <div className="section z-depth-3"> <div className="container"> <div className="row"> <center> <h3>Préstamos</h3> </center> </div> </div> </div> <div className="section"> <div className="container"> <div className="row"> <div className="col s12" style={{align:"left"}}> <div className="chip"> <img src="../assets/img/user.png" alt="Current User"/> {this.props.usrFullName} </div> </div> </div> </div> </div> <div className="section"> <div className="container"> <div className="row"> <div className="col s12"> <center> <h5>Entrega de Materiales</h5> </center> <hr/> </div> </div> <div className="row"> <form className="col s12" onSubmit={this.handleEntregaSubmit} hidden={this.state.searchFormEntrega}> <div className="row"> <div className="input-field col s12 m3 l3 offset-m3 offset-l3"> <input className="validate" type="text" placeholder="Número de Solicitud" id="numSolicitud" onChange={this.handleSolicitudEntregaChange} value={this.state.solicitudEntregaSearch}/> <label for="numSolicitud">Número de Solicitud</label> </div> <div className="input-field col s12 m3 l3 "> <input type="submit" value="Buscar" className="btn btn-small waves-effect waves-light blue darken-4"/> </div> </div> </form> <div className="input-field col s12 m3 l3" hidden={this.state.viewEntrega}> <a href="#" className="btn btn-small waves-effect waves-light red darken-4" onClick={this.handleClearEntrega}>Cancelar</a> </div> </div> <div hidden={this.state.spinnerEntrega}> <div className="progress"> <div className="indeterminate"></div> </div> </div> <div className="row" id="entregaResultados" hidden={this.state.viewEntrega}> <div className="col s12"> <p>Numero de Solicitud: <b>{this.state.solicitudEntregaSearch}</b></p> <p>Alumno/Profesor: <b>{usuario}</b></p> <p>Cantidad: <b>{this.state.entregaItems.length}</b></p> </div> <div className="col s12 m8 l8 offset-m2 offset-l2"> <table className="highlight responsive-table"> <thead> <tr> <th>Nombre</th> <th>Categoría</th> <th>Subcategoría</th> <th>Código Interno</th> <th>Código Económico</th> <th>Código SICOP</th> <th>Estado</th> </tr> </thead> <tbody> {entregaItems} </tbody> </table> </div> <div className="row"> <center> <div className="col s12" hidden={this.state.entregaBoton}> <a href="#" className="btn btn-small waves-effect waves-light blue darken-4" onClick={this.entregarMaterial}>Entregar</a> </div> </center> </div> <div className="row"> <center> <div hidden={this.state.spinnerBotonEntrega}> <div className="preloader-wrapper big active"> <div className="spinner-layer spinner-blue-only"> <div className="circle-clipper left"> <div className="circle"></div> </div><div className="gap-patch"> <div className="circle"></div> </div><div className="circle-clipper right"> <div className="circle"></div> </div> </div> </div> </div> </center> </div> </div> </div> </div> <div className="section"> <div className="container"> <div className="row"> <div className="col s12"> <center> <h5>Recepción de Materiales</h5> </center> <hr/> </div> </div> <div className="row" hidden={this.state.searchFormRecepcion}> <form className="col s12" onSubmit={this.handleRecepcionSubmit}> <div className="row"> <div className="input-field col s12 m3 l3 offset-m3 offset-l3"> <input className="validate" type="text" placeholder="Número de Solicitud" id="numSolicitud" value={this.state.solicitudRecepcionSearch} onChange={this.handleSolicitudRecepcionChange}/> <label for="numSolicitud">Número de Solicitud</label> </div> <div className="input-field col s12 m3 l3 "> <input type="submit" value="Buscar" className="btn btn-small waves-effect waves-light blue darken-4"/> </div> </div> </form> </div> <div className="input-field col s12 m3 l3" hidden={this.state.viewRecepcion}> <a href="#" className="btn btn-small waves-effect waves-light red darken-4" onClick={this.handleClearRecepcion}>Cancelar</a> </div> <div hidden={this.state.spinnerRecepcion}> <div className="progress"> <div className="indeterminate"></div> </div> </div> <div className="row" id="entregaResultados" hidden={this.state.viewRecepcion}> <div className="col s12"> <p>Numero de Solicitud: <b>{this.state.solicitudRecepcionSearch}</b></p> <p>Alumno/Profesor: <b>{usuario}</b></p> <p>Cantidad: <b>{this.state.recepcionItems.length}</b></p> </div> <div className="col s12 m12 l12"> <table className="highlight responsive-table"> <thead> <tr> <th>Nombre</th> <th>Categoría</th> <th>Subcategoría</th> <th>Código Interno</th> <th>Código Económico</th> <th>Código SICOP</th> <th>Estado de Entrega</th> <th>Estado de Recepción</th> <th>Notas</th> <th>¿Adeudo?</th> </tr> </thead> <tbody> {recepcionItems} </tbody> </table> </div> <div className="row"> <center> <div className="col s12" hidden={this.state.recepcionBoton}> <button className="btn btn-small waves-effect waves-light blue darken-4" onClick={this.recibirItems}>Recibir</button> </div> </center> </div> <div className="row"> <center> <div hidden={this.state.spinnerBotonRecepcion}> <div className="preloader-wrapper big active"> <div className="spinner-layer spinner-blue-only"> <div className="circle-clipper left"> <div className="circle"></div> </div><div className="gap-patch"> <div className="circle"></div> </div><div className="circle-clipper right"> <div className="circle"></div> </div> </div> </div> </div> </center> </div> </div> </div> </div> </main> ); } }); var Inventory = React.createClass({ getInitialState: function(){ return {data:[],cat:[],subcat:[],estado:[],currentPage:1,limitPage:10,searchName:''}; }, loadItemsFromServer: function(){ $.ajax({ url: this.props.url, dataType: 'json', cache: true, success: function(data){ this.setState({data:data,spinner:'true'}); }.bind(this), error: function(xhr,status,err){ console.log(this.props.url,status,err.toString()); }.bind(this) }); }, getCategoriesFromServer: function(){ $.ajax({ url: '/scicuec/panel/getCategories/', dataType: 'json', cache: true, success: function(data){ this.setState({cat:data}); }.bind(this), error: function(xhr,status,err){ console.log(this.props.url,status,err.toString()); }.bind(this) }); }, getSubCategoriesFromServer: function(){ $.ajax({ url: '/scicuec/panel/getSubCategories/', dataType: 'json', cache: true, success: function(data){ this.setState({subcat:data}); }.bind(this), error: function(xhr,status,err){ console.log(this.props.url,status,err.toString()); }.bind(this) }); }, getStatesFromServer: function(){ $.ajax({ url: '/scicuec/panel/getStates/', dataType: 'json', cache: true, success: function(data){ this.setState({estado:data}); }.bind(this), error: function(xhr,status,err){ console.log(this.props.url,status,err.toString()); }.bind(this) }); }, componentDidMount: function(){ $('.collapsible').collapsible({ accordion : true }); this.getCategoriesFromServer(); this.getSubCategoriesFromServer(); this.getStatesFromServer(); this.loadItemsFromServer(); this._timer = setInterval(this.loadItemsFromServer,this.props.pollInterval); }, componentDidUpdate: function(){ $('select').material_select(); $('.modal-trigger').leanModal(); $(this.refs.cat).material_select(this.handleNewCatChange.bind(this)); $(this.refs.subcat).material_select(this.handleNewSubCatChange.bind(this)); $(this.refs.state).material_select(this.handleNewStateChange.bind(this)); $(this.refs.catEdit).material_select(this.handleEditCatChange.bind(this)); $(this.refs.subcatEdit).material_select(this.handleEditSubCatChange.bind(this)); $(this.refs.stateEdit).material_select(this.handleEditStateChange.bind(this)); }, componentWillUnmount: function(){ clearInterval(this._timer); }, handleNewFormSubmit: function(e){ e.preventDefault(); if(!this.state.newName){ swal('Error',"Por favor, ingresa el nombre del nuevo elemento.","error"); return; } if(!this.state.newCat){ swal("Error","Por favor, selecciona la categoría del nuevo elemento.","error"); return; } if(!this.state.newSub){ swal("Error","Por favor, selecciona la subcategoría del nuevo elemento.","error"); return; } if(!this.state.newState){ swal("Error","Por favor, selecciona el estado del nuevo elemento.","error"); return; } if(!this.state.newEcon || !this.state.newSico){ swal("Información","Al no ingresar un código económico o SICOP, el sistema generará un código interno.","info"); } var data = {name:this.state.newName,cat:this.state.newCat,subcat:this.state.newSub,state:this.state.newState,econ:this.state.newEcon,sico:this.state.newSico}; swal({ title: '¿Estás seguro?', text: "El elemento será creado en la base de datos.", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then(function() { $.ajax({ url: '/scicuec/panel/newItem/', dataType: 'json', type: 'POST', data: data, success: function(data){ if(data['res'] === 'true'){ swal('Correcto','El elemento se ha creado en la base de datos.','success'); this.loadItemsFromServer(); this.forceUpdate(); }else{ swal('Error','Se produjo un error','error'); } }.bind(this), error: function(xhr,status,err){ swal('Se produjo un error',err.toString(),'error'); console.log(this.props.url,status,err.toString()); }.bind(this) }); }.bind(this)).done(); }, handleNewNameChange: function(e){ this.setState({newName: e.target.value.trim()}); }, handleNewCatChange: function(){ var val = $(this.refs.cat).val(); this.setState({newCat:val}); }, handleEditCatChange: function(){ var val = $(this.refs.catEdit).val(); this.setState({newCat:val}); }, handleNewSubCatChange: function(){ var val = $(this.refs.subcat).val(); this.setState({newSub:val}); }, handleEditSubCatChange: function(){ var val = $(this.refs.subcatEdit).val(); this.setState({newSub:val}); }, handleNewStateChange: function(){ var val = $(this.refs.state).val(); this.setState({newState:val}); }, handleEditStateChange: function(){ var val = $(this.refs.stateEdit).val(); this.setState({newState:val}); }, handleNewEconChange: function(e){ this.setState({newEcon:e.target.value.trim()}); }, handleNewSicoChange: function(e){ this.setState({newSico:e.target.value.trim()}); }, updatePagination: function(index){ var pages = Math.ceil(this.state.data.length / this.state.limitPage); if(!((this.state.currentPage + index) > pages) && !((this.state.currentPage + index) <= 0)){ this.state.currentPage += index; this.forceUpdate(); } }, updatePaginationByPage: function(page){ this.state.currentPage = page; this.forceUpdate(); }, updateItem: function(item){ this.state.cat.map(function(cat){ if(cat.nombre === this.state.data[item].categoria){ this.setState({newCat: cat.id}); return; } }.bind(this)); this.state.subcat.map(function(subcat){ if(subcat.nombre === this.state.data[item].subcategoria){ this.setState({newSub: subcat.id}); return; } }.bind(this)); this.state.estado.map(function(estado){ if(estado.nombre === this.state.data[item].estado){ this.setState({newState: estado.id}); return; } }.bind(this)); this.setState({idEdit: this.state.data[item].id, nameEdit: this.state.data[item].nombre, catEdit: this.state.data[item].categoria, subCatEdit: this.state.data[item].subcategoria, stateEdit: this.state.data[item].estado, codSicoEdit: this.state.data[item].cod_sicop, codEconEdit: this.state.data[item].cod_economico }); }, clearEdit: function(){ this.setState({idEdit: '', nameEdit: '', catEdit: '', subCatEdit: '', stateEdit:'', codSicoEdit: '', codEconEdit: '' }); }, handleEditFormSubmit: function(e){ e.preventDefault(); var id = this.state.idEdit; var name = this.state.nameEdit; var cat = this.state.newCat; var sub = this.state.newSub; var state = this.state.newState; var econ = this.state.codEconEdit; var sico = this.state.codSicoEdit; if(!name){ swal("Error","Por favor, ingresa el nombre del elemento.","error"); return; } var data = { id:id, nombre:name, cat:cat, sub:sub, state:state, econ:econ, sico:sico }; swal({ title: '¿Estás seguro?', text: "El elemento será editado.", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then(function() { $.ajax({ url: '/scicuec/panel/updateItem/', dataType: 'json', type: 'POST', data: data, success: function(data){ if(data['res'] === 'true'){ swal('Correcto','El elemento se ha sido editado correctamente.','success'); this.loadItemsFromServer(); this.forceUpdate(); $('#editModal').closeModal(); }else{ swal('Error','Se produjo un error','error'); } }.bind(this), error: function(xhr,status,err){ swal('Se produjo un error',err.toString(),'error'); console.log(this.props.url,status,err.toString()); }.bind(this) }); }.bind(this)).done(); }, handleEditNameChange: function(e){ this.setState({nameEdit: e.target.value}); }, handleEconEditChange: function(e){ this.setState({codEconEdit: e.target.value}); }, handleSicoEditChange: function(e){ this.setState({codSicoEdit: e.target.value}); }, deleteItem: function(id){ swal({ title: '¿Estás seguro?', text: "Ésta acción no se puede revertir.", type: 'warning', showCancelButton: true, confirmButtonColor: '#3085d6', cancelButtonColor: '#d33', confirmButtonText: 'Aceptar', cancelButtonText: 'Cancelar' }).then(function() { $.ajax({ url: '/scicuec/panel/deleteItem/', dataType: 'json', type: 'POST', data: {id:id}, success: function(data){ if(data['res'] === 'true'){ swal('Correcto','El elemento se ha eliminado correctamente.','success'); this.loadItemsFromServer(); this.forceUpdate(); }else{ swal('Error','Se produjo un error','error'); } }.bind(this), error: function(xhr,status,err){ swal('Se produjo un error',err.toString(),'error'); console.log(this.props.url,status,err.toString()); }.bind(this) }); }.bind(this)).done(); }, handleSearchName: function(e){ this.setState({searchName:e.target.value}); }, handleSearchSubmit: function(e){ e.preventDefault(); return; }, render: function(){ var categories = this.state.cat.map(function(categorie){ return( <option value={categorie.id}>{categorie.nombre}</option> ); }.bind(this)); var categoriesEdit = this.state.cat.map(function(categorie){ if(this.state.catEdit === categorie.nombre){ return( <option value={categorie.id} selected>{categorie.nombre}</option> ); }else{ return( <option value={categorie.id}>{categorie.nombre}</option> ); } }.bind(this)); var subcategories = this.state.subcat.map(function(subcategorie){ return( <option value={subcategorie.id}>{subcategorie.nombre}</option> ); }.bind(this)); var subcategoriesEdit = this.state.subcat.map(function(subcategorie){ if(this.state.subCatEdit === subcategorie.nombre){ return( <option value={subcategorie.id} selected>{subcategorie.nombre}</option> ); }else{ return( <option value={subcategorie.id}>{subcategorie.nombre}</option> ); } }.bind(this)); var states = this.state.estado.map(function(state){ return( <option value={state.id}>{state.nombre}</option> ); }.bind(this)); var statesEdit = this.state.estado.map(function(state){ if(this.state.stateEdit === state.nombre){ return( <option value={state.id} selected>{state.nombre}</option> ); }else{ return( <option value={state.id}>{state.nombre}</option> ); } }.bind(this)); var items = this.state.data.map(function(item,index){ var limit = this.state.currentPage * this.state.limitPage; if(!this.state.searchName){ if(((index + 1) <= limit) && ((index) >= (limit - this.state.limitPage))){ return(<tr> <td>{item.nombre}</td> <td>{item.categoria}</td> <td>{item.subcategoria}</td> <td>{(!(item.cod_economico || item.cod_sicop)?item.id:'N/A')}</td> <td>{(item.cod_economico)?item.cod_economico:"N/A"}</td> <td>{(item.cod_sicop)?item.cod_sicop:"N/A"}</td> <td><i className='material-icons'>{item.prestamo === "1"?"check":""}</i></td> <td><i className='material-icons'>{item.adeudo === "1"?"check":""}</i></td> <td>{item.estado}</td> <td><a className="modal-trigger" href="#editModal" onClick={() => this.updateItem(index)}><i className="material-icons">mode_edit</i></a><a href="#" onClick={() => this.deleteItem(item.id)}><i className="material-icons">delete</i></a></td> </tr>); } }else{ if((item.nombre.toUpperCase().indexOf(this.state.searchName.toUpperCase()) !== -1) || (item.categoria.toUpperCase().indexOf(this.state.searchName.toUpperCase()) !== -1) || (item.subcategoria.toUpperCase().indexOf(this.state.searchName.toUpperCase()) !== -1) || (item.id.toUpperCase().indexOf(this.state.searchName.toUpperCase()) !== -1)){ return(<tr> <td>{item.nombre}</td> <td>{item.categoria}</td> <td>{item.subcategoria}</td> <td>{(!(item.cod_economico || item.cod_sicop)?item.id:'N/A')}</td> <td>{(item.cod_economico)?item.cod_economico:"N/A"}</td> <td>{(item.cod_sicop)?item.cod_sicop:"N/A"}</td> <td><i className='material-icons'>{!item.prestamo?"check":""}</i></td> <td><i className='material-icons'>{item.adeudo === "1"?"check":""}</i></td> <td>{item.estado}</td> <td><a className="modal-trigger" href="#editModal" onClick={() => this.updateItem(index)}><i className="material-icons">mode_edit</i></a><a href="#" onClick={() => this.deleteItem(item.id)}><i className="material-icons">delete</i></a></td> </tr>); } } }.bind(this)); var pagination = function(){ if((this.state.data.length > 10) && !this.state.searchName){ var pages = Math.ceil(this.state.data.length / this.state.limitPage); var pageLinks = []; pageLinks.push(<li><a href="#!" onClick={() => this.updatePagination(-1)}><i className="material-icons">chevron_left</i></a></li>); var pageNumber = 1; for(var i = 1; i <= pages;i++){ let pageNumber = i; if(this.state.currentPage === i){ pageLinks.push(<li className="active indigo"><a href="#!" onClick={() => this.updatePaginationByPage(pageNumber)}>{i}</a></li>); }else{ pageLinks.push(<li><a href="#!" onClick={() => this.updatePaginationByPage(pageNumber)}>{i}</a></li>); } } pageLinks.push(<li className="waves-effect"><a href="#!" onClick={() => this.updatePagination(1)}><i className="material-icons">chevron_right</i></a></li>); return(pageLinks); } }.bind(this)(); return( <main> <div className="section z-depth-3"> <div className="container"> <div className="row"> <center> <h3>Inventario</h3> </center> </div> </div> </div> <div className="section"> <div className="container"> <div className="row"> <div className="col s12" style={{align:"left"}}> <div className="chip"> <img src="../assets/img/user.png" alt="Current User"/> {this.props.usrFullName} </div> </div> </div> </div> </div> <div className="section"> <div className="container"> <div className="row"> <div className="col s12"> <ul className="collapsible" data-collapsible="accordion"> <li> <div className="collapsible-header"><i className="material-icons">library_add</i> Nuevo Elemento</div> <div className="collapsible-body"> <div className="row"> <form className="col s12" onSubmit={this.handleNewFormSubmit}> <div className="row"> <div className="input-field col s12 m6 l6"> <input type="text" placeholder="Nombre" id="nombre" className="validate" onChange={this.handleNewNameChange}/> <label for="nombre">Nombre</label> </div> <div className="input-field col s12 m6 l6"> <select ref="cat" onChange={this.handleNewCatChange}> <option value="" disabled selected>Selecciona una Opción</option> {categories} </select> <label>Categoría</label> </div> </div> <div className="row"> <div className="input-field col s12 m6 l6"> <select ref="subcat" onChange={this.handleNewSubCatChange}> <option value="" disabled selected>Selecciona una Opción</option> {subcategories} </select> <label>Subcategoría</label> </div> <div className="input-field col s12 m6 l6"> <select ref="state" onChange={this.handleNewStateChange}> <option value="" disabled selected>Selecciona una Opción</option> {states} </select> <label>Estado</label> </div> </div> <div className="row"> <div className="input-field col s12 m6 l6"> <input type="text" placeholder="Código Económico" className="validate" id="codEconomico" onChange={this.handleNewEconChange}/> <label for="codEconomico">Código Económico</label> </div> <div className="input-field col s12 m6 l6"> <input type="text" placeholder="Código SICOP" className="validate" id="codSicop" onChange={this.handleNewSicoChange}/> <label for="codSicop">Código SICOP</label> </div> </div> <div className="row"> <center> <input type="submit" className="btn btn-small waves-effect indigo" value="Guardar"/> </center> </div> </form> </div> </div> </li> <li> <div className="collapsible-header"><i className="material-icons">search</i> Búsqueda Avanzada</div> <div className="collapsible-body"> <div className="row"> <form className="col s12" onSubmit={this.handleSearchSubmit}> <div className="row"> <div className="input-field col s12"> <input type="text" placeholder="Criterios" id="nombreBusqueda" className="validate" value={this.state.searchName} onChange={this.handleSearchName}/> <label for="nombreBusqueda">Criterios</label> </div> </div> </form> </div> </div> </li> </ul> </div> </div> </div> </div> <div className="section"> <div className="container"> <div className="row"> <small>Elementos Totales: <b>{this.state.data.length}</b></small> </div> <div className="row"> <i className="material-icons">mode_edit</i> Editar <i className="material-icons">delete</i> Eliminar </div> <div className="row"> <table className="highlight responsive-table"> <thead> <tr> <th>Nombre</th> <th>Categoría</th> <th>Subcategoría</th> <th>Código Interno</th> <th>Código Económico</th> <th>Código SICOP</th> <th>En Préstamo</th> <th>Adeudo</th> <th>Estado</th> <th>Acciones</th> </tr> </thead> <tbody> {items} </tbody> </table> <div hidden={this.state.spinner}> <div className="progress"> <div className="indeterminate"></div> </div> </div> <center> <ul className="pagination"> {pagination} </ul> </center> </div> </div> </div> <div id="editModal" className="modal bottom-sheet"> <div className="modal-content"> <div className="section"> <div className="container"> <div className="row"> <h4>Editar Elemento</h4> <hr/> </div> <div className="row"> <form className="col s12" onSubmit={this.handleEditFormSubmit}> <div className="row"> <div className="input-field col s12 m6 l6"> <input type="text" placeholder="Nombre" id="nombre" className="validate" value={this.state.nameEdit} onChange={this.handleEditNameChange}/> <label for="nombre">Nombre</label> </div> <div className="input-field col s12 m6 l6"> <select ref="catEdit" onChange={this.handleNewCatChange}> <option value="" disabled selected>Selecciona una Opción</option> {categoriesEdit} </select> <label>Categoría</label> </div> </div> <div className="row"> <div className="input-field col s12 m6 l6"> <select ref="subcatEdit" onChange={this.handleNewSubCatChange}> <option value="" disabled selected>Selecciona una Opción</option> {subcategoriesEdit} </select> <label>Subcategoría</label> </div> <div className="input-field col s12 m6 l6"> <select ref="stateEdit" onChange={this.handleNewStateChange}> <option value="" disabled selected>Selecciona una Opción</option> {statesEdit} </select> <label>Estado</label> </div> </div> <div className="row"> <div className="input-field col s12 m6 l6"> <input type="text" placeholder="Código Económico" className="validate" id="codEconomico" value={this.state.codEconEdit} onChange={this.handleEconEditChange}/> <label for="codEconomico">Código Económico</label> </div> <div className="input-field col s12 m6 l6"> <input type="text" placeholder="Código SICOP" className="validate" id="codSicop" value={this.state.codSicoEdit} onChange={this.handleSicoEditChange}/> <label for="codSicop">Código SICOP</label> </div> </div> <div className="row"> <center> <input type="submit" className="btn btn-small waves-effect indigo" value="Guardar"/> </center> </div> </form> </div> </div> </div> </div> <div className="modal-footer"> <a href="#" className="modal-action modal-close waves-effect waves-green btn-flat" onClick={this.clearEdit}>Cancelar</a> </div> </div> </main> ); } }); ReactDOM.render( <App/>, document.getElementById('app') );
/* Copyright (c) 2011 by MapQuery Contributors (see AUTHORS for * full list of contributors). Published under the MIT license. * See https://github.com/mapquery/mapquery/blob/master/LICENSE for the * full text of the license. */ /** #jquery.mapquery.mqMousePosition.js The file containing the mqMousePosition Widget ### *$('selector')*.`mqMousePosition([options])` _version added 0.1_ ####**Description**: create a widget to show the location under the mouse pointer + **options** - **map**: the mapquery instance - **precision**: the number of decimals (default 2) - **x**: the label for the x-coordinate (default x) - **y**: the label for the y-coordinate (default y) >Returns: widget The mqMousePosition allows us to show the coordinates under the mouse pointer $('#mousepointer').mqMousePointer({ map: '#map' }); */ (function($) { $.template('mqMousePosition', '<div class="mq-mouseposition ui-widget ui-helper-clearfix ">'+ '<span class="ui-widget-content ui-helper-clearfix ui-corner-all ui-corner-all">'+ '<div id="mq-mouseposition-x" class="mq-mouseposition-coordinate">'+ '</div><div id="mq-mouseposition-y" class="mq-mouseposition-coordinate">'+ '</div></div></span>'); $.widget("mapQuery.mqMousePosition", { options: { // The MapQuery instance map: undefined, // The number of decimals for the coordinates // default: 2 // TODO: JCB20110630 use dynamic precision based on the pixel // resolution, no need to configure precision precision: 2, // The label of the x-value // default: 'x' x: 'x', // The label of the y-value // default: 'y' y: 'y' }, _create: function() { //get the mapquery object this.map = $(this.options.map).data('mapQuery'); this.map.element.bind('mousemove', {widget: this}, this._onMousemove); $.tmpl('mqMousePosition', {}).appendTo(this.element); }, _destroy: function() { this.element.removeClass('ui-widget ui-helper-clearfix ' + 'ui-corner-all') .empty(); }, _onMousemove: function(evt) { var self = evt.data.widget; var x = evt.pageX; var y = evt.pageY; var mapProjection = self.map.projection; var displayProjection = self.map.displayProjection; var pos = self.map.olMap.getLonLatFromLayerPx( new OpenLayers.Pixel(x, y)); //if the coordinates should be displayed in something else, //set them via the map displayProjection option if(mapProjection != self.map.displayProjection) { pos = pos.transform(mapProjection, displayProjection); } $("#mq-mouseposition-x", self.element).html( self.options.x + ': ' + pos.lon.toFixed(self.options.precision)); $("#mq-mouseposition-y", self.element).html( self.options.y + ': ' + pos.lat.toFixed(self.options.precision)); } }); })(jQuery);
jsonp_handler({ "version": "1", "build": 2, "title": "myapp", "minruntime": 1, "baseurl": "http://yhh52367y@rawgit.com/yhh52367y/myapp/master/", "description": "", "files": [ "index.html", "index.css", "bundle.js", "jquery.js", "react-with-addons.js", "ksana.js", "bootstrap.min.js", "bootstrap.min.css", "sample.kdb" ], "filesizes": [ 552, 64, 155641, 277980, 645243, 325, 35607, 113502, 97542 ], "filedates": [ "2015-02-09T07:41:03.000Z", "2015-02-09T07:41:03.000Z", "2015-02-09T07:42:40.000Z", "2015-02-09T07:41:03.000Z", "2015-02-09T07:41:03.000Z", "2015-02-09T07:41:03.000Z", "2015-02-09T07:41:03.000Z", "2015-02-09T07:41:03.000Z", "2015-02-09T07:42:26.000Z" ], "date": "2015-02-09T07:42:41.384Z" })
'use strict' module.exports = { auth: false, jsonp: 'callback', handler (request, reply) { return reply({ alive: true }) } }
/** * =============================================================================== * * Copyright © 2008/2011 CAMENSULI Christophe | ccamensuli@gmail.com * * =============================================================================== * ____ _ ____ * / ___| | |_ __ _ __ _ ___ | __ ) ___ __ __ * \___ \ | __| / _` | / _` | / _ \ _____ | _ \ / _ \ \ \/ / * ___) | | |_ | (_| | | (_| | | __/ |_____| | |_) | | (_) | > < * |____/ \__| \__,_| \__, | \___| |____/ \___/ /_/\_\ * |___/ * 1.0 * * This file is part of StageBox Project . * * StageBox is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * StageBox is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Leaser General Public License * along with StageBox; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * ================================================================================ * * created by cci * * * Changes : * ========= * * 2011 : creation of the file * --------------------------------------------------------- * * * File description : * ================== * * this file is chat system * */ /* Depandances PROVIDE : * ===================== */ stage.provide("module.chat"); /* * Depandances REQUIRE : * ===================== */ //stage.require("XMPP"); //stage.require("BOSH"); stage.require("ui.i18n"); stage.registerModule("chat", function(){ var i18n = { type:"json", locale:"en-us", localesPath:"/src/stage-modules/chat", fileName:"chat.json", translate : { rosters:"users", addcontact:"Add a new contact" } }; var garbadgeSession = []; var modelRoster = stage.herite( function(localSettings){ var model = stage.extend({ name : "RosterXMPP", ormKey:"jid", design : [{ key:"jid", type:"string" },{ key:"groups", type:"object" },{ key:"name", type:"string" },{ key:"presence", type:"string" },{ key:"show", type:"string" },{ key:"status", type:"string" },{ key:"subscription", type:"string" },{ key:"ask", type:"string" } ] },localSettings); this.$super.constructor(null, null, model); },stage.ui.data.model); var controler = function(container, view, localSettings){ //console.log(this); this.state = "DISCONNECTED"; // model roster this.model = new modelRoster(localSettings.model); //i18n this.i18n = this.createI18nManager(); // view this.view = new chat(container, this, localSettings.viewSettings); this.connect({ urlServer : "http://stage-box.fr", urnServer : "http-bind", portServer : "5280", domain : 'stage-box.fr', userName : "rrd", pwd : "design", proxyUrl : "/src/library/io/protocols/XMPP/test/curlProxy3.php" }); }; controler.prototype.connect = function(protocol){ if(this.state != "DISCONNECTED") return; if(this.xmpp){ this.xmpp.start(); return; } if(this.state != "DISCONNECTED") return; if(protocol) this.protocolParams = protocol; // xmpp session this.xmpp = stage.io.protocols.XMPP(this.protocolParams); garbadgeSession.push(this.xmpp); // roster events this.xmpp.eventsManager.listen(this, "onRoster", this.addRoster); this.xmpp.eventsManager.listen(this, "onPresenceChanged", this.updatePresence); this.xmpp.eventsManager.listen(this, "onStateChanged", this.onStateChanged); this.xmpp.eventsManager.listen(this, "onSubscribeState", this.onSubscribeState); // instant message events this.xmpp.eventsManager.listen(this, "onIM", this.onMessage); // model ready /*this.model.eventsManager.listen(this,"onDataReady", function(){ console.log("onDataReady"); this.model.foreach(function(key, value, i){ console.log(value); }) });*/ }; controler.prototype.disconnect = function(){ if(this.state != "DISCONNECTED" && this.state != "DISCONNECTING"){ // xmpp session disconnect this.xmpp.stop(); } }; controler.prototype.onSubscribeState = function(jid, subscribeState){ // TODO implement this switch(subscribeState){ case "subscribed" : console.log("Confirmation de subscription de "+ jid); break; case "subscribe" : console.log("Demande de subscription de " + jid); this.view.createWindowSubscribe(jid); break; case "unsubscribe" : console.log("Demande de non subscription de " + jid); break; case "unsubscribed" : console.log("Confirmation de non subscription de " + jid); this.xmpp.unsubscribe(jid); break; default: } }; controler.prototype.onStateChanged = function(state){ //console.log("state change = "+state); this.state = state; switch (state){ case "CONNECTED" : this.user = this.xmpp.settings.userName; this.domain = this.xmpp.settings.domain; this.xmpp.setPresence("chat"); break; } // call view this.view.stateChanged(state); }; controler.prototype.updatePresence = function(jid, presence, showStatus, status){ var roster = this.model.get(jid); if(roster){ //if (roster.presence !== presence ){ roster.presence = presence; roster.show = showStatus; roster.status = status; // call view this.view.changePresence(null, roster); this.model.set(jid, roster); //} } //console.log("updatePresence => "); //console.log(roster); }; /* jidContact : contact id * message : message to send * params (optional): {subject:"the_subject", thread:"threadID"} **/ controler.prototype.sendMessage = function(jid, message, options){ this.xmpp.sendIM(jid, message, options); }; controler.prototype.onMessage = function(response){ // if history call model history // call view this.view.logMessage(response); }; controler.prototype.addRoster = function(roster){ //console.log(roster); for (var i=0 ; i<roster.length; i++){ this.model.set(roster[i].jid, roster[i]); } this.view.addRoster(roster); // call view }; controler.prototype.acceptSubscribe = function(from){ this.xmpp.acceptSubscribe(from); }; controler.prototype.refuseSubscribe = function(from){ this.xmpp.cancelSubscribe(from); }; controler.prototype.acceptAddSubscribe = function(from){ this.xmpp.acceptSubscribe(from); this.xmpp.subscribe(from); }; controler.prototype.addContact = function(jid){ this.xmpp.subscribe(jid); }; controler.prototype.unsuscribeContact = function(jid){ this.xmpp.unsubscribe(jid); }; var chat = function(container, controler, localSettings){ // window chat this.dialogs = {}; this.controler = controler; this.container = container; this.settings = stage.extend(true, { appendTo:this.container, header: { title : this.controler.module.getName(), icon : "stageui-icon-cart" }, shadow : false, draggable:{}, resizable:{}, focusable:true, autofocus:true, display:{ position:"absolute" }, closable:true, onClose:function(){ this.close(); }.bind(this), bodyPadding:"0", width:260, height:500 },localSettings); this.windowChat = stage.ui.Window(this.settings); this.layout = this.windowChat.createLayout("simple",{ area : "vertical", align : "stretch", globals : { bodyPadding : "0", border:"0" } }); this.createMenu(); this.createRoster(); this.createTaskBar(); this.windowChat.render(); //this.icon = "url("+this.controler.module.getIcon()+")"; //$$stage("span.stageui-icon").css("background-image",this.icon.src); }; chat.prototype.stateChanged = function(state){ this.state.innerHTML = state; if(state === "DISCONNECTED"){ $$stage(this.goupeConnected.body).children().each(function(item){ stage.dom.attach(stage.dom.detach(item), this.goupeDeconnected.body); }.bind(this)); } }; chat.prototype.close = function(){ this.controler.xmpp.stop(); this.windowChat.destroy(); }; chat.prototype.createMenu = function(roster){ this.slotMenu = this.layout.addSlot({ height : 50 }); stage.css.addClass( this.slotMenu.container , "menuChat"); this.state = document.createElement("span"); stage.css.setStyle(this.state, { "float":"left" }); stage.dom.insert(this.slotMenu.body, this.state); this.state.innerHTML = "DISCONNECTED"; var addContact = document.createElement("button"); stage.css.setStyle(addContact, { "float":"left" }); stage.dom.insert(this.slotMenu.body, addContact); addContact.innerHTML = "+ Contact"; stage.listen(addContact, "click", this.createWindowAddContact.bind(this) ); var disconnect = document.createElement("button"); stage.css.setStyle(disconnect, { "float":"right" }); stage.dom.insert(this.slotMenu.body, disconnect); disconnect.innerHTML = "Disconnect"; stage.listen(disconnect, "click", this.controler.disconnect.bind(this.controler) ); var connect = document.createElement("button"); stage.css.setStyle(connect, { "float":"right" }); stage.dom.insert(this.slotMenu.body, connect); connect.innerHTML = "Connect"; stage.listen(connect, "click", this.controler.connect.bind(this.controler) ); }; chat.prototype.createWindowAddContact = function(){ var win = stage.ui.Window({ appendTo:this.container, header: { title : "Add contact" }, //framed : true, shadow : false, focusable:true, autofocus:true, closable:true, draggable:{ containment:this.settings.draggable.containment || null }, resizable:{ containment:this.settings.resizable.containment || null }, display:{ position:"center" }, width:350, height:100 }); var layout = win.createLayout("simple", { area : "vertical", align : "stretch", globals : { bodyPadding : "0" } }); var sender = layout.addSlot({ height : 25 }); var send = $$stage(document.createElement("input")); win.sendInput = send; send.attribute("type","text"); send.css({ "float":"left", border:"none", height:"23px", paddind:"0 5px" }); send.keypress("enter", function(){} ); var add = document.createElement("button"); stage.css.setStyle(add, { "float":"right" }); stage.dom.insert(sender.body, send.get(0)); stage.dom.insert(sender.body, add); add.innerHTML = "Add Contact"; stage.listen(add, "click", this.addContact.bind(this, send.get(0) , win ) ); win.render(); return win; }; chat.prototype.addContact = function(message, window){ this.controler.addContact(message.value); window.destroy(); }; chat.prototype.createRoster = function(roster){ this.slotRoster = this.layout.addSlot({ flex:1 }); this.layoutAccordion = this.slotRoster.createLayout("Accordion",{}); this.goupeConnected = this.layoutAccordion.addSlot({ header : { title : "Connected" } }); this.goupeDeconnected = this.layoutAccordion.addSlot({ header : { title : "Deconnected" } }); }; chat.prototype.createTaskBar = function(roster){ this.slotTaskBar = this.layout.addSlot({ height : 25, border : "1 0 0 0" }); stage.css.addClass( this.slotTaskBar.container , "menuChat"); }; chat.prototype.addRoster = function(roster){ //this.controler.model.sort("jid"); for (var i = 0; i<roster.length ; i++){ var ele = document.createElement("div"); stage.css.addClass(ele, "roster"); ele.id = roster[i].jid; var id = roster[i].jid.split("@")[0]; this.changePresence(ele, roster[i]) stage.listen(ele,"click", function(id){ if ( ! ( id in this.dialogs) ){ var win = this.createWindowDialog(id); win.sendInput.get(0).focus(); }else{ this.dialogs[id].focus(); } }.bind(this,id)) } //console.log(roster); }; chat.prototype.changePresence = function(jid, roster){ //console.log(roster.show); if (! jid) jid = stage.dom.detach(document.getElementById(roster.jid)); jid.innerHTML = "<strong>"+roster.jid+"</strong> status :"+roster.show; if (roster.presence !== "available") stage.dom.attach(jid, this.goupeDeconnected.body) else stage.dom.attach(jid, this.goupeConnected.body) }; chat.prototype.logMessage = function(response){ //console.log(response); if ( ! ( response.from in this.dialogs) ){ this.createWindowDialog(response.from); } var win = this.createMessage(response.message, response.from, response.from ,"from") win.sendInput.get(0).focus(); }; chat.prototype.createWindowSubscribe = function(from){ var win = stage.ui.Window({ appendTo:this.container, header: { title : from.toUpperCase()+" souhaite vous ajouter a ses contacts" }, //framed : true, shadow : false, focusable:true, autofocus:true, closable:true, draggable:{ containment:this.settings.draggable.containment || null }, resizable:{ containment:this.settings.resizable.containment || null }, display:{ //position:"center" position:"absolute" }, width:350, height:100 }); var layout = win.createLayout("simple", { area : "vertical", align : "stretch", globals : { bodyPadding : "0" } }); var sender = layout.addSlot({ height : 25 }); var accept = document.createElement("button"); stage.css.setStyle(accept, { "float":"left", width:"20%" }); var acceptAdd = document.createElement("button"); stage.css.setStyle(acceptAdd, { "float":"left", width:"20%" }); var refuse = document.createElement("button"); stage.css.setStyle(refuse, { "float":"left", width:"20%" }); stage.dom.insert(sender.body, refuse); stage.dom.insert(sender.body, accept); stage.dom.insert(sender.body, acceptAdd); accept.innerHTML = "Accept"; acceptAdd.innerHTML = "Accept/add"; refuse.innerHTML = "Cancel"; stage.listen(accept, "click", this.acceptSubscribe.bind(this, from, win ) ); stage.listen(refuse, "click", this.refuseSubscribe.bind(this, from, win ) ); stage.listen(acceptAdd, "click", this.acceptAddSubscribe.bind(this, from, win ) ); win.render(); return win; }; chat.prototype.acceptSubscribe = function(from, win){ this.controler.acceptSubscribe(from); win.destroy(); }; chat.prototype.refuseSubscribe = function(from, win){ this.controler.refuseSubscribe(from); win.destroy(); }; chat.prototype.acceptAddSubscribe = function(from, win){ this.controler.acceptAddSubscribe(from); win.destroy(); }; chat.prototype.createWindowDialog = function(from){ var win = stage.ui.Window({ appendTo:this.container, header: { title : "CHAT WITH "+from.toUpperCase() //icon : "stageui-icon-cart" }, //framed : true, shadow : false, focusable:true, autofocus:true, closable:true, onClose:function(win){ win.destroy(); this.dialogs[from] = null; delete this.dialogs[from]; }.bind(this), draggable:{ containment:this.settings.draggable.containment || null }, resizable:{ containment:this.settings.resizable.containment || null }, display:{ //position:"center" position:"absolute" }, width:400, height:200 }); var layout = win.createLayout("simple", { area : "vertical", align : "stretch", globals : { bodyPadding : "0" } }); var infoSlot = layout.addSlot({ height : 25, border:"1", margin:{ left:0 } }); var winDialog = layout.addSlot({ flex : 1, overflow:"auto", border:"0" }); var unsuscribe = document.createElement("button"); stage.css.setStyle(unsuscribe, { "float":"left", width:"20%" }); stage.dom.insert(infoSlot.body, unsuscribe); unsuscribe.innerHTML = "Unsuscribe"; stage.listen(unsuscribe, "click", this.unsuscribeContact.bind(this, from, win)); var sender = layout.addSlot({ height : 25 }); var send = $$stage(document.createElement("input")); win.sendInput = send; send.attribute("type","text"); send.css({ "float":"left", border:"none", height:"23px", paddind:"0 5px", width:"75%" }); send.keypress("enter", this.send.bind(this, from, send.get(0))); var button = document.createElement("button"); stage.css.setStyle(button, { "float":"left", width:"20%" }); stage.dom.insert(sender.body, send.get(0)); stage.dom.insert(sender.body, button); button.innerHTML = "send" stage.listen(button, "click", this.send.bind(this, from, send.get(0))); win.render(); this.dialogs[from] = win; return win; }; chat.prototype.unsuscribeContact = function(jid, window){ this.controler.unsuscribeContact(jid+"@stage-box.fr"); window.destroy(); }; chat.prototype.send = function(from, send){ var to = this.controler.user; var message = send.value ; if (! message ) return ; this.controler.sendMessage(from+"@"+this.controler.xmpp.settings.domain, send.value ); var win = this.createMessage(send.value, from , to,"to"); win.sendInput.get(0).value = ""; }; chat.prototype.createMessage = function(message, from, to,side){ var ele = document.createElement("div"); if (side === "from") stage.css.addClass(ele,"rosterMessageTo"); else stage.css.addClass(ele,"rosterMessageFrom"); ele.innerHTML = to+" say : <strong>"+ message+"</strong>"; stage.dom.insert(this.dialogs[from].layout.slots[1].body , ele); return this.dialogs[from]; }; return { version : 1.0, name:"chat", path:"/src/stage-modules/chat/", controler:controler, views:[chat], models:[modelRoster], i18n:i18n, _onLoad : function() { }, _unLoad : function() { for (var i = 0 ; i < garbadgeSession.length ; i++ ){ garbadgeSession[i].stop(); } } } });
/** * @author xeolabs / https://github.com/xeolabs */ class ArrayBuffer { constructor(gl, type, data, numItems, itemSize, usage) { this._gl = gl; this.type = type; this.allocated = false; switch (data.constructor) { case Uint8Array: this.itemType = gl.UNSIGNED_BYTE; this.itemByteSize = 1; break; case Int8Array: this.itemType = gl.BYTE; this.itemByteSize = 1; break; case Uint16Array: this.itemType = gl.UNSIGNED_SHORT; this.itemByteSize = 2; break; case Int16Array: this.itemType = gl.SHORT; this.itemByteSize = 2; break; case Uint32Array: this.itemType = gl.UNSIGNED_INT; this.itemByteSize = 4; break; case Int32Array: this.itemType = gl.INT; this.itemByteSize = 4; break; default: this.itemType = gl.FLOAT; this.itemByteSize = 4; } this.usage = usage; this.length = 0; this.numItems = 0; this.itemSize = itemSize; this._allocate(data); } _allocate(data) { this.allocated = false; this._handle = this._gl.createBuffer(); if (!this._handle) { throw "Failed to allocate WebGL ArrayBuffer"; } if (this._handle) { this._gl.bindBuffer(this.type, this._handle); this._gl.bufferData(this.type, data, this.usage); this._gl.bindBuffer(this.type, null); this.length = data.length; this.numItems = this.length / this.itemSize; this.allocated = true; } } setData(data, offset) { if (!this.allocated) { return; } if (data.length > this.length) { // Needs reallocation this.destroy(); this._allocate(data, data.length); } else { // No reallocation needed this._gl.bindBuffer(this.type, this._handle); if (offset || offset === 0) { this._gl.bufferSubData(this.type, offset * this.itemByteSize, data); } else { this._gl.bufferData(this.type, data, this.usage); } this._gl.bindBuffer(this.type, null); } } bind() { if (!this.allocated) { return; } this._gl.bindBuffer(this.type, this._handle); } unbind() { if (!this.allocated) { return; } this._gl.bindBuffer(this.type, null); } destroy() { if (!this.allocated) { return; } this._gl.deleteBuffer(this._handle); this._handle = null; this.allocated = false; } } export{ArrayBuffer};
module.exports = function errorHandler(err, req, res, next) { // eslint-disable-line no-unused-var let code = 500, error = 'Internal Server Error'; // Mongoose Validation Error? if(err.name === 'ValidationError' || err.name === "CastError") { console.log(err.errors); code = 400; error = err.errors.name.message; } // is this one of our errors? else if(err.code) { // by convention, we're passing in an object // with a code property === http statusCode // and a error property === message to display code = err.code; error = err.error; console.log(err.code, err.error); } // or something unexpected? else { console.log(err); } res.status(code).send({ error }); };
define(['lazoView'], function (LazoView) { 'use strict'; return LazoView.extend({ }); });
app.config(function($stateProvider, $urlRouterProvider,$locationProvider,$httpProvider) { $urlRouterProvider.otherwise('/home'); $stateProvider .state('admin', { url: '/admin', templateUrl: 'admin/back_login.php', controller: 'AdminController' }) .state('admin/', { url: '/admin/', templateUrl: 'admin/back_login.php', controller: 'AdminController' }) .state('home', { url: '/home', templateUrl: 'home/views/views.html', controller: 'HomeController' }) .state('home/', { url: '/home/', templateUrl: 'home/views/views.html', controller: 'HomeController' }) .state('home_en', { url: '/home_en', templateUrl: 'home/views/views_en.html', controller: 'HomeController_EN' }) .state('about', { url: '/about', templateUrl: 'about/views/views.html', controller: 'AboutController' }) .state('about/', { url: '/about/', templateUrl: 'about/views/views.html', controller: 'AboutController' }) .state('about_form', { url: '/about/about_form/:id', templateUrl: 'about/views/form.html', controller: 'AboutFormController' }) .state('about_form_en', { url: '/about/about_form_en/:id', templateUrl: 'about/views/form_en.html', controller: 'AboutFormController_EN' }) .state('about_en', { url: '/about_en', templateUrl: 'about/views/views_en.html', controller: 'AboutController_EN' }) .state('news', { url: '/news', templateUrl: 'news/views/views.html', controller: 'NewsController' }) .state('news/', { url: '/news/', templateUrl: 'news/views/views.html', controller: 'NewsController' }) .state('news_en', { url: '/news_en', templateUrl: 'news/views/views_en.html', controller: 'NewsController_EN' }) .state('news_new', { url: '/news_new', templateUrl: 'news/views/view_new.html', controller: 'NewsController' }) .state('news_more', { url: '/news/news_more/:id', templateUrl:'news/views/more.html', controller: 'NewsMoreController' }) .state('news_en_more', { url: '/news/news_en_more/:id', templateUrl: 'news/views/more_en.html', controller: 'NewsMoreController' }) .state('news_form', { url: '/news/news_form/:id', templateUrl:'news/views/form.html', controller: 'NewsFormController' }) .state('news_form_en', { url: '/news/news_form_en/:id', templateUrl:'news/views/form_en.html', controller: 'NewsFormController' }) .state('instrument', { url: '/instrument', templateUrl: 'instrument/views/views.html', controller: 'InstrumentController' }) .state('instrument/', { url: '/instrument/', templateUrl: 'instrument/views/views.html', controller: 'InstrumentController' }) .state('instrument_en', { url: '/instrument_en', templateUrl: 'instrument/views/views_en.html', controller: 'InstrumentController_EN' }) .state('/members', { url: '/members', templateUrl: 'members/views/views.html', controller: 'MembersController' }) .state('members/', { url: '/members/', templateUrl: 'members/views/views.html', controller: 'MembersController' }) .state('/members_en', { url: '/members_en', templateUrl: 'members/views/views_en.html', controller: 'MembersController_EN' }) .state('members_form', { url: '/members/members_form/:id', templateUrl:'members/views/form.html', controller: 'MembersFormController' }) .state('members_form_en', { url: '/members/members_form_en/:id', templateUrl:'members/views/form_en.html', controller: 'MembersFormController' }) .state('/credit', { url: '/credit', templateUrl: 'credit/views/views.html', controller: 'CreditController' }) .state('credit/', { url: '/credit/', templateUrl: 'credit/views/views.html', controller: 'CreditController' }) .state('/credit_en', { url: '/credit_en', templateUrl: 'credit/views/views_en.html', controller: 'CreditController_EN' }) .state('/links', { url: '/links', templateUrl: 'links/views/views.html', controller: 'DownloadController' }) .state('links/', { url: '/links/', templateUrl: 'links/views/views.html', controller: 'DownloadController' }) .state('/links_en', { url: '/links_en', templateUrl: 'links/views/views_en.html', controller: 'DownloadController_EN' }) ; $locationProvider.html5Mode(true); });
// The Tern server object // A server is a stateful object that manages the analysis for a // project, and defines an interface for querying the code in the // project. (function(root, mod) { if (typeof exports == "object" && typeof module == "object") // CommonJS return mod(exports, require("./infer"), require("./signal"), require("acorn/acorn"), require("acorn/util/walk")); if (typeof define == "function" && define.amd) // AMD return define(["exports", "./infer", "./signal", "acorn/acorn", "acorn/util/walk"], mod); mod(root.tern || (root.tern = {}), tern, tern.signal, acorn, acorn.walk); // Plain browser env })(this, function(exports, infer, signal, acorn, walk) { "use strict"; var plugins = Object.create(null); exports.registerPlugin = function(name, init) { plugins[name] = init; }; var defaultOptions = exports.defaultOptions = { debug: false, async: false, getFile: function(_f, c) { if (this.async) c(null, null); }, defs: [], plugins: {}, fetchTimeout: 1000, dependencyBudget: 20000, reuseInstances: true }; var queryTypes = { completions: { takesFile: true, run: findCompletions }, properties: { run: findProperties }, type: { takesFile: true, run: findTypeAt }, documentation: { takesFile: true, run: findDocs }, definition: { takesFile: true, run: findDef }, refs: { takesFile: true, fullFile: true, run: findRefs }, rename: { takesFile: true, fullFile: true, run: buildRename }, files: { run: listFiles } }; exports.defineQueryType = function(name, desc) { queryTypes[name] = desc; }; function File(name, parent) { this.name = name; this.parent = parent; this.scope = this.text = this.ast = this.lineOffsets = null; } File.prototype.asLineChar = function(pos) { return asLineChar(this, pos); }; function updateText(file, text, srv) { file.text = text; file.ast = infer.parse(text, srv.passes, {directSourceFile: file, allowReturnOutsideFunction: true}); file.lineOffsets = null; } var Server = exports.Server = function(options) { this.cx = null; this.options = options || {}; for (var o in defaultOptions) if (!options.hasOwnProperty(o)) options[o] = defaultOptions[o]; this.handlers = Object.create(null); this.files = []; this.fileMap = Object.create(null); this.needsPurge = []; this.budgets = Object.create(null); this.uses = 0; this.pending = 0; this.asyncError = null; this.passes = Object.create(null); this.defs = options.defs.slice(0); for (var plugin in options.plugins) if (options.plugins.hasOwnProperty(plugin) && plugin in plugins) { var init = plugins[plugin](this, options.plugins[plugin]); if (init && init.defs) { if (init.loadFirst) this.defs.unshift(init.defs); else this.defs.push(init.defs); } if (init && init.passes) for (var type in init.passes) if (init.passes.hasOwnProperty(type)) (this.passes[type] || (this.passes[type] = [])).push(init.passes[type]); } this.reset(); }; Server.prototype = signal.mixin({ addFile: function(name, /*optional*/ text, parent) { // Don't crash when sloppy plugins pass non-existent parent ids if (parent && !(parent in this.fileMap)) parent = null; ensureFile(this, name, parent, text); }, delFile: function(name) { var file = this.findFile(name); if (file) { this.needsPurge.push(file.name); this.files.splice(this.files.indexOf(file), 1); delete this.fileMap[name]; } }, reset: function() { this.signal("reset"); this.cx = new infer.Context(this.defs, this); this.uses = 0; this.budgets = Object.create(null); for (var i = 0; i < this.files.length; ++i) { var file = this.files[i]; file.scope = null; } }, request: function(doc, c) { var inv = invalidDoc(doc); if (inv) return c(inv); var self = this; doRequest(this, doc, function(err, data) { c(err, data); if (self.uses > 40) { self.reset(); analyzeAll(self, null, function(){}); } }); }, findFile: function(name) { return this.fileMap[name]; }, flush: function(c) { var cx = this.cx; analyzeAll(this, null, function(err) { if (err) return c(err); infer.withContext(cx, c); }); }, startAsyncAction: function() { ++this.pending; }, finishAsyncAction: function(err) { if (err) this.asyncError = err; if (--this.pending === 0) this.signal("everythingFetched"); } }); function doRequest(srv, doc, c) { if (doc.query && !queryTypes.hasOwnProperty(doc.query.type)) return c("No query type '" + doc.query.type + "' defined"); var query = doc.query; // Respond as soon as possible when this just uploads files if (!query) c(null, {}); var files = doc.files || []; if (files.length) ++srv.uses; for (var i = 0; i < files.length; ++i) { var file = files[i]; ensureFile(srv, file.name, null, file.type == "full" ? file.text : null); } var timeBudget = typeof doc.timeout == "number" ? [doc.timeout] : null; if (!query) { analyzeAll(srv, timeBudget, function(){}); return; } var queryType = queryTypes[query.type]; if (queryType.takesFile) { if (typeof query.file != "string") return c(".query.file must be a string"); if (!/^#/.test(query.file)) ensureFile(srv, query.file, null); } analyzeAll(srv, timeBudget, function(err) { if (err) return c(err); var file = queryType.takesFile && resolveFile(srv, files, query.file); if (queryType.fullFile && file.type == "part") return c("Can't run a " + query.type + " query on a file fragment"); function run() { var result; try { result = queryType.run(srv, query, file); } catch (e) { if (srv.options.debug && e.name != "TernError") console.error(e.stack); return c(e); } c(null, result); } infer.withContext(srv.cx, timeBudget ? function() { infer.withTimeout(timeBudget[0], run); } : run); }); } function analyzeFile(srv, file) { infer.withContext(srv.cx, function() { file.scope = srv.cx.topScope; srv.signal("beforeLoad", file); infer.analyze(file.ast, file.name, file.scope, srv.passes); srv.signal("afterLoad", file); }); return file; } function ensureFile(srv, name, parent, text) { var known = srv.findFile(name); if (known) { if (text != null) { if (known.scope) { srv.needsPurge.push(name); known.scope = null; } updateText(known, text, srv); } if (parentDepth(srv, known.parent) > parentDepth(srv, parent)) { known.parent = parent; if (known.excluded) known.excluded = null; } return; } var file = new File(name, parent); srv.files.push(file); srv.fileMap[name] = file; if (text != null) { updateText(file, text, srv); } else if (srv.options.async) { srv.startAsyncAction(); srv.options.getFile(name, function(err, text) { updateText(file, text || "", srv); srv.finishAsyncAction(err); }); } else { updateText(file, srv.options.getFile(name) || "", srv); } } function fetchAll(srv, c) { var done = true, returned = false; srv.files.forEach(function(file) { if (file.text != null) return; if (srv.options.async) { done = false; srv.options.getFile(file.name, function(err, text) { if (err && !returned) { returned = true; return c(err); } updateText(file, text || "", srv); fetchAll(srv, c); }); } else { try { updateText(file, srv.options.getFile(file.name) || "", srv); } catch (e) { return c(e); } } }); if (done) c(); } function waitOnFetch(srv, timeBudget, c) { var done = function() { srv.off("everythingFetched", done); clearTimeout(timeout); analyzeAll(srv, timeBudget, c); }; srv.on("everythingFetched", done); var timeout = setTimeout(done, srv.options.fetchTimeout); } function analyzeAll(srv, timeBudget, c) { if (srv.pending) return waitOnFetch(srv, timeBudget, c); var e = srv.fetchError; if (e) { srv.fetchError = null; return c(e); } if (srv.needsPurge.length > 0) infer.withContext(srv.cx, function() { infer.purge(srv.needsPurge); srv.needsPurge.length = 0; }); var done = true; // The second inner loop might add new files. The outer loop keeps // repeating both inner loops until all files have been looked at. for (var i = 0; i < srv.files.length;) { var toAnalyze = []; for (; i < srv.files.length; ++i) { var file = srv.files[i]; if (file.text == null) done = false; else if (file.scope == null && !file.excluded) toAnalyze.push(file); } toAnalyze.sort(function(a, b) { return parentDepth(srv, a.parent) - parentDepth(srv, b.parent); }); for (var j = 0; j < toAnalyze.length; j++) { var file = toAnalyze[j]; if (file.parent && !chargeOnBudget(srv, file)) { file.excluded = true; } else if (timeBudget) { var startTime = +new Date; infer.withTimeout(timeBudget[0], function() { analyzeFile(srv, file); }); timeBudget[0] -= +new Date - startTime; } else { analyzeFile(srv, file); } } } if (done) c(); else waitOnFetch(srv, timeBudget, c); } function firstLine(str) { var end = str.indexOf("\n"); if (end < 0) return str; return str.slice(0, end); } function findMatchingPosition(line, file, near) { var pos = Math.max(0, near - 500), closest = null; if (!/^\s*$/.test(line)) for (;;) { var found = file.indexOf(line, pos); if (found < 0 || found > near + 500) break; if (closest == null || Math.abs(closest - near) > Math.abs(found - near)) closest = found; pos = found + line.length; } return closest; } function scopeDepth(s) { for (var i = 0; s; ++i, s = s.prev) {} return i; } function ternError(msg) { var err = new Error(msg); err.name = "TernError"; return err; } function resolveFile(srv, localFiles, name) { var isRef = name.match(/^#(\d+)$/); if (!isRef) return srv.findFile(name); var file = localFiles[isRef[1]]; if (!file) throw ternError("Reference to unknown file " + name); if (file.type == "full") return srv.findFile(file.name); // This is a partial file var realFile = file.backing = srv.findFile(file.name); var offset = file.offset; if (file.offsetLines) offset = {line: file.offsetLines, ch: 0}; file.offset = offset = resolvePos(realFile, file.offsetLines == null ? file.offset : {line: file.offsetLines, ch: 0}, true); var line = firstLine(file.text); var foundPos = findMatchingPosition(line, realFile.text, offset); var pos = foundPos == null ? Math.max(0, realFile.text.lastIndexOf("\n", offset)) : foundPos; var inObject, atFunction; infer.withContext(srv.cx, function() { infer.purge(file.name, pos, pos + file.text.length); var text = file.text, m; if (m = text.match(/(?:"([^"]*)"|([\w$]+))\s*:\s*function\b/)) { var objNode = walk.findNodeAround(file.backing.ast, pos, "ObjectExpression"); if (objNode && objNode.node.objType) inObject = {type: objNode.node.objType, prop: m[2] || m[1]}; } if (foundPos && (m = line.match(/^(.*?)\bfunction\b/))) { var cut = m[1].length, white = ""; for (var i = 0; i < cut; ++i) white += " "; text = white + text.slice(cut); atFunction = true; } var scopeStart = infer.scopeAt(realFile.ast, pos, realFile.scope); var scopeEnd = infer.scopeAt(realFile.ast, pos + text.length, realFile.scope); var scope = file.scope = scopeDepth(scopeStart) < scopeDepth(scopeEnd) ? scopeEnd : scopeStart; file.ast = infer.parse(file.text, srv.passes, {directSourceFile: file, allowReturnOutsideFunction: true}); infer.analyze(file.ast, file.name, scope, srv.passes); // This is a kludge to tie together the function types (if any) // outside and inside of the fragment, so that arguments and // return values have some information known about them. tieTogether: if (inObject || atFunction) { var newInner = infer.scopeAt(file.ast, line.length, scopeStart); if (!newInner.fnType) break tieTogether; if (inObject) { var prop = inObject.type.getProp(inObject.prop); prop.addType(newInner.fnType); } else if (atFunction) { var inner = infer.scopeAt(realFile.ast, pos + line.length, realFile.scope); if (inner == scopeStart || !inner.fnType) break tieTogether; var fOld = inner.fnType, fNew = newInner.fnType; if (!fNew || (fNew.name != fOld.name && fOld.name)) break tieTogether; for (var i = 0, e = Math.min(fOld.args.length, fNew.args.length); i < e; ++i) fOld.args[i].propagate(fNew.args[i]); fOld.self.propagate(fNew.self); fNew.retval.propagate(fOld.retval); } } }); return file; } // Budget management function astSize(node) { var size = 0; walk.simple(node, {Expression: function() { ++size; }}); return size; } function parentDepth(srv, parent) { var depth = 0; while (parent) { parent = srv.findFile(parent).parent; ++depth; } return depth; } function budgetName(srv, file) { for (;;) { var parent = srv.findFile(file.parent); if (!parent.parent) break; file = parent; } return file.name; } function chargeOnBudget(srv, file) { var bName = budgetName(srv, file); var size = astSize(file.ast); var known = srv.budgets[bName]; if (known == null) known = srv.budgets[bName] = srv.options.dependencyBudget; if (known < size) return false; srv.budgets[bName] = known - size; return true; } // Query helpers function isPosition(val) { return typeof val == "number" || typeof val == "object" && typeof val.line == "number" && typeof val.ch == "number"; } // Baseline query document validation function invalidDoc(doc) { if (doc.query) { if (typeof doc.query.type != "string") return ".query.type must be a string"; if (doc.query.start && !isPosition(doc.query.start)) return ".query.start must be a position"; if (doc.query.end && !isPosition(doc.query.end)) return ".query.end must be a position"; } if (doc.files) { if (!Array.isArray(doc.files)) return "Files property must be an array"; for (var i = 0; i < doc.files.length; ++i) { var file = doc.files[i]; if (typeof file != "object") return ".files[n] must be objects"; else if (typeof file.text != "string") return ".files[n].text must be a string"; else if (typeof file.name != "string") return ".files[n].name must be a string"; else if (file.type == "part") { if (!isPosition(file.offset) && typeof file.offsetLines != "number") return ".files[n].offset must be a position"; } else if (file.type != "full") return ".files[n].type must be \"full\" or \"part\""; } } } var offsetSkipLines = 25; function findLineStart(file, line) { var text = file.text, offsets = file.lineOffsets || (file.lineOffsets = [0]); var pos = 0, curLine = 0; var storePos = Math.min(Math.floor(line / offsetSkipLines), offsets.length - 1); var pos = offsets[storePos], curLine = storePos * offsetSkipLines; while (curLine < line) { ++curLine; pos = text.indexOf("\n", pos) + 1; if (pos === 0) return null; if (curLine % offsetSkipLines === 0) offsets.push(pos); } return pos; } function resolvePos(file, pos, tolerant) { if (typeof pos != "number") { var lineStart = findLineStart(file, pos.line); if (lineStart == null) { if (tolerant) pos = file.text.length; else throw ternError("File doesn't contain a line " + pos.line); } else { pos = lineStart + pos.ch; } } if (pos > file.text.length) { if (tolerant) pos = file.text.length; else throw ternError("Position " + pos + " is outside of file."); } return pos; } function asLineChar(file, pos) { if (!file) return {line: 0, ch: 0}; var offsets = file.lineOffsets || (file.lineOffsets = [0]); var text = file.text, line, lineStart; for (var i = offsets.length - 1; i >= 0; --i) if (offsets[i] <= pos) { line = i * offsetSkipLines; lineStart = offsets[i]; } for (;;) { var eol = text.indexOf("\n", lineStart); if (eol >= pos || eol < 0) break; lineStart = eol + 1; ++line; } return {line: line, ch: pos - lineStart}; } function outputPos(query, file, pos) { if (query.lineCharPositions) { var out = asLineChar(file, pos); if (file.type == "part") out.line += file.offsetLines != null ? file.offsetLines : asLineChar(file.backing, file.offset).line; return out; } else { return pos + (file.type == "part" ? file.offset : 0); } } // Delete empty fields from result objects function clean(obj) { for (var prop in obj) if (obj[prop] == null) delete obj[prop]; return obj; } function maybeSet(obj, prop, val) { if (val != null) obj[prop] = val; } // Built-in query types function compareCompletions(a, b) { if (typeof a != "string") { a = a.name; b = b.name; } var aUp = /^[A-Z]/.test(a), bUp = /^[A-Z]/.test(b); if (aUp == bUp) return a < b ? -1 : a == b ? 0 : 1; else return aUp ? 1 : -1; } function isStringAround(node, start, end) { return node.type == "Literal" && typeof node.value == "string" && node.start == start - 1 && node.end <= end + 1; } var jsKeywords = ("break do instanceof typeof case else new var " + "catch finally return void continue for switch while debugger " + "function this with default if throw delete in try").split(" "); function findCompletions(srv, query, file) { if (query.end == null) throw ternError("missing .query.end field"); if (srv.passes.completion) for (var i = 0; i < srv.passes.completion.length; i++) { var result = srv.passes.completion[i](file, query); if (result) return result; } var wordStart = resolvePos(file, query.end), wordEnd = wordStart, text = file.text; while (wordStart && acorn.isIdentifierChar(text.charCodeAt(wordStart - 1))) --wordStart; if (query.expandWordForward !== false) while (wordEnd < text.length && acorn.isIdentifierChar(text.charCodeAt(wordEnd))) ++wordEnd; var word = text.slice(wordStart, wordEnd), completions = []; if (query.caseInsensitive) word = word.toLowerCase(); var wrapAsObjs = query.types || query.depths || query.docs || query.urls || query.origins; function gather(prop, obj, depth, addInfo) { // 'hasOwnProperty' and such are usually just noise, leave them // out when no prefix is provided. if (query.omitObjectPrototype !== false && obj == srv.cx.protos.Object && !word) return; if (query.filter !== false && word && (query.caseInsensitive ? prop.toLowerCase() : prop).indexOf(word) !== 0) return; for (var i = 0; i < completions.length; ++i) { var c = completions[i]; if ((wrapAsObjs ? c.name : c) == prop) return; } var rec = wrapAsObjs ? {name: prop} : prop; completions.push(rec); if (obj && (query.types || query.docs || query.urls || query.origins)) { var val = obj.props[prop]; infer.resetGuessing(); var type = val.getType(); rec.guess = infer.didGuess(); if (query.types) rec.type = infer.toString(type); if (query.docs) maybeSet(rec, "doc", val.doc || type && type.doc); if (query.urls) maybeSet(rec, "url", val.url || type && type.url); if (query.origins) maybeSet(rec, "origin", val.origin || type && type.origin); } if (query.depths) rec.depth = depth; if (wrapAsObjs && addInfo) addInfo(rec); } var hookname, prop, objType; var memberExpr = infer.findExpressionAround(file.ast, null, wordStart, file.scope, "MemberExpression"); if (memberExpr && (memberExpr.node.computed ? isStringAround(memberExpr.node.property, wordStart, wordEnd) : memberExpr.node.object.end < wordStart)) { prop = memberExpr.node.property; prop = prop.type == "Literal" ? prop.value.slice(1) : prop.name; memberExpr.node = memberExpr.node.object; objType = infer.expressionType(memberExpr); } else if (text.charAt(wordStart - 1) == ".") { var pathStart = wordStart - 1; while (pathStart && (text.charAt(pathStart - 1) == "." || acorn.isIdentifierChar(text.charCodeAt(pathStart - 1)))) pathStart--; var path = text.slice(pathStart, wordStart - 1); if (path) { objType = infer.def.parsePath(path, file.scope).getType(); prop = word; } } if (prop != null) { srv.cx.completingProperty = prop; if (objType) infer.forAllPropertiesOf(objType, gather); if (!completions.length && query.guess !== false && objType && objType.guessProperties) objType.guessProperties(function(p, o, d) {if (p != prop && p != "✖") gather(p, o, d);}); if (!completions.length && word.length >= 2 && query.guess !== false) for (var prop in srv.cx.props) gather(prop, srv.cx.props[prop][0], 0); hookname = "memberCompletion"; } else { infer.forAllLocalsAt(file.ast, wordStart, file.scope, gather); if (query.includeKeywords) jsKeywords.forEach(function(kw) { gather(kw, null, 0, function(rec) { rec.isKeyword = true; }); }); hookname = "variableCompletion"; } if (srv.passes[hookname]) srv.passes[hookname].forEach(function(hook) {hook(file, wordStart, wordEnd, gather);}); if (query.sort !== false) completions.sort(compareCompletions); srv.cx.completingProperty = null; return {start: outputPos(query, file, wordStart), end: outputPos(query, file, wordEnd), isProperty: hookname == "memberCompletion", completions: completions}; } function findProperties(srv, query) { var prefix = query.prefix, found = []; for (var prop in srv.cx.props) if (prop != "<i>" && (!prefix || prop.indexOf(prefix) === 0)) found.push(prop); if (query.sort !== false) found.sort(compareCompletions); return {completions: found}; } var findExpr = exports.findQueryExpr = function(file, query, wide) { if (query.end == null) throw ternError("missing .query.end field"); if (query.variable) { var scope = infer.scopeAt(file.ast, resolvePos(file, query.end), file.scope); return {node: {type: "Identifier", name: query.variable, start: query.end, end: query.end + 1}, state: scope}; } else { var start = query.start && resolvePos(file, query.start), end = resolvePos(file, query.end); var expr = infer.findExpressionAt(file.ast, start, end, file.scope); if (expr) return expr; expr = infer.findExpressionAround(file.ast, start, end, file.scope); if (expr && (wide || (start == null ? end : start) - expr.node.start < 20 || expr.node.end - end < 20)) return expr; return null; } }; function findExprOrThrow(file, query, wide) { var expr = findExpr(file, query, wide); if (expr) return expr; throw ternError("No expression at the given position."); } function findExprType(srv, query, file, expr) { var type; if (expr) { infer.resetGuessing(); type = infer.expressionType(expr); } if (srv.passes["typeAt"]) { var pos = resolvePos(file, query.end); srv.passes["typeAt"].forEach(function(hook) { type = hook(file, pos, expr, type); }); } if (!type) throw ternError("No type found at the given position."); return type; }; function findTypeAt(srv, query, file) { var expr = findExpr(file, query), exprName; var type = findExprType(srv, query, file, expr); if (query.preferFunction) type = type.getFunctionType() || type.getType(); else type = type.getType(); if (expr) { if (expr.node.type == "Identifier") exprName = expr.node.name; else if (expr.node.type == "MemberExpression" && !expr.node.computed) exprName = expr.node.property.name; } if (query.depth != null && typeof query.depth != "number") throw ternError(".query.depth must be a number"); var result = {guess: infer.didGuess(), type: infer.toString(type, query.depth), name: type && type.name, exprName: exprName}; if (type) storeTypeDocs(type, result); return clean(result); } function findDocs(srv, query, file) { var expr = findExpr(file, query); var type = findExprType(srv, query, file, expr); var result = {url: type.url, doc: type.doc, type: infer.toString(type)}; var inner = type.getType(); if (inner) storeTypeDocs(inner, result); return clean(result); } function storeTypeDocs(type, out) { if (!out.url) out.url = type.url; if (!out.doc) out.doc = type.doc; if (!out.origin) out.origin = type.origin; var ctor, boring = infer.cx().protos; if (!out.url && !out.doc && type.proto && (ctor = type.proto.hasCtor) && type.proto != boring.Object && type.proto != boring.Function && type.proto != boring.Array) { out.url = ctor.url; out.doc = ctor.doc; } } var getSpan = exports.getSpan = function(obj) { if (!obj.origin) return; if (obj.originNode) { var node = obj.originNode; if (/^Function/.test(node.type) && node.id) node = node.id; return {origin: obj.origin, node: node}; } if (obj.span) return {origin: obj.origin, span: obj.span}; }; var storeSpan = exports.storeSpan = function(srv, query, span, target) { target.origin = span.origin; if (span.span) { var m = /^(\d+)\[(\d+):(\d+)\]-(\d+)\[(\d+):(\d+)\]$/.exec(span.span); target.start = query.lineCharPositions ? {line: Number(m[2]), ch: Number(m[3])} : Number(m[1]); target.end = query.lineCharPositions ? {line: Number(m[5]), ch: Number(m[6])} : Number(m[4]); } else { var file = srv.findFile(span.origin); target.start = outputPos(query, file, span.node.start); target.end = outputPos(query, file, span.node.end); } }; function findDef(srv, query, file) { var expr = findExpr(file, query); var type = findExprType(srv, query, file, expr); if (infer.didGuess()) return {}; var span = getSpan(type); var result = {url: type.url, doc: type.doc, origin: type.origin}; if (type.types) for (var i = type.types.length - 1; i >= 0; --i) { var tp = type.types[i]; storeTypeDocs(tp, result); if (!span) span = getSpan(tp); } if (span && span.node) { // refers to a loaded file var spanFile = span.node.sourceFile || srv.findFile(span.origin); var start = outputPos(query, spanFile, span.node.start), end = outputPos(query, spanFile, span.node.end); result.start = start; result.end = end; result.file = span.origin; var cxStart = Math.max(0, span.node.start - 50); result.contextOffset = span.node.start - cxStart; result.context = spanFile.text.slice(cxStart, cxStart + 50); } else if (span) { // external result.file = span.origin; storeSpan(srv, query, span, result); } return clean(result); } function findRefsToVariable(srv, query, file, expr, checkShadowing) { var name = expr.node.name; for (var scope = expr.state; scope && !(name in scope.props); scope = scope.prev) {} if (!scope) throw ternError("Could not find a definition for " + name + " " + !!srv.cx.topScope.props.x); var type, refs = []; function storeRef(file) { return function(node, scopeHere) { if (checkShadowing) for (var s = scopeHere; s != scope; s = s.prev) { var exists = s.hasProp(checkShadowing); if (exists) throw ternError("Renaming `" + name + "` to `" + checkShadowing + "` would make a variable at line " + (asLineChar(file, node.start).line + 1) + " point to the definition at line " + (asLineChar(file, exists.name.start).line + 1)); } refs.push({file: file.name, start: outputPos(query, file, node.start), end: outputPos(query, file, node.end)}); }; } if (scope.originNode) { type = "local"; if (checkShadowing) { for (var prev = scope.prev; prev; prev = prev.prev) if (checkShadowing in prev.props) break; if (prev) infer.findRefs(scope.originNode, scope, checkShadowing, prev, function(node) { throw ternError("Renaming `" + name + "` to `" + checkShadowing + "` would shadow the definition used at line " + (asLineChar(file, node.start).line + 1)); }); } infer.findRefs(scope.originNode, scope, name, scope, storeRef(file)); } else { type = "global"; for (var i = 0; i < srv.files.length; ++i) { var cur = srv.files[i]; infer.findRefs(cur.ast, cur.scope, name, scope, storeRef(cur)); } } return {refs: refs, type: type, name: name}; } function findRefsToProperty(srv, query, expr, prop) { var objType = infer.expressionType(expr).getType(); if (!objType) throw ternError("Couldn't determine type of base object."); var refs = []; function storeRef(file) { return function(node) { refs.push({file: file.name, start: outputPos(query, file, node.start), end: outputPos(query, file, node.end)}); }; } for (var i = 0; i < srv.files.length; ++i) { var cur = srv.files[i]; infer.findPropRefs(cur.ast, cur.scope, objType, prop.name, storeRef(cur)); } return {refs: refs, name: prop.name}; } function findRefs(srv, query, file) { var expr = findExprOrThrow(file, query, true); if (expr && expr.node.type == "Identifier") { return findRefsToVariable(srv, query, file, expr); } else if (expr && expr.node.type == "MemberExpression" && !expr.node.computed) { var p = expr.node.property; expr.node = expr.node.object; return findRefsToProperty(srv, query, expr, p); } else if (expr && expr.node.type == "ObjectExpression") { var pos = resolvePos(file, query.end); for (var i = 0; i < expr.node.properties.length; ++i) { var k = expr.node.properties[i].key; if (k.start <= pos && k.end >= pos) return findRefsToProperty(srv, query, expr, k); } } throw ternError("Not at a variable or property name."); } function buildRename(srv, query, file) { if (typeof query.newName != "string") throw ternError(".query.newName should be a string"); var expr = findExprOrThrow(file, query); if (!expr || expr.node.type != "Identifier") throw ternError("Not at a variable."); var data = findRefsToVariable(srv, query, file, expr, query.newName), refs = data.refs; delete data.refs; data.files = srv.files.map(function(f){return f.name;}); var changes = data.changes = []; for (var i = 0; i < refs.length; ++i) { var use = refs[i]; use.text = query.newName; changes.push(use); } return data; } function listFiles(srv) { return {files: srv.files.map(function(f){return f.name;})}; } exports.version = "0.7.1"; });
var FacebookChat = require('../'); var fbchat = new FacebookChat({ userId: '123456789', appId: '123456789', accessToken: 'abcdefghimnopqrstuvz1234567890' }); fbchat.addListener('connected', function() { console.log('Connected!'); fbchat.getFriends(function (result) { console.log('Friends loaded - callback !'); }); fbchat.whoAmI(function (result) { console.log('Who am i?'); console.log(result.name); }); /* console.log("sending"); fbchat.sendMessage(123456, 'Hi friend!'); */ }); fbchat.addListener('authenticationError', function(e) { console.log('Auth error: ' + e); }); fbchat.addListener('presence:online', function (result) { console.log('New user online', fbchat.utils.resolveFacebookName(result.user)); }); fbchat.addListener('presence:offline', function (result) { console.log('New user offline', fbchat.utils.resolveFacebookName(result.user)); }); fbchat.addListener('status:composing', function (result) { console.log(fbchat.utils.resolveFacebookName(result.user) + ' is composing'); }); fbchat.addListener('message:received', function (result) { console.log(fbchat.utils.resolveFacebookName(result.user) + ' -> Me: ', result.message); }); fbchat.addListener('message:sent', function (result) { console.log('Me -> ' +fbchat.utils.resolveFacebookName(result.user)+': ', result.message); }); fbchat.addListener('list:friends', function (result) { console.log('Friends loaded - event'); }); fbchat.addListener('vCard:result', function (result) { require("fs").writeFile(__dirname+'/images/'+result.user + ".jpeg", result.photoData, 'base64', function(err) { console.log(err); }); }); //fbchat.close();
var Stream = require('stream') var spawn = require('child_process').spawn function execStream (cmd, args, options) { var AB = new Stream.Duplex var A = new Stream.PassThrough var B = new Stream.PassThrough // console.log = function () {} AB._write = function (chunk, encoding, cb) { return A.write(chunk, encoding, cb) } AB.on('finish', function () { A.end() }) AB._read = function (n) { } B.on('readable', function() { AB.push(B.read()) }) B.on('end', function () { AB.push(null) }) B.on('error', function(err) { AB.emit('error', err) }) A.on('error', function(err) { AB.emit('error', err) }) var proc = spawn(cmd, args, options) A.pipe(proc.stdin) proc.stdout.pipe(B) proc.on('error', function(err) { AB.emit('error', err) }) return AB } module.exports = execStream
var assert = require('assert'), fs = require('fs'), rimraf = require('rimraf'); describe('/lib/tar', function() { var tar = null; var cleanup = function() { rimraf.sync(__dirname + '/files/test2.tar'); rimraf.sync(__dirname + '/files/test'); }; before(cleanup); after(cleanup); describe('unix', function() { before(function() { tar = require('../lib/tar/unix') }); describe('unpack()', function() { it('should unpack tarball', function(done) { tar.unpack(__dirname + '/files/test.tar', __dirname + '/files', function(err) { if (err) return done(err); assert(fs.existsSync(__dirname + '/files/test')); done(); }); }); it('should return error for invalid path', function(done) { tar.unpack('/whatever.tar', '/wwwwww', function(err) { assert(err); done(); }); }); }); describe('pack()', function() { it('should create new tarball', function(done) { tar.pack(__dirname + '/files/test', __dirname + '/files/test2.tar', function(err) { if (err) return done(err); assert(fs.existsSync(__dirname + '/files/test2.tar')); done(); }); }); it('should return error for invalid path', function(done) { tar.pack('/whatever', '/whatever.tar', function(err) { assert(err); done(); }); }); }); }); describe('win', function() { before(function() { tar = require('../lib/tar/win') }); describe('unpack()', function() { it('should unpack tarball', function(done) { tar.unpack(__dirname + '/files/test.tar', __dirname + '/files', function(err) { if (err) return done(err); assert(fs.existsSync(__dirname + '/files/test')); done(); }); }); it('should return error for invalid path', function(done) { tar.unpack('/whatever.tar', '/wwwwww', function(err) { assert(err); done(); }); }); }); describe('pack()', function() { it('should create new tarball', function(done) { tar.pack(__dirname + '/files/test', __dirname + '/files/test2.tar', function(err) { if (err) return done(err); assert(fs.existsSync(__dirname + '/files/test2.tar')); done(); }); }); it('should return error for invalid path', function(done) { tar.pack('/whatever', '/whatever.tar', function(err) { assert(err); done(); }); }); }); }); });
/** * Imports */ import React from 'react'; import connectToStores from 'fluxible-addons-react/connectToStores'; import moment from 'moment'; import {FormattedMessage} from 'react-intl'; import {Link} from 'react-router'; // Flux import IntlStore from '../../../../stores/Application/IntlStore'; import OrdersListStore from '../../../../stores/Orders/OrdersListStore'; import fetchOrders from '../../../../actions/Orders/fetchOrders'; // Required components import Heading from '../../../common/typography/Heading'; import OrderStatus from '../../../common/orders/OrderStatus'; import Spinner from '../../../common/indicators/Spinner'; import Table from '../../../common/tables/Table'; import Text from '../../../common/typography/Text'; import ToggleSwitch from '../../../common/buttons/ToggleSwitch'; // Translation data for this component import intlData from './AdminOrders.intl'; /** * Component */ class AdminOrders extends React.Component { static contextTypes = { executeAction: React.PropTypes.func.isRequired, getStore: React.PropTypes.func.isRequired }; //*** Initial State ***// state = { orders: this.context.getStore(OrdersListStore).getOrders(), loading: this.context.getStore(OrdersListStore).isLoading(), showAllOrders: false }; //*** Component Lifecycle ***// componentDidMount() { // Component styles require('./AdminOrders.scss'); // Load required data this.context.executeAction(fetchOrders, {open: true}); // By default, only opened orders } componentWillReceiveProps(nextProps) { this.setState({ orders: nextProps._orders, loading: nextProps._loading }); } //*** View Controllers ***// handleShowAllOrdersChange = () => { if (!this.state.loading) { let showAllOrders = !this.state.showAllOrders; this.context.executeAction(fetchOrders, (showAllOrders) ? {} : {open: true}); this.setState({showAllOrders: showAllOrders}); } }; //*** Template ***// render() { // // Helper methods & variables // let intlStore = this.context.getStore(IntlStore); let routeParams = {locale: this.context.getStore(IntlStore).getCurrentLocale()}; // Base route params // Order list table headings let headings = [ <FormattedMessage message={intlStore.getMessage(intlData, 'dateHeading')} locales={intlStore.getCurrentLocale()} />, <FormattedMessage message={intlStore.getMessage(intlData, 'idHeading')} locales={intlStore.getCurrentLocale()} />, <FormattedMessage message={intlStore.getMessage(intlData, 'nameHeading')} locales={intlStore.getCurrentLocale()} />, <FormattedMessage message={intlStore.getMessage(intlData, 'statusHeading')} locales={intlStore.getCurrentLocale()} /> ]; // Order list table rows let rows = this.state.orders.map(function (order) { console.log("orderr:",order); return { data: [ <Text size="medium">{moment(order.createdAt).format('YYYY/MM/DD HH:mm:ss')}</Text>, <span className="admin-orders__link"> <Link to="adm-order-edit" params={Object.assign({orderId: order.id}, routeParams)}> <Text size="small">{order.id}</Text> </Link> </span>, <Text size="medium"> {order.customer.name} {order.customer.userId ? <span className="adm-orders__user-icon"> <i className="fa fa-user" aria-hidden="true" /> </span> : null } </Text>, <OrderStatus status={order.status} /> ] }; }); // // Return // return ( <div className="admin-orders"> <div className="admin-orders__header"> <div className="admin-orders__title"> <Heading size="medium"> <FormattedMessage message={intlStore.getMessage(intlData, 'title')} locales={intlStore.getCurrentLocale()} /> </Heading> </div> <div className="admin-orders__toolbar"> <div className="admin-orders__toolbar-item"> <ToggleSwitch label={intlStore.getMessage(intlData, 'showAll')} inline enabled={this.state.showAllOrders} onChange={this.handleShowAllOrdersChange} /> </div> </div> </div> {this.state.loading ? <div className="admin-orders__spinner"> <Spinner /> </div> : null } {!this.state.loading && this.state.orders.length > 0 ? <div className="admin-orders__list"> <Table headings={headings} rows={rows} /> </div> : null } {!this.state.loading && this.state.orders.length === 0 ? <div className="admin-orders__no-results"> <Text size="small"> <FormattedMessage message={intlStore.getMessage(intlData, 'noResults')} locales={intlStore.getCurrentLocale()} /> </Text> </div> : null } </div> ); } } /** * Flux */ AdminOrders = connectToStores(AdminOrders, [OrdersListStore], (context) => { return { _orders: context.getStore(OrdersListStore).getOrders(), _loading: context.getStore(OrdersListStore).isLoading() }; }); /** * Exports */ export default AdminOrders;
var usersRouter = require('./users.js'), wrappedResponse = require('./../util').wrappedResponse, cors = require('./../util').cors, config = require('./../config'), clientConfig; if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === undefined) { clientConfig = config.development.client; } if (process.env.NODE_ENV === 'production') { clientConfig = config.production.client; } module.exports = function(app) { //angular CORS app.use(cors({ origin : clientConfig.origin, methods : clientConfig.methods, headers : clientConfig.headers })); app.get('/', function(req , res) { res.json({ message : 'OK' }); }); //Api functionality app.use('/users' , usersRouter); //Testing 500 handler app.get('/fail' , function(req , res) { next(new Error('testing error')); }); //404 responses handler app.use(function(req , res , next) { wrappedResponse({ res : res, code : 404, message : 'Request not found', data : 'Request not found'}); next(); }); //500 responses handler app.use(function(err , req , res , next) { wrappedResponse({ res : res, code : 500, message : 'Unable to process request, reach out to the administraror', data : err }); next(); }); };
(function($) { $(document).ready(function() { $('body').css('overflow', 'hidden'); $(window).load(function() { var preloaderDelay = 350, preloaderFadeOutTime = 800; function hidePreloader() { var loadingAnimation = $('#loading-animation'), preloader = $('#preloader'); loadingAnimation.fadeOut(); preloader.delay(preloaderDelay).fadeOut(preloaderFadeOutTime); } $('body').css('overflow', 'auto'); hidePreloader(); initGooglePlus(); generateSameHeight(); setTimeout(function() { $('.explore').removeClass('hidden'); }, 1000); }); if ($(window).width() > 1500) { $('.effect-wrapper').each(function() { $(this).addClass('col-lg-3'); }); } if ($(window).width() < 768) { $('.animated').removeClass('animated').removeClass('hiding'); $('.appear-animation-trigger').removeClass('appear-animation-trigger'); $('.appear-animation').addClass('visible'); $('.stat span').removeClass('timer'); } if ($(window).height() < 512) { $('#bottom-navlinks').removeClass('bottom-navlinks').addClass('bottom-navlinks-small'); } if ($(window).scrollTop() >= 100) { $('#top-header').addClass('after-scroll'); $('#logo-header .logo').removeClass('logo-light').addClass('logo-dark'); } $(window).scroll(function() { var scroll = $(this).scrollTop(); var header = $('#top-header'); var logo = $('#logo-header .logo'); var src = logo.attr('src'); var buyButton = $('#right-nav-button'); if (scroll >= 100) { header.addClass('after-scroll'); logo.removeClass('logo-light').addClass('logo-dark'); } else { header.removeClass('after-scroll'); logo.removeClass('logo-dark').addClass('logo-light'); } if (scroll >= $(window).height()) { buyButton.removeClass('right-nav-button-hidden'); } else { buyButton.addClass('right-nav-button-hidden'); } }); $(function() { var idArray = []; $('.rockstar-speakers-item').each(function() { idArray[idArray.length] = $(this).attr('data-id'); }); idArray = shuffleArray(idArray); for (var i = 0; i < 4; i++) { $('#rockstar-speaker-' + idArray[i]).removeClass('hidden'); } }); function shuffleArray(o) { for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x); return o; }; var delay = parseInt($('.increment-animation').attr('data-delay')); $('.increment-animation').not('hidden').each(function(index) { $(this).attr('data-delay', index * delay); }); $('.animated').appear(function() { var element = $(this); var animation = element.data('animation'); var animationDelay = element.data('delay'); if (animationDelay) { setTimeout(function() { element.addClass(animation + " visible"); element.removeClass('hiding'); if (element.hasClass('counter')) { element.find('.timer').countTo(); } }, animationDelay); } else { element.addClass(animation + " visible"); element.removeClass('hiding'); if (element.hasClass('counter')) { element.find('.timer').countTo(); } } }, { accY: -150 }); $(function() { var appear, delay, i, offset, _i, _len, _ref; _ref = $(".appear-animation"); for (_i = 0, _len = _ref.length; _i < _len; _i++) { i = _ref[_i]; offset = i.offsetLeft + i.offsetTop; delay = offset / 1000; $(i).css('transition-delay', '' + (delay * 0.47) + 's'); $(i).css('transition-duration', '' + 0.2 + 's'); } }); $('.appear-animation-trigger').appear(function() { setTimeout(function() { $('.appear-animation-trigger').parent('div').find('.appear-animation').addClass('visible'); }, 1000); }); $(function() { $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); $(function() { $('a[href=#]').click(function() { event.preventDefault(); }); }); function generateSameHeight() { if ($(window).width() > 767) { $('.same-height-wrapper').each(function() { var max = 0; $('.same-height').each(function() { var height = $(this).height(); if (height > max) { max = height; } }); $('.same-height').each(function() { $(this).height(max); }); }); } } $('#post-section .post-body p').each(function() { if ($(this).find('.feature-image').length) { var url = $(this).find('.feature-image').prop('src'); $('#top-section').css('background-image', 'url(' + url + ')').addClass('enable-overlay'); } }); $('.slider').each(function() { $(this).find('.slider-item').first().addClass('slider-current-item').removeClass('hidden'); if ($(this).find('.slider-item').length > 1) { $(this).closest('.speaker-item').find('.slider-next-item').removeClass('hidden'); } }); $('.slider-next-item').click(function() { var speakerItem = $(this).closest('.speaker-item'); var elem = speakerItem.find('.slider-current-item').next(); if (elem.length) { elem.addClass('slider-current-item').removeClass('hidden'); speakerItem.find('.slider-current-item').first().removeClass('slider-current-item').addClass('hidden'); } else { speakerItem.find('.slider-item').first().addClass('slider-current-item').removeClass('hidden'); speakerItem.find('.slider-current-item').last().removeClass('slider-current-item').addClass('hidden'); } }); //Side menu var container = $('.st-container'); $('#menu-trigger').click(function(event) { event.stopPropagation(); var top = $(window).scrollTop(); var left = $(window).scrollLeft() var effect = $(this).attr('data-effect'); if (!container.hasClass('st-menu-open')) { container.addClass(effect).delay(25).addClass('st-menu-open'); $('body').css('overflow', 'hidden'); } else { container.removeClass('st-menu-open'); $('body').css('overflow', 'auto'); } }); $('.st-pusher').click(function() { if (container.hasClass('st-menu-open')) { container.removeClass('st-menu-open'); $('body').css('overflow', 'auto'); } }); $(window).resize(function() { if ($(window).width() > 1500) { $('.effect-wrapper').each(function() { $(this).addClass('col-lg-3'); }); } else { $('.effect-wrapper').each(function() { $(this).removeClass('col-lg-3'); }); } if ($(window).width() > 767) { if (container.hasClass('st-menu-open')) { container.removeClass('st-menu-open'); $('body').css('overflow', 'auto'); } generateSameHeight() } var bottomNavLinks = $('#bottom-navlinks'); if ($(window).height() < 512) { bottomNavLinks.removeClass('bottom-navlinks').addClass('bottom-navlinks-small'); } else { bottomNavLinks.removeClass('bottom-navlinks-small').addClass('bottom-navlinks'); } if ($(window).width() < 768) { $('.same-height').css('height', '100%'); } }); $('.modal').on('show.bs.modal', function() { $('body').css('overflow', 'hidden'); }); $('.modal').on('hide.bs.modal', function() { $('body').css('overflow', 'auto'); }); if (typeof twitterFeedUrl !== 'undefined') { var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from json where url="' + twitterFeedUrl + '"') + '&format=json&callback=?'; $.getJSON(yql, function(data) { $.each(data.query.results.json.json, function(i, gist) { var tweetElement = '<div class="tweet animated fadeInUp hidden"><p class="tweet-text">' + linkify(gist.text) + '</p><p class="tweet-meta">by <a href="https://twitter.com/' + gist.user.screen_name + ' target="_blank">@' + gist.user.screen_name + '</a></p></div>'; $('#tweets').append(tweetElement); }); animateTweets(); }); function linkify(inputText) { var replacedText, pattern1, pattern2, pattern3, pattern4; pattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim; replacedText = inputText.replace(pattern1, '<a href="$1" target="_blank">$1</a>'); pattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim; replacedText = replacedText.replace(pattern2, '$1<a href="http://$2" target="_blank">$2</a>'); pattern3 = /#(\S*)/g; replacedText = replacedText.replace(pattern3, '<a href="https://twitter.com/search?q=%23$1" target="_blank">#$1</a>'); pattern4 = /\B@([\w-]+)/gm; replacedText = replacedText.replace(pattern4, '<a href="https://twitter.com/$1" target="_blank">@$1</a>'); return replacedText; } function animateTweets() { var $tweets = $('#tweets').find('.tweet'), i = 0; $($tweets.get(0)).removeClass('hidden'); function changeTweets() { var next = (++i % $tweets.length); $($tweets.get(next - 1)).addClass('hidden'); $($tweets.get(next)).removeClass('hidden'); } var interval = setInterval(changeTweets, 5000); } } }); //Google plus function initGooglePlus() { var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true; po.src = 'https://apis.google.com/js/platform.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s); } //Google maps if (typeof googleMaps !== 'undefined') { var map, autocomplete, directionsDisplay, geocoder, polyline, origin; var markers = []; var directionsService = new google.maps.DirectionsService(); var MY_MAPTYPE_ID = 'custom_style'; function initialize() { directionsDisplay = new google.maps.DirectionsRenderer({ suppressMarkers: true }); geocoder = new google.maps.Geocoder(); polyline = new google.maps.Polyline({ strokeColor: '#03a9f4', strokeOpacity: 1, strokeWeight: 2 }); var defaultOpts = [{ stylers: [{ lightness: 40 }, { visibility: 'on' }, { gamma: 0.9 }, { weight: 0.4 }] }, { elementType: 'labels', stylers: [{ visibility: 'on' }] }, { featureType: 'water', stylers: [{ color: '#5dc7ff' }] }, { featureType: 'road', stylers: [{ visibility: 'off' }] }]; var zoomedOpts = [{ stylers: [{ lightness: 40 }, { visibility: 'on' }, { gamma: 1.1 }, { weight: 0.9 }] }, { elementType: 'labels', stylers: [{ visibility: 'off' }] }, { featureType: 'water', stylers: [{ color: '#5dc7ff' }] }, { featureType: 'road', stylers: [{ visibility: 'on' }] }, { featureType: 'road', elementType: "labels", stylers: [{ saturation: -30 }] }]; var mapOptions = { zoom: 17, minZoom: 2, scrollwheel: false, panControl: false, draggable: true, zoomControl: false, zoomControlOptions: { position: google.maps.ControlPosition.RIGHT_TOP }, scaleControl: false, mapTypeControl: false, streetViewControl: false, center: centerMap, mapTypeControlOptions: { mapTypeIds: [google.maps.MapTypeId.ROADMAP, MY_MAPTYPE_ID] }, mapTypeId: MY_MAPTYPE_ID }; if ($(window).width() < 768) { mapOptions.center = mobileCenterMap; } if (googleMaps == 'logistics') { mapOptions.zoom = 5; mapOptions.zoomControl = true; } map = new google.maps.Map(document.getElementById('canvas-map'), mapOptions); var marker = new google.maps.Marker({ position: eventPlace, animation: google.maps.Animation.DROP, icon: icon, map: map }); markers.push(marker); var defaultMapOptions = { name: 'Default Style' }; var zoomedMapOptions = { name: 'Zoomed Style' }; var defaultMapType = new google.maps.StyledMapType(defaultOpts, defaultMapOptions); var zoomedMapType = new google.maps.StyledMapType(zoomedOpts, zoomedMapOptions); map.mapTypes.set('default', defaultMapType); map.mapTypes.set('zoomed', zoomedMapType); if (googleMaps === 'logistics') { map.setMapTypeId('default'); var input = (document.getElementById('location-input')); autocomplete = new google.maps.places.Autocomplete(input); google.maps.event.addListener(autocomplete, 'place_changed', function() { marker.setVisible(false); var place = autocomplete.getPlace(); if (place.geometry == 'undefined' || !place.geometry) { return; } var address = ''; if (place.address_components) { address = [ (place.address_components[0] && place.address_components[0].short_name || ''), (place.address_components[1] && place.address_components[1].short_name || ''), (place.address_components[2] && place.address_components[2].short_name || '') ].join(' '); } geocoder.geocode({ 'address': address }, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { origin = results[0].geometry.location; calcRoute(origin, 'TRANSIT'); } else { alert('Geocode was not successful for the following reason: ' + status); } }); }); } else { map.setMapTypeId('zoomed'); } function calcRoute(origin, selectedMode) { var request = { origin: origin, destination: eventPlace, travelMode: google.maps.TravelMode[selectedMode] }; directionsService.route(request, function(response, status) { if (status == google.maps.DirectionsStatus.OK) { map.setMapTypeId('zoomed'); directionsDisplay.setMap(map); directionsDisplay.setDirections(response); var leg = response.routes[0].legs[0]; makeMarker(leg.start_location); makeMarker(leg.end_location); $('#distance').text(leg.distance.text); $('#estimateTime').text(leg.duration.text); $('#mode-select').val(selectedMode); $('#mode').removeClass('hidden'); var attribute = $('#mode-icon use').attr('xlink:href'); attribute = attribute.substring(0, attribute.indexOf('#') + 1) + 'icon-' + selectedMode.toLowerCase(); $('#mode-icon use').attr('xlink:href', attribute); } else if (status != google.maps.DirectionsStatus.OK && selectedMode != 'DRIVING') { calcRoute(origin, 'DRIVING'); } else { var path = polyline.getPath(); path.push(origin); path.push(eventPlace); makeMarker(origin); makeMarker(eventPlace); var bounds = new google.maps.LatLngBounds(); bounds.extend(origin); bounds.extend(eventPlace); map.fitBounds(bounds); polyline.setMap(map); var distance = Math.round(google.maps.geometry.spherical.computeDistanceBetween(origin, eventPlace) / 1000); $('#distance').text(distance + ' km'); $('#estimateTime').text(''); $('#find-flight').removeClass('hidden'); $('#mode').addClass('hidden'); } }); deleteMarkers(); $('#find-way').addClass('location-active'); setDirectionInput(origin); $('#find-way h3').removeClass('fadeInUp').addClass('fadeOutDown'); } function makeMarker(position) { var directionMarker = new google.maps.Marker({ position: position, map: map, icon: icon }); markers.push(directionMarker); } function addMarker(location) { var marker = new google.maps.Marker({ position: location, map: map }); markers.push(marker); } function deleteMarkers() { for (var i = 0; i < markers.length; i++) { markers[i].setMap(null); } markers = []; } function smoothZoom(level) { var currentZoom = map.getZoom(), timeStep = 50; var numOfSteps = Math.abs(level - currentZoom); var step = (level > currentZoom) ? 1 : -1; for (var i = 0; i < numOfSteps; i++) { setTimeout(function() { currentZoom += step; map.setZoom(currentZoom); }, (i + 1) * timeStep); } } function setDirectionInput(origin) { geocoder.geocode({ 'latLng': origin }, function(results, status) { if (status == google.maps.GeocoderStatus.OK && results[1]) { var arrAddress = results[1].address_components; $.each(arrAddress, function(i, address_component) { if (address_component.types[0] == "locality") { $('#result-name').text(address_component.long_name); return false; } }); } }); } $('#mode-select').change(function() { var selectedMode = $(this).val(); calcRoute(origin, selectedMode); }); $("#direction-locate").click(function() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(function(position) { origin = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); calcRoute(origin, 'TRANSIT'); }); } }); $("#direction-cancel").click(function() { $('#find-way').removeClass('location-active'); $('#location-input').val(''); $("#find-flight").addClass('hidden'); deleteMarkers(); directionsDisplay.setMap(null); polyline.setMap(null); map.setMapTypeId('default'); map.panTo(eventPlace); if ($(window).width() < 768) { map.setCenter(mobileCenterMap); } else { map.setCenter(centerMap); } makeMarker(eventPlace); smoothZoom(5); $('#find-way h3').removeClass('fadeOutDown').addClass('fadeInUp'); }); } google.maps.event.addDomListener(window, 'load', initialize); } })(jQuery);
version https://git-lfs.github.com/spec/v1 oid sha256:0ca12fe083d6e9ac3432b0e05680d5c8fbfa0d0814f861bcf90dee5b9bad3853 size 202604
'use strict'; myApp.factory('authService', ['$http', '$q', 'localStorageService', 'ngAuthSettings', function($http, $q, localStorageService, ngAuthSettings) { var serviceBase = ngAuthSettings.apiServiceBaseUri; var authServiceFactory = {}; var _authentication = { isAuth: false, userName: "", useRefreshTokens: false }; var _externalAuthData = { provider: "", userName: "", externalAccessToken: "" }; var _saveRegistration = function(registration) { // _logOut(); return $http.post(serviceBase + 'api/account/register', registration).then(function(response) { return response; }); }; var _login = function(loginData) { var deviceData = localStorageService.get('deviceData'); var pass = deviceData.DeviceID.substring(0, 2) + '#Dv0' + deviceData.DeviceID.substring(2, 4); loginData = { userName: deviceData.DeviceID + "_" + deviceData.Email, password: pass, useRefreshTokens: false }; var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password; if (loginData.useRefreshTokens) { data = data + "&client_id=" + ngAuthSettings.clientId; } var deferred = $q.defer(); $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function(response) { if (loginData.useRefreshTokens) { localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName, refreshToken: response.refresh_token, useRefreshTokens: true }); } else { localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName, refreshToken: "", useRefreshTokens: false }); } _authentication.isAuth = true; _authentication.userName = loginData.userName; _authentication.useRefreshTokens = loginData.useRefreshTokens; deferred.resolve(response); }).error(function(err, status) { _logOut(); deferred.reject(err); }); return deferred.promise; }; var _logOut = function() { localStorageService.remove('authorizationData'); _authentication.isAuth = false; _authentication.userName = ""; _authentication.useRefreshTokens = false; }; var _fillAuthData = function() { var authData = localStorageService.get('authorizationData'); if (authData) { _authentication.isAuth = true; _authentication.userName = authData.userName; _authentication.useRefreshTokens = authData.useRefreshTokens; } }; var _refreshToken = function() { var deferred = $q.defer(); var authData = localStorageService.get('authorizationData'); if (authData) { if (authData.useRefreshTokens) { var data = "grant_type=refresh_token&refresh_token=" + authData.refreshToken + "&client_id=" + ngAuthSettings.clientId; localStorageService.remove('authorizationData'); $http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function(response) { localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName, refreshToken: response.refresh_token, useRefreshTokens: true }); deferred.resolve(response); }).error(function(err, status) { _logOut(); deferred.reject(err); }); } } return deferred.promise; }; var _obtainAccessToken = function(externalData) { var deferred = $q.defer(); $http.get(serviceBase + 'api/account/ObtainLocalAccessToken', { params: { provider: externalData.provider, externalAccessToken: externalData.externalAccessToken } }).success(function(response) { localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName, refreshToken: "", useRefreshTokens: false }); _authentication.isAuth = true; _authentication.userName = response.userName; _authentication.useRefreshTokens = false; deferred.resolve(response); }).error(function(err, status) { _logOut(); deferred.reject(err); }); return deferred.promise; }; var _registerExternal = function(registerExternalData) { var deferred = $q.defer(); $http.post(serviceBase + 'api/account/registerexternal', registerExternalData).success(function(response) { localStorageService.set('authorizationData', { token: response.access_token, userName: response.userName, refreshToken: "", useRefreshTokens: false }); _authentication.isAuth = true; _authentication.userName = response.userName; _authentication.useRefreshTokens = false; deferred.resolve(response); }).error(function(err, status) { _logOut(); deferred.reject(err); }); return deferred.promise; }; authServiceFactory.saveRegistration = _saveRegistration; authServiceFactory.login = _login; authServiceFactory.logOut = _logOut; authServiceFactory.fillAuthData = _fillAuthData; authServiceFactory.authentication = _authentication; authServiceFactory.refreshToken = _refreshToken; authServiceFactory.obtainAccessToken = _obtainAccessToken; authServiceFactory.externalAuthData = _externalAuthData; authServiceFactory.registerExternal = _registerExternal; return authServiceFactory; }]);
(function (exports) { 'use strict'; /** * Module : Sparrow touch event * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-28 14:41:17 */ var on = function(element, eventName, child, listener) { if(!element) return; if(arguments.length < 4) { listener = child; child = undefined; } else { var childlistener = function(e) { if(!e) { return; } var tmpchildren = element.querySelectorAll(child); tmpchildren.forEach(function(node) { if(node == e.target) { listener.call(e.target, e); } }); }; } //capture = capture || false; if(!element["uEvent"]) { //在dom上添加记录区 element["uEvent"] = {}; } //判断是否元素上是否用通过on方法填加进去的事件 if(!element["uEvent"][eventName]) { element["uEvent"][eventName] = [child ? childlistener : listener]; if(u.event && u.event[eventName] && u.event[eventName].setup) { u.event[eventName].setup.call(element); } element["uEvent"][eventName + 'fn'] = function(e) { //火狐下有问题修改判断 if(!e) e = typeof event != 'undefined' && event ? event : window.event; element["uEvent"][eventName].forEach(function(fn) { try { e.target = e.target || e.srcElement; //兼容IE8 } catch(ee) {} if(fn) fn.call(element, e); }); }; if(element.addEventListener) { // 用于支持DOM的浏览器 element.addEventListener(eventName, element["uEvent"][eventName + 'fn']); } else if(element.attachEvent) { // 用于IE浏览器 element.attachEvent("on" + eventName, element["uEvent"][eventName + 'fn']); } else { // 用于其它浏览器 element["on" + eventName] = element["uEvent"][eventName + 'fn']; } } else { //如果有就直接往元素的记录区添加事件 var lis = child ? childlistener : listener; var hasLis = false; element["uEvent"][eventName].forEach(function(fn) { if(fn == lis) { hasLis = true; } }); if(!hasLis) { element["uEvent"][eventName].push(child ? childlistener : listener); } } }; var off = function(element, eventName, listener) { //删除事件数组 if(listener) { if(element && element["uEvent"] && element["uEvent"][eventName]) { element["uEvent"][eventName].forEach(function(fn, i) { if(fn == listener) { element["uEvent"][eventName].splice(i, 1); } }); } return; } var eventfn; if(element && element["uEvent"] && element["uEvent"][eventName + 'fn']) eventfn = element["uEvent"][eventName + 'fn']; if(element.removeEventListener) { // 用于支持DOM的浏览器 element.removeEventListener(eventName, eventfn); } else if(element.removeEvent) { // 用于IE浏览器 element.removeEvent("on" + eventName, eventfn); } else { // 用于其它浏览器 delete element["on" + eventName]; } if(u.event && u.event[eventName] && u.event[eventName].teardown) { u.event[eventName].teardown.call(element); } if(element && element["uEvent"] && element["uEvent"][eventName]) element["uEvent"][eventName] = undefined; if(element && element["uEvent"] && element["uEvent"][eventName + 'fn']) element["uEvent"][eventName + 'fn'] = undefined; }; /** * 阻止冒泡 */ var stopEvent = function(e) { if(typeof(e) != "undefined") { if(e.stopPropagation) e.stopPropagation(); else { e.cancelBubble = true; } //阻止默认浏览器动作(W3C) if(e && e.preventDefault) e.preventDefault(); //IE中阻止函数器默认动作的方式 else window.event.returnValue = false; } }; /** * Module : Sparrow dom * Author : Kvkens(yueming@yonyou.com) * Date : 2016-08-16 13:59:17 */ /** * 元素增加指定样式 * @param value * @returns {*} */ var addClass = function(element, value) { if(element){ if(typeof element.classList === 'undefined') { if(u._addClass){ u._addClass(element, value); }else{ $(element).addClass(value); } } else { element.classList.add(value); } } return this; }; /** * 删除元素上指定样式 * @param {Object} element * @param {Object} value */ var removeClass = function(element, value) { if(element){ if(typeof element.classList === 'undefined') { if(u._removeClass){ u._removeClass(element, value); }else{ $(element).removeClass(value); } } else { element.classList.remove(value); } } return this; }; var globalZIndex; /** * 统一zindex值, 不同控件每次显示时都取最大的zindex,防止显示错乱 */ var getZIndex = function() { if(!globalZIndex) { globalZIndex = 2000; } return globalZIndex++; }; var makeDOM = function(htmlString) { var tempDiv = document.createElement("div"); tempDiv.innerHTML = htmlString; var _dom = tempDiv.children[0]; return _dom; }; var showPanelByEle = function(obj) { var ele = obj.ele,panel = obj.panel,position = obj.position, // off = u.getOffset(ele),scroll = u.getScroll(ele), // offLeft = off.left,offTop = off.top, // scrollLeft = scroll.left,scrollTop = scroll.top, // eleWidth = ele.offsetWidth,eleHeight = ele.offsetHeight, // panelWidth = panel.offsetWidth,panelHeight = panel.offsetHeight, bodyWidth = document.body.clientWidth,bodyHeight = document.body.clientHeight, position = position || 'top', // left = offLeft - scrollLeft,top = offTop - scrollTop, eleRect = obj.ele.getBoundingClientRect(), panelRect = obj.panel.getBoundingClientRect(), eleWidth = eleRect.width || 0,eleHeight = eleRect.height || 0, left = eleRect.left || 0,top = eleRect.top || 0, panelWidth = panelRect.width || 0,panelHeight = panelRect.height || 0, docWidth = document.documentElement.clientWidth, docHeight = document.documentElement.clientHeight; // 基准点为Ele的左上角 // 后续根据需要完善 if(position == 'left'){ left=left-panelWidth; top=top+(eleHeight - panelHeight)/2; }else if(position == 'right'){ left=left+eleWidth; top=top+(eleHeight - panelHeight)/2; }else if(position == 'top'||position == 'topCenter'){ left = left + (eleWidth - panelWidth)/2; top = top - panelHeight; }else if(position == 'bottom'||position == 'bottomCenter'){ left = left+ (eleWidth - panelWidth)/2; top = top + eleHeight; }else if(position == 'bottomLeft'){ left = left; top = top + eleHeight; } if((left + panelWidth) > docWidth) left = docWidth - panelWidth - 10; if(left < 0) left = 0; if((top + panelHeight) > docHeight) { top = docHeight - panelHeight - 10; } if(top < 0) top = 0; panel.style.left = left + 'px'; panel.style.top = top + 'px'; }; /** * Module : Sparrow extend enum * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-27 21:46:50 */ var enumerables = true; var enumerablesTest = { toString: 1 }; for(var i in enumerablesTest) { enumerables = null; } if(enumerables) { enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor' ]; } /** * Module : Sparrow extend * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-27 21:46:50 */ /** * 复制对象属性 * * @param {Object} 目标对象 * @param {config} 源对象 */ var extend = function(object, config) { var args = arguments, options; if(args.length > 1) { for(var len = 1; len < args.length; len++) { options = args[len]; if(object && options && typeof options === 'object') { var i, j, k; for(i in options) { object[i] = options[i]; } if(enumerables) { for(j = enumerables.length; j--;) { k = enumerables[j]; if(options.hasOwnProperty && options.hasOwnProperty(k)) { object[k] = options[k]; } } } } } } return object; }; if(!Object.assign){ Object.assign = extend; } /** * Module : Sparrow browser environment * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-27 21:46:50 */ var u$1 = {}; extend(u$1, { isIE: false, isFF: false, isOpera: false, isChrome: false, isSafari: false, isWebkit: false, isIE8_BEFORE: false, isIE8: false, isIE8_CORE: false, isIE9: false, isIE9_CORE: false, isIE10: false, isIE10_ABOVE: false, isIE11: false, isEdge: false, isIOS: false, isIphone: false, isIPAD: false, isStandard: false, version: 0, isWin: false, isUnix: false, isLinux: false, isAndroid: false, isAndroidPAD:false, isAndroidPhone:false, isMac: false, hasTouch: false, isMobile: false }); (function() { var userAgent = navigator.userAgent, rMsie = /(msie\s|trident.*rv:)([\w.]+)/, rFirefox = /(firefox)\/([\w.]+)/, rOpera = /(opera).+version\/([\w.]+)/, rChrome = /(chrome)\/([\w.]+)/, rSafari = /version\/([\w.]+).*(safari)/, version, ua = userAgent.toLowerCase(), s, browserMatch = { browser: "", version: '' }, match = rMsie.exec(ua); if(match != null) { browserMatch = { browser: "IE", version: match[2] || "0" }; } match = rFirefox.exec(ua); if(match != null) { browserMatch = { browser: match[1] || "", version: match[2] || "0" }; } match = rOpera.exec(ua); if(match != null) { browserMatch = { browser: match[1] || "", version: match[2] || "0" }; } match = rChrome.exec(ua); if(match != null) { browserMatch = { browser: match[1] || "", version: match[2] || "0" }; } match = rSafari.exec(ua); if(match != null) { browserMatch = { browser: match[2] || "", version: match[1] || "0" }; } if(userAgent.indexOf("Edge") > -1){ u$1.isEdge = true; } if(s = ua.match(/opera.([\d.]+)/)) { u$1.isOpera = true; } else if(browserMatch.browser == "IE" && browserMatch.version == 11) { u$1.isIE11 = true; u$1.isIE = true; } else if(s = ua.match(/chrome\/([\d.]+)/)) { u$1.isChrome = true; u$1.isStandard = true; } else if(s = ua.match(/version\/([\d.]+).*safari/)) { u$1.isSafari = true; u$1.isStandard = true; } else if(s = ua.match(/gecko/)) { //add by licza : support XULRunner u$1.isFF = true; u$1.isStandard = true; } else if(s = ua.match(/msie ([\d.]+)/)) { u$1.isIE = true; } else if(s = ua.match(/firefox\/([\d.]+)/)) { u$1.isFF = true; u$1.isStandard = true; } if(ua.match(/webkit\/([\d.]+)/)) { u$1.isWebkit = true; } if(ua.match(/ipad/i)) { u$1.isIOS = true; u$1.isIPAD = true; u$1.isStandard = true; } if(ua.match(/iphone/i)) { u$1.isIOS = true; u$1.isIphone = true; } if((navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel")) { //u.isIOS = true; u$1.isMac = true; } if((navigator.platform == "Win32") || (navigator.platform == "Windows") || (navigator.platform == "Win64")) { u$1.isWin = true; } if((navigator.platform == "X11") && !u$1.isWin && !u$1.isMac) { u$1.isUnix = true; } if((String(navigator.platform).indexOf("Linux") > -1)) { u$1.isLinux = true; } if(ua.indexOf('Android') > -1 || ua.indexOf('android') > -1 || ua.indexOf('Adr') > -1 || ua.indexOf('adr') > -1) { u$1.isAndroid = true; } u$1.version = version ? (browserMatch.version ? browserMatch.version : 0) : 0; if(u$1.isAndroid){ if(window.screen.width>=768&&window.screen.width<1024){ u$1.isAndroidPAD=true; } if(window.screen.width<=768) { u$1.isAndroidPhone = true; } } if(u$1.isIE) { var intVersion = parseInt(u$1.version); var mode = document.documentMode; if(mode == null) { if(intVersion == 6 || intVersion == 7) { u$1.isIE8_BEFORE = true; } } else { if(mode == 7) { u$1.isIE8_BEFORE = true; } else if(mode == 8) { u$1.isIE8 = true; } else if(mode == 9) { u$1.isIE9 = true; u$1.isSTANDARD = true; } else if(mode == 10) { u$1.isIE10 = true; u$1.isSTANDARD = true; u$1.isIE10_ABOVE = true; } else { u$1.isSTANDARD = true; } if(intVersion == 8) { u$1.isIE8_CORE = true; } else if(intVersion == 9) { u$1.isIE9_CORE = true; } else if(browserMatch.version == 11) { u$1.isIE11 = true; } } } if("ontouchend" in document) { u$1.hasTouch = true; } if(u$1.isIphone || u$1.isAndroidPhone) u$1.isMobile = true; })(); var env = u$1; /** * Module : Sparrow ripple * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-29 08:42:13 */ var URipple = function URipple(element) { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; this._element = element; // Initialize instance. this.init(); }; //window['URipple'] = URipple; URipple.prototype._down = function(event) { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; if (!this._rippleElement.style.width && !this._rippleElement.style.height) { var rect = this._element.getBoundingClientRect(); this.rippleSize_ = Math.sqrt(rect.width * rect.width + rect.height * rect.height) * 2 + 2; if(this.rippleSize_ > 0){ this._rippleElement.style.width = this.rippleSize_ + 'px'; this._rippleElement.style.height = this.rippleSize_ + 'px'; } } addClass(this._rippleElement, 'is-visible'); if (event.type === 'mousedown' && this._ignoringMouseDown) { this._ignoringMouseDown = false; } else { if (event.type === 'touchstart') { this._ignoringMouseDown = true; } var frameCount = this.getFrameCount(); if (frameCount > 0) { return; } this.setFrameCount(1); var t = event.currentTarget || event.target || event.srcElement; var bound = t.getBoundingClientRect(); var x; var y; // Check if we are handling a keyboard click. if (event.clientX === 0 && event.clientY === 0) { x = Math.round(bound.width / 2); y = Math.round(bound.height / 2); } else { var clientX = event.clientX ? event.clientX : event.touches[0].clientX; var clientY = event.clientY ? event.clientY : event.touches[0].clientY; x = Math.round(clientX - bound.left); y = Math.round(clientY - bound.top); } this.setRippleXY(x, y); this.setRippleStyles(true); if(window.requestAnimationFrame) window.requestAnimationFrame(this.animFrameHandler.bind(this)); } }; /** * Handle mouse / finger up on element. * * @param {Event} event The event that fired. * @private */ URipple.prototype._up = function(event) { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; var self = this; // Don't fire for the artificial "mouseup" generated by a double-click. if (event && event.detail !== 2) { removeClass(this._rippleElement,'is-visible'); } // Allow a repaint to occur before removing this class, so the animation // shows for tap events, which seem to trigger a mouseup too soon after // mousedown. window.setTimeout(function() { removeClass(self._rippleElement,'is-visible'); }, 0); }; /** * Getter for frameCount_. * @return {number} the frame count. */ URipple.prototype.getFrameCount = function() { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; return this.frameCount_; }; /** * Setter for frameCount_. * @param {number} fC the frame count. */ URipple.prototype.setFrameCount = function(fC) { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; this.frameCount_ = fC; }; /** * Getter for _rippleElement. * @return {Element} the ripple element. */ URipple.prototype.getRippleElement = function() { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; return this._rippleElement; }; /** * Sets the ripple X and Y coordinates. * @param {number} newX the new X coordinate * @param {number} newY the new Y coordinate */ URipple.prototype.setRippleXY = function(newX, newY) { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; this.x_ = newX; this.y_ = newY; }; /** * Sets the ripple styles. * @param {boolean} start whether or not this is the start frame. */ URipple.prototype.setRippleStyles = function(start) { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; if (this._rippleElement !== null) { var transformString; var scale; var size; var offset = 'translate(' + this.x_ + 'px, ' + this.y_ + 'px)'; if (start) { scale = 'scale(0.0001, 0.0001)'; size = '1px'; } else { scale = ''; size = this.rippleSize_ + 'px'; } transformString = 'translate(-50%, -50%) ' + offset + scale; this._rippleElement.style.webkitTransform = transformString; this._rippleElement.style.msTransform = transformString; this._rippleElement.style.transform = transformString; if (start) { removeClass(this._rippleElement,'is-animating'); } else { addClass(this._rippleElement,'is-animating'); } } }; /** * Handles an animation frame. */ URipple.prototype.animFrameHandler = function() { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; if (this.frameCount_-- > 0) { window.requestAnimationFrame(this.animFrameHandler.bind(this)); } else { this.setRippleStyles(false); } }; /** * Initialize element. */ URipple.prototype.init = function() { if (env.isIE8 || env.isMobile || env.isAndroidPAD || env.isIPAD) return; var self = this; if (this._element) { this._rippleElement = this._element.querySelector('.u-ripple'); if (!this._rippleElement){ this._rippleElement = document.createElement('span'); addClass(this._rippleElement,'u-ripple'); this._element.appendChild(this._rippleElement); this._element.style.overflow = 'hidden'; this._element.style.position = 'relative'; } this.frameCount_ = 0; this.rippleSize_ = 0; this.x_ = 0; this.y_ = 0; // Touch start produces a compat mouse down event, which would cause a // second ripples. To avoid that, we use this property to ignore the first // mouse down after a touch start. this._ignoringMouseDown = false; on(this._element, 'mousedown',function(e){self._down(e);}); on(this._element, 'touchstart',function(e){self._down(e);}); on(this._element, 'mouseup',function(e){self._up(e);}); on(this._element, 'mouseleave',function(e){self._up(e);}); on(this._element, 'touchend',function(e){self._up(e);}); on(this._element, 'blur',function(e){self._up(e);}); } }; /** * Module : neoui-year * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-11 15:17:07 */ var Year = u.BaseComponent.extend({ DEFAULTS: {}, init: function() { var self = this; var element = this.element; this.options = extend({}, this.DEFAULTS, this.options); this.panelDiv = null; this.input = this.element.querySelector("input"); var d = new Date(); this.year = d.getFullYear(); this.defaultYear = this.year; this.startYear = this.year - this.year % 10 - 1; on(this.input, 'blur', function(e) { self._inputFocus = false; self.setValue(self.input.value); }); // 添加focus事件 this.focusEvent(); // 添加右侧图标click事件 this.clickEvent(); // 添加keydown事件 this.keydownEvent(); }, createPanel: function() { if (this.panelDiv) { this._fillYear(); return; } var oThis = this; this.panelDiv = makeDOM('<div class="u-date-panel" style="margin:0px;"></div>'); this.panelContentDiv = makeDOM('<div class="u-date-content"></div>'); this.panelDiv.appendChild(this.panelContentDiv); this.preBtn = makeDOM('<button class="u-date-pre-button u-button mini">&lt;</button>'); this.nextBtn = makeDOM('<button class="u-date-next-button u-button mini">&gt;</button>'); on(this.preBtn, 'click', function(e) { oThis.startYear -= 10; oThis._fillYear(); }); on(this.nextBtn, 'click', function(e) { oThis.startYear += 10; oThis._fillYear(); }); this.panelContentDiv.appendChild(this.preBtn); this.panelContentDiv.appendChild(this.nextBtn); this._fillYear(); }, /** *填充年份选择面板 * @private */ _fillYear: function(type) { var oldPanel, year, template, yearPage, titleDiv, yearDiv, i, cell; oldPanel = this.panelContentDiv.querySelector('.u-date-content-page'); if (oldPanel) this.panelContentDiv.removeChild(oldPanel); template = ['<div class="u-date-content-page">', '<div class="u-date-content-title"></div>', '<div class="u-date-content-panel"></div>', '</div>' ].join(""); yearPage = makeDOM(template); titleDiv = yearPage.querySelector('.u-date-content-title'); titleDiv.innerHTML = (this.startYear) + '-' + (this.startYear + 11); yearDiv = yearPage.querySelector('.u-date-content-panel'); for (i = 0; i < 12; i++) { cell = makeDOM('<div class="u-date-content-year-cell">' + (this.startYear + i) + '</div>'); new URipple(cell); if (this.startYear + i == this.year) { addClass(cell, 'current'); } cell._value = this.startYear + i; yearDiv.appendChild(cell); } on(yearDiv, 'click', function(e) { var _y = e.target._value; this.year = _y; this.setValue(_y); this.hide(); stopEvent(e); }.bind(this)); this.preBtn.style.display = 'block'; this.nextBtn.style.display = 'block'; this.panelContentDiv.appendChild(yearPage); this.currentPanel = 'year'; }, setValue: function(value) { value = value ? value : ''; this.value = value; if (value) { this.year = value; } else { this.year = this.defaultYear; } this.startYear = this.year - this.year % 10 - 1; this.input.value = value; this.trigger('valueChange', { value: value }); }, focusEvent: function() { var self = this; on(this.input, 'focus', function(e) { self._inputFocus = true; self.show(e); stopEvent(e); }); }, keydownEvent: function() { var self = this; on(self.input, "keydown", function(e) { var code = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode; if (!(code >= 48 && code <= 57 || code == 37 || code == 39 || code == 8 || code == 46)) { //阻止默认浏览器动作(W3C) if (e && e.preventDefault) e.preventDefault(); //IE中阻止函数器默认动作的方式 else window.event.returnValue = false; return false; } }); }, //下拉图标的点击事件 clickEvent: function() { var self = this; var caret = this.element.nextSibling; on(caret, 'click', function(e) { self.input.focus(); stopEvent(e); }); }, show: function(evt) { var oThis = this; this.createPanel(); this.width = this.element.offsetWidth; if (this.width < 300) this.width = 300; this.panelDiv.style.width = 152 + 'px'; if (this.options.showFix) { document.body.appendChild(this.panelDiv); this.panelDiv.style.position = 'fixed'; showPanelByEle({ ele: this.input, panel: this.panelDiv, position: "bottomLeft" }); } else { var bodyWidth = document.body.clientWidth, bodyHeight = document.body.clientHeight, panelWidth = this.panelDiv.offsetWidth, panelHeight = this.panelDiv.offsetHeight; this.element.appendChild(this.panelDiv); this.element.style.position = 'relative'; this.left = this.input.offsetLeft; var inputHeight = this.input.offsetHeight; this.top = this.input.offsetTop + inputHeight; if (this.left + panelWidth > bodyWidth) { this.left = bodyWidth - panelWidth; } if ((this.top + panelHeight) > bodyHeight) { this.top = bodyHeight - panelHeight; } this.panelDiv.style.left = this.left + 'px'; this.panelDiv.style.top = this.top + 'px'; } this.panelDiv.style.zIndex = getZIndex(); addClass(this.panelDiv, 'is-visible'); var callback = function(e) { if (e !== evt && e.target !== this.input && !oThis.clickPanel(e.target) && oThis._inputFocus != true) { off(document, 'click', callback); // document.removeEventListener('click', callback); this.hide(); } }.bind(this); on(document, 'click', callback); // document.addEventListener('click', callback); }, clickPanel: function(dom) { while (dom) { if (dom == this.panelDiv) { return true } else { dom = dom.parentNode; } } return false; }, hide: function() { removeClass(this.panelDiv, 'is-visible'); this.panelDiv.style.zIndex = -1; } }); if (u.compMgr) u.compMgr.regComp({ comp: Year, compAsString: 'u.Year', css: 'u-year' }); /** * Module : Sparrow util tools * Author : Kvkens(yueming@yonyou.com) * Date : 2016-07-27 21:46:50 */ /** * 创建一个带壳的对象,防止外部修改 * @param {Object} proto */ var getFunction = function(target, val) { if(!val || typeof val == 'function') return val if(typeof target[val] == 'function') return target[val] else if(typeof window[val] == 'function') return window[val] else if(val.indexOf('.') != -1) { var func = getJSObject(target, val); if(typeof func == 'function') return func func = getJSObject(window, val); if(typeof func == 'function') return func } return val }; var getJSObject = function(target, names) { if(!names) { return; } if(typeof names == 'object') return names var nameArr = names.split('.'); var obj = target; for(var i = 0; i < nameArr.length; i++) { obj = obj[nameArr[i]]; if(!obj) return null } return obj }; var isNumber$1 = function(obj) { //return obj === +obj //加了个typeof 判断,因为'431027199110.078573'会解析成number return obj - parseFloat(obj) + 1 >= 0; }; var isArray = Array.isArray || function(val) { return Object.prototype.toString.call(val) === '[object Array]'; }; var isEmptyObject = function(obj) { var name; for(name in obj) { return false; } return true; }; try{ NodeList.prototype.forEach = Array.prototype.forEach; }catch(e){ } /** * 获得字符串的字节长度 */ String.prototype.lengthb = function() { // var str = this.replace(/[^\x800-\x10000]/g, "***"); var str = this.replace(/[^\x00-\xff]/g, "**"); return str.length; }; /** * 将AFindText全部替换为ARepText */ String.prototype.replaceAll = function(AFindText, ARepText) { //自定义String对象的方法 var raRegExp = new RegExp(AFindText, "g"); return this.replace(raRegExp, ARepText); }; /** * Module : kero DataTable copyRow * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /** * 在指定index位置插入单条数据行 * @memberof DataTable * @param {number} index 数据行插入之后的位置 * @param {object} row 数据行信息 * @example * var row = { * field1:'value1' * } * datatable.copyRow(1,row) */ const copyRow = function(index, row) { this.copyRows(index, [row]); }; /** * 在指定index位置插入多条数据行 * @memberof DataTable * @param {number} index 数据行插入之后的位置 * @param {array} rows 存储数据行信息的数组 * @example * var row1 = { * field1:'value1' * } * var row2 = { * field1:'value1' * } * datatable.copyRow(1,[row1,row2]) */ const copyRows = function(index, rows) { for (var i = 0; i < rows.length; i++) { var newRow = new Row({ parent: this }); if (rows[i]) { newRow.setData(rows[i].getData()); } this.insertRows(index === undefined ? this.rows().length : index, [newRow]); } }; const copyRowFunObj = { copyRow: copyRow, copyRows: copyRows }; /** * Module : kero DataTable data * Author : liuyk(liuyk@yonyou.com) * Date : 2016-07-30 14:34:01 */ /** * 设置数据信息 * @memberof DataTable * @param {object} data 需要设置的数据信息,必须包含rows或者pages属性 * @param {array} [data.rows] 数据信息中的行信息数组 * @param {array} [data.pages] 数据信息中的page对象数组 * @param {number} [data.pageIndex=DataTable对象当前的页码] 数据信息中的当前页码 * @param {number} [data.pageSize=DataTable对象当前的每页显示条数] 数据信息中的每页显示条数 * @param {number} [data.totalPages=DataTable对象当前的总页数] 数据信息中的总页数 * @param {number} [data.totalRow=如果存在rows则为rows的长度,否则为DataTable对象当前的总条数] 数据信息中的总条数 * @param {number} [data.select] 数据信息中的选中行行号 * @param {number} [data.focus] 数据信息中的focus行行号 * @param {object} options 设置数据时的配置参数 * @param {boolean} options.unSelect=false 是否默认选中第一行,如果为true则不选中第一行,否则选中第一行 * @example * // 不包含分页的情况 * var data = { * pageIndex:0, * pageSize:5, * totalPages:5, * totalRow:22, * rows:[{ * id:'r41201', // 如果需要添加 * status:'nrm', // 如果需要添加 * data:{ * field1:'value1', * field2:'value2' * } * },{ * id:'r41202', * status:'nrm', * data:{ * field1:'value11', * field2:'value21' * } * },...], * select:[0] * } * // 包含分页的情况 * var data = { * pageIndex:0, * pageSize:5, * totalPages:5, * totalRow:22, * pages:[{ * index: 0, * select: [], * current: -1, * rows:[{ * id:'r41201', // 如果需要添加 * status:'nrm', // 如果需要添加 * data:{ * field1:'value1', * field2:'value2' * } * },{ * id:'r41202', * status:'nrm', * data:{ * field1:'value11', * field2:'value21' * } * },...] * },...], * } * var op = { * unSelect:true * } * datatable.setData(data,op) */ const setData = function(data, options) { if (data.pageIndex || data.pageIndex === 0) { var newIndex = data.pageIndex; } else { var newIndex = this.pageIndex(); } if (data.pageSize || data.pageSize === 0) { var newSize = data.pageSize; } else { var newSize = this.pageSize(); } if (data.totalPages || data.totalPages === 0) { var newTotalPages = data.totalPages; } else { var newTotalPages = this.totalPages(); } if (data.totalRow || data.totalRow === 0) { var newTotalRow = data.totalRow; } else { if (data.rows) var newTotalRow = data.rows.length; else var newTotalRow = this.totalRow(); } var select, focus, unSelect = options ? options.unSelect : false; this.pageIndex(newIndex); this.pageSize(newSize); this.pageCache = data.pageCache || this.pageCache; if (this.pageCache === true) { this.updatePages(data.pages); if (newIndex != this.pageIndex()) { this.setCurrentPage(newIndex, true); this.totalPages(newTotalPages); this.totalRow(newTotalRow + this.newCount); return; } else { // 首先删除数据,然后将当前页数据插入 this.removeAllRows(); select = this.getPage(newIndex).selectedIndices; focus = this.getPage(newIndex).focus; var rows = this.setRows(this.getPage(newIndex).rows, options); this.getPage(newIndex).rows = rows; } // 后台传入totalPages及totalRow才进行更新 if (data.totalPages) { this.totalPages(data.totalPages); } if (data.totalRow || data.totalRow === 0) { this.totalRow(data.totalRow + this.newCount); } } else { select = data.select || (!unSelect ? [0] : []); focus = data.focus !== undefined ? data.focus : data.current; this.setRows(data.rows, options); this.totalPages(newTotalPages); this.totalRow(newTotalRow); } this.updateSelectedIndices(); if (select && select.length > 0 && this.rows().length > 0) this.setRowsSelect(select); if (focus !== undefined && this.getRow(focus)) this.setRowFocus(focus); }; /** * 设置对应行对应字段的值 * @memberof DataTable * @param {string} fieldName 需要设置的字段 * @param {string} value 需要设置的值 * @param {u.row} [row=当前行] 需要设置的u.row对象, * @param {*} [ctx] 自定义属性,在valuechange监听传入对象中可通过ctx获取此处设置 * @param {string} validType 传递值的字符类型,如string,integer等 * @example * datatable.setValue('filed1','value1') //设置当前行字段值 * var row = datatable.getRow(1) * datatable.setValue('filed1','value1',row) //设置在指定行字段值 * datatable.setValue('filed1','value1',row,'ctx') //设置在指定行字段值,同时传入自定义数据 */ const setValue = function(fieldName, value, row, ctx, validType) { if (arguments.length === 1) { value = fieldName; fieldName = '$data'; } row = row ? row : this.getCurrentRow(); if (row) row.setValue(fieldName, value, ctx, undefined, validType); }; /** * 重置所有行的数据至nrm状态时的数据 */ const resetAllValue = function() { var rows = new Array(); rows = rows.concat(this.rows()); for (var i = 0; i < rows.length; i++) { var row = rows[i]; this.resetValueByRow(row); } }; /** * 根据row对象重置数据至nrm状态时的数据 * @param {u.row} row 需要重置数据的row对象 */ const resetValueByRow = function(row) { if (row.status == Row.STATUS.NEW) { this.setRowsDelete(row); } else if (row.status == Row.STATUS.FALSE_DELETE) { row.status = Row.STATUS.NORMAL; var rows = [row]; this.trigger(DataTable.ON_INSERT, { index: 0, rows: rows }); } else if (row.status == Row.STATUS.UPDATE) { row.status = Row.STATUS.NORMAL; row.resetValue(); } }; const dataFunObj = { setData: setData, setValue: setValue, resetAllValue: resetAllValue, resetValueByRow: resetValueByRow }; /** * Module : kero DataTable enable * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-08 09:59:01 */ /** * 判断DataTable或指定字段是否可修改 * @memberof DataTable * @param {string} [fieldName] 需要进行判断的字段值 * @return {boolean} DataTable/指定字段是否可修改 * @example * datatable.isEnable() //获取datatable是否可修改 * datatable.isEnable('field1') //获取字段field1是否可修改 */ const isEnable = function(fieldName) { var fieldEnable = this.getMeta(fieldName, 'enable'); if (typeof fieldEnable == 'undefined' || fieldEnable == null) fieldEnable = true; return fieldEnable && this.enable }; /** * 设置DataTable是否可修改 * @memberof DataTable * @param {boolean} enable true表示可修改,否则表示不可修改 * @example * datatable.setEnable(true) */ const setEnable = function(enable) { if (this.enable == enable) return //当传入的参数不为false时,默认enable为true if (enable === false) { enable = false; } else { enable = true; } this.enable = enable; this.enableChange(-this.enableChange()); this.trigger(DataTable.ON_ENABLE_CHANGE, { enable: this.enable }); }; const enableFunObj = { isEnable: isEnable, setEnable: setEnable }; /** * Module : kero DataTable getCurrent * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-08 09:59:01 */ /** * 获取DataTable对象的当前行 * @memberof DataTable * @return {null|u.Row} DataTable对象的当前行 * @example * datatable.getCurrentRow() */ const getCurrentRow = function() { if (this.focusIndex() != -1) return this.getFocusRow() var index = this.getSelectedIndex(); if (index == -1) return null else return this.getRow(index) }; /** * 获取DataTable对象的当前行对应的index * @memberof DataTable * @return {number} DataTable对象的当前行对应的index * @example * datatable.getCurrentIndex() */ const getCurrentIndex = function() { if (this.focusIndex() != -1) return this.focusIndex() var index = this.getSelectedIndex(); if (index == -1) return -1 else return index }; const getCurrentFunObj = { getCurrentRow: getCurrentRow, getCurrentIndex: getCurrentIndex }; /** * Module : kero DataTable getData * Author : liuyk(liuyk@yonyou.com) * Date : 2016-07-30 14:34:01 */ /** * 获取DataTable的数据信息 * @memberof DataTable * @return {array} 数据信息对应的数组,每项对应一条数据 * @example * datatable.getData() */ const getData = function() { var datas = [], rows = this.rows(); for (var i = 0; i < rows.length; i++) { datas.push(rows[i].getData()); } return datas }; // 将page转为row对象格式 const page2data = function(page, pageIndex) { var data = {}; data.focus = page.focus; data.index = pageIndex; data.select = page.selectedIndices; return data; }; /** * 按照特定规则获取数据 * @memberof DataTable * @param {string} rule * DataTable.SUBMIT.current('current') :当前选中行 * DataTable.SUBMIT.focus('focus') :当前focus行 * DataTable.SUBMIT.all('all') :所有行 * DataTable.SUBMIT.select('select') :当前页选中行 * DataTable.SUBMIT.change('change') :发生改变的行 * DataTable.SUBMIT.empty('empty') :不获取数据,返回空数组 * DataTable.SUBMIT.allSelect('allSelect') :所有页选中行 * DataTable.SUBMIT.allPages('allPages') :所有页的数据 * @return {array} 按照规则获取到的数据信息 * @example * datatable.getDataByRule(‘all’) */ const getDataByRule = function(rule) { var returnData = {}, datas = null, rows; returnData.meta = this.meta; returnData.params = this.params; rule = rule || DataTable.SUBMIT.current; // 存在多页及不存在多页分开处理 if (this.pageCache) { var pages = this.getPages(); if (rule == DataTable.SUBMIT.current || rule == DataTable.SUBMIT.focus) { datas = []; var pageIndex = this.pageIndex(); var currPage = pages[pageIndex]; if (currPage) { var currIndex = this.focusIndex(); if (rule == DataTable.SUBMIT.current) { if (currIndex == -1) currIndex = this.getSelectedIndex(); } var data = page2data(currPage, pageIndex); data.rows = []; for (var i = 0, count = currPage.rows.length; i < count; i++) { var row = currPage.rows[i].getData(); if (i != currIndex) row.data = {}; data.rows.push(row); } datas.push(data); } } else if (rule == DataTable.SUBMIT.all || rule == DataTable.SUBMIT.allPages) { datas = []; for (var i = 0; i < pages.length; i++) { var currPage = pages[i]; var data = page2data(currPage, i); data.rows = []; for (var i = 0; i < currPage.rows.length; i++) { data.rows.push(currPage.rows[i].getData()); } datas.push(data); } } else if (rule == DataTable.SUBMIT.select) { datas = []; var pageIndex = this.pageIndex(); var currPage = pages[pageIndex]; if (currPage) { var data = page2data(currPage, pageIndex); data.rows = []; for (var i = 0, count = currPage.rows.length; i < count; i++) { var row = currPage.rows[i].getData(); if (data.select.indexOf(i) < 0) row.data = {}; data.rows.push(row); } datas.push(data); } } else if (rule == DataTable.SUBMIT.allSelect) { datas = []; for (var i = 0; i < pages.length; i++) { var currPage = pages[i]; var data = page2data(currPage, i); data.rows = []; for (var j = 0, count = currPage.rows.length; j < count; j++) { var row = currPage.rows[j].getData(); if (data.select.indexOf(j) < 0) row.data = {}; data.rows.push(row); } datas.push(data); } } else if (rule == DataTable.SUBMIT.change) { datas = []; for (var i = 0; i < pages.length; i++) { var currPage = pages[i]; var data = page2data(currPage, i); data.rows = []; for (var j = 0, count = currPage.rows.length; j < count; j++) { var row = currPage.rows[j].getData(); if (row.status == Row.STATUS.NORMAL) { row.data = {}; } data.rows.push(row); } datas.push(data); } } else if (rule === DataTable.SUBMIT.empty) { datas = []; } if (pages.length < 1 || !pages[this.pageIndex()]) { datas = [{ index: this.pageIndex(), select: [], focus: -1, rows: [] }]; } returnData.pages = datas; } else { if (rule == DataTable.SUBMIT.current) { datas = []; var currIndex = this.focusIndex(); if (currIndex == -1) currIndex = this.getSelectedIndex(); rows = this.rows(); for (var i = 0, count = rows.length; i < count; i++) { if (i == currIndex) datas.push(rows[i].getData()); else datas.push(rows[i].getEmptyData()); } } else if (rule == DataTable.SUBMIT.focus) { datas = []; rows = this.rows(); for (var i = 0, count = rows.length; i < count; i++) { if (i == this.focusIndex()) datas.push(rows[i].getData()); else datas.push(rows[i].getEmptyData()); } } else if (rule == DataTable.SUBMIT.all) { datas = this.getData(); } else if (rule == DataTable.SUBMIT.select) { datas = this.getSelectedDatas(true); } else if (rule == DataTable.SUBMIT.change) { datas = this.getChangedDatas(); } else if (rule === DataTable.SUBMIT.empty) { datas = []; } returnData.rows = datas; returnData.select = this.getSelectedIndexs(); returnData.focus = this.getFocusIndex(); } returnData.pageSize = this.pageSize(); returnData.pageIndex = this.pageIndex(); returnData.isChanged = this.isChanged(); returnData.master = this.master; returnData.pageCache = this.pageCache; return returnData }; /** * 根据索引获取指定行数据信息 * @memberof DataTable * @param {number} index 需要获取的数据信息的索引 * @return {object} 获取到的指定行数据信息 * @example * datatable.getRow(1) */ const getRow = function(index) { //return this.rows()[index] //modify by licza. improve performance return this.rows.peek()[index] }; // 获取子表的数据行 const getChildRow = function(obj) { var fullField = obj.fullField, index = obj.index, row = null; if (parseInt(index) > -1) { if ((index + '').indexOf('.') > 0) { var fieldArr = fullField.split('.'); var indexArr = index.split('.'); var nowDataTable = this; var nowRow = null; for (var i = 0; i < indexArr.length; i++) { nowRow = nowDataTable.getRow(indexArr[i]); if (i < indexArr.length - 1) { if (nowRow) { nowDataTable = nowRow.getValue(fieldArr[i]); } else { nowRow = null; break; } } } row = nowRow; } else { row = this.getRow(index); } } return row; }; /** * 根据rowid获取Row对象 * @memberof DataTable * @param {string} rowid 需要获取的Row对应的rowid * @returns {Row} * @example * datatable.getRowByRowId('rowid') */ const getRowByRowId = function(rowid) { var rows = this.rows.peek(); for (var i = 0, count = rows.length; i < count; i++) { if (rows[i].rowId == rowid) return rows[i] } return null }; /** * 获取Row对象对应的索引 * @memberof DataTable * @param {u.Row} 需要获取索引的row对象 * @returns {*} * @example * var row = datatable.getRow(1) * datatable.getRowIndex(row) // 1 */ const getRowIndex = function(row) { var rows = this.rows.peek(); for (var i = 0, count = rows.length; i < count; i++) { if (rows[i].rowId === row.rowId) return i; } return -1; }; /** * 根据字段及字段值获取所有数据行 * @memberof DataTable * @param {string} field 需要获取行的对应字段 * @param {string} value 需要获取行的对应字段值 * @return {array} 根据字段及字段值获取的所有数据行 * @example * datatable.getRowsByField('field1','value1') */ const getRowsByField = function(field, value) { var rows = this.rows.peek(); var returnRows = new Array(); for (var i = 0, count = rows.length; i < count; i++) { if (rows[i].getValue(field) === value) returnRows.push(rows[i]); } return returnRows; }; /** * 根据多个字段及字段值获取所有数据行 * @memberof DataTable * @param {string} fields 需要获取行的对应字段及对应值数组 * @return {array} 根据字段及字段值获取的所有数据行 * @example * datatable.getRowsByFields([{field:'field1',value:'value1'},{field:'field2',value:'value2'}]) */ const getRowsByFields = function(fileds) { var rows = this.rows.peek(); var returnRows = new Array(); if (fileds && fileds.length > 0) { for (var i = 0, count = rows.length; i < count; i++) { var matchCount = 0; var l = fileds.length; for (var j = 0; j < l; j++) { if (rows[i].getValue(fileds[j]['field']) === fileds[j]['value']) matchCount++; } if (matchCount == l) returnRows.push(rows[i]); } } return returnRows; }; /** * 根据字段及字段值获取第一条数据行 * @memberof DataTable * @param {string} field 需要获取行的对应字段 * @param {string} value 需要获取行的对应字段值 * @return {u.Row} 根据字段及字段值获取第一条数据行 * @example * datatable.getRowByField('field1','value1') */ const getRowByField = function(field, value) { var rows = this.rows.peek(); for (var i = 0, count = rows.length; i < count; i++) { if (rows[i].getValue(field) === value) return rows[i] } return null; }; /** * 获取当前页的所有数据行 * @memberof DataTable * @return {array} 获取到的数据行 * @example * datatable.getAllRows() */ const getAllRows = function() { return this.rows.peek(); }; /** * 获取所有页的所有数据行 * @memberof DataTable * @return {array} 获取到的数据行 * @example * datatable.getAllPageRows() */ const getAllPageRows = function() { var datas = [], rows; for (var i = 0; i < this.totalPages(); i++) { rows = []; if (i == this.pageIndex()) { rows = this.getData(); } else { var page = this.cachedPages[i]; if (page) { rows = page.getData(); } } for (var j = 0; j < rows.length; j++) { datas.push(rows[j]); } } return datas; }; /** * 获取发生变化的数据信息 * @memberof DataTable * @param {boolean} withEmptyRow=false 未发生变化的数据是否使用空行代替,true表示以空行代替未发生变化行,false相反 * @return {array} 发生变化的数据信息 * @example * datatable.getChangedDatas() */ const getChangedDatas = function(withEmptyRow) { var datas = [], rows = this.rows(); for (var i = 0, count = rows.length; i < count; i++) { if (rows[i] && rows[i].status != Row.STATUS.NORMAL) { datas.push(rows[i].getData()); } else if (withEmptyRow == true) { datas.push(rows[i].getEmptyData()); } } return datas }; /** * 获取发生改变的Row对象 * @memberof DataTable * @return {array} 发生改变的Row对象 * @example * datatable.getChangedRows() */ const getChangedRows = function() { var changedRows = [], rows = this.rows.peek(); for (var i = 0, count = rows.length; i < count; i++) { if (rows[i] && rows[i].status != Row.STATUS.NORMAL) { changedRows.push(rows[i]); } } return changedRows }; const getDeleteRows = function() { var deleteRows = [], rows = this.rows.peek(); for (var i = 0, count = rows.length; i < count; i++) { if (rows[i] && rows[i].status == Row.STATUS.FALSE_DELETE) { deleteRows.push(rows[i]); } } return deleteRows }; /** * 根据字段获取对应Row对象的字段值 * @memberof DataTable * @param {string} fieldName 需要获取的值对应的字段 * @param {u.Row} [row=默认为当前行] 对应的数据行 * @return {string} 获取到的字段值 * @example * datatable.getValue('field1') * var row = datatable.getRow(1) * datatable.getValue('field1',row) */ const getValue = function(fieldName, row) { row = row || this.getCurrentRow(); if (row) return row.getValue(fieldName) else return '' }; /** * 根据行号获取行索引 * @memberof DataTable * @param {String} rowId * @example * datatable.getIndexByRowId('rowid') */ const getIndexByRowId = function(rowId) { var rows = this.rows(); for (var i = 0, count = rows.length; i < count; i++) { if (rows[i].rowId == rowId) return i } return -1 }; /** * 获取所有行数据信息 * @memberof DataTable * @return {array} 所有行数据信息 * @example * datatable.getAllDatas() */ const getAllDatas = function() { var rows = this.getAllRows(); var datas = []; for (var i = 0, count = rows.length; i < count; i++) if (rows[i]) datas.push(rows[i].getData()); return datas }; /** * 根据索引获取rowid * @memberof DataTable * @param {array} indices 需要获取rowid的索引值 * @return {array} 获取到的rowid * @example * datatable.getRowIdsByIndices([1,2,5]) */ const getRowIdsByIndices = function(indices) { var rowIds = []; for (var i = 0; i < indices.length; i++) { if (this.getRow(indices[i])) rowIds.push(this.getRow(indices[i]).rowId); } return rowIds }; /** * 根据索引获取row * @memberof DataTable * @param {array} indices 需要获取rowid的索引值 * @return {array} 获取到的row * @example * datatable.getRowIdsByIndices([1,2,5]) */ const getRowsByIndices = function(indices) { var rows = []; for (var i = 0; i < indices.length; i++) { rows.push(this.getRow(indices[i])); } return rows }; const getDataFunObj = { getData: getData, getDataByRule: getDataByRule, getRow: getRow, getChildRow: getChildRow, getRowByRowId: getRowByRowId, getRowIndex: getRowIndex, getRowsByField: getRowsByField, getRowByField: getRowByField, getAllRows: getAllRows, getAllPageRows: getAllPageRows, getChangedDatas: getChangedDatas, getChangedRows: getChangedRows, getDeleteRows: getDeleteRows, getValue: getValue, getIndexByRowId: getIndexByRowId, getAllDatas: getAllDatas, getRowIdsByIndices: getRowIdsByIndices, getRowsByIndices: getRowsByIndices, getRowsByFields:getRowsByFields }; /** * Module : kero dataTable getFocus * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-08 09:59:01 */ /** * 获取焦点行 * @memberof DataTable * @return {u.Row} 焦点行 * @example * datatable.getFocusRow() */ const getFocusRow = function() { if (this.focusIndex() != -1) return this.getRow(this.focusIndex()) else return null }; /** * 获取焦点行索引 * @memberof DataTable * @return {number} 焦点行索引 * @example * datatable.getFocusIndex() */ const getFocusIndex = function() { return this.focusIndex() }; const getFocusFunObj = { getFocusRow: getFocusRow, getFocusIndex: getFocusIndex }; /** * Module : kero dataTable getMete * Author : liuyk(liuyk@yonyou.com) * Date : 2016-07-30 14:34:01 */ /** * 获取meta信息 * @memberof DataTable * @param {string} [fieldName] 需要获取的字段 * @param {string} [key] 需要获取的字段指定meta信息 * @return {object} meta信息 * @example * datatable.getMeta() // 获取所有meta信息 * datatable.getMeta('field1') // 获取field1所有meta信息 * datatable.getMeta('field1','type') // 获取field1的key信息 */ const getMeta = function(fieldName, key) { if (arguments.length === 0) return this.meta; else if (arguments.length === 1) return this.meta[fieldName]; if (this.meta[fieldName] && typeof this.meta[fieldName][key] !== 'undefined') { return this.meta[fieldName][key]; } else { return null; } }; /** * 获取当前行的meta信息,如果不存在当前行则获取DataTable的meta信息 * @memberof DataTable * @param {string} [fieldName] 需要获取的字段 * @param {string} [key] 需要获取的字段指定meta信息 * @return {object} meta信息 * @example * datatable.getRowMeta() // 获取当前行所有meta信息 * datatable.getRowMeta('field1') // 获取当前行field1所有meta信息 * datatable.getRowMeta('field1','type') // 获取当前行field1的key信息 */ const getRowMeta = function(fieldName, key) { var row = this.getCurrentRow(); if (row) return row.getMeta(fieldName, key) else return this.getMeta(fieldName, key) }; const getMetaFunObj = { getMeta: getMeta, getRowMeta: getRowMeta }; /** * Module : kero dataTable getPage * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /** * 获取指定索引的Page对象 * @memberof DataTable * @param {number} pageIndex 需要获取的page对应的索引 * @return {Page|-1} 获取到的Page对象,不存在则返回-1 * @example * datatable.getPage(1) */ const getPage = function(pageIndex) { if (this.pageCache) { return this.cachedPages[pageIndex] } return -1; }; /** * 获取所有的Page对象 * @memberof DataTable * @return {array} 所有的Page对象 * @example * datatable.getPages() */ const getPages = function() { if (this.pageCache) { return this.cachedPages } return []; }; const getPageFunObj = { getPage: getPage, getPages: getPages }; /** * Module : kero dataTable getParam * Author : liuyk(liuyk@yonyou.com) * Date : 2016-07-30 14:34:01 */ /** * 获取Param参数值 * @memberof DataTable * @param {string} key Param对应的key * @return {*} Param参数值 * @example * datatable.getParam('param1') */ const getParam = function(key) { return this.params[key] }; const getParamFunObj = { getParam: getParam }; /** * Module : kero dataTable getSelect * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /** * 获取选中行索引,多选时,只返回第一个行索引 * @memberof DataTable * @return {number} 选中行索引 * @example * datatable.getSelectedIndex() */ const getSelectedIndex = function() { var selectedIndices = this.selectedIndices(); if (selectedIndices == null || selectedIndices.length == 0) return -1 return selectedIndices[0] }; /** * 获取选中的所有行索引数组 * @memberof DataTable * @return {array} 所有行索引数组 * @example * datatable.getSelectedIndices() */ const getSelectedIndices = function() { var selectedIndices = this.selectedIndices(); if (selectedIndices == null || selectedIndices.length == 0) return [] return selectedIndices }; // 兼容保留,不要用 const getSelectedIndexs = function() { return this.getSelectedIndices(); }; /** * 获取选中行的数据信息 * @memberof DataTable * @param {boolean} [withEmptyRow=false] 未选中的数据是否使用空行代替,true表示以空行代替未选中行,false相反 * @return {array} 发生变化的数据信息 * @example * datatable.getSelectedDatas() * datatable.getSelectedDatas(true) */ const getSelectedDatas = function(withEmptyRow) { var selectedIndices = this.selectedIndices(); var datas = []; var sIndices = []; for (var i = 0, count = selectedIndices.length; i < count; i++) { sIndices.push(selectedIndices[i]); } var rows = this.rows(); for (var i = 0, count = rows.length; i < count; i++) { if (sIndices.indexOf(i) != -1) datas.push(rows[i].getData()); else if (withEmptyRow == true) datas.push(rows[i].getEmptyData()); } return datas }; /** * 获取选中的Row对象 * @memberof DataTable * @return {array} 选中的Row对象 * @example * datatable.getSelectedRows() */ const getSelectedRows = function() { var selectedIndices = this.selectedIndices(); var selectRows = []; var rows = this.rows.peek(); var sIndices = []; for (var i = 0, count = selectedIndices.length; i < count; i++) { sIndices.push(selectedIndices[i]); } for (var i = 0, count = rows.length; i < count; i++) { if (sIndices.indexOf(i) != -1) selectRows.push(rows[i]); } return selectRows }; const getAllPageSelectedRows = function() { var rows = []; if (this.pageCache) { var pages = this.getPages(); for (var i = 0; i < pages.length; i++) { var page = pages[i]; if (page) { rows = rows.concat(page.getSelectRows()); } } } return rows; }; const getSelectFunObj = { getSelectedIndex: getSelectedIndex, getSelectedIndices: getSelectedIndices, getSelectedIndexs: getSelectedIndexs, getSelectedDatas: getSelectedDatas, getSelectedRows: getSelectedRows, getAllPageSelectedRows: getAllPageSelectedRows }; /** * Module : kero dataTable getSimpleData * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /** * 获取数据信息,只获取字段名与字段值 * @memberof DataTable * @param {object} [options] [description] * @param {string} [options.type=all] 获取数据的规则 * all:所有数据 * current:当前行数据 * focus:焦点行数据 * select:选中行数据 * change:发生改变的数据 * @param {array} [options.fields] 需要获取数据的字段名数组 * @return {array} 获取到的数据信息 * @example * datatable.getSimpleData() // 获取所有数据信息 * datatable.getSimpleData({type:'current'}) // 获取当前行数据信息 * datatable.getSimpleData({type:'current','fields':['filed1','field3']}) // 获取当前行field1和filed3数据信息 */ const getSimpleData = function(options) { options = options || {}; var rows, _rowData = [], type = options['type'] || 'all', fields = options['fields'] || null; if (type === 'current') { var currRow = this.getCurrentRow(); rows = currRow == null ? [] : [currRow]; } else if (type === 'focus') { var focusRow = this.getFocusRow(); rows = focusRow == null ? [] : [focusRow]; } else { if (this.pageCache) { var pages = this.getPages(); rows = []; for (var i = 0; i < pages.length; i++) { var page = pages[i]; if (page) { if (type === 'all') { rows = rows.concat(page.rows); } else if (type === 'select') { rows = rows.concat(page.getSelectRows()); } else if (type === 'change') { rows = rows.concat(page.getChangedRows()); } } } } else { if (type === 'all') { rows = this.rows.peek(); } else if (type === 'select') { rows = this.getSelectedRows(); } else if (type === 'change') { rows = this.getChangedRows(); } } } for (var i = 0; i < rows.length; i++) { _rowData.push(rows[i].getSimpleData({ fields: fields })); } if (_rowData.length == 0) { _rowData = this.setSimpleDataReal; //云采提的#需求 } return _rowData; }; const getSimpleDataFunObj = { getSimpleData: getSimpleData }; /** * Module : kero dataTable mete * Author : liuyk(liuyk@yonyou.com) * Date : 2016-07-30 14:34:01 */ /** * 设置meta信息 * @memberof DataTable * @param {string} fieldName 需要设置meta信息的字段名 * @param {string} key meta信息的key * @param {string} value meta信息的值 * @example * datatable.setMeta('filed1','type','string') */ const setMeta = function(fieldName, key, value) { if (!this.meta[fieldName]) return; var oldValue = this.meta[fieldName][key]; var currRow = this.getCurrentRow(); this.meta[fieldName][key] = value; if (this.metaChange[fieldName + '.' + key]) this.metaChange[fieldName + '.' + key](-this.metaChange[fieldName + '.' + key]()); if (key == 'enable') this.enableChange(-this.enableChange()); this.trigger(DataTable.ON_META_CHANGE, { eventType: 'dataTableEvent', dataTable: this.id, field: fieldName, meta: key, oldValue: oldValue, newValue: value }); if (currRow && !currRow.getMeta(fieldName, key, false)) { this.trigger(fieldName + '.' + key + '.' + DataTable.ON_CURRENT_META_CHANGE, { eventType: 'dataTableEvent', dataTable: this.id, oldValue: oldValue, newValue: value }); } }; /** * 更新meta信息 * @memberof DataTable * @param {object} meta 需要更新的meta信息 * @example * var metaObj = {supplier: {meta: {precision:'3', default: '0239900x', display:'显示名称'}}} * datatable.updateMeta(metaObj) */ const updateMeta = function(meta) { if (!meta) { return; } for (var fieldKey in meta) { for (var propKey in meta[fieldKey]) { var oldValue = this.meta[fieldKey][propKey]; var newValue = meta[fieldKey][propKey]; if (propKey === 'default') { if (!this.meta[fieldKey]['default']) { this.meta[fieldKey]['default'] = {}; } this.meta[fieldKey]['default'].value = meta[fieldKey][propKey]; } else if (propKey === 'display') { if (!this.meta[fieldKey]['default']) { this.meta[fieldKey]['default'] = {}; } this.meta[fieldKey]['default'].display = meta[fieldKey][propKey]; } else { this.meta[fieldKey][propKey] = meta[fieldKey][propKey]; } if (this.metaChange[fieldKey + '.' + propKey]) this.metaChange[fieldKey + '.' + propKey](-this.metaChange[fieldKey + '.' + propKey]()); this.trigger(DataTable.ON_META_CHANGE, { eventType: 'dataTableEvent', dataTable: this.id, field: fieldKey, meta: propKey, oldValue: oldValue, newValue: newValue }); } } }; // 字段不存在时创建字段,fieldName为需要创建的字段 // options.meta为对应的meta信息 const createField = function(fieldName, options) { //字段不主动定义,则不创建 if (this.root.strict == true) return; //有子表的情况不创建字段 if (fieldName.indexOf('.') != -1) { var fNames = fieldName.split('.'); var _name = fNames[0]; for (var i = 0, count = fNames.length; i < count; i++) { if (this.meta[_name] && this.meta[_name]['type'] === 'child') return; if ((i + 1) < count) _name = _name + '.' + fNames[i + 1]; } } if (!this.meta[fieldName]) { this.meta[fieldName] = {}; } if (typeof options === 'object') { if (options['meta']) { for (var key in options['meta']) { //if (!this.meta[fieldName][key]){ this.meta[fieldName]['meta'][key] = options['meta'][key]; //} } } else { for (var key in options) { //if (!this.meta[fieldName][key]){ this.meta[fieldName][key] = options[key]; //} } } } // 在顶层dataTable上定义field信息 if (this.root !== this) { var nsArr = this.ns.split('.'); var _fieldMeta = this.root.meta; for (var i = 0; i < nsArr.length; i++) { _fieldMeta[nsArr[i]] = _fieldMeta[nsArr[i]] || {}; _fieldMeta[nsArr[i]]['type'] = _fieldMeta[nsArr[i]]['type'] || 'child'; _fieldMeta[nsArr[i]]['meta'] = _fieldMeta[nsArr[i]]['meta'] || {}; _fieldMeta = _fieldMeta[nsArr[i]]['meta']; } if (!_fieldMeta[fieldName]) { _fieldMeta[fieldName] = {}; } if (typeof options === 'object') { for (var key in options) { if (!_fieldMeta[fieldName][key]) { _fieldMeta[fieldName][key] = options[key]; } } } } }; const metaFunObj = { setMeta: setMeta, updateMeta: updateMeta, createField: createField }; /** * Module : kero dataTable page * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ // 设置当前页 const setCurrentPage = function(pageIndex, notCacheCurrentPage) { var nowTotalRow = this.totalRow(); if (pageIndex != this.pageIndex() && notCacheCurrentPage != true) this.cacheCurrentPage(); this.pageIndex(pageIndex); var cachedPage = this.cachedPages[this.pageIndex()]; if (cachedPage) { // 取当前页的选中行重设选中行 var selectedIndices = cachedPage.selectedIndices; this.removeAllRows(); this.setRows(cachedPage.rows); this.setRowsSelect(selectedIndices); } this.totalRow(nowTotalRow); }; // 更新分页信息,通过fire调用,不对外提供 const updatePages = function(pages) { var pageSize = this.pageSize(), pageIndex = 0, page, r, row; var page, index, i, rows, focus, selectIndices, status, j, row, originRow; for (i = 0; i < pages.length; i++) { index = pages[i].index; rows = pages[i].rows; focus = pages[i].current; selectIndices = pages[i].select; status = pages[i].status; if (status === 'del') { this.cachedPages[index] = null; continue; } if (!this.cachedPages[index]) { page = new Page({ parent: this }); page.rows = rows; for (var j = 0; j < page.rows.length; j++) { page.rows[j].rowId = page.rows[j].id; delete page.rows[j].id; } this.cachedPages[index] = page; page.selectedIndices = selectIndices; page.focus = focus; } else { page = this.cachedPages[index]; page.selectedIndices = selectIndices; page.focus = focus; for (var j = 0; j < rows.length; j++) { r = rows[j]; if (!r.id) r.id = Row.getRandomRowId(); if (r.status == Row.STATUS.DELETE) { var row = page.getRowByRowId(r.id); if (row) { // 针对后台不传回总行数的情况下更新总行数 var oldTotalRow = this.totalRow(); var newTotalRow = oldTotalRow - 1; this.totalRow(newTotalRow); if (row.status == Row.STATUS.NEW) { this.newCount -= 1; if (this.newCount < 0) this.newCount = 0; } } this.removeRowByRowId(r.id); page.removeRowByRowId(r.id); } else { row = page.getRowByRowId(r.id); if (row) { page.updateRow(row, r); // if(row.status == Row.STATUS.NEW){ // // 针对后台不传回总行数的情况下更新总行数 // var oldTotalRow = this.totalRow(); // var newTotalRow = oldTotalRow + 1; // this.totalRow(newTotalRow); // } if (row.status == Row.STATUS.NEW && r.status != Row.STATUS.NEW) { this.newCount -= 1; if (this.newCount < 0) this.newCount = 0; } row.setStatus(Row.STATUS.NORMAL); if (r.status == Row.STATUS.NEW) { row.setStatus(Row.STATUS.NEW); } } else { r.rowId = r.id; delete r.id; page.rows.push(r); if (r.status != Row.STATUS.NEW) { row.setStatus(Row.STATUS.NORMAL); } else { this.newCount += 1; } // 针对后台不传回总行数的情况下更新总行数 var oldTotalRow = this.totalRow(); var newTotalRow = oldTotalRow + 1; this.totalRow(newTotalRow); } } } } } }; // 前端分页方法,不建议使用,建议在后端进行分页 const setPages = function(allRows) { var pageSize = this.pageSize(), pageIndex = 0, page; this.cachedPages = []; for (var i = 0; i < allRows.length; i++) { pageIndex = Math.floor(i / pageSize); if (!this.cachedPages[pageIndex]) { page = new Page({ parent: this }); this.cachedPages[pageIndex] = page; } page.rows.push(allRows[i]); } if (this.pageIndex() > -1) this.setCurrentPage(this.pageIndex()); this.totalRow(allRows.length); this.totalPages(pageIndex + 1); }; // 判断是否存在索引对应的Page const hasPage = function(pageIndex) { return (this.pageCache && this.cachedPages[pageIndex]) ? true : false }; // 清空cachedPages const clearCache = function() { this.cachedPages = []; }; // 更新当前分页的page对象 const cacheCurrentPage = function() { if (this.pageCache && this.pageIndex() > -1) { var page = new Page({ parent: this }); page.focus = this.getFocusIndex(); page.selectedIndices = this.selectedIndices().slice(); var rows = this.rows.peek(); for (var i = 0; i < rows.length; i++) { var r = rows[i].getData(); r.rowId = r.id; delete r.id; page.rows.push(r); } this.cachedPages[this.pageIndex()] = page; } }; //根据datatable的选中行更新每页的选中行 const updatePagesSelect = function() { var selectRows = this.getSelectedRows(); var pages = this.getPages(); for (var i = 0; i < pages.length; i++) { var rows = pages[i].rows; var selectedIndices = []; for (var j = 0; j < selectRows.length; j++) { var nowSelectRow = selectRows[j]; for (var k = 0; k < rows.length; k++) { var row = rows[k]; if (nowSelectRow == row) { selectedIndices.push(k); break; } } } pages[i].selectedIndices = selectedIndices; } }; //根据datatable的rows更新当前页的rows const updatePageRows = function() { if (this.pageCache) { var pageIndex = this.pageIndex(); var page = this.getPages()[pageIndex]; if (page) { page.rows = this.rows(); } } }; //根据datatable的选中行更新page的选中行 const updatePageSelect = function() { if (this.pageCache) { var pageIndex = this.pageIndex(); var page = this.getPages()[pageIndex]; if (page) { var selectedIndices = this.selectedIndices().slice(); page.selectedIndices = selectedIndices; } } }; //根据datatable的focus更新page的focus const updatePageFocus = function() { if (this.pageCache) { var pageIndex = this.pageIndex(); var page = this.getPages()[pageIndex]; if (page) { page.focus = this.getFocusIndex(); } } }; // 根据datatable更新page对象 const updatePageAll = function() { this.updatePageRows(); this.updatePageSelect(); this.updatePageFocus(); }; const pageFunObj = { setCurrentPage: setCurrentPage, updatePages: updatePages, setPages: setPages, hasPage: hasPage, clearCache: clearCache, cacheCurrentPage: cacheCurrentPage, updatePagesSelect: updatePagesSelect, updatePageRows: updatePageRows, updatePageSelect: updatePageSelect, updatePageFocus: updatePageFocus, updatePageAll: updatePageAll }; /** * Module : kero dataTable param * Author : liuyk(liuyk@yonyou.com) * Date : 2016-07-30 14:34:01 */ /** * 增加Param参数 * @memberof DataTable * @param {string} key 需要增加的key值 * @param {*} value 需要增加的具体指 * @example * datatable.addParam('precision','3') */ const addParam = function(key, value) { this.params[key] = value; }; /** * 增加多个Param参数 * @memberof DataTable * @param {object} params 需要增加的Param对象 * @example * var paramsObj = { * 'precision':'3', * 'default':'1.234' * } * datatable.addParams(paramsObj) */ const addParams = function(params) { for (var key in params) { this.params[key] = params[key]; } }; const paramFunObj = { addParam: addParam, addParams: addParams }; /** * Module : kero dataTable ref * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /** * 为选中行绑定监听,当选中行发生改变时触发对应方法 * @memberof DataTable * @param {string} fieldName 绑定的字段名 * @example * datatable.refSelectedRows().subscribe(function(){}) */ const refSelectedRows = function() { return ko.pureComputed({ read: function() { var ins = this.selectedIndices() || []; var rs = this.rows(); var selectedRows = []; for (var i = 0; i < ins.length; i++) { selectedRows.push(rs[i]); } return selectedRows }, owner: this }) }; /** * 为某个字段绑定监听,当字段发生改变时触发对应方法 * @memberof DataTable * @param {string} fieldName 绑定的字段名 * @example * datatable.ref('field1').subscribe(function(){}) */ const ref = function(fieldName) { this.createField(fieldName); if (!this.valueChange[fieldName]) this.valueChange[fieldName] = ko.observable(1); return ko.pureComputed({ read: function() { this.valueChange[fieldName](); this.currentRowChange(); var row = this.getCurrentRow(); if (row) { return row.getChildValue(fieldName) } else return '' }, write: function(value) { var row = this.getCurrentRow(); if (row) row.setChildValue(fieldName, value); }, owner: this }) }; /** * 绑定字段属性,当字段属性发生改变时触发对应方法 * @memberof DataTable * @param {string} fieldName 绑定的字段名 * @param {string} key 绑定的属性key * @example * datatable.refMeta('field1','type').subscribe(function(){}) */ const refMeta = function(fieldName, key) { if (!this.metaChange[fieldName + '.' + key]) this.metaChange[fieldName + '.' + key] = ko.observable(1); return ko.pureComputed({ read: function() { this.metaChange[fieldName + '.' + key](); this.currentRowChange(); return this.getMeta(fieldName, key) }, write: function(value) { this.setMeta(fieldName, key, value); }, owner: this }) }; /** * 绑定当前行的字段属性,当字段属性发生改变时触发对应方法 * @memberof DataTable * @param {string} fieldName 绑定的字段名 * @param {string} key 绑定的属性key * @example * datatable.refRowMeta('field1','type').subscribe(function(){}) */ const refRowMeta = function(fieldName, key) { if (!this.metaChange[fieldName + '.' + key]) this.metaChange[fieldName + '.' + key] = ko.observable(1); return ko.pureComputed({ read: function() { this.metaChange[fieldName + '.' + key](); this.currentRowChange(); var row = this.getCurrentRow(); if (row) return row.getMeta(fieldName, key) else return this.getMeta(fieldName, key) }, write: function(value) { var row = this.getCurrentRow(); if (row) row.setMeta(fieldName, value); }, owner: this }) }; /** * 绑定字段是否可修改属性,当字段可修改属性发生改变时触发对应方法 * @memberof DataTable * @param {string} fieldName 绑定的字段名 * @example * datatable.refEnable('field1').subscribe(function(){}) */ const refEnable = function(fieldName) { return ko.pureComputed({ //enable优先级: dataTable.enable > row上的enable > field中的enable定义 read: function() { this.enableChange(); if (!fieldName) return this.enable; var fieldEnable = this.getRowMeta(fieldName, 'enable'); if (typeof fieldEnable == 'undefined' || fieldEnable == null) fieldEnable = true; return fieldEnable && this.enable }, owner: this }) }; const refFunObj = { refSelectedRows: refSelectedRows, ref: ref, refMeta: refMeta, refRowMeta: refRowMeta, refEnable: refEnable }; /** * Module : kero dataTable util * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-08 09:59:01 */ // 判断DataTable对象是否发生了改变 const isChanged = function() { var rows = this.getAllRows(); for (var i = 0; i < rows.length; i++) { if (rows[i].status != Row.STATUS.NORMAL) return true } return false }; // 将Row对象转为索引数组或者将Row对象数组转为索引数组 const _formatToIndicesArray = function(dataTableObj, indices) { if (typeof indices == 'string' || typeof indices == 'number') { indices = [indices]; } else if (indices instanceof Row) { indices = [dataTableObj.getIndexByRowId(indices.rowId)]; } else if (isArray(indices) && indices.length > 0 && indices[0] instanceof Row) { for (var i = 0; i < indices.length; i++) { indices[i] = dataTableObj.getIndexByRowId(indices[i].rowId); } } return indices; }; const utilFunObj = { isChanged: isChanged, _formatToIndicesArray: _formatToIndicesArray }; /** * Module : kero dataTable removeRow * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /** * 根据rowId删除指定行 * @memberof DataTable * @param {string} rowId 需要删除行的rowId * @example * datatable.removeRowByRowId('rowid1') */ const removeRowByRowId = function(rowId) { var index = this.getIndexByRowId(rowId); if (index != -1) this.removeRow(index); }; /** *根据索引删除指定行 * @memberof DataTable * @param {number} index 需要删除行的索引 * @example * datatable.removeRow(1) */ const removeRow = function(index) { if (index instanceof Row) { index = this.getIndexByRowId(index.rowId); } this.removeRows([index]); }; /** * 删除所有行 * @memberof DataTable * @example * datatable.removeAllRows(); */ const removeAllRows = function() { this.rows([]); this.selectedIndices([]); this.focusIndex(-1); this.trigger(DataTable.ON_DELETE_ALL); this.updateCurrIndex(); }; /** * 根据索引数据删除多条数据行 * @memberof DataTable * @param {array} indices 需要删除的数据行对应数组,数组中既可以是索引也可以是row对象 * @example * datatable.removeRows([1,2]) * datatable.removeRows([row1,row2]) */ const removeRows = function(indices, obj) { this.setRowsDelete(indices, obj); }; /** * 清空datatable的所有数据以及分页数据以及index * @memberof DataTable * @example * datatable.clear() */ const clear = function() { this.removeAllRows(); this.cachedPages = []; this.totalPages(1); this.pageIndex(0); this.focusIndex(-1); this.selectedIndices([]); }; const removeRowFunObj = { removeRowByRowId: removeRowByRowId, removeRow: removeRow, removeAllRows: removeAllRows, removeRows: removeRows, clear: clear }; /** * Module : kero dataTable row * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ // 添加数据,建议使用setData或者setSimpleData const setRows = function(rows, options) { var insertRows = [], _id; for (var i = 0; i < rows.length; i++) { var r = rows[i]; _id = r.rowId || r.id; if (!_id) _id = Row.getRandomRowId(); if (r.status == Row.STATUS.DELETE) { this.removeRowByRowId(_id); } else { var row = this.getRowByRowId(_id); if (row) { row.updateRow(r); if (!isEmptyObject(r.data)) { this.trigger(DataTable.ON_UPDATE, { index: i, rows: [row] }); if (row == this.getCurrentRow()) { this.currentRowChange(-this.currentRowChange()); row.currentRowChange(-row.currentRowChange()); this.trigger(DataTable.ON_CURRENT_UPDATE, { index: i, rows: [row] }); } else { row.currentRowChange(-row.currentRowChange()); } } } else { row = new Row({ parent: this, id: _id }); row.setData(rows[i], null, options); insertRows.push(row); } // 如果r对象中存在状态则更新状态为返回的状态 if (r.status) { row.setStatus(r.status); } } } if (insertRows.length > 0) this.addRows(insertRows); return insertRows; }; /** * 在最后位置添加一条数据行 * @memberof DataTable * @param {u.Row} row 数据行 * @example * var row1 = new Row({parent: datatable}) * row1.setData({ * data:{ * field1: 'value1', * field2: 'value2' * } * }) * datatable.addRow(row1) */ const addRow = function(row) { this.insertRow(this.rows().length, row); this.resetDelRowEnd(); }; const resetDelRowEnd = function() { for (var i = this.rows().length - 1; i > -1; i--) { var row = this.rows()[i]; if (row.status == Row.STATUS.DELETE || row.status == Row.STATUS.FALSE_DELETE) { this.rows().splice(i, 1); this.rows().push(row); } } }; /** * 在最后位置添加多条数据行 * @memberof DataTable * @param {array} rows 数据行数组 * @example * var row1 = new Row({parent: datatable}) * row1.setData({ * data:{ * field1: 'value1', * field2: 'value2' * } * }) * var row2 = new Row({parent: datatable}) * row2.setData({ * data:{ * field1: 'value11', * field2: 'value22' * } * }) * datatable.addRows([row1,row2]) */ const addRows = function(rows) { this.insertRows(this.rows().length, rows); this.resetDelRowEnd(); }; /** * 在指定索引位置添加一条数据行 * @memberof DataTable * @param {number} index 指定索引 * @param {u.Row} row 数据行 * @example * var row1 = new Row({parent: datatable}) * row1.setData({ * data:{ * field1: 'value1', * field2: 'value2' * } * }) * datatable.insertRow(1,row1) */ const insertRow = function(index, row) { if (!row) { row = new Row({ parent: this }); } this.insertRows(index, [row]); }; /** * 在指定索引位置添加多条数据行 * @memberof DataTable * @param {number} index 指定索引 * @param {array} rows 数据行数组 * var row1 = new Row({parent: datatable}) * row1.setData({ * data:{ * field1: 'value1', * field2: 'value2' * } * }) * var row2 = new Row({parent: datatable}) * row2.setData({ * data:{ * field1: 'value11', * field2: 'value22' * } * }) * datatable.insertRows(1,[row1,row2]) */ const insertRows = function(index, rows) { var args = [index, 0]; for (var i = 0; i < rows.length; i++) { args.push(rows[i]); } this.rows.splice.apply(this.rows, args); this.updateSelectedIndices(index, '+', rows.length); this.updateFocusIndex(index, '+', rows.length); this.updatePageAll(); var insertRows = []; $.each(rows,function(i){ if(this.status == Row.STATUS.NORMAL || this.status == Row.STATUS.UPDATE || this.status == Row.STATUS.NEW){ insertRows.push(this); } }); this.trigger(DataTable.ON_INSERT, { index: index, rows: insertRows }); if (this.ns) { if (this.root.valueChange[this.ns]) this.root.valueChange[this.ns](-this.root.valueChange[this.ns]()); } }; /** * 创建空行 * @memberof DataTable * @return {u.Row} 空行对象 * @example * datatable.createEmptyRow(); * datatable.createEmptyRow({unSelect:true}) */ const createEmptyRow = function(options) { var r = new Row({ parent: this }); this.addRow(r); var unSelect = options ? options.unSelect : false; if (!unSelect) { if (!this.getCurrentRow()) this.setRowSelect(r); } return r }; const rowFunObj = { setRows: setRows, addRow: addRow, addRows: addRows, insertRow: insertRow, insertRows: insertRows, createEmptyRow: createEmptyRow, resetDelRowEnd: resetDelRowEnd }; /*** * Module : kero dataTable rowCurrent * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-08 09:59:01 */ // 更新当前行对应索引 const updateCurrIndex = function() { var currentIndex = this.focusIndex() != -1 ? this.focusIndex() : this.getSelectedIndex(); if (this._oldCurrentIndex != currentIndex) { this._oldCurrentIndex = currentIndex; this.trigger(DataTable.ON_CURRENT_ROW_CHANGE); this.currentRowChange(-this.currentRowChange()); if (this.ns) { if (this.root.valueChange[this.ns]) this.root.valueChange[this.ns](-this.root.valueChange[this.ns]()); } } }; const rowCurrentFunObj = { updateCurrIndex: updateCurrIndex }; /** * Module : kero dataTable rowDelete * Desc: 不建议使用此库方法 * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /*** * 根据索引删除数据行 * @param {number} index 需要删除数据行的索引 */ const setRowDelete = function(index) { if (index instanceof Row) { index = this.getIndexByRowId(index.rowId); } this.setRowsDelete([index]); }; /*** * 删除所有数据行 */ const setAllRowsDelete = function() { var indices = new Array(this.rows().length); for (var i = 0; i < indices.length; i++) { indices[i] = i; } this.setRowsDelete(indices); }; /*** * 根据索引数组删除数据行 * @param {Array} indices 需要删除数据行的索引数组 */ const setRowsDelete = function(indices, obj) { var forceDel = obj ? obj.forceDel : false; indices = utilFunObj._formatToIndicesArray(this, indices); indices = indices.sort(function(a, b) { return b - a; }); var rowIds = this.getRowIdsByIndices(indices); var rows = this.getRowsByIndices(indices); var ros = this.rows(); for (var i = 0; i < indices.length; i++) { var row = this.getRow(indices[i]); if (row.status == Row.STATUS.NEW || this.forceDel || forceDel) { ros.splice(indices[i], 1); } else { row.setStatus(Row.STATUS.FALSE_DELETE); var temprows = ros.splice(indices[i], 1); ros.push(temprows[0]); } this.updateSelectedIndices(indices[i], '-'); this.updateFocusIndex(indices[i], '-'); } this.rows(ros); this.updateCurrIndex(); this.trigger(DataTable.ON_DELETE, { falseDelete: true, indices: indices, rowIds: rowIds, rows: rows }); }; const rowDeleteFunObj = { setRowDelete: setRowDelete, setAllRowsDelete: setAllRowsDelete, setRowsDelete: setRowsDelete }; /** * Module : kero dataTable rowSelect * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /** * 设置所有行选中 * @memberof DataTable * @example * datatable.setAllRowsSelect() */ const setAllRowsSelect = function() { var indices = new Array(this.rows().length); for (var i = 0; i < indices.length; i++) { indices[i] = i; } this.setRowsSelect(indices); this.allSelected(true); this.trigger(DataTable.ON_ROW_ALLSELECT, {}); }; /** * 根据索引设置选中行,清空之前已选中的所有行 * @memberof DataTable * @param {number} index 需要选中行的索引 * @example * datatable.setRowSelect(1) */ const setRowSelect = function(index) { if (index instanceof Row) { index = this.getIndexByRowId(index.rowId); } this.setRowsSelect([index]); this.setRowFocus(this.getSelectedIndex()); }; /** * 根据索引数组设置选中行,清空之前已选中的所有行 * @memberof DataTable * @param {array} indices 需要选中行的索引数组 * @example * datatable.setRowsSelect([1,2]) */ const setRowsSelect = function(indices) { indices = indices || -1; if (indices == -1) { this.setAllRowsUnSelect({ quiet: true }); return; } indices = utilFunObj._formatToIndicesArray(this, indices); var sIns = this.selectedIndices(); if (isArray(indices) && isArray(sIns) && indices.join() == sIns.join()) { // 避免与控件循环触发 return; } if (isArray(indices)) { var rowNum = this.rows().length; for (var i = 0; i < indices.length; i++) { if (indices[i] < 0 || indices[i] >= rowNum) indices.splice(i, 1); } } this.setAllRowsUnSelect({ quiet: true }); try { this.selectedIndices(indices); } catch (e) { } this.updatePageSelect(); var rowIds = this.getRowIdsByIndices(indices); this.currentRowChange(-this.currentRowChange()); this.trigger(DataTable.ON_ROW_SELECT, { indices: indices, rowIds: rowIds }); this.updateCurrIndex(); this.setRowFocus(indices[0]); }; /** * 根据索引添加选中行,不会清空之前已选中的行 * @memberof DataTable * @param {number} index 需要选中行的索引 * @example * datatable.addRowSelect(1) */ const addRowSelect = function(index) { if (index instanceof Row) { index = this.getIndexByRowId(index.rowId); } this.addRowsSelect([index]); }; /** * 根据索引数组添加选中行,不会清空之前已选中的行 * @memberof DataTable * @param {array} indices 需要选中行的索引数组 * @example * datatabel.addRowsSelect([1,2]) */ const addRowsSelect = function(indices) { indices = utilFunObj._formatToIndicesArray(this, indices); var selectedIndices = this.selectedIndices().slice(); var needTrigger = false; for (var i = 0; i < indices.length; i++) { var ind = indices[i], toAdd = true; for (var j = 0; j < selectedIndices.length; j++) { if (selectedIndices[j] == ind) { toAdd = false; } } //indices[i]存在并且大于-1 if (toAdd && indices[i] > -1) { needTrigger = true; selectedIndices.push(indices[i]); } } this.selectedIndices(selectedIndices); this.updatePageSelect(); var rowIds = this.getRowIdsByIndices(selectedIndices); if (needTrigger) { this.trigger(DataTable.ON_ROW_SELECT, { indices: selectedIndices, rowIds: rowIds }); } this.updateCurrIndex(); }; /** * 全部取消选中 * @memberof DataTable * @param {object} [options] 可选参数 * @param {boolean} [options.quiet] 如果为true则不触发事件,否则触发事件 * @example * datatable.setAllRowsUnSelect() // 全部取消选中 * datatable.setAllRowsUnSelect({quiet:true}) // 全部取消选中,不触发事件 */ const setAllRowsUnSelect = function(options) { this.selectedIndices([]); this.updatePageSelect(); if (!(options && options.quiet)) { this.trigger(DataTable.ON_ROW_ALLUNSELECT); } this.updateCurrIndex(); this.allSelected(false); }; /** * 根据索引取消选中 * @memberof DataTable * @param {number} index 需要取消选中的行索引 * @example * datatable.setRowUnSelect(1) */ const setRowUnSelect = function(index) { if (index instanceof Row) { index = this.getIndexByRowId(index.rowId); } this.setRowsUnSelect([index]); }; /** * 根据索引数组取消选中 * @memberof DataTable * @param {array} indices 需要取消选中的行索引数组 * @example * datatable.setRowsUnSelect([1,2]) */ const setRowsUnSelect = function(indices) { indices = utilFunObj._formatToIndicesArray(this, indices); var selectedIndices = this.selectedIndices().slice(); // 避免与控件循环触发 if (selectedIndices.indexOf(indices[0]) == -1) return; for (var i = 0; i < indices.length; i++) { var index = indices[i]; var pos = selectedIndices.indexOf(index); if (pos != -1) selectedIndices.splice(pos, 1); } this.selectedIndices(selectedIndices); this.updatePageSelect(); var rowIds = this.getRowIdsByIndices(indices); this.trigger(DataTable.ON_ROW_UNSELECT, { indices: indices, rowIds: rowIds }); this.updateCurrIndex(); this.allSelected(false); }; /** * 当全部选中时取消选中,否则全部选中 * @memberof DataTable */ const toggleAllSelect = function() { if (this.allSelected()) { this.setAllRowsUnSelect(); } else { this.setAllRowsSelect(); } }; /*** * 数据行发生改变时更新focusindex * @memberof DataTable * @param {number} index 发生改变的数据行位置 * @param {string} type +表示新增行,-表示减少行 * @param {number} num 新增/减少的行数 */ const updateSelectedIndices = function(index, type, num) { if (!isNumber$1(num)) { num = 1; } var selectedIndices = this.selectedIndices().slice(); if (selectedIndices == null || selectedIndices.length == 0) return for (var i = 0, count = selectedIndices.length; i < count; i++) { if (type == '+') { if (selectedIndices[i] >= index) selectedIndices[i] = parseInt(selectedIndices[i]) + num; } else if (type == '-') { if (selectedIndices[i] >= index && selectedIndices[i] <= index + num - 1) { selectedIndices.splice(i, 1); } else if (selectedIndices[i] > index + num - 1) selectedIndices[i] = selectedIndices[i] - num; } } this.selectedIndices(selectedIndices); this.updatePageSelect(); }; const rowSelectFunObj = { setAllRowsSelect: setAllRowsSelect, setRowSelect: setRowSelect, setRowsSelect: setRowsSelect, addRowSelect: addRowSelect, addRowsSelect: addRowsSelect, setAllRowsUnSelect: setAllRowsUnSelect, setRowUnSelect: setRowUnSelect, setRowsUnSelect: setRowsUnSelect, toggleAllSelect: toggleAllSelect, updateSelectedIndices: updateSelectedIndices }; /** * Module : kero dataTable rowFocus * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-08 09:59:01 */ /** * 设置焦点行 * @memberof DataTable * @param {number|u.Row} index 行对象或者行index * @param {boolean} [quiet] 如果为true则不触发事件,否则触发事件 * @param {boolean} [force] 如果为true当index行与已focus的行相等时,仍然触发事件,否则不触发事件 * @example * datatable.setRowFocus(1) // 设置第二行为焦点行 * datatable.setRowFocus(1,true) // 设置第二行为焦点行,不触发事件 * datatable.setRowFocus(1,false,true) // 设置第二行为焦点行,如果当前焦点行为第二行,仍旧触发事件 */ const setRowFocus = function(index, quiet, force) { var rowId = null; if (index instanceof Row) { index = this.getIndexByRowId(index.rowId); rowId = index.rowId; } if (index === -1 || (index === this.focusIndex() && !force)) { return; } if (this.focusIndex() > -1) { this.setRowUnFocus(this.focusIndex()); } this.focusIndex(index); if (quiet) { return; } this.currentRowChange(-this.currentRowChange()); if (!rowId) { rowId = this.getRow(index).rowId; } this.trigger(DataTable.ON_ROW_FOCUS, { index: index, rowId: rowId }); this.updateCurrIndex(); }; /** * 焦点行反选 * @memberof DataTable * @example * datatable.setRowUnFocus() */ const setRowUnFocus = function() { this.currentRowChange(-this.currentRowChange()); var indx = this.focusIndex(), rowId = null; if (indx !== -1) { rowId = this.getRow(indx).rowId; } this.trigger(DataTable.ON_ROW_UNFOCUS, { index: indx, rowId: rowId }); this.focusIndex(-1); this.updateCurrIndex(); }; /*** * 数据行发生改变时更新focusindex * @memberof DataTable * @param {number} opIndex 发生改变的数据行位置 * @param {string} opType +表示新增行,-表示减少行 * @param {number} num 新增/减少的行数 * */ const updateFocusIndex = function(opIndex, opType, num) { if (!isNumber$1(num)) { num = 1; } if (opIndex <= this.focusIndex() && this.focusIndex() != -1) { if (opType === '+') { this.focusIndex(this.focusIndex() + num); } else if (opType === '-') { if (this.focusIndex() >= opIndex && this.focusIndex() <= opIndex + num - 1) { this.focusIndex(-1); } else if (this.focusIndex() > opIndex + num - 1) { this.focusIndex(this.focusIndex() - num); } } } }; const rowFocusFunObj = { setRowFocus: setRowFocus, setRowUnFocus: setRowUnFocus, updateFocusIndex: updateFocusIndex }; /** * Module : kero dataTable simpleData * Author : liuyk(liuyk@yonyou.com) * Date : 2016-08-01 14:34:01 */ /** * 设置数据, 只设置字段值 * @memberof DataTable * @param {array} data 数据信息 * @param {boject} [options] 可配置参数 * @param {boject} [options.unSelect=false] 是否默认选中第一行,如果为true则不选中第一行,否则选中第一行 * @example * var data = [{ * filed1:'value1', * field2:'value2' * },{ * filed1:'value11', * field2:'value21' * }] * datatable.setSimpleData(data) * datatable.setSimpleData(data,{unSelect:true}) */ const setSimpleData = function(data, options) { this.removeAllRows(); this.cachedPages = []; this.focusIndex(-1); this.selectedIndices([]); this.setSimpleDataReal = []; if (!data) { this.setSimpleDataReal = data; // throw new Error("dataTable.setSimpleData param can't be null!"); return; } var rows = []; if (!isArray(data)) data = [data]; for (var i = 0; i < data.length; i++) { var _data = data[i]; /* 判断data中的字段在datatable中是否存在,如果不存在则创建 */ // for(var f in _data){ // this.createField(f) // } if (typeof data[i] !== 'object') _data = { $data: data[i] }; if (options && options.status) { rows.push({ status: options.status, data: _data }); } else { rows.push({ status: Row.STATUS.NORMAL, data: _data }); } } var _data = { rows: rows }; if (options) { if (typeof options.fieldFlag == 'undefined') { options.fieldFlag = true; } } this.setData(_data, options); }; /** * 追加数据, 只设置字段值 * @memberof DataTable * @param {array} data 数据信息 * @param {string} [status=nrm] 追加数据信息的状态,参照Row对象的状态介绍 * @param {boject} [options] 可配置参数 * @param {boject} [options.unSelect=false] 是否默认选中第一行,如果为true则不选中第一行,否则选中第一行 * @example * var data = [{ * filed1:'value1', * field2:'value2' * },{ * filed1:'value11', * field2:'value21' * }] * datatable.addSimpleData(data,Row.STATUS.NEW) * datatable.addSimpleData(data, null, {unSelect:true}) */ const addSimpleData = function(data, status, options) { if (!data) { throw new Error("dataTable.addSimpleData param can't be null!"); } if (!isArray(data)) data = [data]; for (var i = 0; i < data.length; i++) { var r = this.createEmptyRow(options); r.setSimpleData(data[i], status); } }; const simpleDataFunObj = { setSimpleData: setSimpleData, addSimpleData: addSimpleData }; /** * Module : kero DataTable events * Author : liuyk(liuyk@yonyou.com) * Date : 2016-07-30 14:34:01 */ /** * 为DataTable对象添加监听 * @memberof DataTable * @param {string|array|object} name 针对不同用法分别对应监听名称、监听名称对应的数组、监听名称及对应的回调组成的对象 * @param {function} [callback] 监听对应的回调函数 * @param {boolean} [one] 是否只执行一次监听,为true则表示只执行一次回调函数,否则每次触发监听都是执行回调函数 * @return {DataTable} 当前的DataTable对象 * @example * datatable.on(u.DataTable.ON_ROW_FOCUS, function() {}) // 普通 * datatable.on([u.DataTable.ON_INSERT, u.DataTable.ON_DELETE], function() {}) // 数组 * datatable.on({u.DataTable.ON_INSERT: function() {}, u.DataTable.ON_DELETE: function() {}}) // map */ const on$1 = function(name, callback, one) { var self = this, origCb = callback; if (Object.prototype.toString.call(name) == '[object Array]') { // 数组 for (var i in name) { this.on(name[i], callback); } return this; } else if (typeof name == 'object') { // map for (var key in name) { this.on(key, name[key]); } return this; } if (one) { callback = function() { self.off(name, callback); origCb.apply(this, arguments); }; } name = name.toLowerCase(); this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({ callback: callback }); return this; }; /** * 为DataTable对象取消监听 * @memberof DataTable * @param {string|array|object} name 针对不同用法分别对应监听名称、监听名称对应的数组、监听名称及对应的回调组成的对象 * @param {function} [callback] 监听对应的回调函数 * @return {DataTable} 当前的DataTable对象 * @example * datatable.off(u.DataTable.ON_ROW_FOCUS, function() {}) // 普通 * datatable.off([u.DataTable.ON_INSERT, u.DataTable.ON_DELETE], function() {}) // 数组 * datatable.off({u.DataTable.ON_INSERT: function() {}, u.DataTable.ON_DELETE: function() {}}) // map */ const off$1 = function(name, callback) { name = name.toLowerCase(); if (!this._events) return this; if (Object.prototype.toString.call(name) == '[object Array]') { // 数组 for (var i in name) { this.off(name[i], callback); } return this; } else if (typeof name == 'object') { // map for (var key in name) { this.off(key, name[key]); } return this; } var cbs = this._events[name]; if (!cbs) return this; if (!callback) { // 解绑所有事件 cbs = null; } else { for (var i = cbs.length - 1; i >= 0; i--) { if (cbs[i] == callback) { cbs.splice(i, 1); } } } this._events[name] = cbs; return this; }; /** * 为DataTable对象添加只执行一次的监听 * @memberof DataTable * @param {string|array|object} name 针对不同用法分别对应监听名称、监听名称对应的数组、监听名称及对应的回调组成的对象 * @param {function} [callback] 监听对应的回调函数 * @example * datatable.one(u.DataTable.ON_ROW_FOCUS, function() {}) // 普通 * datatable.one([u.DataTable.ON_INSERT, u.DataTable.ON_DELETE], function() {}) // 数组 * datatable.one({u.DataTable.ON_INSERT: function() {}, u.DataTable.ON_DELETE: function() {}}) // map */ const one = function(name, callback) { this.on(name, callback, 1); }; /** * 触发DataTable对象绑定的事件监听 * @memberof DataTable * @param {string} name 需要触发的事件监听对应的名称 * @return {DataTable} 当前的DataTable对象 * @example * datatable.trigger('valuechange') */ const trigger$1 = function(name) { name = name.toLowerCase(); if (!this._events || !this._events[name]) return this; var args = Array.prototype.slice.call(arguments, 1); var events = this._events[name]; for (var i = 0, count = events.length; i < count; i++) { events[i].callback.apply(this, args); } return this; }; // 带返回值的trigger,可以获取回调函数的返回值 const triggerReturn = function(name) { name = name.toLowerCase(); if (!this._events || !this._events[name]) return this; var args = Array.prototype.slice.call(arguments, 1); var events = this._events[name]; var flag = true; for (var i = 0, count = events.length; i < count; i++) { flag = flag && events[i].callback.apply(this, args); } return flag; }; // 获取监听名称对应的回调函数 const getEvent = function(name) { name = name.toLowerCase(); this._events || (this._events = {}); return this._events[name] }; const eventsFunObj = { on: on$1, off: off$1, one: one, trigger: trigger$1, triggerReturn: triggerReturn, getEvent: getEvent }; /** * Module : Kero webpack entry dataTable index * Author : huyue(huyueb@yonyou.com) * Date : 2016-08-09 15:24:46 */ /** * DataTable * @namespace * @description 前端数据模型对象 */ class DataTable$1 { constructor(options) { options = options || {}; /** * DataTable对应的唯一标识 * @type {string} */ this.id = options['id']; /** * 在设置数据时是否自动创建对应字段,如果为true则不自动创建,如果为false则自动创建缺失的字段 * @type {boolean} * @default false */ this.strict = options['strict'] || false; /** * DataTable的所有字段属性信息 * @type {object} */ this.meta = DataTable$1.createMetaItems(options['meta']); /** * DataTable的是否支持编辑功能 * @type {boolean} * @default true */ this.enable = options['enable'] || DataTable$1.DEFAULTS.enable; /** * DataTable支持翻页功能时每页显示数据条数 * @type {number} * @default 20 */ this.pageSize = ko.observable(options['pageSize'] || DataTable$1.DEFAULTS.pageSize); /** * DataTable支持翻页功能时当前页码 * @type {number} * @default 0 */ this.pageIndex = ko.observable(options['pageIndex'] || DataTable$1.DEFAULTS.pageIndex); /** * DataTable支持翻页功能时总页数 * @type {number} * @default 0 */ this.totalPages = ko.observable(options['totalPages'] || DataTable$1.DEFAULTS.totalPages); // 存储所有行对象 this.totalRow = ko.observable(); /** * DataTable的是否支持前端缓存,支持前端缓存则前端会存储所有页的数据信息,否则只保存当前页的数据信息。如果使用前端缓存则需要使用框架封装的fire方法来与后台进行交互 * @type {boolean} * @default false */ this.pageCache = options['pageCache'] === undefined ? DataTable$1.DEFAULTS.pageCache : options['pageCache']; /** * DataTable删除数据时是否强制删除,如果设置为true则不再考虑数据的状态,执行删除时则删除此条数据。如果设置为false则需要考虑数据的状态,如果状态为new则删除此条数据否则将状态修改为fdel * @type {boolean} * @default false */ this.forceDel = options['forceDel'] === undefined ? DataTable$1.DEFAULTS.forceDel : options['forceDel']; // 存储所有row对象 this.rows = ko.observableArray([]); // 存储所有的选中行的index this.selectedIndices = ko.observableArray([]); // 原有的当前行,用于判断当前行是否发生变化 this._oldCurrentIndex = -1; // 当前focus行 this.focusIndex = ko.observable(-1); // 存储所有页对象 this.cachedPages = []; // 存储meta改变信息 this.metaChange = {}; // 存储valuecahnge改变信息 this.valueChange = {}; //ko.observable(1); // 监听当前行改变 this.currentRowChange = ko.observable(1); // 监听是否可修改属性的改变 this.enableChange = ko.observable(1); /** * 使用者自定义的属性合集,框架内部不会针对此属性进行特殊处理,仅用于设置及获取 * @type {object} */ this.params = options['params'] || {}; /** * 使用者自定义的属性,框架内部不会针对此属性进行特殊处理,仅用于设置及获取。 * @type {string} */ this.master = options['master'] || ''; // 监听是否全部选中 this.allSelected = ko.observable(false); /** * 通过getSimpleData获取数据时,日期字段是否转化为long型,如果为true时不进行转化,为false时转化为long型 * @type {boolean} * @default false */ this.dateNoConvert = options['dateNoConvert'] || false; // 对于子表通过root字段存储根datatable对象 if (options['root']) { this.root = options['root']; } else { this.root = this; } // 记录子表的路径 if (options['ns']) { this.ns = options['ns']; } else { this.ns = ''; } // 前端分页情况下记录前端新增的数据 this.newCount = 0; } } var DataTableProto = DataTable$1.prototype; Object.assign(DataTableProto, copyRowFunObj); Object.assign(DataTableProto, dataFunObj); Object.assign(DataTableProto, enableFunObj); Object.assign(DataTableProto, getCurrentFunObj); Object.assign(DataTableProto, getDataFunObj); Object.assign(DataTableProto, getFocusFunObj); Object.assign(DataTableProto, getMetaFunObj); Object.assign(DataTableProto, getPageFunObj); Object.assign(DataTableProto, getParamFunObj); Object.assign(DataTableProto, getSelectFunObj); Object.assign(DataTableProto, getSimpleDataFunObj); Object.assign(DataTableProto, pageFunObj); Object.assign(DataTableProto, metaFunObj); Object.assign(DataTableProto, refFunObj); Object.assign(DataTableProto, paramFunObj); Object.assign(DataTableProto, rowFunObj); Object.assign(DataTableProto, removeRowFunObj); Object.assign(DataTableProto, rowCurrentFunObj); Object.assign(DataTableProto, simpleDataFunObj); Object.assign(DataTableProto, rowFocusFunObj); Object.assign(DataTableProto, eventsFunObj); Object.assign(DataTableProto, utilFunObj); Object.assign(DataTableProto, rowSelectFunObj); Object.assign(DataTableProto, rowDeleteFunObj); DataTable$1.DEFAULTS = { pageSize: 20, pageIndex: 0, totalPages: 0, pageCache: false, enable: true, forceDel: false }; DataTable$1.META_DEFAULTS = { enable: true, required: false, descs: {} }; //事件类型 DataTable$1.ON_ROW_SELECT = 'select'; DataTable$1.ON_ROW_UNSELECT = 'unSelect'; DataTable$1.ON_ROW_ALLSELECT = 'allSelect'; DataTable$1.ON_ROW_ALLUNSELECT = 'allUnselect'; DataTable$1.ON_VALUE_CHANGE = 'valueChange'; DataTable$1.ON_BEFORE_VALUE_CHANGE = 'beforeValueChange'; DataTable$1.ON_CURRENT_VALUE_CHANGE = 'currentValueChange'; //当前行变化 // DataTable.ON_AFTER_VALUE_CHANGE = 'afterValueChange' // DataTable.ON_ADD_ROW = 'addRow' DataTable$1.ON_INSERT = 'insert'; DataTable$1.ON_UPDATE = 'update'; DataTable$1.ON_CURRENT_UPDATE = 'currentUpdate'; DataTable$1.ON_DELETE = 'delete'; DataTable$1.ON_DELETE_ALL = 'deleteAll'; DataTable$1.ON_ROW_FOCUS = 'focus'; DataTable$1.ON_ROW_UNFOCUS = 'unFocus'; DataTable$1.ON_LOAD = 'load'; DataTable$1.ON_ENABLE_CHANGE = 'enableChange'; DataTable$1.ON_META_CHANGE = 'metaChange'; DataTable$1.ON_ROW_META_CHANGE = 'rowMetaChange'; DataTable$1.ON_CURRENT_META_CHANGE = 'currentMetaChange'; DataTable$1.ON_CURRENT_ROW_CHANGE = 'currentRowChange'; DataTable$1.SUBMIT = { current: 'current', focus: 'focus', all: 'all', select: 'select', change: 'change', empty: 'empty', allSelect: 'allSelect', allPages: 'allPages' }; /** * 将默认meta与传入进行的meta对象进行合并 * meta: { f1: { enable:false } } newMetas:{ f1:{ enable:false, required:false, descs:{ } } } */ DataTable$1.createMetaItems = function(metas) { var newMetas = {}; for (var key in metas) { var meta = metas[key]; if (typeof meta == 'string') meta = {}; newMetas[key] = extend({}, DataTable$1.META_DEFAULTS, meta); } return newMetas }; /** * Module : Kero tree adapter * Author : Kvkens(yueming@yonyou.com) * Date : 2016-08-16 10:44:14 */ var TreeAdapter = u.BaseAdapter.extend({ mixins: [], init: function() { var options = this.options, opt = options || {}, viewModel = this.viewModel; var element = this.element; this.id = opt['id']; var oThis = this; this.dataTable = getJSObject(viewModel, options["data"]); this.element = element; this.$element = $(element); this.id = options['id']; this.element.id = this.id; this.options = options; this.events = $.extend(true, {}, options.events); var treeSettingDefault = { // async: { //缓加载 // enable: oThis.options.asyncFlag, // url: oThis.options.asyncFun // }, data: { simpleData: { enable: true } }, check: { chkboxType: { "Y": "", "N": "" } }, callback: { //点击前 beforeClick: function(e, id, node) { if (oThis.events.beforeClick) { getFunction(viewModel, oThis.events.beforeClick)(e, id, node); } }, // 选中/取消选中事件 onCheck: function(e, id, node) { if (oThis.selectSilence) { return; } var nodes = oThis.tree.getCheckedNodes(); var nowSelectIndexs = oThis.dataTable.getSelectedIndexs(); var indexArr = []; for (var i = 0; i < nodes.length; i++) { // 获取到节点的idValue var idValue = nodes[i].id; // 根据idValue查找到对应数据的rowId var rowId = oThis.getRowIdByIdValue(idValue); var index = oThis.dataTable.getIndexByRowId(rowId); indexArr.push(index); } // 比较2个数组的差异然后进行选中及反选 var needSelectArr = []; for (var i = 0; i < indexArr.length; i++) { var nowIndex = indexArr[i]; var hasFlag = false; for (var j = 0; j < nowSelectIndexs.length; j++) { if (nowIndex == nowSelectIndexs[j]) { hasFlag = true; break; } } if (!hasFlag) { needSelectArr.push(nowIndex); } } var needUnSelectArr = []; for (var i = 0; i < nowSelectIndexs.length; i++) { var nowIndex = nowSelectIndexs[i]; var hasFlag = false; for (var j = 0; j < indexArr.length; j++) { if (nowIndex == indexArr[j]) { hasFlag = true; break; } } if (!hasFlag) { needUnSelectArr.push(nowIndex); } } oThis.dataTable.addRowsSelect(needSelectArr); oThis.dataTable.setRowsUnSelect(needUnSelectArr); // 获取到节点的idValue var idValue = node.id; // 根据idValue查找到对应数据的rowId var rowId = oThis.getRowIdByIdValue(idValue); var index = oThis.dataTable.getIndexByRowId(rowId); oThis.dataTable.setRowFocus(index); }, // 单选时点击触发选中 onClick: function(e, id, node) { if (oThis.selectSilence) { return; } //点击时取消所有超链接效果 $('#' + id + ' li').removeClass('focusNode'); $('#' + id + ' a').removeClass('focusNode'); //添加focusNode样式 $('#' + node.tId).addClass('focusNode'); $('#' + node.tId + '_a').addClass('focusNode'); // 获取到节点的idValue var idValue = node.id; // 根据idValue查找到对应数据的rowId var rowId = oThis.getRowIdByIdValue(idValue); var index = oThis.dataTable.getIndexByRowId(rowId); //上面这种情况说明是checkbox选中需要addRowSelect if (oThis.tree.setting.check.enable && oThis.tree.setting.check.chkStyle === 'checkbox') { oThis.dataTable.addRowSelect(index); } else { oThis.dataTable.setRowSelect(index); } oThis.dataTable.setRowFocus(index); if (oThis.events.onClick) { getFunction(viewModel, oThis.events.onClick)(e, id, node); } } } }; var setting = {}; if (this.options.setting) { //if (typeof(JSON) == "undefined") // setting = eval("(" + this.options.setting + ")"); //else setting = getJSObject(viewModel, this.options.setting) || getJSObject(window, this.options.setting); } // 遍历callback先执行默认之后再执行用户自定义的。 var callbackObj = treeSettingDefault.callback; var userCallbackObj = setting.callback; var callbackObj = treeSettingDefault.callback; var userCallbackObj = setting.callback; var userBeforeClick = userCallbackObj && userCallbackObj['beforeClick']; if (userBeforeClick) { var newBeforeClick = function() { callbackObj['beforeClick'].apply(this, arguments); userBeforeClick.apply(this, arguments); }; userCallbackObj['beforeClick'] = newBeforeClick; } var userOnCheck = userCallbackObj && userCallbackObj['onCheck']; if (userOnCheck) { var newOnCheck = function() { callbackObj['onCheck'].apply(this, arguments); userOnCheck.apply(this, arguments); }; userCallbackObj['onCheck'] = newOnCheck; } var userOnClick = userCallbackObj && userCallbackObj['onClick']; if (userOnClick) { var newOnClick = function() { callbackObj['onClick'].apply(this, arguments); userOnClick.apply(this, arguments); }; userCallbackObj['onClick'] = newOnClick; } /*for(var f in callbackObj){ var fun = callbackObj[f], userFun = userCallbackObj && userCallbackObj[f]; if(userFun){ var newF = function(){ fun.apply(this,arguments); userFun.apply(this,arguments); } userCallbackObj[f] = newF; } }*/ var treeSetting = $.extend(true, {}, treeSettingDefault, setting); var treeData = []; // 根据idField、pidField、nameField构建ztree所需data var data = this.dataTable.rows(); if (data.length > 0) { if (this.options.codeTree) { // 首先按照string进行排序 data.sort(function(a, b) { var aObj = a.data; var bObj = b.data; var v1 = aObj[oThis.options.idField].value + ''; var v2 = bObj[oThis.options.idField].value + ''; try { return v1.localeCompare(v2); } catch (e) { return 0; } }); var idArr = new Array(); $.each(data, function() { var dataObj = this.data; var idValue = dataObj[oThis.options.idField].value; idArr.push(idValue); }); var preValue = ''; $.each(data, function() { var value = oThis.cloneValue(this.data); var dataObj = this.data; var idValue = dataObj[oThis.options.idField].value; var nameValue = dataObj[oThis.options.nameField].value; var pidValue = ''; var startFlag = -1; // 如果当前值包含上一个值则上一个值为pid if (preValue != '') { var startFlag = idValue.indexOf(preValue); } if (startFlag == 0) { pidValue = preValue; } else { for (var i = 1; i < preValue.length; i++) { var s = preValue.substr(0, i); var f = idValue.indexOf(s); if (f == 0) { var index = $.inArray(s, idArr); if (index > 0 || index == 0) { pidValue = s; } } else { break; } } } value['id'] = idValue; value['pId'] = pidValue; value['name'] = nameValue; treeData.push(value); preValue = idValue; }); } else { var values = new Array(); $.each(data, function() { var value = oThis.cloneValue(this.data); var dataObj = this.data; var idValue = dataObj[oThis.options.idField].value; var pidValue = dataObj[oThis.options.pidField].value; var nameValue = dataObj[oThis.options.nameField].value; value['id'] = idValue; value['pId'] = pidValue; value['name'] = nameValue; treeData.push(value); }); } } this.tree = $.fn.zTree.init(this.$element, treeSetting, treeData); // dataTable事件 this.dataTable.on(DataTable$1.ON_ROW_SELECT, function(event) { oThis.selectSilence = true; var nodes = oThis.tree.getCheckedNodes(); $.each(nodes, function() { var node = this; if (oThis.tree.setting.view.selectedMulti == true && node.checked) { oThis.tree.checkNode(node, false, true, true); } else { oThis.tree.cancelSelectedNode(node); } }); /*index转化为grid的index*/ $.each(event.rowIds, function() { var row = oThis.dataTable.getRowByRowId(this); var dataObj = row.data; var idValue = dataObj[oThis.options.idField].value; var node = oThis.tree.getNodeByParam('id', idValue); if (oThis.tree.setting.view.selectedMulti == true) { if (!node.checked) oThis.tree.checkNode(node, true, false, true); } else { oThis.tree.selectNode(node, false); } }); oThis.selectSilence = false; }); this.dataTable.on(DataTable$1.ON_ROW_UNSELECT, function(event) { /*index转化为grid的index*/ $.each(event.rowIds, function() { var row = oThis.dataTable.getRowByRowId(this); var dataObj = row.data; var idValue = dataObj[oThis.options.idField].value; var node = oThis.tree.getNodeByParam('id', idValue); if (oThis.tree.setting.view.selectedMulti == true && node.checked) { oThis.tree.checkNode(node, false, true, true); } else { oThis.tree.cancelSelectedNode(node); } }); }); this.dataTable.on(DataTable$1.ON_INSERT, function(event) { //var gridRows = new Array(); var dataArray = [], nodes = []; var hasChild = false; //是否含有子节点 $.each(event.rows, function() { var value = oThis.cloneValue(this.data), hasPar = false; var dataObj = this.data; var idValue = dataObj[oThis.options.idField].value; var pidValue = dataObj[oThis.options.pidField].value; var nameValue = dataObj[oThis.options.nameField].value; value['id'] = idValue; value['pId'] = pidValue; value['name'] = nameValue; var childNode = oThis.tree.getNodeByParam('pid', idValue); var pNode = oThis.tree.getNodeByParam('id', pidValue); if (childNode && childNode.length > 0) { hasChild = true; } if (pNode && pNode.length > 0) { hasPar = true; //oThis.tree.addNodes(pNode, value, true); } if (!hasChild && hasPar) { //不存在子节点,存在父节点之间插入 oThis.tree.addNodes(pNode, value, true); } else { dataArray.push(value); } }); if (!hasChild) { //如果没有子节点,将当前节点作为根节点之间插入 nodes = oThis.tree.transformTozTreeNodes(dataArray); oThis.tree.addNodes(null, nodes, true, event.index); } else { //如果含有子节点,重新渲染 } }); this.dataTable.on(DataTable$1.ON_DELETE, function(event) { /*index转化为grid的index*/ $.each(event.rows, function() { var row = this; var idValue = row.getValue(oThis.options.idField); var node = oThis.tree.getNodeByParam('id', idValue); oThis.tree.removeNode(node); }); }); this.dataTable.on(DataTable$1.ON_DELETE_ALL, function(event) { var nodes = oThis.tree.getNodes(); for (var i = 0, l = nodes.length; i < l; i++) { var node = oThis.tree.getNodeByParam('id', nodes[i].id); oThis.tree.removeNode(node); i--; l = nodes.length; } }); // 加载数据,只考虑viewModel传入grid this.dataTable.on(DataTable$1.ON_LOAD, function(data) { var data = oThis.dataTable.rows(); if (data.length > 0) { var values = new Array(); $.each(data, function() { var value = {}; var dataObj = this.data; var idValue = dataObj[oThis.options.idField].value; var pidValue = dataObj[oThis.options.pidField].value; var nameValue = dataObj[oThis.options.nameField].value; value['id'] = idValue; value['pId'] = pidValue; value['name'] = nameValue; treeData.push(value); }); } this.tree = $.fn.zTree.init(this.$element, treeSetting, treeData); }); this.dataTable.on(DataTable$1.ON_VALUE_CHANGE, function(event) { var row = oThis.dataTable.getRowByRowId(event.rowId); if (!row) return var treeArray = oThis.tree.getNodes(); var id = row.getValue(oThis.options.idField); var node = oThis.tree.getNodeByParam('id', id); if (!node && treeArray) { //如果node为null则取树数组的最后一个节点 node = treeArray[treeArray.length - 1]; } var field = event.field; var value = event.newValue; if (oThis.options.idField == field && node) { node.id = value; oThis.tree.updateNode(node); } if (oThis.options.nameField == field && node) { node.name = value; oThis.tree.updateNode(node); } else if (oThis.options.pidField == field) { var targetNode = oThis.tree.getNodeByParam('id', value); oThis.tree.moveNode(targetNode, node, "inner"); } }); // 通过树id获取dataTable的rowId this.getRowIdByIdValue = function(idValue) { var oThis = this; var rowId = null; $.each(this.dataTable.rows(), function() { var dataObj = this.data; var id = this.rowId; if (dataObj[oThis.options.idField].value == idValue) { rowId = id; } }); return rowId; }; return this; }, getName: function() { return 'tree' }, cloneValue: function(Data) { var newData = {}; for (var field in Data) { var value = Data[field].value; newData[field] = value; } return newData; } }); if (u.compMgr) u.compMgr.addDataAdapter({ adapter: TreeAdapter, name: 'tree' //dataType: 'float' }); exports.TreeAdapter = TreeAdapter; }((this.bar = this.bar || {})));
function BounceGA(gaConfig, fitnessConfig) { /* TO DO - fill in unprovided inputs */ this.gaConfig = gaConfig; this.fitnessConfig = fitnessConfig; /* get axes for surfaces, surfaces will always have bottom edge perpendicular to y-axis */ for (var i = 0; i < this.fitnessConfig.surfaces.length; i++) { var surface = this.fitnessConfig.surfaces[i]; surface.normal.normalize(); var axis1; if (surface.normal.x == 0 && surface.normal.z == 0) { axis1 = new THREE.Vector3(1,0,0); } else { axis1 = new THREE.Vector3(-surface.normal.z,0,surface.normal.x); } var axis2 = (new THREE.Vector3()).crossVectors(surface.normal,axis1); axis1.normalize().multiplyScalar(surface.scale); axis2.normalize().multiplyScalar(surface.scale); surface.axis1 = axis1; surface.axis2 = axis2; } this.generations = 0; this.rankedPopulation = []; // the current, ranked, population this.fittestMembers = []; // array of the fittest members by generation this.ableToFindSolution = undefined; } BounceGA.prototype.getBouncePath = function(v) { var pt = (new THREE.Vector3()).copy(this.fitnessConfig.p0); var vt = (new THREE.Vector3()).copy(v); var p = []; p.push((new THREE.Vector3()).copy(pt)); // reset surfaces for (var i = 0; i < this.fitnessConfig.surfaces.length; i++) { this.fitnessConfig.surfaces[i].bounces = 0; this.fitnessConfig.surfaces[i].colliding = false; } var totalBounces = 0; var actualBounceOrder = []; var pTchoices = []; for (var t = 0; t <= this.fitnessConfig.maxT; t += this.fitnessConfig.dt) { // update position / velocity pt.add((new THREE.Vector3()).add(vt).multiplyScalar(this.fitnessConfig.dt)); vt.y += this.fitnessConfig.G*this.fitnessConfig.dt; p.push((new THREE.Vector3()).copy(pt)); // check for collisions for (var i = 0; i < this.fitnessConfig.surfaces.length; i++) { var surface = this.fitnessConfig.surfaces[i]; var distance = (surface.normal.x*pt.x + surface.normal.y*pt.y + surface.normal.z*pt.z - surface.normal.x*surface.position.x - surface.normal.y*surface.position.y - surface.normal.z*surface.position.z); if ( Math.abs(distance) <= this.fitnessConfig.R // distance from plane is within radius && Math.abs((new THREE.Vector3()).subVectors(pt,surface.position).dot(surface.axis1)) <= surface.scale // ball is within range of surface && Math.abs((new THREE.Vector3()).subVectors(pt,surface.position).dot(surface.axis2)) <= surface.scale && !surface.colliding ) { surface.colliding = true; surface.bounces++; actualBounceOrder.push(i); totalBounces++; //new velocity from bounce var bounceV = (new THREE.Vector3()).copy(surface.normal); bounceV.multiplyScalar(vt.dot(surface.normal)).multiplyScalar(2*this.fitnessConfig.C); /* if the surface normal and the velocity are in opposite directions, make sure to negate the bounceV */ bounceV.negate(); vt.add(bounceV); } else if (Math.abs(distance) > this.fitnessConfig.R && surface.colliding) { surface.colliding = false; } } if (t >= this.fitnessConfig.minT) { /* if bounce order is specified, check that it is followed */ var correctBounceOrder = true; if (this.fitnessConfig.surfaceBounceOrder && actualBounceOrder.toString() != this.fitnessConfig.surfaceBounceOrder.toString()) { correctBounceOrder = false; } var enoughBounces = false; /* check that the total number of bounces was correct */ if (totalBounces == this.fitnessConfig.numBounces) { enoughBounces = true; } // must match expected number of bounces, otherwise fitness is terrible if ( correctBounceOrder && enoughBounces && ( (this.fitnessConfig.catchSign == 1 && vt.y >= 0) || (this.fitnessConfig.catchSign == -1 && vt.y <= 0 ) || this.fitnessConfig.catchSign == undefined ) && ( (this.fitnessConfig.tossSign == 1 && v.y >= 0) || (this.fitnessConfig.tossSign == -1 && v.y <= 0 ) || this.fitnessConfig.tossSign == undefined ) ) { pTchoices.push({ pT: pt, T: t, actualpT: this.fitnessConfig.pT // need this for comparator function below }); //return {path: p, T: t}; } } } if (pTchoices.length > 0) { // go through pT choices and grab the best pTchoices.sort(function(a,b) { return a.pT.distanceTo(a.actualpT) - b.pT.distanceTo(a.actualpT); }); return {path: p.splice(0,pTchoices[0].T/this.fitnessConfig.dt), T: pTchoices[0].T}; } else { return {path: undefined, T: undefined}; } } BounceGA.prototype.generateMember = function(parent) { var v = new THREE.Vector3(); if (parent && parent.fitness < 100) { if (Math.random() < this.gaConfig.mutationChance) { v.x = (1-2*Math.random())*(parent.fitness < this.gaConfig.mutationScale ? parent.fitness : this.gaConfig.mutationScale); v.y = (1-2*Math.random())*(parent.fitness < this.gaConfig.mutationScale ? parent.fitness : this.gaConfig.mutationScale); v.z = (1-2*Math.random())*(parent.fitness < this.gaConfig.mutationScale ? parent.fitness : this.gaConfig.mutationScale); v.add(parent.v); } else { v.copy(parent.v); } } else { // v.x = getRandomV(); // v.y = getRandomV(); // v.z = getRandomV(); // should always be tossing towards the first bounce surface // TO DO - get this working... var targetSurface; if(this.fitnessConfig.surfaceBounceOrder) { targetSurface = this.fitnessConfig.surfaces[this.fitnessConfig.surfaceBounceOrder[0]]; } else { targetSurface = this.fitnessConfig.surfaces[Math.floor(Math.random()*this.fitnessConfig.surfaces.length)]; } // first find a random spot on the surface v.copy(targetSurface.position); v.add((new THREE.Vector3()).copy(targetSurface.axis1).multiplyScalar(1-2*Math.random())); v.add((new THREE.Vector3()).copy(targetSurface.axis2).multiplyScalar(1-2*Math.random())); // save and remove the y component var targetY = v.y; v.y = 0; var p0copy = (new THREE.Vector3()).copy(this.fitnessConfig.p0); p0copy.y = 0; var pTcopy = (new THREE.Vector3()).copy(this.fitnessConfig.pT); pTcopy.y = 0; // the minimum possible velocity is for us to get to this spot at the half-way point // var minV = p0copy.distanceTo(v)+pTcopy.distanceTo(v) / (this.fitnessConfig.maxT); // maximum velocity is for us to go directly to the spot and back in minT // ACTUALLY THIS SHOULD BE HIGHER // var maxV = (p0copy.distanceTo(v)+pTcopy.distanceTo(v) / (this.fitnessConfig.minT))/this.fitnessConfig.C; var minV = 0; var maxV = this.gaConfig.initialScale; // create velocity vector from p0 to random spot on surface v.sub(this.fitnessConfig.p0); v.normalize(); v.multiplyScalar(minV + (maxV-minV)*Math.random()); // now get minV and maxV for y-component // the min velocity (or max velocity down) is either 0 if tossSign is 1 or targetY is above, or the time it takes to bounce back from straight down // this calculation is naively simplified to not consider C or G, may need to refactor minV = (this.fitnessConfig.tossSign == 1 || targetY > this.fitnessConfig.p0.y) ? 0 : -( (this.fitnessConfig.p0.y - targetY)*2 / (this.fitnessConfig.minT) ); // the max velocity is either 0 if tossSign is -1 or the time it takes to get back from a straight toss up //maxV = (this.fitnessConfig.pT.y - this.fitnessConfig.p0.y - .5*this.fitnessConfig.G*this.fitnessConfig.maxT*this.fitnessConfig.maxT)/this.fitnessConfig.maxT; maxV = this.gaConfig.initialScale; v.y = minV + (maxV-minV)*Math.random(); } var bouncePath = this.getBouncePath(v); return { v: v, T: bouncePath.T, fitness: bouncePath.path ? bouncePath.path[bouncePath.path.length-1].distanceTo(this.fitnessConfig.pT) : 100 }; } BounceGA.prototype.evolve = function() { if (this.generations >= this.gaConfig.maxGenerations) { this.ableToFindSolution = false; } else if (this.rankedPopulation.length > 0 && this.rankedPopulation[0].fitness <= this.gaConfig.fitnessThreshold) { this.ableToFindSolution = true; } else { /* if this is first generation, we have no viable solutions yet, or we the noGA flag is set create them all from scratch */ if (this.rankedPopulation.length == 0 || this.gaConfig.noGA) { this.rankedPopulation = []; // just make sure the population is empty for (var i = 0; i < this.gaConfig.populationSize; i++) { this.rankedPopulation.push(this.generateMember(undefined)); } } /* otherwise create the next generation */ else { /* we want to create a selection bias based on the fitness */ var totalWeights = 0; var selectorHelper = []; for (var i = 0; i < this.rankedPopulation.length; i++) { totalWeights += 1/this.rankedPopulation[i].fitness; selectorHelper.push(totalWeights); } /* select and mutate to create new members using the weighted selector helper array, so we'll pick more of the better members */ var newPopulation = []; for (var i = 0; i < this.gaConfig.populationSize; i++) { // make half the population completely new members, the other half choose based on fitness if (i < this.gaConfig.populationSize/2) { newPopulation.push(this.generateMember(undefined)); } else { var rand = Math.random()*totalWeights; for (var j = 0; j < selectorHelper.length; j++) { if (rand < selectorHelper[j]) { newPopulation.push(this.generateMember(this.rankedPopulation[j])); break; } } } } this.rankedPopulation = newPopulation; } /* sort population, hence the variable name */ this.rankedPopulation.sort(function(a,b) { return a.fitness - b.fitness; }); this.fittestMembers.push(this.rankedPopulation[0]); this.generations++; /* call evolve again, make sure to use setTimeout so we don't lock the browser */ var self = this; setTimeout(function() { self.evolve(); }, 0); } } function Animator(ga) { var container, width, height, camera, scene, renderer, /* camera starting point */ camTheta = Math.PI, camPhi = .3, camRadius = 5, /* helpers for mouse interaction */ isMouseDown = false, onMouseDownTheta, onMouseDownPhi, onMouseDownPosition; container = $('#animationContainer'); width = container.width(); height = container.height(); camera = new THREE.PerspectiveCamera( 75, width / height, .05, 100 ); updateCamera(); scene = new THREE.Scene(); /* lights */ var ceilingLight = new THREE.PointLight( 0xffffff ); ceilingLight.position.set(0,20,0); scene.add( ceilingLight ); /* surfaces */ for (var i = 0; i < ga.fitnessConfig.surfaces.length; i++) { var surface = ga.fitnessConfig.surfaces[i]; var surfaceGeom = new THREE.Geometry(); surfaceGeom.vertices.push( (new THREE.Vector3()).copy(surface.position).add((new THREE.Vector3()).add(surface.axis1).add(surface.axis2)) ); surfaceGeom.vertices.push( (new THREE.Vector3()).copy(surface.position).add((new THREE.Vector3()).add(surface.axis1).negate().add(surface.axis2)) ); surfaceGeom.vertices.push( (new THREE.Vector3()).copy(surface.position).add((new THREE.Vector3()).add(surface.axis1).add(surface.axis2).negate()) ); surfaceGeom.vertices.push( (new THREE.Vector3()).copy(surface.position).add((new THREE.Vector3()).add(surface.axis2).negate().add(surface.axis1)) ); surfaceGeom.faces.push( new THREE.Face3( 0, 1, 2 ) ); surfaceGeom.faces.push( new THREE.Face3( 2, 0, 3 ) ); var surfaceMesh = new THREE.Mesh(surfaceGeom, new THREE.MeshBasicMaterial( { color: 'grey', side: THREE.DoubleSide } )); scene.add(surfaceMesh); } /* draw ball */ var ballMesh = new THREE.Mesh(new THREE.SphereGeometry( .1, 32, 32 ), new THREE.MeshBasicMaterial( { color: 'red' } )); ballMesh.position = ga.fitnessConfig.p0; scene.add(ballMesh); var targetMesh = new THREE.Mesh(new THREE.SphereGeometry( .1, 32, 32 ), new THREE.MeshBasicMaterial( { color: 'green' } )); targetMesh.position = ga.fitnessConfig.pT; scene.add(targetMesh); /* add axes for debugging */ axes = buildAxes( 1 ); scene.add(axes); /* create the renderer and add it to the canvas container */ if( !window.WebGLRenderingContext ) { renderer = new THREE.CanvasRenderer(); } else { renderer = new THREE.WebGLRenderer( {antialias: true} ); } renderer.setSize( width, height ); container.empty(); container.append(renderer.domElement); //add the event listeners for mouse interaction renderer.domElement.addEventListener( 'mousemove', onDocumentMouseMove, false ); renderer.domElement.addEventListener( 'mousedown', onDocumentMouseDown, false ); renderer.domElement.addEventListener( 'mouseup', onDocumentMouseUp, false ); renderer.domElement.addEventListener( 'mousewheel', onDocumentMouseWheel, false ); onMouseDownPosition = new THREE.Vector2(); renderer.setClearColor( 0xffffff, 1); renderer.render(scene,camera); function updateCamera() { camera.position.x = camRadius * Math.sin( camTheta ) * Math.cos( camPhi ); camera.position.y = camRadius * Math.sin( camPhi ); camera.position.z = camRadius * Math.cos( camTheta ) * Math.cos( camPhi ); camera.lookAt(new THREE.Vector3(0,1,0)); } /* got the camera rotation code from: http://www.mrdoob.com/projects/voxels/#A/ */ function onDocumentMouseDown( event ) { isMouseDown = true; onMouseDownTheta = camTheta; onMouseDownPhi = camPhi; onMouseDownPosition.x = event.clientX; onMouseDownPosition.y = event.clientY; } function onDocumentMouseMove( event ) { event.preventDefault(); if ( isMouseDown ) { camTheta = - ( ( event.clientX - onMouseDownPosition.x ) * 0.01 ) + onMouseDownTheta; var dy = event.clientY - onMouseDownPosition.y; var newCamPhi = ( ( dy ) * 0.01 ) + onMouseDownPhi; if (newCamPhi < Math.PI/2 && newCamPhi > -Math.PI/2) { camPhi = newCamPhi; } } updateCamera(); renderer.render(scene, camera); } function onDocumentMouseUp( event ) { event.preventDefault(); isMouseDown = false; } function onDocumentMouseWheel( event ) { camRadius -= event.wheelDeltaY*.01; } function buildAxes( length ) { var axes = new THREE.Object3D(); axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( length, 0, 0 ), 0xFF0000 ) ); // +X axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( -length, 0, 0 ), 0xFF0000) ); // -X axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, length, 0 ), 0x00FF00 ) ); // +Y axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, -length, 0 ), 0x00FF00 ) ); // -Y axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, length ), 0x0000FF ) ); // +Z axes.add( buildAxis( new THREE.Vector3( 0, 0, 0 ), new THREE.Vector3( 0, 0, -length ), 0x0000FF ) ); // -Z return axes; } function buildAxis( src, dst, colorHex, dashed ) { var geom = new THREE.Geometry(), mat; if(dashed) { mat = new THREE.LineDashedMaterial({ linewidth: 3, color: colorHex, dashSize: 3, gapSize: 3 }); } else { mat = new THREE.LineBasicMaterial({ linewidth: 3, color: colorHex }); } geom.vertices.push( src.clone() ); geom.vertices.push( dst.clone() ); geom.computeLineDistances(); // This one is SUPER important, otherwise dashed lines will appear as simple plain lines var axis = new THREE.Line( geom, mat, THREE.LinePieces ); return axis; } this.animate = function(bouncePath,startTime) { if (startTime === undefined) { startTime = (new Date()).getTime(); } var animationSpeed = 1; /* find time in the pattern and translate that to a discrete step in the prop position arrays */ var timeElapsed = ((new Date()).getTime() - startTime)*animationSpeed/1000; var t = timeElapsed % bouncePath.T; // need to *1000 b/c timeElapsed is in ms var step = Math.floor(t/bouncePath.T*bouncePath.path.length); ballMesh.position = bouncePath.path[step]; renderer.render(scene, camera); if (timeElapsed < bouncePath.T) { var self = this; requestAnimationFrame(function() { self.animate(bouncePath,startTime); }); } } } function reportStats(ga) { var bestFitness; var T; if (ga.fittestMembers[ga.generations-1].fitness < 100) { bestFitness = ga.fittestMembers[ga.generations-1].fitness; T = ga.fittestMembers[ga.generations-1].T; var msg = 'Generation ' + ga.generations + ', best fitness: ' + bestFitness.toFixed(2) + ', ' + T.toFixed(2) + 's'; $('#stats').append('<a href="#" onclick="animator.animate(ga.getBouncePath(ga.fittestMembers[' + (ga.generations-1).toString() + '].v))">'+msg+'</span><br/>'); } if (ga.ableToFindSolution === undefined) { setTimeout(function() { reportStats(ga); },100); } } function getConfigFromInput() { var input = $('#fitness').val().split('\n'); /* p0.x,p0.y,p0.z,pT.x,pT.y,pT.z,T R,C numBounces,bounceOrder tossSign,catchSign surface1 surface2 surfaceN */ var posAndTime = input[0].split(','); var p0 = new THREE.Vector3(parseFloat(posAndTime[0]),parseFloat(posAndTime[1]),parseFloat(posAndTime[2])); var pT = new THREE.Vector3(parseFloat(posAndTime[3]),parseFloat(posAndTime[4]),parseFloat(posAndTime[5])); var minT = parseFloat(posAndTime[6]); var maxT = parseFloat(posAndTime[7]); var ballProperties = input[1].split(','); var R = parseFloat(ballProperties[0]); var C = parseFloat(ballProperties[1]); var bounces = input[2].split(','); var numBounces = parseInt(bounces[0]); var surfaceBounceOrder = undefined; if (bounces.length > 1) { surfaceBounceOrder = bounces.splice(1).map(function(a) { return parseInt(a); }); } var tossCatchSigns = input[3].split(','); var tossSign = tossCatchSigns[0].trim() == 'u' ? undefined : parseInt(tossCatchSigns[0]); var catchSign = tossCatchSigns[1].trim() == 'u' ? undefined : parseInt(tossCatchSigns[1]); var surfaces = []; for (var i = 4; i < input.length; i++) { var surfaceProperties = input[i].split(','); var normal = new THREE.Vector3(parseFloat(surfaceProperties[0]),parseFloat(surfaceProperties[1]),parseFloat(surfaceProperties[2])); var position = new THREE.Vector3(parseFloat(surfaceProperties[3]),parseFloat(surfaceProperties[4]),parseFloat(surfaceProperties[5])); var scale = surfaceProperties[6]; surfaces.push({ normal: normal, position: position, scale: scale }); } var fitnessConfig = { p0: p0, pT: pT, minT: minT, maxT: maxT, R: R, C: C, dt: .01, G: -9.8, numBounces: numBounces, surfaceBounceOrder: surfaceBounceOrder, tossSign: tossSign, catchSign: catchSign, surfaces: surfaces }; input = $('#ga').val().split(','); var gaConfig = { maxGenerations: parseInt(input[0]), populationSize: parseInt(input[1]), mutationChance: parseFloat(input[2]), mutationScale: parseFloat(input[3]), initialScale: parseFloat(input[4]), fitnessThreshold: parseFloat(input[5]), noGA: input.length > 6 && input[6] == 1 ? true : false } return {fitnessConfig: fitnessConfig, gaConfig: gaConfig}; } var ga; var animator; function go() { var configs = getConfigFromInput(); ga = new BounceGA(configs.gaConfig,configs.fitnessConfig); var done = ga.evolve(); animator = new Animator(ga); function runAnimation() { if (ga.ableToFindSolution == true) { animator.animate(ga.getBouncePath(ga.fittestMembers[ga.fittestMembers.length-1].v)); } else { setTimeout(runAnimation,0); } } $('#stats').empty(); setTimeout(function() { reportStats(ga); },0); setTimeout(runAnimation,0); } function setExample(i) { switch (i) { case 0: $('#fitness').val("-.5,1.5,0, .5,1.5,0, 1.5,2\n\ .05, .97\n\ 1\n\ 1, -1\n\ 0,1,0, 0,0,0, 1"); break; case 1: $('#fitness').val("-.5,1.5,0, .5,1.5,0, 2,2.1\n\ .05, .97\n\ 2, 0,1\n\ u, u\n\ .4,1,-.3, -1,0,1, 1\n\ -.4,1,-.3, 1,0,1, 1"); break; case 2: $('#fitness').val("-.5,1.5,0, .5,1.5,0, .3,1\n\ .05, .97\n\ 2\n\ u, u\n\ 1,0,0, 1,2,0, 2\n\ 1,0,0, -1,2,0, 2"); break; case 3: $('#fitness').val("-.5,1.5,0, .5,1.5,0, 2,3\n\ .05, .97\n\ 3, 1,2,0\n\ u, u\n\ 1,0,0, 1,2,0, 1\n\ 1,0,0, -1,2,0, 1\n\ 0,1,0, 0,0,0, 1"); break; } } setExample(0);
const expect = require('chai').expect; const utils = require('../lib/utils/utils'); const AcceptsParser = utils.AcceptsParser; const traverseJson = utils.traverseJson; const returnsParser = utils.returnsParser; const returnClasses = utils.returnClasses; let accepts; describe('Traverse json', () => { it('should recurcive traverse json and apply function to value', () => { let json = { PersistedModel: 'content', folder: { SomeModel: 'another content', }, }; let traverseFn = value => 'hello ' + value; let modifiedJson = traverseJson(json, {}, traverseFn); expect(modifiedJson).to.be.deep.equal({ PersistedModel: 'hello content', folder: { SomeModel: 'hello another content', }, }); }); }); describe('AcceptsParser filtering accept params', function() { it('AcceptsParser with one param', () => { let route = '/Notes/:model/:id/:arg1'; let accepts = { arg: 'arg1' }; let instance = new AcceptsParser(accepts, route, 'GET'); expect(instance.pathParams).to.include(accepts); }); it('AcceptsParser should filter params, that recieved from context', () => { let route = '/Notes/:model/:id/:arg1'; accepts = [ { arg: 'arg1' }, { arg: 'arg2', http: function() {}, }, { arg: 'query1', http: { source: 'req', }, }, { arg: 'query2' }, ]; let instance = new AcceptsParser(accepts, route, 'GET'); expect(instance.innerParams).to.include(accepts[1]); expect(instance.innerParams).to.include(accepts[2]); expect(instance.innerParams).to.not.include(accepts[0]); expect(instance.innerParams).to.not.include(accepts[4]); }); it('AcceptsParser should have routeArgs names', () => { let route = '/Notes/:model/:id/:arg1'; let instance = new AcceptsParser(accepts, route, 'GET'); expect(instance.routeArgs).to.have.members(['model', 'id', 'arg1']); expect(instance.routeArgs.length).to.equal(3); }); it('AcceptsParser should filter input params, and populate proper data', () => { let routeArgs = ['arg1']; let inputGET = [ { arg: 'arg1' }, { arg: 'query2' }, { arg: 'arg2', http: function() {}, }, ]; let inputPOST = [ { arg: 'arg1' }, { arg: 'query2' }, { arg: 'arg2', http: function() {}, }, ]; let acceptsGET = AcceptsParser.prepareAccepts( inputGET, routeArgs, [accepts[2]], 'GET' ); let acceptsPOST = AcceptsParser.prepareAccepts( inputPOST, routeArgs, [accepts[2]], 'POST' ); expect(acceptsGET[0].http.source).to.be.equal('path'); expect(acceptsPOST[0].http.source).to.be.equal('path'); expect(acceptsGET[1].http.source).to.be.equal('query'); expect(acceptsPOST[1].http.source).to.be.equal('form'); }); it('AcceptsParser should sort accept params by http input (GET)', () => { let route = '/Notes/:model/:id/:arg1'; let accepts = [ // query but not in path { arg: 'arg1', http: { source: 'query', }, }, // in path but without source { arg: 'id', }, // all right { arg: 'model', http: { source: 'path', }, }, // form and body won't work for GET ]; let instance = new AcceptsParser(accepts, route, 'GET'); expect(instance.queryParams).to.have.include(accepts[0]); expect(instance.queryParams.length).to.equal(1); expect(instance.pathParams).to.have.members([accepts[1], accepts[2]]); expect(instance.pathParams.length).to.equal(2); }); it('AcceptsParser should sort accept params by http input (POST)', () => { let route = '/Notes/:model/:id/:arg1'; let accepts = [ { arg: 'arg1', http: { source: 'query', }, }, { arg: 'id', }, { arg: 'model', http: { source: 'body', }, }, { arg: 'arg2', http: { source: 'form', }, }, { arg: 'arg3', }, ]; let instance = new AcceptsParser(accepts, route, 'POST'); expect(instance.queryParams).to.have.include(accepts[0]); expect(instance.queryParams.length).to.equal(1); expect(instance.pathParams).to.have.members([accepts[1]]); expect(instance.pathParams.length).to.equal(1); expect(instance.bodyParams).to.have.members([accepts[2]]); expect(instance.bodyParams.length).to.equal(1); expect(instance.formParams).to.have.members([accepts[3], accepts[4]]); expect(instance.formParams.length).to.equal(2); }); }); describe('AcceptsParser instance method templateString()', () => { it('replace :arg in string to ${arg}', function() { let route = '/Notes/:model/:id/:arg1'; let accepts = [{ arg: 'model' }, { arg: 'id' }, { arg: 'arg1' }]; let instance = new AcceptsParser(accepts, route, 'GET'); let output = instance.templateString(); expect(output).to.be.equal('/Notes/${model}/${id}/${arg1}'); }); it('same with query', function() { let route = '/Notes/:model/:id/:arg1'; let accepts = [ { arg: 'model' }, { arg: 'id' }, { arg: 'arg1', http: { source: 'query', }, }, ]; let instance = new AcceptsParser(accepts, route, 'GET'); let output = instance.templateString(); expect(output).to.be.equal( '/Notes/${model}/${id}/${this.arg1}${queryParams({ arg1 })}' ); }); }); describe('ReturnsParser', () => { it('Array of models', () => { let models = ['Note', 'Customer']; let returns = { arg: 'data', type: ['Note'], root: true, }; let info = returnsParser(models, returns); expect(info.isArray).to.be.equal(true); expect(info.instanceClass).to.be.equal('Note'); }); it('Model instance', () => { let models = ['Note', 'Customer']; let returns = [ { arg: 'data', type: 'Note', root: true, }, ]; let info = returnsParser(models, returns); expect(info.isArray).to.be.equal(false); expect(info.instanceClass).to.be.equal('Note'); }); it('Some JSON data', () => { let models = ['Note', 'Customer']; let returns = [ { arg: 'data', type: 'string', }, ]; let info = returnsParser(models, returns); expect(info.isArray).to.be.equal(false); expect(info.instanceClass).to.be.equal(null); returns = [ { arg: 'data', type: 'string', }, { arg: 'data2', type: 'Note', }, ]; info = returnsParser(models, returns); expect(info.isArray).to.be.equal(false); expect(info.instanceClass).to.be.equal(null); }); it('Return all models in returns', () => { let returns = [ [ { arg: 'data', type: 'Customer', root: true, }, ], [ { arg: 'data', type: 'Review', root: true, }, ], [ { arg: 'data', type: 'object', root: true, }, ], ]; let models = returnClasses(['Customer', 'Note', 'Review'], returns); expect(models).to.have.members(['Customer', 'Review']); }); });
(function () { 'use strict'; /** * @param Base * @param {User} user * @param {app.utils} utils * @return {UserNameService} */ const factory = function (Base, user, utils) { class UserNameService extends Base { /** * @public * @type {string} */ name; constructor(base) { super(base); this.MAX_USER_NAME_LENGTH = 24; user.loginSignal.on(() => { this.name = user.name; }); user.logoutSignal.on(() => { this.name = ''; }); this.receive(utils.observe(user, 'name'), () => { this.name = user.name; }, this); } /** * @public */ save() { return this.isUniqueName().then(isUniqueName => { const isNameValid = isUniqueName && this._isNameLengthValid(); if (isNameValid) { user.name = this.name; } else { this.name = user.name; } }); } /** * @public * @param {string} */ setName(name) { this.name = name; } /** * @public * @return {boolean} */ isUniqueName() { return this._getUserList().then(list => { const isUnique = list .filter(item => item.address !== user.address) .every(item => item.name !== this.name); return !this.name || isUnique; }); } /** * @return {boolean} * @private */ _isNameLengthValid() { return this.name ? this.name.length <= this.MAX_USER_NAME_LENGTH : true; } /** * @return {Promise[]} * @private */ _getUserList() { return Promise.all([ user.getFilteredUserList(), user.getMultiAccountUsers() ]).then(([legacyUsers = [], users = []]) => { return [...legacyUsers, ...users]; }); } } return new UserNameService(); }; factory.$inject = ['Base', 'user', 'utils']; angular.module('app.ui').factory('userNameService', factory); })();
(function () { 'use strict'; describe('Dashboards Controller Tests', function () { // Initialize global variables var DashboardsController, $scope, $httpBackend, $state, Authentication, DashboardsService, mockDashboard; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function () { jasmine.addMatchers({ toEqualData: function (util, customEqualityTesters) { return { compare: function (actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _DashboardsService_) { // Set a new global scope $scope = $rootScope.$new(); // Point global variables to injected services $httpBackend = _$httpBackend_; $state = _$state_; Authentication = _Authentication_; DashboardsService = _DashboardsService_; // create mock Dashboard mockDashboard = new DashboardsService({ _id: '525a8422f6d0f87f0e407a33', name: 'Dashboard Name' }); // Mock logged in user Authentication.user = { roles: ['user'] }; // Initialize the Dashboards controller. DashboardsController = $controller('DashboardsController as vm', { $scope: $scope, dashboardResolve: {} }); // Spy on state go spyOn($state, 'go'); })); describe('vm.save() as create', function () { var sampleDashboardPostData; beforeEach(function () { // Create a sample Dashboard object sampleDashboardPostData = new DashboardsService({ name: 'Dashboard Name' }); $scope.vm.dashboard = sampleDashboardPostData; }); it('should send a POST request with the form input values and then locate to new object URL', inject(function (DashboardsService) { // Set POST response $httpBackend.expectPOST('api/dashboards', sampleDashboardPostData).respond(mockDashboard); // Run controller functionality $scope.vm.save(true); $httpBackend.flush(); // Test URL redirection after the Dashboard was created expect($state.go).toHaveBeenCalledWith('dashboards.view', { dashboardId: mockDashboard._id }); })); it('should set $scope.vm.error if error', function () { var errorMessage = 'this is an error message'; $httpBackend.expectPOST('api/dashboards', sampleDashboardPostData).respond(400, { message: errorMessage }); $scope.vm.save(true); $httpBackend.flush(); expect($scope.vm.error).toBe(errorMessage); }); }); describe('vm.save() as update', function () { beforeEach(function () { // Mock Dashboard in $scope $scope.vm.dashboard = mockDashboard; }); it('should update a valid Dashboard', inject(function (DashboardsService) { // Set PUT response $httpBackend.expectPUT(/api\/dashboards\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality $scope.vm.save(true); $httpBackend.flush(); // Test URL location to new object expect($state.go).toHaveBeenCalledWith('dashboards.view', { dashboardId: mockDashboard._id }); })); it('should set $scope.vm.error if error', inject(function (DashboardsService) { var errorMessage = 'error'; $httpBackend.expectPUT(/api\/dashboards\/([0-9a-fA-F]{24})$/).respond(400, { message: errorMessage }); $scope.vm.save(true); $httpBackend.flush(); expect($scope.vm.error).toBe(errorMessage); })); }); describe('vm.remove()', function () { beforeEach(function () { // Setup Dashboards $scope.vm.dashboard = mockDashboard; }); it('should delete the Dashboard and redirect to Dashboards', function () { // Return true on confirm message spyOn(window, 'confirm').and.returnValue(true); $httpBackend.expectDELETE(/api\/dashboards\/([0-9a-fA-F]{24})$/).respond(204); $scope.vm.remove(); $httpBackend.flush(); expect($state.go).toHaveBeenCalledWith('dashboards.list'); }); it('should should not delete the Dashboard and not redirect', function () { // Return false on confirm message spyOn(window, 'confirm').and.returnValue(false); $scope.vm.remove(); expect($state.go).not.toHaveBeenCalled(); }); }); }); }());
var appBookshelf = require('./base'), Basetoken = require('./base/token'), Accesstoken, Accesstokens; Accesstoken = Basetoken.extend({ tableName: 'accesstokens' }); Accesstokens = appBookshelf.Collection.extend({ model: Accesstoken }); module.exports = { Accesstoken: appBookshelf.model('Accesstoken', Accesstoken), Accesstokens: appBookshelf.collection('Accesstokens', Accesstokens) };
$(document).ready(function(){ lastfmRadio.init(); });
import { registerComponent } from 'nornj'; import Stepper from 'antd-mobile/lib/stepper/index'; registerComponent({ 'antm-Stepper': Stepper }); export default Stepper;
import React from 'react'; import {RadioButton, RadioButtonGroup} from 'material-ui/RadioButton'; import ActionFavorite from 'material-ui/svg-icons/action/favorite'; import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border'; const styles = { block: { maxWidth: 250, }, radioButton: { marginBottom: 16, }, }; const RadioButtonExampleSimple = () => ( <div className="row"> <div className="col-lg-6"> <RadioButtonGroup name="shipSpeed" defaultSelected="not_light"> <RadioButton value="light" label="Simple" style={styles.radioButton} /> <RadioButton value="not_light" label="Selected by default" style={styles.radioButton} /> <RadioButton value="ludicrous" label="Custom icon" checkedIcon={<ActionFavorite />} uncheckedIcon={<ActionFavoriteBorder />} style={styles.radioButton} /> </RadioButtonGroup> <RadioButtonGroup name="shipName" defaultSelected="community"> <RadioButton value="enterprise" label="Disabled unchecked" disabled style={styles.radioButton} /> <RadioButton value="community" label="Disabled checked" disabled style={styles.radioButton} /> </RadioButtonGroup> </div> <div className="col-lg-6"> <RadioButtonGroup name="notRight" labelPosition="left" defaultSelected="not_light" style={styles.block}> <RadioButton value="reverse" label="Label on the left" style={styles.radioButton} /> <RadioButton value="not_light" label="Selected by default" style={styles.radioButton} /> <RadioButton value="ludicrous" label="Custom icon" checkedIcon={<ActionFavorite />} uncheckedIcon={<ActionFavoriteBorder />} style={styles.radioButton} /> </RadioButtonGroup> <RadioButtonGroup name="shipName2" labelPosition="left" defaultSelected="community" style={styles.block}> <RadioButton value="enterprise" label="Disabled unchecked" disabled style={styles.radioButton} /> <RadioButton value="community" label="Disabled checked" disabled style={styles.radioButton} /> </RadioButtonGroup> </div> </div> ); const RadioButtonSection = () => ( <article className="article"> <h2 className="article-title">Material Radio Button</h2> <section className="box box-default"> <div className="box-body padding-xl"> <div className="col-xl-10"> <RadioButtonExampleSimple /> </div> </div> </section> </article> ); module.exports = RadioButtonSection;
;(function() { var app = angular.module('service-storage',[]); // Remove angular specifics function cleanObject(obj) { return angular.fromJson( angular.toJson(obj) ); } app.factory('homyStorage', ['$q', '$rootScope', function($q, $rootScope) { var DEFAULT = { _version: '1', _rev: (new Date()).getTime(), _next: 1, background: 'rgb(51,62,76)', links: [] }; function cleanup(data) { // Normalize data using default values data = angular.extend({}, DEFAULT, data); // Remove invalid links (like drag&drop bug) data.links = data.links.filter(function(b) { if(!b) return false; return true; }); // Clean up link data.links = data.links.map(function(b) { // Limit name size b.name = b.name.substr(0,128); // Limit url size: b.url = b.url.substr(0,2048); return b; }); return data; } var service = { data: null ,load: function() { var d = $q.defer(); chrome.storage.local.get(function(value) { if(chrome.runtime.lastError) { return d.reject(chrome.runtime.lastError); } if(value._rev) { service.data = cleanup(value); } else { service.data = DEFAULT; } d.resolve(service.data); }); return d.promise; } ,save: function(data) { var d = $q.defer(); if(data) { service.data = data; } service.data._rev = (new Date()).getTime(); service.data = cleanup(service.data); chrome.storage.local.set(cleanObject(service.data), function() { $rootScope.$apply(function() { if(chrome.runtime.lastError) { d.reject(chrome.runtime.lastError); } else { d.resolve(true); } }); }); return d.promise; } ,import: function(jsonSource) { var data; try { data = angular.fromJson(jsonSource); } catch(e) { alert('Invalid file content: Is it a valid Homy file?'); return; } switch(data._version) { case "1": service.data = cleanup(data); return service.save(); default: alert('Sorry, this file is from a earlier version of Homy, please update to the last version to import this file.'); } } ,getLinkFor: function(url, title) { return service.load().then(function(data) { var link; data.links.some(function(b) { if(b.url === url) { link = b; return true; } return false; }); if(link) { return link; } if(!link) { link = { id : data._next++, url : url || '', name: title || '' } data.links.push(link); return service.save(data).then(function() { return link }); } }) } , createLink: function() { return service.getLinkFor('',''); } ,saveLink: function(link) { return service.load().then(function(data) { if(!link.id) { // Add new link link.id = data._next++; data.links.push(link); } else { // Update current link data.links = data.links.map(function(current) { if(current.id !== link.id) return current; return link; }) } return service.save(data).then(function() { return link }); }) } ,removeLink: function(link) { return service.load().then(function(data) { data.links = data.links.filter(function(b) { return (b.id !== link.id); }); return service.save(data); }) } ,clear: function() { var d = $q.defer(); chrome.storage.local.clear(function() { $rootScope.$apply(function() { if(chrome.runtime.lastError) { d.reject(chrome.runtime.lastError); } else { d.resolve(true); } }); }); return d.promise; } ,addChangeListener: function(cb) { chrome.storage.onChanged.addListener(function(changes, namespace) { if(namespace !== 'local') return; if(!changes._rev) return; if(service.data._rev === changes._rev.newValue) return; service.load().then(function(data) { cb(data); }) }); } }; return service; }]); })();
!(function(r) { var a = {}; function s(t) { if (a[t]) return a[t].exports; var e = (a[t] = { i: t, l: !1, exports: {} }); return r[t].call(e.exports, e, e.exports, s), (e.l = !0), e.exports; } (s.m = r), (s.c = a), (s.d = function(r, a, t) { s.o(r, a) || Object.defineProperty(r, a, { enumerable: !0, get: t }); }), (s.r = function(r) { 'undefined' != typeof Symbol && Symbol.toStringTag && Object.defineProperty(r, Symbol.toStringTag, { value: 'Module' }), Object.defineProperty(r, '__esModule', { value: !0 }); }), (s.t = function(r, a) { if ((1 & a && (r = s(r)), 8 & a)) return r; if (4 & a && 'object' == typeof r && r && r.__esModule) return r; var t = Object.create(null); if ( (s.r(t), Object.defineProperty(t, 'default', { enumerable: !0, value: r }), 2 & a && 'string' != typeof r) ) for (var e in r) s.d( t, e, function(a) { return r[a]; }.bind(null, e), ); return t; }), (s.n = function(r) { var a = r && r.__esModule ? function() { return r.default; } : function() { return r; }; return s.d(a, 'a', a), a; }), (s.o = function(r, a) { return Object.prototype.hasOwnProperty.call(r, a); }), (s.p = ''), s((s.s = 8)); })([ function(r, a, s) { 'use strict'; var t = s(5), e = { body: '', args: [], thisVars: [], localVars: [] }; function n(r) { if (!r) return e; for (var a = 0; a < r.args.length; ++a) { var s = r.args[a]; r.args[a] = 0 === a ? { name: s, lvalue: !0, rvalue: !!r.rvalue, count: r.count || 1 } : { name: s, lvalue: !1, rvalue: !0, count: 1 }; } return ( r.thisVars || (r.thisVars = []), r.localVars || (r.localVars = []), r ); } function o(r) { for (var a = [], s = 0; s < r.args.length; ++s) a.push('a' + s); return new Function( 'P', [ 'return function ', r.funcName, '_ndarrayops(', a.join(','), ') {P(', a.join(','), ');return a0}', ].join(''), )( (function(r) { return t({ args: r.args, pre: n(r.pre), body: n(r.body), post: n(r.proc), funcName: r.funcName, }); })(r), ); } var i = { add: '+', sub: '-', mul: '*', div: '/', mod: '%', band: '&', bor: '|', bxor: '^', lshift: '<<', rshift: '>>', rrshift: '>>>', }; !(function() { for (var r in i) { var s = i[r]; (a[r] = o({ args: ['array', 'array', 'array'], body: { args: ['a', 'b', 'c'], body: 'a=b' + s + 'c' }, funcName: r, })), (a[r + 'eq'] = o({ args: ['array', 'array'], body: { args: ['a', 'b'], body: 'a' + s + '=b' }, rvalue: !0, funcName: r + 'eq', })), (a[r + 's'] = o({ args: ['array', 'array', 'scalar'], body: { args: ['a', 'b', 's'], body: 'a=b' + s + 's' }, funcName: r + 's', })), (a[r + 'seq'] = o({ args: ['array', 'scalar'], body: { args: ['a', 's'], body: 'a' + s + '=s' }, rvalue: !0, funcName: r + 'seq', })); } })(); var u = { not: '!', bnot: '~', neg: '-', recip: '1.0/' }; !(function() { for (var r in u) { var s = u[r]; (a[r] = o({ args: ['array', 'array'], body: { args: ['a', 'b'], body: 'a=' + s + 'b' }, funcName: r, })), (a[r + 'eq'] = o({ args: ['array'], body: { args: ['a'], body: 'a=' + s + 'a' }, rvalue: !0, count: 2, funcName: r + 'eq', })); } })(); var h = { and: '&&', or: '||', eq: '===', neq: '!==', lt: '<', gt: '>', leq: '<=', geq: '>=', }; !(function() { for (var r in h) { var s = h[r]; (a[r] = o({ args: ['array', 'array', 'array'], body: { args: ['a', 'b', 'c'], body: 'a=b' + s + 'c' }, funcName: r, })), (a[r + 's'] = o({ args: ['array', 'array', 'scalar'], body: { args: ['a', 'b', 's'], body: 'a=b' + s + 's' }, funcName: r + 's', })), (a[r + 'eq'] = o({ args: ['array', 'array'], body: { args: ['a', 'b'], body: 'a=a' + s + 'b' }, rvalue: !0, count: 2, funcName: r + 'eq', })), (a[r + 'seq'] = o({ args: ['array', 'scalar'], body: { args: ['a', 's'], body: 'a=a' + s + 's' }, rvalue: !0, count: 2, funcName: r + 'seq', })); } })(); var c = [ 'abs', 'acos', 'asin', 'atan', 'ceil', 'cos', 'exp', 'floor', 'log', 'round', 'sin', 'sqrt', 'tan', ]; !(function() { for (var r = 0; r < c.length; ++r) { var s = c[r]; (a[s] = o({ args: ['array', 'array'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b'], body: 'a=this_f(b)', thisVars: ['this_f'] }, funcName: s, })), (a[s + 'eq'] = o({ args: ['array'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a'], body: 'a=this_f(a)', thisVars: ['this_f'] }, rvalue: !0, count: 2, funcName: s + 'eq', })); } })(); var l = ['max', 'min', 'atan2', 'pow']; !(function() { for (var r = 0; r < l.length; ++r) { var s = l[r]; (a[s] = o({ args: ['array', 'array', 'array'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b', 'c'], body: 'a=this_f(b,c)', thisVars: ['this_f'], }, funcName: s, })), (a[s + 's'] = o({ args: ['array', 'array', 'scalar'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b', 'c'], body: 'a=this_f(b,c)', thisVars: ['this_f'], }, funcName: s + 's', })), (a[s + 'eq'] = o({ args: ['array', 'array'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b'], body: 'a=this_f(a,b)', thisVars: ['this_f'], }, rvalue: !0, count: 2, funcName: s + 'eq', })), (a[s + 'seq'] = o({ args: ['array', 'scalar'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b'], body: 'a=this_f(a,b)', thisVars: ['this_f'], }, rvalue: !0, count: 2, funcName: s + 'seq', })); } })(); var f = ['atan2', 'pow']; !(function() { for (var r = 0; r < f.length; ++r) { var s = f[r]; (a[s + 'op'] = o({ args: ['array', 'array', 'array'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b', 'c'], body: 'a=this_f(c,b)', thisVars: ['this_f'], }, funcName: s + 'op', })), (a[s + 'ops'] = o({ args: ['array', 'array', 'scalar'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b', 'c'], body: 'a=this_f(c,b)', thisVars: ['this_f'], }, funcName: s + 'ops', })), (a[s + 'opeq'] = o({ args: ['array', 'array'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b'], body: 'a=this_f(b,a)', thisVars: ['this_f'], }, rvalue: !0, count: 2, funcName: s + 'opeq', })), (a[s + 'opseq'] = o({ args: ['array', 'scalar'], pre: { args: [], body: 'this_f=Math.' + s, thisVars: ['this_f'] }, body: { args: ['a', 'b'], body: 'a=this_f(b,a)', thisVars: ['this_f'], }, rvalue: !0, count: 2, funcName: s + 'opseq', })); } })(), (a.any = t({ args: ['array'], pre: e, body: { args: [{ name: 'a', lvalue: !1, rvalue: !0, count: 1 }], body: 'if(a){return true}', localVars: [], thisVars: [], }, post: { args: [], localVars: [], thisVars: [], body: 'return false' }, funcName: 'any', })), (a.all = t({ args: ['array'], pre: e, body: { args: [{ name: 'x', lvalue: !1, rvalue: !0, count: 1 }], body: 'if(!x){return false}', localVars: [], thisVars: [], }, post: { args: [], localVars: [], thisVars: [], body: 'return true' }, funcName: 'all', })), (a.sum = t({ args: ['array'], pre: { args: [], localVars: [], thisVars: ['this_s'], body: 'this_s=0', }, body: { args: [{ name: 'a', lvalue: !1, rvalue: !0, count: 1 }], body: 'this_s+=a', localVars: [], thisVars: ['this_s'], }, post: { args: [], localVars: [], thisVars: ['this_s'], body: 'return this_s', }, funcName: 'sum', })), (a.prod = t({ args: ['array'], pre: { args: [], localVars: [], thisVars: ['this_s'], body: 'this_s=1', }, body: { args: [{ name: 'a', lvalue: !1, rvalue: !0, count: 1 }], body: 'this_s*=a', localVars: [], thisVars: ['this_s'], }, post: { args: [], localVars: [], thisVars: ['this_s'], body: 'return this_s', }, funcName: 'prod', })), (a.norm2squared = t({ args: ['array'], pre: { args: [], localVars: [], thisVars: ['this_s'], body: 'this_s=0', }, body: { args: [{ name: 'a', lvalue: !1, rvalue: !0, count: 2 }], body: 'this_s+=a*a', localVars: [], thisVars: ['this_s'], }, post: { args: [], localVars: [], thisVars: ['this_s'], body: 'return this_s', }, funcName: 'norm2squared', })), (a.norm2 = t({ args: ['array'], pre: { args: [], localVars: [], thisVars: ['this_s'], body: 'this_s=0', }, body: { args: [{ name: 'a', lvalue: !1, rvalue: !0, count: 2 }], body: 'this_s+=a*a', localVars: [], thisVars: ['this_s'], }, post: { args: [], localVars: [], thisVars: ['this_s'], body: 'return Math.sqrt(this_s)', }, funcName: 'norm2', })), (a.norminf = t({ args: ['array'], pre: { args: [], localVars: [], thisVars: ['this_s'], body: 'this_s=0', }, body: { args: [{ name: 'a', lvalue: !1, rvalue: !0, count: 4 }], body: 'if(-a>this_s){this_s=-a}else if(a>this_s){this_s=a}', localVars: [], thisVars: ['this_s'], }, post: { args: [], localVars: [], thisVars: ['this_s'], body: 'return this_s', }, funcName: 'norminf', })), (a.norm1 = t({ args: ['array'], pre: { args: [], localVars: [], thisVars: ['this_s'], body: 'this_s=0', }, body: { args: [{ name: 'a', lvalue: !1, rvalue: !0, count: 3 }], body: 'this_s+=a<0?-a:a', localVars: [], thisVars: ['this_s'], }, post: { args: [], localVars: [], thisVars: ['this_s'], body: 'return this_s', }, funcName: 'norm1', })), (a.sup = t({ args: ['array'], pre: { body: 'this_h=-Infinity', args: [], thisVars: ['this_h'], localVars: [], }, body: { body: 'if(_inline_1_arg0_>this_h)this_h=_inline_1_arg0_', args: [{ name: '_inline_1_arg0_', lvalue: !1, rvalue: !0, count: 2 }], thisVars: ['this_h'], localVars: [], }, post: { body: 'return this_h', args: [], thisVars: ['this_h'], localVars: [], }, })), (a.inf = t({ args: ['array'], pre: { body: 'this_h=Infinity', args: [], thisVars: ['this_h'], localVars: [], }, body: { body: 'if(_inline_1_arg0_<this_h)this_h=_inline_1_arg0_', args: [{ name: '_inline_1_arg0_', lvalue: !1, rvalue: !0, count: 2 }], thisVars: ['this_h'], localVars: [], }, post: { body: 'return this_h', args: [], thisVars: ['this_h'], localVars: [], }, })), (a.argmin = t({ args: ['index', 'array', 'shape'], pre: { body: '{this_v=Infinity;this_i=_inline_0_arg2_.slice(0)}', args: [ { name: '_inline_0_arg0_', lvalue: !1, rvalue: !1, count: 0 }, { name: '_inline_0_arg1_', lvalue: !1, rvalue: !1, count: 0 }, { name: '_inline_0_arg2_', lvalue: !1, rvalue: !0, count: 1 }, ], thisVars: ['this_i', 'this_v'], localVars: [], }, body: { body: '{if(_inline_1_arg1_<this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}', args: [ { name: '_inline_1_arg0_', lvalue: !1, rvalue: !0, count: 2 }, { name: '_inline_1_arg1_', lvalue: !1, rvalue: !0, count: 2 }, ], thisVars: ['this_i', 'this_v'], localVars: ['_inline_1_k'], }, post: { body: '{return this_i}', args: [], thisVars: ['this_i'], localVars: [], }, })), (a.argmax = t({ args: ['index', 'array', 'shape'], pre: { body: '{this_v=-Infinity;this_i=_inline_0_arg2_.slice(0)}', args: [ { name: '_inline_0_arg0_', lvalue: !1, rvalue: !1, count: 0 }, { name: '_inline_0_arg1_', lvalue: !1, rvalue: !1, count: 0 }, { name: '_inline_0_arg2_', lvalue: !1, rvalue: !0, count: 1 }, ], thisVars: ['this_i', 'this_v'], localVars: [], }, body: { body: '{if(_inline_1_arg1_>this_v){this_v=_inline_1_arg1_;for(var _inline_1_k=0;_inline_1_k<_inline_1_arg0_.length;++_inline_1_k){this_i[_inline_1_k]=_inline_1_arg0_[_inline_1_k]}}}', args: [ { name: '_inline_1_arg0_', lvalue: !1, rvalue: !0, count: 2 }, { name: '_inline_1_arg1_', lvalue: !1, rvalue: !0, count: 2 }, ], thisVars: ['this_i', 'this_v'], localVars: ['_inline_1_k'], }, post: { body: '{return this_i}', args: [], thisVars: ['this_i'], localVars: [], }, })), (a.random = o({ args: ['array'], pre: { args: [], body: 'this_f=Math.random', thisVars: ['this_f'] }, body: { args: ['a'], body: 'a=this_f()', thisVars: ['this_f'] }, funcName: 'random', })), (a.assign = o({ args: ['array', 'array'], body: { args: ['a', 'b'], body: 'a=b' }, funcName: 'assign', })), (a.assigns = o({ args: ['array', 'scalar'], body: { args: ['a', 'b'], body: 'a=b' }, funcName: 'assigns', })), (a.equals = t({ args: ['array', 'array'], pre: e, body: { args: [ { name: 'x', lvalue: !1, rvalue: !0, count: 1 }, { name: 'y', lvalue: !1, rvalue: !0, count: 1 }, ], body: 'if(x!==y){return false}', localVars: [], thisVars: [], }, post: { args: [], localVars: [], thisVars: [], body: 'return true' }, funcName: 'equals', })); }, function(r, a, s) { var t = s(7), e = s(6), n = 'undefined' != typeof Float64Array; function o(r, a) { return r[0] - a[0]; } function i() { var r, a = this.stride, s = new Array(a.length); for (r = 0; r < s.length; ++r) s[r] = [Math.abs(a[r]), r]; s.sort(o); var t = new Array(s.length); for (r = 0; r < t.length; ++r) t[r] = s[r][1]; return t; } function u(r, a) { var s = ['View', a, 'd', r].join(''); a < 0 && (s = 'View_Nil' + r); var e = 'generic' === r; if (-1 === a) { var n = 'function ' + s + '(a){this.data=a;};var proto=' + s + ".prototype;proto.dtype='" + r + "';proto.index=function(){return -1};proto.size=0;proto.dimension=-1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function(){return new " + s + '(this.data);};proto.get=proto.set=function(){};proto.pick=function(){return null};return function construct_' + s + '(a){return new ' + s + '(a);}'; return new Function(n)(); } if (0 === a) { n = 'function ' + s + '(a,d) {this.data = a;this.offset = d};var proto=' + s + ".prototype;proto.dtype='" + r + "';proto.index=function(){return this.offset};proto.dimension=0;proto.size=1;proto.shape=proto.stride=proto.order=[];proto.lo=proto.hi=proto.transpose=proto.step=function " + s + '_copy() {return new ' + s + '(this.data,this.offset)};proto.pick=function ' + s + '_pick(){return TrivialArray(this.data);};proto.valueOf=proto.get=function ' + s + '_get(){return ' + (e ? 'this.data.get(this.offset)' : 'this.data[this.offset]') + '};proto.set=function ' + s + '_set(v){return ' + (e ? 'this.data.set(this.offset,v)' : 'this.data[this.offset]=v') + '};return function construct_' + s + '(a,b,c,d){return new ' + s + '(a,d)}'; return new Function('TrivialArray', n)(h[r][0]); } n = ["'use strict'"]; var o = t(a), u = o.map(function(r) { return 'i' + r; }), c = 'this.offset+' + o .map(function(r) { return 'this.stride[' + r + ']*i' + r; }) .join('+'), l = o .map(function(r) { return 'b' + r; }) .join(','), f = o .map(function(r) { return 'c' + r; }) .join(','); n.push( 'function ' + s + '(a,' + l + ',' + f + ',d){this.data=a', 'this.shape=[' + l + ']', 'this.stride=[' + f + ']', 'this.offset=d|0}', 'var proto=' + s + '.prototype', "proto.dtype='" + r + "'", 'proto.dimension=' + a, ), n.push( "Object.defineProperty(proto,'size',{get:function " + s + '_size(){return ' + o .map(function(r) { return 'this.shape[' + r + ']'; }) .join('*'), '}})', ), 1 === a ? n.push('proto.order=[0]') : (n.push("Object.defineProperty(proto,'order',{get:"), a < 4 ? (n.push('function ' + s + '_order(){'), 2 === a ? n.push( 'return (Math.abs(this.stride[0])>Math.abs(this.stride[1]))?[1,0]:[0,1]}})', ) : 3 === a && n.push( 'var s0=Math.abs(this.stride[0]),s1=Math.abs(this.stride[1]),s2=Math.abs(this.stride[2]);if(s0>s1){if(s1>s2){return [2,1,0];}else if(s0>s2){return [1,2,0];}else{return [1,0,2];}}else if(s0>s2){return [2,0,1];}else if(s2>s1){return [0,1,2];}else{return [0,2,1];}}})', )) : n.push('ORDER})')), n.push('proto.set=function ' + s + '_set(' + u.join(',') + ',v){'), e ? n.push('return this.data.set(' + c + ',v)}') : n.push('return this.data[' + c + ']=v}'), n.push('proto.get=function ' + s + '_get(' + u.join(',') + '){'), e ? n.push('return this.data.get(' + c + ')}') : n.push('return this.data[' + c + ']}'), n.push( 'proto.index=function ' + s + '_index(', u.join(), '){return ' + c + '}', ), n.push( 'proto.hi=function ' + s + '_hi(' + u.join(',') + '){return new ' + s + '(this.data,' + o .map(function(r) { return [ '(typeof i', r, "!=='number'||i", r, '<0)?this.shape[', r, ']:i', r, '|0', ].join(''); }) .join(',') + ',' + o .map(function(r) { return 'this.stride[' + r + ']'; }) .join(',') + ',this.offset)}', ); var p = o.map(function(r) { return 'a' + r + '=this.shape[' + r + ']'; }), g = o.map(function(r) { return 'c' + r + '=this.stride[' + r + ']'; }); n.push( 'proto.lo=function ' + s + '_lo(' + u.join(',') + '){var b=this.offset,d=0,' + p.join(',') + ',' + g.join(','), ); for (var y = 0; y < a; ++y) n.push( 'if(typeof i' + y + "==='number'&&i" + y + '>=0){d=i' + y + '|0;b+=c' + y + '*d;a' + y + '-=d}', ); n.push( 'return new ' + s + '(this.data,' + o .map(function(r) { return 'a' + r; }) .join(',') + ',' + o .map(function(r) { return 'c' + r; }) .join(',') + ',b)}', ), n.push( 'proto.step=function ' + s + '_step(' + u.join(',') + '){var ' + o .map(function(r) { return 'a' + r + '=this.shape[' + r + ']'; }) .join(',') + ',' + o .map(function(r) { return 'b' + r + '=this.stride[' + r + ']'; }) .join(',') + ',c=this.offset,d=0,ceil=Math.ceil', ); for (y = 0; y < a; ++y) n.push( 'if(typeof i' + y + "==='number'){d=i" + y + '|0;if(d<0){c+=b' + y + '*(a' + y + '-1);a' + y + '=ceil(-a' + y + '/d)}else{a' + y + '=ceil(a' + y + '/d)}b' + y + '*=d}', ); n.push( 'return new ' + s + '(this.data,' + o .map(function(r) { return 'a' + r; }) .join(',') + ',' + o .map(function(r) { return 'b' + r; }) .join(',') + ',c)}', ); var d = new Array(a), _ = new Array(a); for (y = 0; y < a; ++y) (d[y] = 'a[i' + y + ']'), (_[y] = 'b[i' + y + ']'); n.push( 'proto.transpose=function ' + s + '_transpose(' + u + '){' + u .map(function(r, a) { return r + '=(' + r + '===undefined?' + a + ':' + r + '|0)'; }) .join(';'), 'var a=this.shape,b=this.stride;return new ' + s + '(this.data,' + d.join(',') + ',' + _.join(',') + ',this.offset)}', ), n.push( 'proto.pick=function ' + s + '_pick(' + u + '){var a=[],b=[],c=this.offset', ); for (y = 0; y < a; ++y) n.push( 'if(typeof i' + y + "==='number'&&i" + y + '>=0){c=(c+this.stride[' + y + ']*i' + y + ')|0}else{a.push(this.shape[' + y + ']);b.push(this.stride[' + y + '])}', ); return ( n.push('var ctor=CTOR_LIST[a.length+1];return ctor(this.data,a,b,c)}'), n.push( 'return function construct_' + s + '(data,shape,stride,offset){return new ' + s + '(data,' + o .map(function(r) { return 'shape[' + r + ']'; }) .join(',') + ',' + o .map(function(r) { return 'stride[' + r + ']'; }) .join(',') + ',offset)}', ), new Function('CTOR_LIST', 'ORDER', n.join('\n'))(h[r], i) ); } var h = { float32: [], float64: [], int8: [], int16: [], int32: [], uint8: [], uint16: [], uint32: [], array: [], uint8_clamped: [], buffer: [], generic: [], }; r.exports = function(r, a, s, t) { if (void 0 === r) return (0, h.array[0])([]); 'number' == typeof r && (r = [r]), void 0 === a && (a = [r.length]); var o = a.length; if (void 0 === s) { s = new Array(o); for (var i = o - 1, c = 1; i >= 0; --i) (s[i] = c), (c *= a[i]); } if (void 0 === t) for (t = 0, i = 0; i < o; ++i) s[i] < 0 && (t -= (a[i] - 1) * s[i]); for ( var l = (function(r) { if (e(r)) return 'buffer'; if (n) switch (Object.prototype.toString.call(r)) { case '[object Float64Array]': return 'float64'; case '[object Float32Array]': return 'float32'; case '[object Int8Array]': return 'int8'; case '[object Int16Array]': return 'int16'; case '[object Int32Array]': return 'int32'; case '[object Uint8Array]': return 'uint8'; case '[object Uint16Array]': return 'uint16'; case '[object Uint32Array]': return 'uint32'; case '[object Uint8ClampedArray]': return 'uint8_clamped'; } return Array.isArray(r) ? 'array' : 'generic'; })(r), f = h[l]; f.length <= o + 1; ) f.push(u(l, f.length - 1)); return (0, f[o + 1])(r, a, s, t); }; }, function(r, a, s) { 'use strict'; r.exports = function(r, a, s) { return 0 === r.length ? r : a ? (s || r.sort(a), (function(r, a) { for (var s = 1, t = r.length, e = r[0], n = r[0], o = 1; o < t; ++o) if (((n = e), a((e = r[o]), n))) { if (o === s) { s++; continue; } r[s++] = e; } return (r.length = s), r; })(r, a)) : (s || r.sort(), (function(r) { for ( var a = 1, s = r.length, t = r[0], e = r[0], n = 1; n < s; ++n, e = t ) if (((e = t), (t = r[n]) !== e)) { if (n === a) { a++; continue; } r[a++] = t; } return (r.length = a), r; })(r)); }; }, function(r, a, s) { 'use strict'; var t = s(2); function e(r, a, s) { var t, e, n = r.length, o = a.arrayArgs.length, i = a.indexArgs.length > 0, u = [], h = [], c = 0, l = 0; for (t = 0; t < n; ++t) h.push(['i', t, '=0'].join('')); for (e = 0; e < o; ++e) for (t = 0; t < n; ++t) (l = c), (c = r[t]), 0 === t ? h.push(['d', e, 's', t, '=t', e, 'p', c].join('')) : h.push( [ 'd', e, 's', t, '=(t', e, 'p', c, '-s', l, '*t', e, 'p', l, ')', ].join(''), ); for (h.length > 0 && u.push('var ' + h.join(',')), t = n - 1; t >= 0; --t) (c = r[t]), u.push(['for(i', t, '=0;i', t, '<s', c, ';++i', t, '){'].join('')); for (u.push(s), t = 0; t < n; ++t) { for (l = c, c = r[t], e = 0; e < o; ++e) u.push(['p', e, '+=d', e, 's', t].join('')); i && (t > 0 && u.push(['index[', l, ']-=s', l].join('')), u.push(['++index[', c, ']'].join(''))), u.push('}'); } return u.join('\n'); } function n(r, a, s) { for (var t = r.body, e = [], n = [], o = 0; o < r.args.length; ++o) { var i = r.args[o]; if (!(i.count <= 0)) { var u = new RegExp(i.name, 'g'), h = '', c = a.arrayArgs.indexOf(o); switch (a.argTypes[o]) { case 'offset': var l = a.offsetArgIndex.indexOf(o); (c = a.offsetArgs[l].array), (h = '+q' + l); case 'array': h = 'p' + c + h; var f = 'l' + o, p = 'a' + c; if (0 === a.arrayBlockIndices[c]) 1 === i.count ? 'generic' === s[c] ? i.lvalue ? (e.push(['var ', f, '=', p, '.get(', h, ')'].join('')), (t = t.replace(u, f)), n.push([p, '.set(', h, ',', f, ')'].join(''))) : (t = t.replace(u, [p, '.get(', h, ')'].join(''))) : (t = t.replace(u, [p, '[', h, ']'].join(''))) : 'generic' === s[c] ? (e.push(['var ', f, '=', p, '.get(', h, ')'].join('')), (t = t.replace(u, f)), i.lvalue && n.push([p, '.set(', h, ',', f, ')'].join(''))) : (e.push(['var ', f, '=', p, '[', h, ']'].join('')), (t = t.replace(u, f)), i.lvalue && n.push([p, '[', h, ']=', f].join(''))); else { for ( var g = [i.name], y = [h], d = 0; d < Math.abs(a.arrayBlockIndices[c]); d++ ) g.push('\\s*\\[([^\\]]+)\\]'), y.push('$' + (d + 1) + '*t' + c + 'b' + d); if ( ((u = new RegExp(g.join(''), 'g')), (h = y.join('+')), 'generic' === s[c]) ) throw new Error( 'cwise: Generic arrays not supported in combination with blocks!', ); t = t.replace(u, [p, '[', h, ']'].join('')); } break; case 'scalar': t = t.replace(u, 'Y' + a.scalarArgs.indexOf(o)); break; case 'index': t = t.replace(u, 'index'); break; case 'shape': t = t.replace(u, 'shape'); } } } return [e.join('\n'), t, n.join('\n')].join('\n').trim(); } r.exports = function(r, a) { for ( var s = (a[1].length - Math.abs(r.arrayBlockIndices[0])) | 0, o = new Array(r.arrayArgs.length), i = new Array(r.arrayArgs.length), u = 0; u < r.arrayArgs.length; ++u ) (i[u] = a[2 * u]), (o[u] = a[2 * u + 1]); var h = [], c = [], l = [], f = [], p = []; for (u = 0; u < r.arrayArgs.length; ++u) { r.arrayBlockIndices[u] < 0 ? (l.push(0), f.push(s), h.push(s), c.push(s + r.arrayBlockIndices[u])) : (l.push(r.arrayBlockIndices[u]), f.push(r.arrayBlockIndices[u] + s), h.push(0), c.push(r.arrayBlockIndices[u])); for (var g = [], y = 0; y < o[u].length; y++) l[u] <= o[u][y] && o[u][y] < f[u] && g.push(o[u][y] - l[u]); p.push(g); } var d = ['SS'], _ = ["'use strict'"], b = []; for (y = 0; y < s; ++y) b.push(['s', y, '=SS[', y, ']'].join('')); for (u = 0; u < r.arrayArgs.length; ++u) { for ( d.push('a' + u), d.push('t' + u), d.push('p' + u), y = 0; y < s; ++y ) b.push(['t', u, 'p', y, '=t', u, '[', l[u] + y, ']'].join('')); for (y = 0; y < Math.abs(r.arrayBlockIndices[u]); ++y) b.push(['t', u, 'b', y, '=t', u, '[', h[u] + y, ']'].join('')); } for (u = 0; u < r.scalarArgs.length; ++u) d.push('Y' + u); if ( (r.shapeArgs.length > 0 && b.push('shape=SS.slice(0)'), r.indexArgs.length > 0) ) { var v = new Array(s); for (u = 0; u < s; ++u) v[u] = '0'; b.push(['index=[', v.join(','), ']'].join('')); } for (u = 0; u < r.offsetArgs.length; ++u) { var m = r.offsetArgs[u], j = []; for (y = 0; y < m.offset.length; ++y) 0 !== m.offset[y] && (1 === m.offset[y] ? j.push(['t', m.array, 'p', y].join('')) : j.push([m.offset[y], '*t', m.array, 'p', y].join(''))); 0 === j.length ? b.push('q' + u + '=0') : b.push(['q', u, '=', j.join('+')].join('')); } var V = t( [] .concat(r.pre.thisVars) .concat(r.body.thisVars) .concat(r.post.thisVars), ); for ( (b = b.concat(V)).length > 0 && _.push('var ' + b.join(',')), u = 0; u < r.arrayArgs.length; ++u ) _.push('p' + u + '|=0'); r.pre.body.length > 3 && _.push(n(r.pre, r, i)); var w = n(r.body, r, i), A = (function(r) { for (var a = 0, s = r[0].length; a < s; ) { for (var t = 1; t < r.length; ++t) if (r[t][a] !== r[0][a]) return a; ++a; } return a; })(p); A < s ? _.push( (function(r, a, s, t) { for ( var n = a.length, o = s.arrayArgs.length, i = s.blockSize, u = s.indexArgs.length > 0, h = [], c = 0; c < o; ++c ) h.push(['var offset', c, '=p', c].join('')); for (c = r; c < n; ++c) h.push( ['for(var j' + c + '=SS[', a[c], ']|0;j', c, '>0;){'].join( '', ), ), h.push(['if(j', c, '<', i, '){'].join('')), h.push(['s', a[c], '=j', c].join('')), h.push(['j', c, '=0'].join('')), h.push(['}else{s', a[c], '=', i].join('')), h.push(['j', c, '-=', i, '}'].join('')), u && h.push(['index[', a[c], ']=j', c].join('')); for (c = 0; c < o; ++c) { for (var l = ['offset' + c], f = r; f < n; ++f) l.push(['j', f, '*t', c, 'p', a[f]].join('')); h.push(['p', c, '=(', l.join('+'), ')'].join('')); } for (h.push(e(a, s, t)), c = r; c < n; ++c) h.push('}'); return h.join('\n'); })(A, p[0], r, w), ) : _.push(e(p[0], r, w)), r.post.body.length > 3 && _.push(n(r.post, r, i)), r.debug && console.log( '-----Generated cwise routine for ', a, ':\n' + _.join('\n') + '\n----------', ); var k = [ r.funcName || 'unnamed', '_cwise_loop_', o[0].join('s'), 'm', A, (function(r) { for (var a = new Array(r.length), s = !0, t = 0; t < r.length; ++t) { var e = r[t], n = e.match(/\d+/); (n = n ? n[0] : ''), 0 === e.charAt(0) ? (a[t] = 'u' + e.charAt(1) + n) : (a[t] = e.charAt(0) + n), t > 0 && (s = s && a[t] === a[t - 1]); } return s ? a[0] : a.join(''); })(i), ].join(''); return new Function( [ 'function ', k, '(', d.join(','), '){', _.join('\n'), '} return ', k, ].join(''), )(); }; }, function(r, a, s) { 'use strict'; var t = s(3); r.exports = function(r) { var a = ["'use strict'", 'var CACHED={}'], s = [], e = r.funcName + '_cwise_thunk'; a.push(['return function ', e, '(', r.shimArgs.join(','), '){'].join('')); for ( var n = [], o = [], i = [ [ 'array', r.arrayArgs[0], '.shape.slice(', Math.max(0, r.arrayBlockIndices[0]), r.arrayBlockIndices[0] < 0 ? ',' + r.arrayBlockIndices[0] + ')' : ')', ].join(''), ], u = [], h = [], c = 0; c < r.arrayArgs.length; ++c ) { var l = r.arrayArgs[c]; s.push( ['t', l, '=array', l, '.dtype,', 'r', l, '=array', l, '.order'].join( '', ), ), n.push('t' + l), n.push('r' + l), o.push('t' + l), o.push('r' + l + '.join()'), i.push('array' + l + '.data'), i.push('array' + l + '.stride'), i.push('array' + l + '.offset|0'), c > 0 && (u.push( 'array' + r.arrayArgs[0] + '.shape.length===array' + l + '.shape.length+' + (Math.abs(r.arrayBlockIndices[0]) - Math.abs(r.arrayBlockIndices[c])), ), h.push( 'array' + r.arrayArgs[0] + '.shape[shapeIndex+' + Math.max(0, r.arrayBlockIndices[0]) + ']===array' + l + '.shape[shapeIndex+' + Math.max(0, r.arrayBlockIndices[c]) + ']', )); } for ( r.arrayArgs.length > 1 && (a.push( 'if (!(' + u.join(' && ') + ")) throw new Error('cwise: Arrays do not all have the same dimensionality!')", ), a.push( 'for(var shapeIndex=array' + r.arrayArgs[0] + '.shape.length-' + Math.abs(r.arrayBlockIndices[0]) + '; shapeIndex--\x3e0;) {', ), a.push( 'if (!(' + h.join(' && ') + ")) throw new Error('cwise: Arrays do not all have the same shape!')", ), a.push('}')), c = 0; c < r.scalarArgs.length; ++c ) i.push('scalar' + r.scalarArgs[c]); return ( s.push(['type=[', o.join(','), '].join()'].join('')), s.push('proc=CACHED[type]'), a.push('var ' + s.join(',')), a.push( [ 'if(!proc){', 'CACHED[type]=proc=compile([', n.join(','), '])}', 'return proc(', i.join(','), ')}', ].join(''), ), r.debug && console.log( '-----Generated thunk:\n' + a.join('\n') + '\n----------', ), new Function('compile', a.join('\n'))(t.bind(void 0, r)) ); }; }, function(r, a, s) { 'use strict'; var t = s(4); r.exports = function(r) { var a = new (function() { (this.argTypes = []), (this.shimArgs = []), (this.arrayArgs = []), (this.arrayBlockIndices = []), (this.scalarArgs = []), (this.offsetArgs = []), (this.offsetArgIndex = []), (this.indexArgs = []), (this.shapeArgs = []), (this.funcName = ''), (this.pre = null), (this.body = null), (this.post = null), (this.debug = !1); })(); (a.pre = r.pre), (a.body = r.body), (a.post = r.post); var s = r.args.slice(0); a.argTypes = s; for (var e = 0; e < s.length; ++e) { var n = s[e]; if ('array' === n || ('object' == typeof n && n.blockIndices)) { if ( ((a.argTypes[e] = 'array'), a.arrayArgs.push(e), a.arrayBlockIndices.push(n.blockIndices ? n.blockIndices : 0), a.shimArgs.push('array' + e), e < a.pre.args.length && a.pre.args[e].count > 0) ) throw new Error('cwise: pre() block may not reference array args'); if (e < a.post.args.length && a.post.args[e].count > 0) throw new Error('cwise: post() block may not reference array args'); } else if ('scalar' === n) a.scalarArgs.push(e), a.shimArgs.push('scalar' + e); else if ('index' === n) { if ( (a.indexArgs.push(e), e < a.pre.args.length && a.pre.args[e].count > 0) ) throw new Error('cwise: pre() block may not reference array index'); if (e < a.body.args.length && a.body.args[e].lvalue) throw new Error('cwise: body() block may not write to array index'); if (e < a.post.args.length && a.post.args[e].count > 0) throw new Error( 'cwise: post() block may not reference array index', ); } else if ('shape' === n) { if ( (a.shapeArgs.push(e), e < a.pre.args.length && a.pre.args[e].lvalue) ) throw new Error('cwise: pre() block may not write to array shape'); if (e < a.body.args.length && a.body.args[e].lvalue) throw new Error('cwise: body() block may not write to array shape'); if (e < a.post.args.length && a.post.args[e].lvalue) throw new Error('cwise: post() block may not write to array shape'); } else { if ('object' != typeof n || !n.offset) throw new Error('cwise: Unknown argument type ' + s[e]); (a.argTypes[e] = 'offset'), a.offsetArgs.push({ array: n.array, offset: n.offset }), a.offsetArgIndex.push(e); } } if (a.arrayArgs.length <= 0) throw new Error('cwise: No array arguments specified'); if (a.pre.args.length > s.length) throw new Error('cwise: Too many arguments in pre() block'); if (a.body.args.length > s.length) throw new Error('cwise: Too many arguments in body() block'); if (a.post.args.length > s.length) throw new Error('cwise: Too many arguments in post() block'); return ( (a.debug = !!r.printCode || !!r.debug), (a.funcName = r.funcName || 'cwise'), (a.blockSize = r.blockSize || 64), t(a) ); }; }, function(r, a) { function s(r) { return ( !!r.constructor && 'function' == typeof r.constructor.isBuffer && r.constructor.isBuffer(r) ); } /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh <https://feross.org> * @license MIT */ r.exports = function(r) { return ( null != r && (s(r) || (function(r) { return ( 'function' == typeof r.readFloatLE && 'function' == typeof r.slice && s(r.slice(0, 0)) ); })(r) || !!r._isBuffer) ); }; }, function(r, a, s) { 'use strict'; r.exports = function(r) { for (var a = new Array(r), s = 0; s < r; ++s) a[s] = s; return a; }; }, function(r, a, s) { 'use strict'; s.r(a); var t = s(1), e = s.n(t), n = s(0), o = s.n(n); const i = document.getElementById('file'), u = document.getElementById('canvas').getContext('2d'), h = document.querySelector('log'); function c(r) { (h.innerHTML = r), console.log(r); } const l = new KerasJS.Model({ filepath: './training/dog.bin', gpu: !1 }); l.events.on('loadingProgress', (r) => { c('LoadingProgress: ' + r + '%'); }), i.addEventListener('change', (r) => { const a = new FileReader(); a.addEventListener('load', (r) => { c('Receive file success'); const a = new Image(); a.addEventListener('load', () => { c('Load image success'), u.drawImage(a, 0, 0, 128, 128); const r = u.getImageData(0, 0, 128, 128), s = e()(new Float32Array(r.data), [r.width, r.height, 4]), t = e()(new Float32Array(r.width * r.height * 3), [ r.width, r.height, 3, ]); o.a.divseq(s, 255), o.a.assign(t.pick(null, null, 0), s.pick(null, null, 0)), o.a.assign(t.pick(null, null, 1), s.pick(null, null, 1)), o.a.assign(t.pick(null, null, 2), s.pick(null, null, 2)); const n = t.data; l.predict({ [l.inputLayerNames[0]]: new Float32Array(n) }) .then((r) => { c('Predict result: ' + r.output[0]); }) .catch((r) => { c('Predict error: ' + r.stack); }); }), (a.src = r.target.result); }), a.readAsDataURL(r.target.files[0]); }); }, ]);
javascript: (function() { var re_num = /\d/gi; function walkTextNodes(node, callback) { var nextNode, n; if ('undefined' === typeof node.nodeName) return; n = node.nodeName.toLowerCase(); if (-1 !== ['script', 'style'].indexOf(n)) return; if (node.nodeType === Node.ELEMENT_NODE) { if (node = node.firstChild) { do { nextNode = node.nextSibling; walkTextNodes(node, callback); } while(node = nextNode); } } else if (node.nodeType === Node.TEXT_NODE) { callback(node); } } function highlight(node) { s = node.data; if (typeof s === 'undefined') { return; } if (s.match(re_num)) { var span = document.createElement('span'); span.setAttribute('style', 'background:yellow'); span.textContent = s; node.parentNode.replaceChild(span, node); } } walkTextNodes(document.body, highlight); })();
//Next //By Dean Peterson //provides convenient way to return an array of strings //Allows for multiple instances function Next(itemList, options) { "use strict"; options = options || {}; if( Object.prototype.toString.call( itemList ) !== '[object Array]' ) { throw new Error("An array is required."); } this.original = itemList; this.itemList = itemList.slice(0); this.len = this.itemList.length - 1; this.index = 0; } Next.prototype = { next: function(options) { "use strict"; options = options || {}; var item = this.itemList[this.index]; //increment or reset index this.index = this.index >= this.len ? 0 : this.index + 1; return item; } }; if(exports){ exports.Next = Next; }
'use strict'; /*! * Module dependencies. */ var pjson = require('./package.json'); var fs = require('fs'); var join = require('path').join; var mongoose = require('mongoose'); var restify = require('restify'); var config = require('./config/config.js'); // hook up DB var connect = function () { var options = {server: {socketOptions: {keepAlive: 1}}}; mongoose.connect(config.db, options); }; connect(); mongoose.connection.on('error', console.log); mongoose.connection.on('disconnected', connect); // configure restify var server = restify.createServer({ name: pjson.name, version: pjson.version }); server.use(restify.bodyParser()); server.use(restify.acceptParser(server.acceptable)); server.use(restify.gzipResponse()); // bootstrap models fs.readdirSync(join(__dirname, 'app/models')).forEach(function (file) { if (~file.indexOf('.js')) { require(join(__dirname, 'app/models', file))(mongoose); } }); // setup routes require('./config/routes.js')(server); // start listening server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function () { var addr = server.address(); console.log("%s (v%s) listening at %s", pjson.name, pjson.version, addr.address + ":" + addr.port); });