code
stringlengths
2
1.05M
import React from 'react' import PropTypes from 'prop-types' import { connect } from 'react-redux' import * as Humanize from 'humanize-plus' import {gameObjectSelectors} from '../../../selectors' import './ResourceSlot.css' const ResourceSlot = ({ resourceRef, value, resource }) => ( <span className={'ResourceSlot' + (resource.premium ? ' ResourceSlot-premium':'')}> {resource.slug}: {value ? Humanize.intComma(value): '???'} </span> ) ResourceSlot.propTypes = { //name: PropTypes.string.isRequired, value: PropTypes.number, premium: PropTypes.bool } const mapStateToProps = (state, props) => { return { // WARNING: THE FOLLOWING SELECTOR DOES NOT CORRECTLY MEMOIZE resource: gameObjectSelectors.getGameObject(state, props.resourceRef) } } const DataResourceSlot = connect( mapStateToProps )(ResourceSlot) // export default DataResourceSlot
$(document).ready(function(){ var container = $('#target'); $('.ajaxtrigger').click(function(){ doAjax($(this).attr('href')); return false; }); function doAjax(url){ if(url.match('^http')){ $.getJSON("http://query.yahooapis.com/v1/public/yql?"+ "q=select%20*%20from%20html%20where%20url%3D%22"+ encodeURIComponent(url)+ "%22&format=xml'&callback=?", function(data){ if(data.results[0]){ var data = filterData(data.results[0]); container.html(data); } else { var errormsg = '<p>Error: could not load the page.</p>'; container.html(errormsg); } } ); } else { $('#target').load(url); } } function filterData(data){ data = data.replace(/<?\/body[^>]*>/g,''); data = data.replace(/[\r|\n]+/g,''); data = data.replace(/<--[\S\s]*?-->/g,''); data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,''); data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,''); data = data.replace(/<script.*\/>/,''); return data; } });
define([ "text!templates/Users/CreateTemplate.html", "models/UsersModel", "common", "populate" ], function (CreateTemplate, UsersModel, common, populate) { var UsersCreateView = Backbone.View.extend({ el: "#content-holder", contentType: "Users", template: _.template(CreateTemplate), imageSrc: '', initialize: function () { _.bindAll(this, "saveItem"); this.model = new UsersModel(); this.responseObj = {}; this.render(); }, events: { "submit form": "submit", "mouseenter .avatar": "showEdit", "mouseleave .avatar": "hideEdit", "click .current-selected": "showNewSelect", "click .newSelectList li:not(.miniStylePagination)": "chooseOption", "click .newSelectList li.miniStylePagination": "notHide", "click .newSelectList li.miniStylePagination .next:not(.disabled)": "nextSelect", "click .newSelectList li.miniStylePagination .prev:not(.disabled)": "prevSelect", "click": "hideNewSelect" }, notHide: function () { return false; }, showNewSelect: function (e, prev, next) { populate.showSelect(e, prev, next, this); return false; }, chooseOption: function (e) { $(e.target).parents("dd").find(".current-selected").text($(e.target).text()).attr("data-id", $(e.target).attr("id")); $(".newSelectList").hide(); }, nextSelect: function (e) { this.showNewSelect(e, false, true); }, prevSelect: function (e) { this.showNewSelect(e, true, false); }, hideNewSelect: function () { $(".newSelectList").hide(); }, hideDialog: function () { $(".edit-dialog").remove(); $(".crop-images-dialog").remove(); }, showEdit: function () { $(".upload").animate({ height: "20px", display:"block" }, 250); }, hideEdit: function () { $(".upload").animate({ height: "0px", display: "block" }, 250); }, saveItem: function () { var self = this; var mid = 39; this.model.save({ imageSrc: this.imageSrc, email: $.trim(this.$el.find('#email').val()), login: $.trim(this.$el.find('#login').val()), pass: $.trim(this.$el.find('#password').val()), profile: $.trim(this.$el.find('#profilesDd').data("id")) }, { headers: { mid: mid }, wait: true, success: function () { Backbone.history.fragment = ''; Backbone.history.navigate(window.location.hash, { trigger: true }); }, error: function (model, xhr) { self.errorNotification(xhr); }, confirmPass: $('#confirmpassword').val() }); }, render: function () { var formString = this.template(); var self = this; this.$el = $(formString).dialog({ closeOnEscape: false, autoOpen: true, dialogClass: "edit-dialog", width: "600", resizable: true, title: "Create User", buttons:{ save:{ text:"Create", class:"btn", click: self.saveItem }, cancel:{ text:"Cancel", class:"btn", click: function(){ self.hideDialog(); } } } }); populate.get("#profilesDd", "ProfilesForDd", {}, "profileName", this, true); common.canvasDraw({ model: this.model.toJSON() }, this); return this; } }); return UsersCreateView; });
/* Simple tool to accurately measure the time between 2 points */ var Benchmark = function(){ this.m1 = 0; this.m2 = 0; this.benchmarks = []; }; Benchmark.prototype.start = function(){ this.m1 = process.hrtime(); }; Benchmark.prototype.stop = function(){ this.m2 = process.hrtime(this.m1); this.benchmarks.push(this.toMS()); return this.toMS(); }; Benchmark.prototype.toMS = function(){ return (this.m2[1] / 1000000); }; Benchmark.prototype.toAvgMS = function(){ return (this.benchmarks.reduce(function(a, b) { return a + b; }) / this.benchmarks.length); }; Benchmark.prototype.formatMS = function(d){ var d = d || 2; return this.toMS().toFixed(d); }; Benchmark.prototype.formatAvgMS = function(d){ var d = d || 2; return this.toAvgMS().toFixed(d); }; module.exports = Benchmark;
import React from 'react'; import AuthProviderNone from './none'; import AuthProviderOIDC from './oidc'; const AuthProvider = ({ store, children }) => { const { authType } = store.getState(); if (authType === 'NONE') return <AuthProviderNone>{children}</AuthProviderNone>; if (authType === 'OIDC') return <AuthProviderOIDC store={store}>{children}</AuthProviderOIDC>; return <div>{`Auth type ${authType} is nor recognized`}</div>; }; export default AuthProvider;
var express = require('express'), url = require('url'), request = require('request'), u = require('underscore'); var app = express.createServer( express.logger(), express.static(__dirname + '/public') ); function except(obj /*, properties */){ var result = u.extend({}, obj), properties = u.rest(arguments); properties.forEach(function(prop){ delete result[prop]; }); return result; } app.get('/', function(req, res) { var params = url.parse(req.url, true).query, apiUrl = params.url || params.src; if (!apiUrl){ res.render('index.ejs', { layout: false, host: req.headers.host }); } else { var externalReqHeaders = except(req.headers, 'accept-encoding', 'host'); // 'accept-encoding', 'connection', 'cookie', 'host', 'user-agent'); externalReqHeaders.accept = 'application/json'; request({ uri: apiUrl, strictSSL: false, headers: externalReqHeaders }, function(error, response, body){ // copy headers from the external request, but remove those that node should generate var callbackName = params.callback || params.jsonp, finalHeaders, status; if (error){ status = 502; // bad gateway finalHeaders = {}; body = JSON.stringify({ error: error.message || body }); } else { status = response.statusCode; finalHeaders = except(response.headers, 'content-length', 'connection', 'server'); } // enable cross-domain-ness delete finalHeaders['x-frame-options']; finalHeaders['access-control-allow-origin'] = '*'; // CORS if (callbackName) { finalHeaders['content-type'] = 'text/javascript'; body = callbackName + '(' + body + ');'; } else { // treat as an AJAX request finalHeaders['content-type'] = 'application/json'; } res.writeHead(status, finalHeaders); res.end(body); }); } }); var apiPort = process.argv[2] || process.env.PORT || 8000; app.listen(apiPort); console.log('Server running at http://127.0.0.1:' + apiPort);
//----------------------------------------------------------------------------// var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); var User = require('../models/user.model'); var Draft = require('../models/draft.model'); var Post = require('../models/post.model'); //----------------------------------------------------------------------------// // post user data from firebase to the database router.post('/createUser', function(req, res){ var query = { uid: req.body.uid }; var update = { username: req.body.username, displayName: req.body.displayName, photoURL: req.body.photoURL, email: req.body.email }; var options = { upsert: true, new: true, setDefaultsOnInsert: true }; User.findOneAndUpdate(query, update, options, function(error, result){ if(error){ res.sendStatus(500); } else { res.sendStatus(201); } }); }); // create new blank draft router.post('/draft/newBlank', function(req, res){ User.findOne({ uid: req.body.uid }, function(error, user){ user.drafts.push(new Draft); if(error){ res.sendStatus(500); } else { user.save(); res.status(201).send(user.drafts[user.drafts.length-1]); } }); }); // post draft data to the database router.post('/draft/saveDraft/:tweetText', function(req, res){ var query = { 'drafts._id': req.body._id }; var update = { 'drafts.$.text': req.params.tweetText }; var options = { upsert: true, new: true, setDefaultsOnInsert: true }; User.findOneAndUpdate(query, update, options, function(error, result){ if(error){ res.sendStatus(500); } else { res.sendStatus(201); } }); }); router.get('/getDrafts/:uid', function(req, res){ User.findOne({ uid: req.params.uid }, function(error, result){ if(error){ res.sendStatus(500); } else { res.send(result.drafts); } }); }); router.delete('/draft/deleteDraft/:_id', function(req, res){ User.findOne({ uid: req.headers.uid }, function(error, user){ user.drafts.pull({ _id: req.params._id }); if(error){ res.sendStatus(500); } else { user.save(); res.sendStatus(200); } }); }); module.exports = router;
/** * Created with JetBrains WebStorm. * User: Bloodyaugust * Date: 12/10/13 * Time: 1:40 AM * To change this template use File | Settings | File Templates. */ (function () { templates = { modal: function () { div( {'class': 'modal'} ) }, menu: function () { div( {'class': 'menu'}, div( {'class': 'game-title'}, 'Menu' ), div( {'class': 'button', 'id': 'game', 'onClick': 'logPlay();'}, 'Play' ) ) }, score: function () { div( {'class': 'menu'}, div( {'class': 'game-title'}, 'Score' ), div( {'class': 'button', 'id': 'menu'}, 'Menu' ), div( {'class': 'button'}, a( {'class': 'twitter-share-button', 'href': 'https://twitter.com/share', 'data-via': 'twitterdev', 'style': 'color:#0C0;'}, 'Tweet Your Score!' ) ) ) } }; })();
import React from 'react' import { Link } from 'react-router' import Helmet from 'react-helmet' import { config } from 'config' import get from 'lodash/get' import _ from 'lodash' import Topic from '../../components/Topic' import { prefixLink } from 'gatsby-helpers' export default class Index extends React.Component { render() { const sortedPages = _.orderBy(this.props.route.pages, 'data.date', "desc") // Posts are those with md extension that are not 404 pages OR have a date (meaning they're a react component post). const visibleTutorials = sortedPages.filter(page => ( ( get(page, 'file.ext') === 'md' && !_.includes(page.path, '/404') || get(page, 'data.date') ) && (_.includes(get(page, 'file.dir'), 'research')) )) return ( <div> <Helmet title={config.siteTitle + ' | research'} /> <h1> Research </h1> <ul className="ulTopics"> {_.map(visibleTutorials, tutorial => ( <li key={tutorial.data.title + tutorial.data.date}> <Topic {...tutorial} /> </li> ))} </ul> </div> ) } }
// ## Globals var argv = require('minimist')(process.argv.slice(2)); var autoprefixer = require('gulp-autoprefixer'); var browserSync = require('browser-sync').create(); var changed = require('gulp-changed'); var concat = require('gulp-concat'); var flatten = require('gulp-flatten'); var gulp = require('gulp'); var gulpif = require('gulp-if'); var imagemin = require('gulp-imagemin'); var jshint = require('gulp-jshint'); var lazypipe = require('lazypipe'); var less = require('gulp-less'); var merge = require('merge-stream'); var cssNano = require('gulp-cssnano'); var plumber = require('gulp-plumber'); var rev = require('gulp-rev'); var runSequence = require('run-sequence'); var sass = require('gulp-sass'); var sourcemaps = require('gulp-sourcemaps'); var uglify = require('gulp-uglify'); // See https://github.com/austinpray/asset-builder var manifest = require('asset-builder')('./assets/manifest.json'); // `path` - Paths to base asset directories. With trailing slashes. // - `path.source` - Path to the source files. Default: `assets/` // - `path.dist` - Path to the build directory. Default: `dist/` var path = manifest.paths; // `config` - Store arbitrary configuration values here. var config = manifest.config || {}; // `globs` - These ultimately end up in their respective `gulp.src`. // - `globs.js` - Array of asset-builder JS dependency objects. Example: // ``` // {type: 'js', name: 'main.js', globs: []} // ``` // - `globs.css` - Array of asset-builder CSS dependency objects. Example: // ``` // {type: 'css', name: 'main.css', globs: []} // ``` // - `globs.fonts` - Array of font path globs. // - `globs.images` - Array of image path globs. // - `globs.bower` - Array of all the main Bower files. var globs = manifest.globs; // `project` - paths to first-party assets. // - `project.js` - Array of first-party JS assets. // - `project.css` - Array of first-party CSS assets. var project = manifest.getProjectGlobs(); // CLI options var enabled = { // Enable static asset revisioning when `--production` // rev: argv.production, rev: false, // Disable source maps when `--production` maps: !argv.production, // Fail styles task on error when `--production` failStyleTask: argv.production, // Fail due to JSHint warnings only when `--production` failJSHint: argv.production, // Strip debug statments from javascript when `--production` stripJSDebug: argv.production }; // Path to the compiled assets manifest in the dist directory var revManifest = path.dist + 'assets.json'; // ## Reusable Pipelines // See https://github.com/OverZealous/lazypipe // ### CSS processing pipeline // Example // ``` // gulp.src(cssFiles) // .pipe(cssTasks('main.css') // .pipe(gulp.dest(path.dist + 'styles')) // ``` var cssTasks = function(filename) { return lazypipe() .pipe(function() { return gulpif(!enabled.failStyleTask, plumber()); }) .pipe(function() { return gulpif(enabled.maps, sourcemaps.init()); }) .pipe(function() { return gulpif('*.less', less()); }) .pipe(function() { return gulpif('*.scss', sass({ outputStyle: 'nested', // libsass doesn't support expanded yet precision: 10, includePaths: ['.'], errLogToConsole: !enabled.failStyleTask })); }) .pipe(concat, filename) .pipe(autoprefixer, { browsers: [ 'last 2 versions', 'android 4', 'opera 12' ] }) .pipe(cssNano, { safe: true }) .pipe(function() { return gulpif(enabled.rev, rev()); }) .pipe(function() { return gulpif(enabled.maps, sourcemaps.write('.', { sourceRoot: 'assets/styles/' })); })(); }; // ### JS processing pipeline // Example // ``` // gulp.src(jsFiles) // .pipe(jsTasks('main.js') // .pipe(gulp.dest(path.dist + 'scripts')) // ``` var jsTasks = function(filename) { return lazypipe() .pipe(function() { return gulpif(enabled.maps, sourcemaps.init()); }) .pipe(concat, filename) .pipe(uglify, { compress: { 'drop_debugger': enabled.stripJSDebug } }) .pipe(function() { return gulpif(enabled.rev, rev()); }) .pipe(function() { return gulpif(enabled.maps, sourcemaps.write('.', { sourceRoot: 'assets/scripts/' })); })(); }; // ### Write to rev manifest // If there are any revved files then write them to the rev manifest. // See https://github.com/sindresorhus/gulp-rev var writeToManifest = function(directory) { return lazypipe() .pipe(gulp.dest, path.dist + directory) .pipe(browserSync.stream, {match: '**/*.{js,css}'}) .pipe(rev.manifest, revManifest, { base: path.dist, merge: true }) .pipe(gulp.dest, path.dist)(); }; // ## Gulp tasks // Run `gulp -T` for a task summary // ### Styles // `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS. // By default this task will only log a warning if a precompiler error is // raised. If the `--production` flag is set: this task will fail outright. gulp.task('styles', ['wiredep'], function() { var merged = merge(); manifest.forEachDependency('css', function(dep) { var cssTasksInstance = cssTasks(dep.name); if (!enabled.failStyleTask) { cssTasksInstance.on('error', function(err) { console.error(err.message); this.emit('end'); }); } merged.add(gulp.src(dep.globs, {base: 'styles'}) .pipe(cssTasksInstance)); }); return merged .pipe(writeToManifest('styles')); }); // ### Scripts // `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS // and project JS. gulp.task('scripts', ['jshint'], function() { var merged = merge(); manifest.forEachDependency('js', function(dep) { merged.add( gulp.src(dep.globs, {base: 'scripts'}) .pipe(jsTasks(dep.name)) ); }); return merged .pipe(writeToManifest('scripts')); }); // ### Fonts // `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory // structure. See: https://github.com/armed/gulp-flatten gulp.task('fonts', function() { return gulp.src(globs.fonts) .pipe(flatten()) .pipe(gulp.dest(path.dist + 'fonts')) .pipe(browserSync.stream()); }); // ### Images // `gulp images` - Run lossless compression on all the images. gulp.task('images', function() { return gulp.src(globs.images) .pipe(imagemin({ progressive: true, interlaced: true, svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}] })) .pipe(gulp.dest(path.dist + 'images')) .pipe(browserSync.stream()); }); // ### JSHint // `gulp jshint` - Lints configuration JSON and project JS. gulp.task('jshint', function() { return gulp.src([ 'bower.json', 'gulpfile.js' ].concat(project.js)) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(gulpif(enabled.failJSHint, jshint.reporter('fail'))); }); // ### Clean // `gulp clean` - Deletes the build folder entirely. gulp.task('clean', require('del').bind(null, [path.dist])); // ### Watch // `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code // changes across devices. Specify the hostname of your dev server at // `manifest.config.devUrl`. When a modification is made to an asset, run the // build step for that asset and inject the changes into the page. // See: http://www.browsersync.io gulp.task('watch', function() { browserSync.init({ files: ['{lib,templates}/**/*.php', '*.php'], notify: false, proxy: config.devUrl, snippetOptions: { whitelist: ['/wp-admin/admin-ajax.php'], blacklist: ['/wp-admin/**'] } }); gulp.watch([path.source + 'styles/**/*'], ['styles']); gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']); gulp.watch([path.source + 'fonts/**/*'], ['fonts']); gulp.watch([path.source + 'images/**/*'], ['images']); gulp.watch(['bower.json', 'assets/manifest.json'], ['build']); }); // ### Build // `gulp build` - Run all the build tasks but don't clean up beforehand. // Generally you should be running `gulp` instead of `gulp build`. gulp.task('build', function(callback) { runSequence('styles', 'scripts', ['fonts', 'images'], callback); }); // ### Wiredep // `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See // https://github.com/taptapship/wiredep gulp.task('wiredep', function() { var wiredep = require('wiredep').stream; return gulp.src(project.css) .pipe(wiredep()) .pipe(changed(path.source + 'styles', { hasChanged: changed.compareSha1Digest })) .pipe(gulp.dest(path.source + 'styles')); }); // ### Gulp // `gulp` - Run a complete build. To compile for production run `gulp --production`. gulp.task('default', ['clean'], function() { gulp.start('build'); });
$("#sticky-tab").stick_in_parent({ sticky_class: 'is-stuck' });
define(function(require) { var text = require('text!./template.html'); return { template: text }; });
export const UPDATE_PLAYERS = 'UPDATE_PLAYERS'; export const SAVE_GAME_INFO = 'SAVE_GAME_INFO'; export const CREATING_GAME = 'CREATING_GAME'; export const CLEAR_CREATING_GAME = 'CLEAR_CREATING_GAME'; export const CLEAR_GAME = 'CLEAR_GAME'; export const RENDER_GAME_INFO = 'RENDER_GAME_INFO';
module.exports = { ENDPOINT_URI: "kahoot.it", ENDPOINT_PORT: 443, TOKEN_ENDPOINT: "/reserve/session/", EVAL_: "var _ = {" + " replace: function() {" + " var args = arguments;" + " var str = arguments[0];" + " return str.replace(args[1], args[2]);" + " }" + "}; " + "var log = function(){};" + "return ", WSS_ENDPOINT: "wss://kahoot.it/cometd/", CHANNEL_HANDSHAKE: "/meta/handshake", CHANNEL_SUBSCR: "/meta/subscribe", CHANNEL_CONN: "/meta/connect", SUPPORTED_CONNTYPES: [ "websocket", "long-polling" ] }
/** * Minjector element representing a "define" or "require" definition. * * @param {TokenStructure} tokenStructure The corresponding tokenStructure * of this element. * @param {string} type "define" | "require" * @param {Token} firstBracketToken The token representing the first bracket of * the element e.g. "define ->(<-" * @param {Param} id The id of the module. Null for "require". * @param {Param} dependencies * @this {Element} */ var MinjectorElement = function( tokenStructure, type, firstBracketToken, id, dependencies) { this.tokenStructure = tokenStructure; this.type = type; this.firstBracketToken = firstBracketToken; this.id = id; this.dependencies = dependencies; this.parent = null; this.children = []; }; /** * Prototype shortcut. * @type {object} */ var _pt = MinjectorElement.prototype; /** * Return the element type. * @return {string} * @this {MinjectorElement} */ _pt.getType = function() { return this.type; }; /** * Return the element dependencies param. * @return {Param} * @this {MinjectorElement} */ _pt.getDependencies = function() { return this.dependencies; }; /** * Return the element id param. * @return {Param} * @this {MinjectorElement} */ _pt.getId = function() { return this.id; }; /** * Return if this module is and inline element or has a parent. * * @return {Boolean} * @this {MinjectorElement} */ _pt.isInline = function() { return this.parent !== null; }; /** * Set the parent element. * @param {MinjectorElement} parent * @this {MinjectorElement} */ _pt.setParent = function(parent) { this.parent = parent; }; /** * Retrieve the parent element. * @return {MinjectorElement} * @this {MinjectorElement} */ _pt.getParent = function() { return this.parent; }; /** * Add a children element. * @param {MinjectorElement} child * @this {MinjectorElement} */ _pt.addChildren = function(child) { this.children.push(child); child.setParent(this); }; /** * Return all children of this element. * @return {array} * @this {MinjectorElement} */ _pt.getChildren = function() { return this.children; }; /** * Return the code of this element. Inserting the given id as parameter if no * id exists per definition. * * @param {string} id The id which this module should have due to its file path. * @return {array} * @this {MinjectorElement} */ _pt.getCode = function(id) { var code = this.tokenStructure.getStructureCodePart(); var idParam = this.getId(); if (idParam === null || (!idParam.isDynamic() && idParam.getValue() === '')) { var firstBracketIndex = this.firstBracketToken.startIndex + 1; // Because the startIndex of firstBracketToken is relative to the file it // lives in but the code we extracted for this element the index does not // fit anylonger. Therefore substract the start index of the first token // to retrieve the correct index. firstBracketIndex -= this.tokenStructure.getTokens()[0].startIndex; code = code.substr(0, firstBracketIndex) + '\'' + id + '\', ' + code.substr(firstBracketIndex); } return code + ';\n'; }; /** * Representing a parameter of an element. The id or the dependencies. * @param {id|array} value The value of the param. * @param {Boolean} isDynamic Is this a dynamic created value. * @this {Param} */ var Param = function(value, isDynamic) { this.value = value; this.dynamic = isDynamic === undefined ? false : isDynamic; }; /** * Retrieve the value of this parameter. Null if this param is a dynamic value. * @return {id|array|null} */ Param.prototype.getValue = function() { return this.value; }; /** * Return if this parameter has a dynamic computed value. * @return {Boolean} */ Param.prototype.isDynamic = function() { return this.dynamic; }; /** * Set public access for the Param class. * @type {Param} */ MinjectorElement.Param = Param; /** * @type {MinjectorElement} */ module.exports = MinjectorElement;
'use strict'; describe('formInput', function () { var elm, scope; // load the form code beforeEach(angular.mock.module('formsAngular')); describe('simple text input', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input formStyle="horizontalCompact" schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = {name: 'desc', id: 'descId', label: 'Description', type: 'text'}; $compile(elm)(scope); scope.$digest(); })); it('should have a label', function () { var label = elm.find('label'); expect(label.text()).toBe('Description'); expect(label.attr('for')).toBe('descId'); expect(label).toHaveClass('control-label'); }); it('should have input', function () { var input = elm.find('input'); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('descId'); expect(input.attr('type')).toBe('text'); }); it('should connect the input to the form', function () { expect(scope.myForm.descId.$pristine).toBe(true); }); }); describe('generate inputs from schema', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = [ {name: 'name', id: '1', label: 'Name', type: 'text'}, {name: 'eyecolour', id: '2', label: 'Colour of Eyes', type: 'text'} ]; $compile(elm)(scope); scope.$digest(); })); it('should have 2 inputs', function () { var input = elm.find('input'); expect(input.length).toBe(2); input = angular.element(elm.find('input')[0]); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('1'); expect(input.attr('autofocus')).toBe(''); expect(input.attr('type')).toBe('text'); input = angular.element(elm.find('input')[1]); expect(input.attr('id')).toBe('2'); expect(input.attr('type')).toBe('text'); expect(input.attr('autofocus')).toBe(undefined); }); it('should have 2 labels', function () { var label = elm.find('label'); expect(label.length).toBe(2); label = angular.element(elm.find('label')[0]); expect((label).text()).toBe('Name'); expect(label.attr('for')).toBe('1'); label = angular.element(elm.find('label')[1]); expect(label.text()).toBe('Colour of Eyes'); expect(label.attr('for')).toBe('2'); }); }); describe('handles sub schemas', function () { describe('default behaviour', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = [ {'name': 'surname', 'id': 'f_surname', 'label': 'Surname', 'type': 'text'}, {'name': 'forename', 'id': 'f_forename', 'label': 'Forename', 'type': 'text'}, {'name': 'exams', 'id': 'f_exams', 'label': 'Exams', 'schema': [ {'name': 'exams.subject', 'id': 'f_exams.subject', 'label': 'Subject', 'type': 'text'}, {'name': 'exams.score', 'id': 'f_exams.score', 'label': 'Score', 'type': 'number'} ]} ]; scope.record = {'surname': 'Smith', 'forename': 'Anne', 'exams': [ {'subject': 'English', 'score': 83}, {'subject': 'Maths', 'score': 97} ]}; $compile(elm)(scope); scope.$digest(); })); it('has Exams section', function () { var thisElm = angular.element(elm.find('div')[5]); expect(thisElm).toHaveClass('schema-head'); expect(thisElm.text()).toBe('Exams'); thisElm = angular.element(elm.find('div')[20]); expect(thisElm).toHaveClass('schema-foot'); thisElm = thisElm.find('button'); expect((thisElm).text()).toMatch(/Add/); thisElm = elm.find('div'); expect(thisElm).toHaveClassCount('sub-doc', 2); thisElm = angular.element(elm.find('div')[6]); expect(thisElm.attr('id')).toBe('f_examsList_0'); thisElm = angular.element(elm.find('div')[13]); expect(thisElm.attr('id')).toBe('f_examsList_1'); thisElm = elm.find('input'); expect(thisElm).toHaveTypeCount('number', 2); thisElm = angular.element(elm.find('button')[0]); expect(thisElm.text()).toMatch(/Remove/); }); }); describe('Inhibit add and remove', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = [ {'name': 'surname', 'id': 'f_surname', 'label': 'Surname', 'type': 'text'}, {'name': 'forename', 'id': 'f_forename', 'label': 'Forename', 'type': 'text'}, {'name': 'exams', 'id': 'f_exams', 'label': 'Exams', 'noAdd': true, 'noRemove': true, 'schema': [ {'name': 'exams.subject', 'id': 'f_exams.subject', 'label': 'Subject', 'type': 'text'}, {'name': 'exams.score', 'id': 'f_exams.score', 'label': 'Score', 'type': 'number'} ]} ]; scope.record = {'surname': 'Smith', 'forename': 'Anne', 'exams': [ {'subject': 'English', 'score': 83}, {'subject': 'Maths', 'score': 97} ]}; $compile(elm)(scope); scope.$digest(); })); it('has amended Exams section head', function () { var thisElm = elm.find('div'); expect(thisElm).toHaveClassCount('schema-head', 1); thisElm = angular.element(elm.find('div')[5]); expect(thisElm.text()).toBe('Exams'); }); it('has amended Exams section foot', function () { var thisElm = elm.find('.schema-foot'); expect(thisElm.length).toBe(0); }); it('has amended Exams section buttons', function () { var thisElm = elm.find('button'); expect(thisElm.length).toBe(0); }); it('has amended Exams section subdoc', function () { var thisElm = elm.find('div'); expect(thisElm).toHaveClassCount('sub-doc', 2); }); }); }); describe('does not generate label element when label is blank', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text'}, {name: 'nickname', type: 'text'}, {name: 'hairColour', label: null, type: 'text'}, {name: 'eyecolour', id: '2', label: '', type: 'text'} ]; $compile(elm)(scope); scope.$digest(); })); it('should have 3 inputs', function () { var input = elm.find('input'); expect(input.length).toBe(4); input = angular.element(elm.find('input')[0]); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('1'); expect(input.attr('type')).toBe('text'); input = angular.element(elm.find('input')[3]); expect(input.attr('id')).toBe('2'); expect(input.attr('type')).toBe('text'); }); it('should have 2 label', function () { var label = elm.find('label'); expect(label.length).toBe(2); label = angular.element(elm.find('label')[0]); expect((label).text()).toBe('Name'); expect(label.attr('for')).toBe('1'); label = angular.element(elm.find('label')[1]); expect((label).text()).toBe('Nickname'); expect(label.attr('for')).toBe('f_nickname'); }); }); describe('generates "required" attribute when appropriate', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text', required: true}, {name: 'eyecolour', id: '2', label: '', type: 'text'} ]; $compile(elm)(scope); scope.$digest(); })); it('should have correct inputs', function () { var input = elm.find('input'); expect(input.length).toBe(2); input = angular.element(elm.find('input')[0]); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-invalid'); expect(input.attr('id')).toBe('1'); expect(input.attr('required')).toBe('required'); expect(input.attr('type')).toBe('text'); input = angular.element(elm.find('input')[1]); expect(input.attr('id')).toBe('2'); expect(input.attr('required')).toBe(undefined); expect(input.attr('type')).toBe('text'); }); }); describe('generates help elements', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text', help: 'This is some help'}, {name: 'eyecolour', id: '2', label: '', type: 'text', helpInline: 'This is some inline help'} ]; $compile(elm)(scope); scope.$digest(); })); it('should have correct help blocks', function () { var help = elm.find('span'); expect(help.length).toBe(2); help = angular.element(elm.find('span')[0]); expect(help).toHaveClass('help-block'); expect(help.text()).toBe('This is some help'); help = angular.element(elm.find('span')[1]); expect(help).toHaveClass('help-inline'); expect(help.text()).toBe('This is some inline help'); }); }); describe('generates textarea inputs', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text'}, {name: 'description', id: '2', label: 'Desc', type: 'textarea', rows: 10} ]; $compile(elm)(scope); scope.$digest(); })); it('should have correct textarea', function () { var input = elm.find('input'); expect(input.length).toBe(1); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('1'); expect(input.attr('type')).toBe('text'); input = elm.find('textarea'); expect(input.length).toBe(1); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('2'); expect(input.attr('rows')).toBe('10'); }); }); describe('generates readonly inputs', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.fEyeColourOptions = ['Blue', 'Brown', 'Green', 'Hazel']; scope.fSexOptions = ['Male', 'Female']; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text', readonly: true}, {name: 'description', id: '2', label: 'Desc', type: 'textarea', rows: 10, readonly: true}, {name: 'eyeColour', 'id': 'f_eyeColour', 'label': 'Eye Colour', 'type': 'select', 'options': 'fEyeColourOptions', readonly: true}, {name: 'eyeColour2', 'id': 'f_eyeColour2', 'label': 'Eye Colour2', 'type': 'select', 'options': 'fEyeColourOptions', readonly: true, 'select2': { 's2query': 'select2eyeColour' }}, {name: 'accepted', 'helpInline': 'Did we take them?','type': 'checkbox', readonly: true, 'id': 'f_accepted', 'label': 'Accepted'}, {name: 'sex', type: 'radio', 'inlineRadio': true, 'options': 'fSexOptions', 'id': 'f_sex', 'label': 'Sex', readonly: true} ]; $compile(elm)(scope); scope.$digest(); })); it('text and textarea', function () { var input = angular.element(elm.find('input')[0]); expect(input.attr('readonly')).toBe('readonly'); input = elm.find('textarea'); expect(input.attr('readonly')).toBe('readonly'); }); it('select', function () { var input = angular.element(elm.find('select')[0]); expect(input.attr('disabled')).toBe('disabled'); }); it('select2', function () { var input = angular.element(elm.find('input')[1]); expect(input.attr('readonly')).toBe('readonly'); }); it('checkbox', function () { var input = angular.element(elm.find('input')[2]); expect(input.attr('disabled')).toBe('disabled'); }); it('radio button', function () { var input = angular.element(elm.find('input')[3]); expect(input.attr('disabled')).toBe('disabled'); }); }); describe('generates required inputs', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.fEyeColourOptions = ['Blue', 'Brown', 'Green', 'Hazel']; scope.fSexOptions = ['Male', 'Female']; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text', required: true}, {name: 'description', id: '2', label: 'Desc', type: 'textarea', rows: 10, required: true}, {'name': 'eyeColour', 'id': 'f_eyeColour', 'label': 'Eye Colour', 'type': 'select', 'options': 'fEyeColourOptions', required: true}, {'name': 'eyeColour2', 'id': 'f_eyeColour2', 'label': 'Eye Colour2', 'type': 'select', 'options': 'fEyeColourOptions', required: true, 'select2': { 's2query': 'select2eyeColour' }}, {name: 'accepted', 'helpInline': 'Did we take them?','type': 'checkbox', required: true, 'id': 'f_accepted', 'label': 'Accepted'}, {name: 'sex', type: 'radio', 'inlineRadio': true, 'options': 'fSexOptions', 'id': 'f_sex', 'label': 'Sex', required: true} ]; $compile(elm)(scope); scope.$digest(); })); it('text and textarea', function () { var input = angular.element(elm.find('input')[0]); expect(input.attr('required')).toBe('required'); input = elm.find('textarea'); expect(input.attr('required')).toBe('required'); }); it('select', function () { var input = angular.element(elm.find('select')[0]); expect(input.attr('required')).toBe('required'); }); it('select2', function () { var input = angular.element(elm.find('input')[1]); expect(input.attr('required')).toBe('required'); }); it('checkbox', function () { var input = angular.element(elm.find('input')[2]); expect(input.attr('required')).toBe('required'); }); it('radio button', function () { var input = angular.element(elm.find('input')[3]); expect(input.attr('required')).toBe('required'); }); }); describe('generates password inputs', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.schema = [ {name: 'password', id: '1', label: 'Name', type: 'password'} ]; $compile(elm)(scope); scope.$digest(); })); it('creates password field', function () { var input = elm.find('input'); expect(input.attr('type')).toBe('password'); }); }); describe('generates selects for enumerated lists stored in scope', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.fEyeColourOptions = ['Blue', 'Brown', 'Green', 'Hazel']; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text'}, {'name': 'eyeColour', 'id': 'f_eyeColour', 'label': 'Eye Colour', 'type': 'select', 'options': 'fEyeColourOptions'} ]; $compile(elm)(scope); scope.$digest(); })); it('should have combobox', function () { var input = elm.find('select'); expect(input.length).toBe(1); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('f_eyeColour'); input = elm.find('option'); expect(input.length).toBe(5); input = angular.element(elm.find('option')[0]); expect(input.attr('value')).toBe(''); expect(input.text()).toBe(''); input = angular.element(elm.find('option')[4]); expect(input.attr('value')).toBe('Hazel'); expect(input.text()).toBe('Hazel'); }); }); describe('generates selects for passed enumerated lists', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text'}, {'name': 'eyeColour', 'id': 'f_eyeColour', 'label': 'Eye Colour', 'type': 'select', 'options': ['Blue', 'Brown', 'Green', 'Hazel']} ]; $compile(elm)(scope); scope.$digest(); })); it('should have combobox', function () { var input = elm.find('select'); expect(input.length).toBe(1); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('f_eyeColour'); input = elm.find('option'); expect(input.length).toBe(5); input = angular.element(elm.find('option')[0]); expect(input.attr('value')).toBe(''); expect(input.text()).toBe(''); input = angular.element(elm.find('option')[4]); expect(input.attr('value')).toBe('Hazel'); expect(input.text()).toBe('Hazel'); }); }); describe('generates selects for reference lookups', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.fEyeColourOptions = ['Blue', 'Brown', 'Green', 'Hazel']; scope.fEyeColourIds = ['1234', '5678', '90ab', 'cdef']; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text'}, {'name': 'eyeColour', 'id': 'f_eyeColour', 'label': 'Eye Colour', 'type': 'select', 'options': 'fEyeColourOptions', 'ids': 'fEyeColourIds'} ]; $compile(elm)(scope); scope.$digest(); })); it('should have combobox', function () { var input = elm.find('select'); expect(input.length).toBe(1); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('f_eyeColour'); input = elm.find('option'); expect(input.length).toBe(5); input = angular.element(elm.find('option')[0]); expect(input.attr('value')).toBe(''); expect(input.text()).toBe(''); input = angular.element(elm.find('option')[4]); expect(input.text()).toBe('Hazel'); }); }); describe('generates radio buttons for enumerated lists stored in scope', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.fEyeColourOptions = ['Blue', 'Brown', 'Green', 'Hazel']; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text'}, {'name': 'eyeColour', 'id': 'f_eyeColour', 'label': 'Eye Colour', 'type': 'radio', 'options': 'fEyeColourOptions'} ]; $compile(elm)(scope); scope.$digest(); })); it('should have radio buttons', function () { var input = elm.find('input'); expect(input.length).toBe(5); input = angular.element(elm.find('input')[4]); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('f_eyeColour'); expect(input.attr('value')).toBe('Hazel'); }); }); describe('generates radio buttons for passed enumerated lists', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.schema = [ {name: 'name', id: '1', label: 'Name', type: 'text'}, {'name': 'eyeColour', 'id': 'f_eyeColour', 'label': 'Eye Colour', 'type': 'radio', 'options': ['Blue', 'Brown', 'Green', 'Hazel']} ]; $compile(elm)(scope); scope.$digest(); })); it('should have radio buttons', function () { var input = elm.find('input'); expect(input.length).toBe(5); input = angular.element(elm.find('input')[4]); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input.attr('id')).toBe('f_eyeColour'); expect(input.attr('value')).toBe('Hazel'); }); }); describe('supports radio buttons in sub schemas', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="schema"></form-input></div>'); scope = $rootScope; scope.fResultOptions = ['Fail', 'Pass', 'Merit', 'Distinction']; scope.schema = [ {'name': 'surname', 'type': 'text', 'add': 'autofocus ', 'id': 'f_surname', 'label': 'Surname'}, {'name': 'forename', 'type': 'text', 'id': 'f_forename', 'label': 'Forename'}, {'name': 'exams', 'schema': [ {'name': 'exams.subject', 'type': 'text', 'id': 'f_exams_subject', 'label': 'Subject'}, {'type': 'radio', 'inlineRadio': true, 'name': 'exams.result', 'options': 'fResultOptions', 'id': 'f_exams_result', 'label': 'Result'} ], 'type': 'text', 'id': 'f_exams', 'label': 'Exams' } ]; scope.record = {surname: 'Smith', forename: 'Alan', exams: [{subject: 'English', result: 'pass'}, {subject: 'Maths', result: 'fail'}]}; $compile(elm)(scope); scope.$digest(); })); it('modifies name and model attributes', function () { var input = elm.find('input'); expect(input.length).toBe(12); input = angular.element(elm.find('input')[11]); expect(input.attr('name')).toBe('1-exams-result'); expect(input.attr('ng-model')).toBe('record.exams[$parent.$index].result'); }); }); describe('displays error messages', function () { beforeEach( inject(function ($rootScope, $compile) { elm = angular.element( '<div ng-show="errorMessage" class="row-fluid">' + '<div class="span6 offset3 alert alert-error">' + '<button type="button" class="close" ng-click="dismissError()">&times;</button>' + '<h4>{{alertTitle}}</h4>' + '<span class="errMsg">{{errorMessage}}</span>' + '</div>' + '</div>' + '<div class="row-fluid">' + '<form-input ng-repeat="field in formSchema" info="{{field}}"></form-input>' + '</div>' + '</div>'); scope = $rootScope; scope.schema = [ {name: 'email', id: '1', label: 'Email', type: 'text', directive: 'email-field'} ]; scope.errorMessage = 'Test error'; scope.alertTitle = 'Error!'; $compile(elm)(scope); scope.$digest(); })); it('displays appropriately', function () { var h4 = elm.find('h4'); expect(h4.text()).toBe('Error!'); var alert = elm.find('span'); expect(alert.text()).toBe('Test error'); }); }); describe('supports bootstrap control sizing', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = {name: 'desc', id: 'desc_id', label: 'Description', size: 'small', type: 'text'}; $compile(elm)(scope); scope.$digest(); })); it('should have input', function () { var input = elm.find('input'); expect(input).toHaveClass('ng-pristine'); expect(input).toHaveClass('ng-valid'); expect(input).toHaveClass('input-small'); expect(input.attr('id')).toBe('desc_id'); expect(input.attr('type')).toBe('text'); }); }); describe('supports showWhen', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = [ {name: 'boolean', type: 'checkbox'}, {name: 'desc', id: 'desc_id', label: 'Description', size: 'small', type: 'text', showWhen: {lhs: '$boolean', comp: 'eq', rhs: true}}, {'formStyle': 'inline', 'name': 'exams', 'schema': [ {showWhen: {lhs: '$boolean', comp: 'eq', rhs: true}, 'name': 'exams.subject', 'type': 'text', 'id': 'f_exams_subject', 'label': 'Subject'}, {'name': 'exams.result', 'type': 'select', 'options': 'f_exams_resultOptions', 'id': 'f_exams_result', 'label': 'Result'}, { 'name': 'exams.retakeDate', 'showWhen': {'lhs': '$exams.result', 'comp': 'eq', 'rhs': 'fail'}, 'type': 'text', 'add': 'ui-date ui-date-format ', 'id': 'f_exams_retakeDate', 'label': 'Retake Date' } ]} ]; scope.record = {boolean: true, name: 'any name', exams: [ {subject: 'Maths'} ]}; $compile(elm)(scope); scope.$digest(); })); it('on simple field', function () { var cg = angular.element(elm.find('div')[2]); expect(cg.attr('id')).toBe('cg_desc_id'); expect(cg.attr('ng-show')).toBe('record.boolean===true'); }); it('on nested field', function () { var cg = angular.element(elm.find('span')[0]); expect(cg.attr('id')).toBe('cg_f_exams_subject'); expect(cg.attr('ng-show')).toBe('record.boolean===true'); }); it('dependent on nested field', function () { var cg = angular.element(elm.find('span')[2]); expect(cg.attr('id')).toBe('cg_f_exams_retakeDate'); expect(cg.attr('ng-show')).toBe('record.exams[$index].result===\'fail\''); }); }); describe('Issue 41', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = [ { 'name': 'theThing', 'type': 'text', 'add': 'autofocus ', 'id': 'f_theThing', 'label': 'The Thing' }, { 'name': 'mentions', 'schema': [ { 'name': 'mentions.someString', 'type': 'text', 'id': 'f_mentions_someString', 'label': 'Some String' }, { 'name': 'mentions.grades.low', 'type': 'number', 'id': 'f_mentions_grades_low', 'label': 'Low' }, { 'name': 'mentions.grades.high', 'type': 'number', 'id': 'f_mentions_grades_high', 'label': 'High' } ], 'type': 'text', 'id': 'f_mentions', 'label': 'Mentions' } ]; scope.record = {theThing: 'a name', mentions: [ {someString: 'Maths', grades:{low:10, high:20}}, {someString: 'English', grades:{low:30, high:40}}] }; $compile(elm)(scope); scope.$digest(); })); it('should put the index in the correct place in the ng-model attribute', function () { var input = angular.element(elm.find('input')[1]); expect(input.attr('ng-model')).toBe('record.mentions[$index].someString'); input = angular.element(elm.find('input')[2]); expect(input.attr('ng-model')).toBe('record.mentions[$index].grades.low'); }); }); describe('Testing add all functionality, ', function () { describe('a text box', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema" add-all-field="bobby"></form-input></div>'); scope = $rootScope; scope.formSchema = { name: 'desc', id: 'desc_id', label: 'Description', type: 'text' }; $compile(elm)(scope); scope.$digest(); })); it('should have an attribute of bobby', function () { var input = elm.find('input'); expect(input.attr('bobby')).toBeDefined(); }); describe('a text box label', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema" add-all-label="bobby"></form-input></div>'); scope = $rootScope; scope.formSchema = { name: 'desc', id: 'desc_id', label: 'Description', type: 'text' }; $compile(elm)(scope); scope.$digest(); })); it('should have an attribute of bobby', function () { var label = elm.find('label'); expect(label.attr('bobby')).toBeDefined(); }); }); describe('a control group', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input schema="formSchema" add-all-group="bobby"></form-input></div>'); scope = $rootScope; scope.formSchema = { name: 'desc', id: 'desc_id', label: 'Description', type: 'text' }; $compile(elm)(scope); scope.$digest(); })); it('should have an attribute of bobby', function () { var group = angular.element(elm.find('div')[0]); expect(group.attr('bobby')).toBeDefined(); }); }); }); }); describe('arbitrary attributes get passed in', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input formStyle="horizontalCompact" schema="formSchema" test-me="A Test"></form-input></div>'); scope = $rootScope; scope.formSchema = {name: 'desc', id: 'desc_id', label: 'Description', type: 'text'}; $compile(elm)(scope); scope.$digest(); })); it('should have the test-me attribute', function () { var form = elm.find('form'); expect(form.attr('test-me')).toBe('A Test'); }); }); describe('labels in inline forms (BS2)', function () { beforeEach(inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input formStyle="inline" schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = {name: 'desc', id: 'descId', label: 'Description', type: 'text'}; $compile(elm)(scope); scope.$digest(); })); it('should not have a label', function () { var label = elm.find('label'); expect(label.length).toBe(0); }); }); describe('add arbitrary markup', function () { it('adds an attribute to a text input', function() { inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input formStyle="inline" schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = {name: 'desc', id: 'descId', label: 'Description', type: 'text', add: 'thing'}; $compile(elm)(scope); scope.$digest(); var input = elm.find('input'); expect(input.attr('thing')).toBe(''); expect(input.attr('controlthing')).toBe(undefined); }); }); it('adds a class to text input without size using add (deprecated behaviour)', function() { inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input formStyle="inline" schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = {name: 'desc', id: 'descId', label: 'Description', type: 'text', add: 'class="some class"'}; $compile(elm)(scope); scope.$digest(); var input = elm.find('input'); expect(input).toHaveClass('some'); expect(input).toHaveClass('class'); }); }); it('adds a class to text input without size using class', function() { inject(function ($rootScope, $compile) { elm = angular.element('<div><form-input formStyle="inline" schema="formSchema"></form-input></div>'); scope = $rootScope; scope.formSchema = {name: 'desc', id: 'descId', label: 'Description', type: 'text', class: 'some class'}; $compile(elm)(scope); scope.$digest(); var input = elm.find('input'); expect(input).toHaveClass('some'); expect(input).toHaveClass('class'); }); }); }); });
'use strict'; const listSequences = require('./list-sequences'); const shouldIgnoreRule = require('./should-ignore-rule'); const shouldIgnoreSelector = require('./should-ignore-selector'); const toInterpoloatedRegexp = require('./to-interpolated-regexp'); const getSelectors = require('./get-selectors'); /** * @param {Object} config * @param {Rule} config.rule - PostCSS Rule * @param {String} config.componentName * @param {Boolean} config.weakMode * @param {Object} config.selectorPattern * @param {Object} config.selectorPatternOptions * @param {RegExp} config.ignorePattern * @param {Result} config.result - PostCSS Result, for registering warnings */ module.exports = config => { if (shouldIgnoreRule(config.rule)) return; const rule = config.rule; const initialPattern = config.selectorPattern.initial ? toInterpoloatedRegexp(config.selectorPattern.initial)( config.componentName, config.selectorPatternOptions ) : toInterpoloatedRegexp(config.selectorPattern)( config.componentName, config.selectorPatternOptions ); const combinedPattern = config.selectorPattern.combined ? toInterpoloatedRegexp(config.selectorPattern.combined)( config.componentName, config.selectorPatternOptions ) : toInterpoloatedRegexp(initialPattern); const selectors = getSelectors(rule); selectors.forEach(selector => { // Don't bother with :root if (selector === ':root') return; const allSequences = listSequences(selector); let sequence; for (let i = 0, l = allSequences.length; i < l; i++) { if (config.weakMode && i !== 0) return; sequence = allSequences[i]; if ( config.ignorePattern && shouldIgnoreSelector(sequence, config.ignorePattern) ) continue; if (i === 0 && initialPattern.test(sequence)) continue; if (i !== 0 && combinedPattern.test(sequence)) continue; config.result.warn(`Invalid component selector "${selector}"`, { node: rule, word: selector, }); return; } }); };
// @flow /* eslint-env mocha */ /* global suite, benchmark */ import startOfMonth from '.' import moment from 'moment' suite('startOfMonth', function () { benchmark('date-fns', function () { return startOfMonth(this.date) }) benchmark('Moment.js', function () { return this.moment.startOf('month') }) }, { setup: function () { this.date = new Date() this.moment = moment() } })
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/sstephenson/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require angular //= require things-app //= require_tree .
'use strict'; var postcss = require('postcss'); var filterDeclarations = require('./'); var test = require('tape'); var fixture = [ 'a {', ' display: none;', ' border: 1px solid #000;', '}', '@media screen {', ' b:after {', ' content: "b";', ' }', ' @media (min-width: 300px) {', ' p q {', ' display: block;', ' }', ' }', '}' ].join('\n'); var includeDisplay = [ 'a {', ' display: none;', '}', '@media screen {', ' b:after {', ' }', ' @media (min-width: 300px) {', ' p q {', ' display: block;', ' }', ' }', '}' ].join('\n'); var includeBorderAndContent = [ 'a {', ' border: 1px solid #000;', '}', '@media screen {', ' b:after {', ' content: "b";', ' }', ' @media (min-width: 300px) {', ' p q {', ' }', ' }', '}' ].join('\n'); var includeNothing = [ 'a {', '}', '@media screen {', ' b:after {', ' }', ' @media (min-width: 300px) {', ' p q {', ' }', ' }', '}' ].join('\n'); test('postcssFilterDeclarations()', function(t) { t.plan(8); t.equal(filterDeclarations.name, 'postcssFilterDeclarations', 'should have a function name.'); t.equal( postcss().use(filterDeclarations({properties: 'display'})).process(fixture).css, includeDisplay, 'should select the rules based on the property name.' ); t.equal( postcss().use(filterDeclarations({props: 'display'})).process(fixture).css, includeDisplay, 'should use `props` option as an alias of `properties` option.' ); t.equal( postcss().use(filterDeclarations({props: ['border', 'content']})).process(fixture).css, includeBorderAndContent, 'should select the rules in response to the array of property names.' ); var options = { props: ['border', 'content'], exclude: true }; t.equal( postcss().use(filterDeclarations(options)).process(fixture).css, includeDisplay, 'should exclude the rules in response to the property names, using `exclude` option.' ); t.deepEqual( options, { props: ['border', 'content'], exclude: true }, 'should not modify the original option object.' ); t.equal( postcss().use(filterDeclarations({properties: [{foo: 'bar'}, 123]})).process(fixture).css, includeNothing, 'should ignore non-string values in the `properties` option.' ); t.equal( postcss().use(filterDeclarations()).process(fixture).css, includeNothing, 'should exclude all properties when it takes no arguments.' ); });
import url from 'url'; import gulp from 'gulp'; import gulpLoadPlugins from 'gulp-load-plugins'; import autoprefixer from 'autoprefixer-core'; import browserSync from 'browser-sync'; import del from 'del'; import nunjucks from 'nunjucks'; import map from 'vinyl-map'; import quaff from 'quaff'; import runSequence from 'run-sequence'; import yargs from 'yargs'; const $ = gulpLoadPlugins(); const args = yargs.argv; const bs = browserSync.create(); const config = require('./config'); let data = quaff(config.dataFolder); let basePath = args.production ? url.resolve('/', config.deploy.key) + '/' : '/'; data.PATH_PREFIX = basePath; let fullPath = url.format({ protocol: 'http', host: config.deploy.bucket, pathname: config.deploy.key }) + '/'; data.PATH_FULL = fullPath; let published_stories = data.metadata.storylist.filter((d) => d.published); data.LATEST_STORY = published_stories[published_stories.length - 1]; let env = nunjucks.configure(config.templateFolder, {autoescape: false}); env.addFilter('widont', (str) => { let lastSpace = str.trim().lastIndexOf(' '); return str.substring(0, lastSpace) + '&nbsp;' + str.substring(lastSpace + 1); }); gulp.task('jshint', () => { return gulp.src('./app/scripts/**/*.js') .pipe(bs.reload({stream: true, once: true})) .pipe($.jshint()) .pipe($.jshint.reporter('jshint-stylish')) .pipe($.if(!bs.active, $.jshint.reporter('fail'))); }); gulp.task('scripts', () => { return gulp.src('./app/scripts/**/*.js') .pipe(gulp.dest('./dist/scripts')) .pipe($.size({title: 'scripts'})); }); gulp.task('images', () => { return gulp.src('./app/assets/images/**/*') .pipe($.imagemin({ progressive: true, interlaced: true })) .pipe(gulp.dest('./dist/assets/images')) .pipe($.size({title: 'images'})); }); gulp.task('fonts', () => { return gulp.src(['./app/assets/fonts/**/*']) .pipe(gulp.dest('./dist/assets/fonts')) .pipe($.size({title: 'fonts'})); }); gulp.task('assets', () => { return gulp.src(['app/assets/*', '!app/assets/images', '!app/assets/fonts']) .pipe(gulp.dest('./dist/assets')) .pipe($.size({title: 'assets'})); }); gulp.task('templates', () => { let nunjuckify = map((code, filename) => { return env.renderString(code.toString(), {data: data}); }); // All .html files are valid, unless they are found in templates return gulp.src(['./app/**/*.html', `!${config.templateFolder}/**`]) .pipe(nunjuckify) .pipe(gulp.dest('./.tmp')) .pipe($.if(args.production, $.htmlmin({collapseWhitespace: true}))) .pipe($.if(args.production, gulp.dest('./dist'))) .pipe($.size({title: 'templates'})); }); gulp.task('styles', () => { let nunjuckify = map((code, filename) => { return env.renderString(code.toString(), {data: data}); }); return gulp.src(['./app/styles/**/*.scss']) .pipe($.sourcemaps.init()) .pipe($.sass({ includePaths: ['node_modules'], precision: 10 }).on('error', $.sass.logError)) .pipe(nunjuckify) .pipe($.postcss([ autoprefixer({ browsers: ['last 2 versions'] }) ])) .pipe($.if(args.production, $.minifyCss({ keepSpecialComments: 0 }))) .pipe($.sourcemaps.write(args.production ? '.' : undefined)) .pipe(gulp.dest('./.tmp/styles/')) .pipe($.if(args.production, gulp.dest('./dist/styles'))) .pipe(bs.stream({ match: '**/*.css' })) .pipe($.size({title: 'styles'})); }); gulp.task('serve', ['templates', 'styles'], () => { bs.init({ notify: false, logConnections: true, logPrefix: 'NEWSAPPS', open: false, server: { baseDir: ['./.tmp', './app'], routes: { '/node_modules': 'node_modules', } } }); gulp.watch(['./app/styles/**/*.scss'], ['styles']); gulp.watch(['./app/scripts/**/*.js'], ['jshint']); gulp.watch(['./app/**/*.html'], ['templates', bs.reload]); }); gulp.task('clean', cb => { return del(['./.tmp/**', './dist/**', '!dist/.git'], {dot: true}, cb); }); gulp.task('rev', () => { return gulp.src(['./dist/**/*.css', './dist/**/*.js', './dist/assets/images/**/*'], { base: './dist' }) .pipe($.rev()) .pipe(gulp.dest('./dist')) .pipe($.rev.manifest()) .pipe(gulp.dest('./dist')); }); gulp.task('revreplace', ['rev'], () => { var manifest = gulp.src('./dist/rev-manifest.json'); return gulp.src('./dist/**/*.html') .pipe($.revReplace({manifest: manifest})) .pipe(gulp.dest('./dist')); }); gulp.task('gzip', () => { return gulp.src('./dist/**/*.{html,js,css,json,eot,ttf,svg}') .pipe($.gzip({append: false})) .pipe(gulp.dest('./dist')); }); gulp.task('build', ['clean'], cb => { runSequence(['assets', 'fonts', 'images', 'scripts', 'styles', 'templates'], ['revreplace'], ['gzip'], cb); }); gulp.task('default', ['build']);
/*global Widget */ function IncrementalGraphWidget(widget, configName) { this.widget = widget; this.configName = configName; this.chart = null; this.dataToBind = { 'value': '', 'arrowClass': '', 'percentageDiff': 0, 'oldValue': '' }; } IncrementalGraphWidget.prototype = new Widget(); IncrementalGraphWidget.prototype.constructor = IncrementalGraphWidget; $.extend(IncrementalGraphWidget.prototype, { /** * Invoked after each response from long polling server * * @param response Response from long polling server */ handleResponse: function (response) { this.prepareData(response); }, /** * Updates widget's state */ prepareData: function (response) { var currentPoint = response.data, currentValue = currentPoint.y, pointX = parseFloat(currentPoint.x) * 1000, pointY = parseFloat(currentPoint.y); /** * Calculating diff from last collected value */ $.extend(this.dataToBind, this.setDifference(this.oldValue, currentValue)); this.dataToBind.value = currentValue; this.oldValue = currentValue; if (this.chart !== null) { this.handleChangeRate(); this.updateValue(); } else { this.renderTemplate(this.dataToBind); this.setupGraph(); } this.chart.highcharts().series[0].addPoint([pointX, pointY], true, (this.chart.highcharts().series[0].data.length >= this.params.maxPoints)); $(this.widget).blinkStop(); if (((this.params.thresholdComparator == 'higherIsBetter') && (currentValue <= this.params.criticalValue)) || ((this.params.thresholdComparator == 'lowerIsBetter') && (currentValue >= this.params.criticalValue))) { $(this.widget).blink({opacity: 0.2}); } this.chart.highcharts().xAxis[0].removePlotLine('deployment'); for (var i=0; i<currentPoint.events.length; i++) { var deployment = currentPoint.events[i]; this.chart.highcharts().xAxis[0].addPlotLine({ id: 'deployment', label: { text: deployment.title, style: { color: 'orange' } }, value: parseFloat(deployment.date) * 1000, color: 'orange', width: 2, zIndex: 5 }); } }, handleChangeRate: function() { $('.change-rate', this.widget) .show() .removeClass('better worse').addClass(this.dataToBind.trend) .find('i') .removeClass().addClass(this.dataToBind.arrowClass).parent() .find('.percentageDiff') .html(this.dataToBind.percentageDiff).parent() .find('.old-value') .html(this.dataToBind.oldValue); }, updateValue: function() { $('h2.value > .content', this.widget).html(this.dataToBind.value); }, setupGraph: function() { Highcharts.setOptions({ global: { useUTC: false } }); $('.change-rate', this.widget).hide(); this.chart = $('.graph', this.widget).highcharts({ chart: { type: this.params.graphType }, title: { text: '' }, xAxis: { title: '', type: 'datetime', dateTimeLabelFormats: { millisecond: '%H:%M', second: '%H:%M' }, tickPixelInterval: this.params.graphTickPixelInterval }, yAxis: { title: '' }, tooltip: { pointFormat: 'Value of <b>{point.y}</b> noted.' }, plotOptions: { area: { pointStart: 1940, marker: { enabled: false, symbol: 'circle', radius: 2, states: { hover: { enabled: true } } } } }, legend: { enabled: false }, exporting: { enabled: false }, series: [ { title: { text: '' }, data: [] } ] }); } });
import $dataAccess from './$dataAccess'; import components from './fallbacks/components'; import loadComponents from '../app/profile/loadcomponents'; export default function daComponents() { return $dataAccess(loadComponents, components); }
'use strict'; // Add ability to create directories var mkdirp = require('mkdirp'); const Generator = require('yeoman-generator'); const chalk = require('chalk'); const yosay = require('yosay'); module.exports = class extends Generator { prompting() { // Have Yeoman greet the user. this.log(yosay( 'Welcome to the wonderful ' + chalk.red('tads') + ' generator!' )); const prompts = [ { type: 'list', name: 'projecttype', message: 'What type of application do you want to create?', choices: [ { name: 'adv3 Application', value: 'adv3' }, { name: 'adv3Lite Application', value: 'adv3lite' } ] }, { type: 'input', name: 'name', message: 'Project Name: Cannot contain \ / : * ? " < > | or <space> characters. This is the project filename.', default: this.appname }, { type: 'input', name: 'author', message: 'Authors Name', store: true }, { type: 'input', name: 'email', message: 'Authors Email Address', store: true }, { type: 'input', name: 'title', message: 'The Title of your interactive fiction game' }, { type: 'input', name: 'desc', message: 'The Text description of your interactive fiction game' }, { type: 'input', name: 'htmldesc', message: 'The HTML description of your interactive fiction game' }, { type: 'input', name: 'ifid', message: 'The IFID for your interactive fiction game. This must be unique for each game the same way as an ISBN is unique for each book. You can get an IFID at http://www.tads.org/ifidgen/ifidgen' }, { type: 'input', name: 'libpath', message: 'The root path to third-party extensions like adv3Lite: Do not add a trailing / E.g. ../extensions', default: '../extensions', store: true } ]; return this.prompt(prompts).then(props => { // To access props later use this.props.someAnswer; this.props = props; }); } writing() { // Create the required directories mkdirp(this.destinationPath('debug')); mkdirp(this.destinationPath('web')); mkdirp(this.destinationPath('obj')); mkdirp(this.destinationPath('scripts')); // Project Specific Files // adv3 Project Files if (this.props.projecttype == 'adv3') { this.fs.copyTpl( this.templatePath('adv3/adv3.t'), this.destinationPath(this.props.name + '.t'), { name: this.props.name, title: this.props.title, author: this.props.author, email: this.props.email, desc: this.props.desc, htmldesc: this.props.htmldesc, ifid: this.props.ifid } ); this.fs.copyTpl( this.templatePath('adv3/adv3.t3m'), this.destinationPath('Makefile.t3m'), { name: this.props.name } ); this.fs.copyTpl( this.templatePath('adv3web/adv3web.t3m'), this.destinationPath('Makefile-web.t3m'), { name: this.props.name } ); } // adv3Lite Project Files else if (this.props.projecttype == 'adv3lite') { this.fs.copyTpl( this.templatePath('adv3Lite/adv3Lite.t'), this.destinationPath(this.props.name + '.t'), { name: this.props.name, title: this.props.title, author: this.props.author, email: this.props.email, desc: this.props.desc, htmldesc: this.props.htmldesc, ifid: this.props.ifid } ); this.fs.copyTpl( this.templatePath('adv3Lite/adv3Lite.t3m'), this.destinationPath('Makefile.t3m'), { name: this.props.name, libpath: this.props.libpath } ); this.fs.copyTpl( this.templatePath('adv3Liteweb/adv3Liteweb.t3m'), this.destinationPath('Makefile-web.t3m'), { name: this.props.name, libpath: this.props.libpath } ); } } /* install() { this.installDependencies(); } */ };
var request = require('superagent'); var port = process.env.PORT || 3000; describe('Our server getweather route', function () { describe('when posted a single zip', function () { it('should provide weather data for that zip', function (done) { request .post('http://localhost:' + port + '/getweather') .send({ zipcodes: '90210' }) .set('Accept', 'application/json') .end(function (res) { var data = res.body || {}; data.status.should.equal('ok'); data.data.currently.should.be.an.instanceOf(Object); data.data.currently.should.have.property([ 'time', 'summary', 'icon', 'temperature' ]); done(); }); }); }); describe('when posting 2 valid zips', function () { it('should provide results for both', function (done) { request .post('http://localhost:' + port + '/getweather') .send({ zipcodes: '90210 44093' }) .set('Accept', 'application/json') .end(function (res) { var data = res.body || {}; data.status.should.equal('ok'); data.results.should.equal(2); data.data['90210'].should.be.an.instanceOf(Object); data.data['44093'].should.be.an.instanceOf(Object); done(); }); }); }); describe('when posting 5 valid zips', function () { it('should provide results for all', function (done) { request .post('http://localhost:' + port + '/getweather') .send({ zipcodes: '90210 44093 28173 21431 28210' }) .set('Accept', 'application/json') .end(function (res) { var data = res.body || {}; data.status.should.equal('ok'); data.results.should.equal(5); data.data['90210'].should.be.an.instanceOf(Object); data.data['44093'].should.be.an.instanceOf(Object); data.data['28173'].should.be.an.instanceOf(Object); data.data['21431'].should.be.an.instanceOf(Object); data.data['28210'].should.be.an.instanceOf(Object); done(); }); }); }); });
/* Copyright 2014, KISSY v1.43 MIT Licensed build time: May 22 12:18 */ /* Combined processedModules by KISSY Module Compiler: dd/plugin/proxy */ KISSY.add("dd/plugin/proxy", ["node", "dd", "base"], function(S, require) { var Node = require("node"), DD = require("dd"), Base = require("base"); var DDM = DD.DDM, PROXY_EVENT = ".-ks-proxy" + S.now(); return Base.extend({pluginId:"dd/plugin/proxy", pluginInitializer:function(drag) { var self = this, hideNodeOnDrag = self.get("hideNodeOnDrag"); function start() { var node = self.get("node"), dragNode = drag.get("node"); if(!self.get("proxyNode")) { if(typeof node === "function") { node = node(drag); node.addClass("ks-dd-proxy"); self.set("proxyNode", node) } }else { node = self.get("proxyNode") } node.show(); dragNode.parent().append(node); DDM.cacheWH(node); node.offset(dragNode.offset()); drag.setInternal("dragNode", dragNode); drag.setInternal("node", node); if(hideNodeOnDrag) { dragNode.css("visibility", "hidden") } } function end() { var node = self.get("proxyNode"), dragNode = drag.get("dragNode"); if(self.get("moveOnEnd")) { dragNode.offset(node.offset()) } if(self.get("destroyOnEnd")) { node.remove(); self.set("proxyNode", 0) }else { node.hide() } drag.setInternal("node", dragNode); if(hideNodeOnDrag) { dragNode.css("visibility", "") } } drag.on("dragstart" + PROXY_EVENT, start).on("dragend" + PROXY_EVENT, end) }, pluginDestructor:function(drag) { drag.detach(PROXY_EVENT) }}, {ATTRS:{node:{value:function(drag) { return new Node(drag.get("node").clone(true)) }}, hideNodeOnDrag:{value:false}, destroyOnEnd:{value:false}, moveOnEnd:{value:true}, proxyNode:{}}}) });
var argument__data__type_8h = [ [ "ArgumentDataType", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7", [ [ "Char", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7a8e95e84813830072b7516cfaa7dbc1a9", null ], [ "UnsignedChar", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7aa93f121640d609f8772397a0f40f40d6", null ], [ "Short", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7a30bb747c98bccdd11b3f89e644c4d0ad", null ], [ "UnsignedShort", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7aeb51124277f3ec904a9af74d5de34e7b", null ], [ "Int", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7a1686a6c336b71b36d77354cea19a8b52", null ], [ "UnsignedInt", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7ac93cff91b6b9a57fa32bbe1863150070", null ], [ "Long", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7a8394f0347c184cf156ac5924dccb773b", null ], [ "UnsignedLong", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7a0c72cf9e88a9782dbad0fde761ae9352", null ], [ "Half", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7ac48615a1bc4197056d522af276aa5a85", null ], [ "Float", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7a22ae0e2b89e5e3d477f988cc36d3272b", null ], [ "Double", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7ad909d38d705ce75386dd86e611a82f5b", null ], [ "Custom", "argument__data__type_8h.html#a79871821a23eee2b543fec77b52c54d7a90589c47f06eb971d548591f23c285af", null ] ] ] ];
/* * Copyright (c) 2010 Kai Zimmer [http://www.kaizimmer.com] * * Permission is hereby granted to use, modify, and distribute this file * in accordance with the terms of the license agreement accompanying it. */ org.rialoom.utils.ClassUtils.createPackage("org.rialoom.drupal.events"); /** * BehaviorEvent constructor * @author k.zimmer aka engimono */ org.rialoom.drupal.events.BehaviorEvent = function ( type, target, data ) { org.rialoom.events.Event.call(this, type, target); this.data = data; }; org.rialoom.utils.ClassUtils.inherits(org.rialoom.drupal.events.BehaviorEvent, org.rialoom.events.Event); /** * Sets data to be injected into behaviors */ org.rialoom.drupal.events.BehaviorEvent.prototype.setData = function ( data ) { this.data = data; }; /** * Returns behavior data */ org.rialoom.drupal.events.BehaviorEvent.prototype.getData = function ( ) { return this.data; }; /** * toString Method */ org.rialoom.drupal.events.BehaviorEvent.prototype.toString = function ( ) { return "[org.rialoom.drupal.events.BehaviorEvent type: " + this.getType() + " | target: " + this.getTarget() + " | data: " + this.data + " ]"; }; org.rialoom.drupal.events.BehaviorEvent.ON_UPDATE = "ON_UPDATE";
'use strict'; /* Services */ var ampServices = angular.module('ampServices', ['ngResource']); ampServices.factory('Phone', ['$resource', function($resource){ return $resource('data/:phoneId.json', {}, { query: {method:'GET', params:{phoneId:'phones'}, isArray:true} }); }]);
var gulp = require('gulp'); var runSequence=require('run-sequence').use(gulp); gulp.task('build-all', function(cb){ runSequence('markup'); });
// Original implementation from : https://github.com/visionmedia/connect-jsonrpc/blob/master/lib/connect-jsonrpc.js /*! * Ext JS Connect * Copyright(c) 2010 Sencha Inc. * MIT Licensed */ /** * Module dependencies. */ var parse = require('url').parse, http = require('http'); /** * JSON-RPC version. */ var VERSION = exports.VERSION = '2.0'; /** * JSON parse error. */ var PARSE_ERROR = exports.PARSE_ERROR = -32700; /** * Invalid request due to invalid or missing properties. */ var INVALID_REQUEST = exports.INVALID_REQUEST = -32600; /** * Service method does not exist. */ var METHOD_NOT_FOUND = exports.METHOD_NOT_FOUND = -32601; /** * Invalid parameters. */ var INVALID_PARAMS = exports.INVALID_PARAMS = -32602; /** * Internal JSON-RPC error. */ var INTERNAL_ERROR = exports.INTERNAL_ERROR = -32603; /** * Default error messages. */ var errorMessages = exports.errorMessages = {}; errorMessages[PARSE_ERROR] = 'Parse Error.'; errorMessages[INVALID_REQUEST] = 'Invalid Request.'; errorMessages[METHOD_NOT_FOUND] = 'Method Not Found.'; errorMessages[INVALID_PARAMS] = 'Invalid Params.'; errorMessages[INTERNAL_ERROR] = 'Internal Error.'; function mergeObjects() { var obj = {}; // Merge methods for (var i = 0, len = arguments.length; i < len; ++i) { var args = arguments[i]; Object.keys(args).forEach(function (key) { obj[key] = args[key]; }); } return obj; } /** * Accepts any number of objects, exposing their methods. * * @param {Object} ... * @return {Function} * @api public */ function jsonrpc(services, httpMethod) { services = services || {}; /** * Handle JSON-RPC request. * * @param {Object} rpc * @param {Function} respond */ function handleRequest(rpc, respond){ if (validRequest(rpc)) { var method = services[rpc.method]; if (typeof method === 'function') { var params = []; // Unnamed params if (Array.isArray(rpc.params)) { params = rpc.params; // Named params } else if (typeof rpc.params === 'object') { var names = method.toString().match(/\((.*?)\)/)[1].match(/[\w]+/g); if (names) { for (var i = 0, len = names.length - 1; i < len; ++i) { params.push(rpc.params[names[i]]); } } else { // Function does not have named parameters return respond({ error: { code: INVALID_PARAMS, message: 'This service does not support named parameters.' }}); } } // Reply with the given err and result function reply(err, result){ if (err) { if (typeof err === 'number') { respond({ error: { code: err } }); } else { respond({ error: { code: err.code || INTERNAL_ERROR, message: err.message } }); } } else { respond({ result: result }); } } // Push reply function as the last argument params.push(reply); // Invoke the method try { method.apply(this, params); } catch (err) { reply(err); } } else { respond({ error: { code: METHOD_NOT_FOUND }}); } } else { respond({ error: { code: INVALID_REQUEST }}); } } return function jsonrpc(req, res, next) { var me = this, contentType = req.headers['content-type'] || ''; if (httpMethod && req.method !== httpMethod.toUpperCase()) return next(); if (contentType.indexOf('application/json') < 0) return next(); var data = ''; /** * Normalize response object. */ function normalize(rpc, obj) { obj.id = rpc && typeof rpc.id === 'number' ? rpc.id : null; obj.jsonrpc = VERSION; if (obj.error && !obj.error.message) { obj.error.message = errorMessages[obj.error.code]; } return obj; } /** * Respond with the given response object. */ function respond(obj) { var body = JSON.stringify(obj); res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }); res.end(body); } function handleRequests(rpc) { var batch = Array.isArray(rpc); // Handle requests if (batch) { var responses = [], len = rpc.length, pending = len; for (var i = 0; i < len; ++i) { (function(rpc){ handleRequest.call(me, rpc, function(obj){ responses.push(normalize(rpc, obj)); if (!--pending) { respond(responses); } }); })(rpc[i]); } } else { handleRequest.call(me, rpc, function(obj){ respond(normalize(rpc, obj)); }); } } if (req.body) handleRequests(req.body); else { req.setEncoding('utf8'); req.addListener('data', function(chunk) { data += chunk; }); req.addListener('end', function() { // Attempt to parse incoming JSON string try { var rpc = JSON.parse(data); } catch (err) { return respond(normalize(rpc, { error: { code: PARSE_ERROR }})); } handleRequests(rpc); }); } }; }; /** * Check if the given request is a valid * JSON remote procedure call. * * - "jsonrpc" must match the supported version ('2.0') * - "id" must be numeric * - "method" must be a string * * @param {Object} rpc * @return {Boolean} * @api private */ function validRequest(rpc){ return rpc.jsonrpc === VERSION && (typeof rpc.id === 'number' || typeof rpc.id === 'string') && typeof rpc.method === 'string'; } exports.route = jsonrpc; exports.serve = function(services) { return jsonrpc(services, "POST"); }
#!/usr/bin/env node /* mrkdwn v0.1.0 : github.com/benvacha/mrkdwn */ /* Test suite for javascript mrkdwn implementation. Exercises the mrkdwn implementation through node interface. Requires: colors : https://github.com/Marak/colors.js diff : https://github.com/kpdecker/jsdiff All Commands From Root (not javascript) Directory Initial Setup npm install colors npm install diff Run All Tests, prints pass or fail node javascript/test.js Run All Tests, prints pass or fail and diff node javascript/test.js -v Run A Test, prints pass or fail node javascript/test.js testName Run A Test, prints pass or fail and diff node javascript/test.js -v testName Run Multiple Tests, prints pass or fail node javascript/test.js testName testName testName Run Multiple Tests, prints pass or fail and diff node javascript/test.js -v testName testName testName */ /* * */ // import node modules var fs = require('fs'), colors = require('colors'), jsdiff = require('diff'), mrkdwn = require('./mrkdwn.js'); // parse command line arguements var testDirectory = 'test/', verbose = false, testRuns = []; for(var i=2; i<process.argv.length; i++) { if(process.argv[i] === '-v') { verbose = true; } else { testRuns.push(process.argv[i]); } } /* * */ var utils = { // return blank string if invalid file, else return file contents as string readFile: function(fileName) { fileName = testDirectory + fileName; if(!fs.existsSync(fileName)) { console.log('## Invalid File: ' + fileName); return ''; } return fs.readFileSync(fileName, {encoding:'utf8'}) }, // load markdownFile and markupFile, run testMethod on the markdown, return diff runTest: function(test) { if(!test) return null; var markdown = utils.readFile(test.markdown), markup = utils.readFile(test.markup); return jsdiff.diffChars(markup, test.method(markdown)); }, // print if the test passed or failed printPassFail: function(testName, diff) { if(diff && diff.length === 1) { console.log('# Passed Test: ' + testName); } else if(diff) { console.log('# Failed Test: ' + testName); } else { console.log('# Invalid Test: ' + testName); } }, // print if the test passed or failed, print color coded diff printPassFailDiff: function(testName, diff) { utils.printPassFail(testName, diff); if(diff) { diff.forEach(function(part){ if(part.added || part.removed) { part.value = part.value.replace(/ /g, '_'); } process.stdout.write(part.value.replace(/\n/g, '\\n\n')[part.added ? 'green' : part.removed ? 'red' : 'grey']); }); } console.log('# End Test: ' + testName + '\n'); } }; /* * */ var tests = { escapedChars: { markdown: 'unit/escaped-chars.markdown', markup: 'unit/escaped-chars.markup', method: mrkdwn.markup.escapedChars }, comments: { markdown: 'unit/comments.markdown', markup: 'unit/comments.markup', method: mrkdwn.markup.comments }, metas: { markdown: 'unit/metas.markdown', markup: 'unit/metas.markup', method: mrkdwn.markup.metas }, blockquotes: { markdown: 'unit/blockquotes.markdown', markup: 'unit/blockquotes.markup', method: mrkdwn.markup.blockquotes }, details: { markdown: 'unit/details.markdown', markup: 'unit/details.markup', method: mrkdwn.markup.details }, lists: { markdown: 'unit/lists.markdown', markup: 'unit/lists.markup', method: mrkdwn.markup.lists }, codes: { markdown: 'unit/codes.markdown', markup: 'unit/codes.markup', method: mrkdwn.markup.codesSamples }, samples: { markdown: 'unit/samples.markdown', markup: 'unit/samples.markup', method: mrkdwn.markup.codesSamples }, variables: { markdown: 'unit/variables.markdown', markup: 'unit/variables.markup', method: mrkdwn.markup.variables }, abbreviations: { markdown: 'unit/abbreviations.markdown', markup: 'unit/abbreviations.markup', method: mrkdwn.markup.abbreviations }, images: { markdown: 'unit/images.markdown', markup: 'unit/images.markup', method: mrkdwn.markup.images }, macros: { markdown: 'unit/macros.markdown', markup: 'unit/macros.markup', method: mrkdwn.markup.macros }, citations: { markdown: 'unit/citations.markdown', markup: 'unit/citations.markup', method: mrkdwn.markup.citations }, notes: { markdown: 'unit/notes.markdown', markup: 'unit/notes.markup', method: mrkdwn.markup.notes }, links: { markdown: 'unit/links.markdown', markup: 'unit/links.markup', method: mrkdwn.markup.links }, headers: { markdown: 'unit/headers.markdown', markup: 'unit/headers.markup', method: mrkdwn.markup.headers }, horizontalRules: { markdown: 'unit/horizontal-rules.markdown', markup: 'unit/horizontal-rules.markup', method: mrkdwn.markup.horizontalRules }, phraseFormattings: { markdown: 'unit/phrase-formattings.markdown', markup: 'unit/phrase-formattings.markup', method: mrkdwn.markup.phraseFormattings }, spans: { markdown: 'unit/spans.markdown', markup: 'unit/spans.markup', method: mrkdwn.markup.spans }, tables: { markdown: 'unit/tables.markdown', markup: 'unit/tables.markup', method: mrkdwn.markup.tables }, paragraphs: { markdown: 'unit/paragraphs.markdown', markup: 'unit/paragraphs.markup', method: mrkdwn.markup.paragraphs } }; /* * */ // if tests specified, run just those // if no tests specified, run all tests // if verbose print pass or fail and diff // if not verbose print pass or fail var diff; if(testRuns.length) { for(var i=0; i<testRuns.length; i++) { diff = utils.runTest(tests[testRuns[i]]); if(verbose) { utils.printPassFailDiff(testRuns[i], diff); } else { utils.printPassFail(testRuns[i], diff); } } } else { for(var test in tests) { diff = utils.runTest(tests[test]); if(verbose) { utils.printPassFailDiff(test, diff); } else { utils.printPassFail(test, diff); } } }
'use strict'; var cls = require('continuation-local-storage') var logContext = cls.createNamespace('app-log-ctx') module.exports = function (req, res, next) { logContext.bindEmitter(req) logContext.bindEmitter(res) logContext.run(function () { logContext.set('requestId', req.headers['x-unique-id']) logContext.set('sessionId', req.cookies['accessToken']) logContext.set('clientIP', req.ip) next() }) }
function deletePref(player, element) { var prefs = JSON.parse(localStorage['prefs']); delete prefs[player]; localStorage['prefs'] = JSON.stringify(prefs); element.parentElement.removeChild(element); } function listPlayers() { var prefs = {}; if (localStorage['prefs']) { prefs = JSON.parse(localStorage['prefs']); } // clear the list of player prefs var playersList = document.getElementById("players"); while (playersList.firstChild) { playersList.removeChild(playersList.firstChild); } // build list of player prefs from localStorage for (let name in prefs) { let pref_el = document.createElement('div'); pref_el.className = 'pref'; var name_el = document.createElement('span'); name_el.innerText = name; name_el.className = 'name'; pref_el.appendChild(name_el); var image_list = document.createElement('div'); for (var hero in prefs[name]) { var hero_img = document.createElement("img"); hero_img.src = "/static/img/" + prefs[name][hero] + ".png"; image_list.appendChild(hero_img); } var delete_button = document.createElement('div'); delete_button.className = 'delete'; delete_button.innerText = '✖'; delete_button.addEventListener('click', function() { deletePref(name, pref_el); }); pref_el.appendChild(delete_button); pref_el.appendChild(image_list); playersList.appendChild(pref_el); } } function savePlayer(e) { e.preventDefault(); var prefs = {}; if (localStorage['prefs']) { prefs = JSON.parse(localStorage['prefs']); } var form = document.getElementById("new_player"); var playerName = form.elements['player_name'].value; prefs[playerName] = []; var hero_prefs = form.elements['hero_pref']; for (var i = 0; i < hero_prefs.length; i++) { if (hero_prefs[i].checked) { prefs[playerName].push(hero_prefs[i].value); hero_prefs[i].checked = false; } } form.elements['player_name'].value = ""; localStorage['prefs'] = JSON.stringify(prefs); listPlayers(); } function ready(fn) { if (document.readyState != 'loading'){ fn(); } else { document.addEventListener('DOMContentLoaded', fn); } } ready(function() { var form = document.getElementById("new_player"); form.addEventListener("submit", savePlayer, false); listPlayers(); });
/* * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Web Client * Copyright (C) 2009, 2010 Zimbra, Inc. * * The contents of this file are subject to the Zimbra Public License * Version 1.3 ("License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.zimbra.com/license. * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. * ***** END LICENSE BLOCK ***** */ /* Copyright (c) 2009, Yahoo! Inc. All rights reserved. Code licensed under the BSD License: http://developer.yahoo.net/yui/license.txt version: 2.7.0 */ (function () { var lang = YAHOO.lang, util = YAHOO.util, Ev = util.Event; /** * The DataSource utility provides a common configurable interface for widgets to * access a variety of data, from JavaScript arrays to online database servers. * * @module datasource * @requires yahoo, event * @optional json, get, connection * @title DataSource Utility */ /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * Base class for the YUI DataSource utility. * * @namespace YAHOO.util * @class YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.DataSourceBase = function(oLiveData, oConfigs) { if(oLiveData === null || oLiveData === undefined) { return; } this.liveData = oLiveData; this._oQueue = {interval:null, conn:null, requests:[]}; this.responseSchema = {}; // Set any config params passed in to override defaults if(oConfigs && (oConfigs.constructor == Object)) { for(var sConfig in oConfigs) { if(sConfig) { this[sConfig] = oConfigs[sConfig]; } } } // Validate and initialize public configs var maxCacheEntries = this.maxCacheEntries; if(!lang.isNumber(maxCacheEntries) || (maxCacheEntries < 0)) { maxCacheEntries = 0; } // Initialize interval tracker this._aIntervals = []; ///////////////////////////////////////////////////////////////////////////// // // Custom Events // ///////////////////////////////////////////////////////////////////////////// /** * Fired when a request is made to the local cache. * * @event cacheRequestEvent * @param oArgs.request {Object} The request object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("cacheRequestEvent"); /** * Fired when data is retrieved from the local cache. * * @event cacheResponseEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {Object} The response object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("cacheResponseEvent"); /** * Fired when a request is sent to the live data source. * * @event requestEvent * @param oArgs.request {Object} The request object. * @param oArgs.callback {Object} The callback object. * @param oArgs.tId {Number} Transaction ID. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("requestEvent"); /** * Fired when live data source sends response. * * @event responseEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {Object} The raw response object. * @param oArgs.callback {Object} The callback object. * @param oArgs.tId {Number} Transaction ID. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("responseEvent"); /** * Fired when response is parsed. * * @event responseParseEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {Object} The parsed response object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("responseParseEvent"); /** * Fired when response is cached. * * @event responseCacheEvent * @param oArgs.request {Object} The request object. * @param oArgs.response {Object} The parsed response object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. */ this.createEvent("responseCacheEvent"); /** * Fired when an error is encountered with the live data source. * * @event dataErrorEvent * @param oArgs.request {Object} The request object. * @param oArgs.callback {Object} The callback object. * @param oArgs.caller {Object} (deprecated) Use callback.scope. * @param oArgs.message {String} The error message. */ this.createEvent("dataErrorEvent"); /** * Fired when the local cache is flushed. * * @event cacheFlushEvent */ this.createEvent("cacheFlushEvent"); var DS = util.DataSourceBase; this._sName = "DataSource instance" + DS._nIndex; DS._nIndex++; }; var DS = util.DataSourceBase; lang.augmentObject(DS, { ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase public constants // ///////////////////////////////////////////////////////////////////////////// /** * Type is unknown. * * @property TYPE_UNKNOWN * @type Number * @final * @default -1 */ TYPE_UNKNOWN : -1, /** * Type is a JavaScript Array. * * @property TYPE_JSARRAY * @type Number * @final * @default 0 */ TYPE_JSARRAY : 0, /** * Type is a JavaScript Function. * * @property TYPE_JSFUNCTION * @type Number * @final * @default 1 */ TYPE_JSFUNCTION : 1, /** * Type is hosted on a server via an XHR connection. * * @property TYPE_XHR * @type Number * @final * @default 2 */ TYPE_XHR : 2, /** * Type is JSON. * * @property TYPE_JSON * @type Number * @final * @default 3 */ TYPE_JSON : 3, /** * Type is XML. * * @property TYPE_XML * @type Number * @final * @default 4 */ TYPE_XML : 4, /** * Type is plain text. * * @property TYPE_TEXT * @type Number * @final * @default 5 */ TYPE_TEXT : 5, /** * Type is an HTML TABLE element. Data is parsed out of TR elements from all TBODY elements. * * @property TYPE_HTMLTABLE * @type Number * @final * @default 6 */ TYPE_HTMLTABLE : 6, /** * Type is hosted on a server via a dynamic script node. * * @property TYPE_SCRIPTNODE * @type Number * @final * @default 7 */ TYPE_SCRIPTNODE : 7, /** * Type is local. * * @property TYPE_LOCAL * @type Number * @final * @default 8 */ TYPE_LOCAL : 8, /** * Error message for invalid dataresponses. * * @property ERROR_DATAINVALID * @type String * @final * @default "Invalid data" */ ERROR_DATAINVALID : "Invalid data", /** * Error message for null data responses. * * @property ERROR_DATANULL * @type String * @final * @default "Null data" */ ERROR_DATANULL : "Null data", ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase private static properties // ///////////////////////////////////////////////////////////////////////////// /** * Internal class variable to index multiple DataSource instances. * * @property DataSourceBase._nIndex * @type Number * @private * @static */ _nIndex : 0, /** * Internal class variable to assign unique transaction IDs. * * @property DataSourceBase._nTransactionId * @type Number * @private * @static */ _nTransactionId : 0, ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase public static methods // ///////////////////////////////////////////////////////////////////////////// /** * Executes a configured callback. For object literal callbacks, the third * param determines whether to execute the success handler or failure handler. * * @method issueCallback * @param callback {Function|Object} the callback to execute * @param params {Array} params to be passed to the callback method * @param error {Boolean} whether an error occurred * @param scope {Object} the scope from which to execute the callback * (deprecated - use an object literal callback) * @static */ issueCallback : function (callback,params,error,scope) { if (lang.isFunction(callback)) { callback.apply(scope, params); } else if (lang.isObject(callback)) { scope = callback.scope || scope || window; var callbackFunc = callback.success; if (error) { callbackFunc = callback.failure; } if (callbackFunc) { callbackFunc.apply(scope, params.concat([callback.argument])); } } }, /** * Converts data to type String. * * @method DataSourceBase.parseString * @param oData {String | Number | Boolean | Date | Array | Object} Data to parse. * The special values null and undefined will return null. * @return {String} A string, or null. * @static */ parseString : function(oData) { // Special case null and undefined if(!lang.isValue(oData)) { return null; } //Convert to string var string = oData + ""; // Validate if(lang.isString(string)) { return string; } else { return null; } }, /** * Converts data to type Number. * * @method DataSourceBase.parseNumber * @param oData {String | Number | Boolean} Data to convert. Note, the following * values return as null: null, undefined, NaN, "". * @return {Number} A number, or null. * @static */ parseNumber : function(oData) { if(!lang.isValue(oData) || (oData === "")) { return null; } //Convert to number var number = oData * 1; // Validate if(lang.isNumber(number)) { return number; } else { return null; } }, // Backward compatibility convertNumber : function(oData) { return DS.parseNumber(oData); }, /** * Converts data to type Date. * * @method DataSourceBase.parseDate * @param oData {Date | String | Number} Data to convert. * @return {Date} A Date instance. * @static */ parseDate : function(oData) { var date = null; //Convert to date if(!(oData instanceof Date)) { date = new Date(oData); } else { return oData; } // Validate if(date instanceof Date) { return date; } else { return null; } }, // Backward compatibility convertDate : function(oData) { return DS.parseDate(oData); } }); // Done in separate step so referenced functions are defined. /** * Data parsing functions. * @property DataSource.Parser * @type Object * @static */ DS.Parser = { string : DS.parseString, number : DS.parseNumber, date : DS.parseDate }; // Prototype properties and methods DS.prototype = { ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase private properties // ///////////////////////////////////////////////////////////////////////////// /** * Name of DataSource instance. * * @property _sName * @type String * @private */ _sName : null, /** * Local cache of data result object literals indexed chronologically. * * @property _aCache * @type Object[] * @private */ _aCache : null, /** * Local queue of request connections, enabled if queue needs to be managed. * * @property _oQueue * @type Object * @private */ _oQueue : null, /** * Array of polling interval IDs that have been enabled, needed to clear all intervals. * * @property _aIntervals * @type Array * @private */ _aIntervals : null, ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase public properties // ///////////////////////////////////////////////////////////////////////////// /** * Max size of the local cache. Set to 0 to turn off caching. Caching is * useful to reduce the number of server connections. Recommended only for data * sources that return comprehensive results for queries or when stale data is * not an issue. * * @property maxCacheEntries * @type Number * @default 0 */ maxCacheEntries : 0, /** * Pointer to live database. * * @property liveData * @type Object */ liveData : null, /** * Where the live data is held: * * <dl> * <dt>TYPE_UNKNOWN</dt> * <dt>TYPE_LOCAL</dt> * <dt>TYPE_XHR</dt> * <dt>TYPE_SCRIPTNODE</dt> * <dt>TYPE_JSFUNCTION</dt> * </dl> * * @property dataType * @type Number * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN * */ dataType : DS.TYPE_UNKNOWN, /** * Format of response: * * <dl> * <dt>TYPE_UNKNOWN</dt> * <dt>TYPE_JSARRAY</dt> * <dt>TYPE_JSON</dt> * <dt>TYPE_XML</dt> * <dt>TYPE_TEXT</dt> * <dt>TYPE_HTMLTABLE</dt> * </dl> * * @property responseType * @type Number * @default YAHOO.util.DataSourceBase.TYPE_UNKNOWN */ responseType : DS.TYPE_UNKNOWN, /** * Response schema object literal takes a combination of the following properties: * * <dl> * <dt>resultsList</dt> <dd>Pointer to array of tabular data</dd> * <dt>resultNode</dt> <dd>Pointer to node name of row data (XML data only)</dd> * <dt>recordDelim</dt> <dd>Record delimiter (text data only)</dd> * <dt>fieldDelim</dt> <dd>Field delimiter (text data only)</dd> * <dt>fields</dt> <dd>Array of field names (aka keys), or array of object literals * such as: {key:"fieldname",parser:YAHOO.util.DataSourceBase.parseDate}</dd> * <dt>metaFields</dt> <dd>Object literal of keys to include in the oParsedResponse.meta collection</dd> * <dt>metaNode</dt> <dd>Name of the node under which to search for meta information in XML response data</dd> * </dl> * * @property responseSchema * @type Object */ responseSchema : null, /** * Additional arguments passed to the JSON parse routine. The JSON string * is the assumed first argument (where applicable). This property is not * set by default, but the parse methods will use it if present. * * @property parseJSONArgs * @type {MIXED|Array} If an Array, contents are used as individual arguments. * Otherwise, value is used as an additional argument. */ // property intentionally undefined ///////////////////////////////////////////////////////////////////////////// // // DataSourceBase public methods // ///////////////////////////////////////////////////////////////////////////// /** * Public accessor to the unique name of the DataSource instance. * * @method toString * @return {String} Unique name of the DataSource instance. */ toString : function() { return this._sName; }, /** * Overridable method passes request to cache and returns cached response if any, * refreshing the hit in the cache as the newest item. Returns null if there is * no cache hit. * * @method getCachedResponse * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object. * @param oCaller {Object} (deprecated) Use callback object. * @return {Object} Cached response object or null. */ getCachedResponse : function(oRequest, oCallback, oCaller) { var aCache = this._aCache; // If cache is enabled... if(this.maxCacheEntries > 0) { // Initialize local cache if(!aCache) { this._aCache = []; } // Look in local cache else { var nCacheLength = aCache.length; if(nCacheLength > 0) { var oResponse = null; this.fireEvent("cacheRequestEvent", {request:oRequest,callback:oCallback,caller:oCaller}); // Loop through each cached element for(var i = nCacheLength-1; i >= 0; i--) { var oCacheElem = aCache[i]; // Defer cache hit logic to a public overridable method if(this.isCacheHit(oRequest,oCacheElem.request)) { // The cache returned a hit! // Grab the cached response oResponse = oCacheElem.response; this.fireEvent("cacheResponseEvent", {request:oRequest,response:oResponse,callback:oCallback,caller:oCaller}); // Refresh the position of the cache hit if(i < nCacheLength-1) { // Remove element from its original location aCache.splice(i,1); // Add as newest this.addToCache(oRequest, oResponse); } // Add a cache flag oResponse.cached = true; break; } } return oResponse; } } } else if(aCache) { this._aCache = null; } return null; }, /** * Default overridable method matches given request to given cached request. * Returns true if is a hit, returns false otherwise. Implementers should * override this method to customize the cache-matching algorithm. * * @method isCacheHit * @param oRequest {Object} Request object. * @param oCachedRequest {Object} Cached request object. * @return {Boolean} True if given request matches cached request, false otherwise. */ isCacheHit : function(oRequest, oCachedRequest) { return (oRequest === oCachedRequest); }, /** * Adds a new item to the cache. If cache is full, evicts the stalest item * before adding the new item. * * @method addToCache * @param oRequest {Object} Request object. * @param oResponse {Object} Response object to cache. */ addToCache : function(oRequest, oResponse) { var aCache = this._aCache; if(!aCache) { return; } // If the cache is full, make room by removing stalest element (index=0) while(aCache.length >= this.maxCacheEntries) { aCache.shift(); } // Add to cache in the newest position, at the end of the array var oCacheElem = {request:oRequest,response:oResponse}; aCache[aCache.length] = oCacheElem; this.fireEvent("responseCacheEvent", {request:oRequest,response:oResponse}); }, /** * Flushes cache. * * @method flushCache */ flushCache : function() { if(this._aCache) { this._aCache = []; this.fireEvent("cacheFlushEvent"); } }, /** * Sets up a polling mechanism to send requests at set intervals and forward * responses to given callback. * * @method setInterval * @param nMsec {Number} Length of interval in milliseconds. * @param oRequest {Object} Request object. * @param oCallback {Function} Handler function to receive the response. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Interval ID. */ setInterval : function(nMsec, oRequest, oCallback, oCaller) { if(lang.isNumber(nMsec) && (nMsec >= 0)) { var oSelf = this; var nId = setInterval(function() { oSelf.makeConnection(oRequest, oCallback, oCaller); }, nMsec); this._aIntervals.push(nId); return nId; } else { } }, /** * Disables polling mechanism associated with the given interval ID. * * @method clearInterval * @param nId {Number} Interval ID. */ clearInterval : function(nId) { // Remove from tracker if there var tracker = this._aIntervals || []; for(var i=tracker.length-1; i>-1; i--) { if(tracker[i] === nId) { tracker.splice(i,1); clearInterval(nId); } } }, /** * Disables all known polling intervals. * * @method clearAllIntervals */ clearAllIntervals : function() { var tracker = this._aIntervals || []; for(var i=tracker.length-1; i>-1; i--) { clearInterval(tracker[i]); } tracker = []; }, /** * First looks for cached response, then sends request to live data. The * following arguments are passed to the callback function: * <dl> * <dt><code>oRequest</code></dt> * <dd>The same value that was passed in as the first argument to sendRequest.</dd> * <dt><code>oParsedResponse</code></dt> * <dd>An object literal containing the following properties: * <dl> * <dt><code>tId</code></dt> * <dd>Unique transaction ID number.</dd> * <dt><code>results</code></dt> * <dd>Schema-parsed data results.</dd> * <dt><code>error</code></dt> * <dd>True in cases of data error.</dd> * <dt><code>cached</code></dt> * <dd>True when response is returned from DataSource cache.</dd> * <dt><code>meta</code></dt> * <dd>Schema-parsed meta data.</dd> * </dl> * <dt><code>oPayload</code></dt> * <dd>The same value as was passed in as <code>argument</code> in the oCallback object literal.</dd> * </dl> * * @method sendRequest * @param oRequest {Object} Request object. * @param oCallback {Object} An object literal with the following properties: * <dl> * <dt><code>success</code></dt> * <dd>The function to call when the data is ready.</dd> * <dt><code>failure</code></dt> * <dd>The function to call upon a response failure condition.</dd> * <dt><code>scope</code></dt> * <dd>The object to serve as the scope for the success and failure handlers.</dd> * <dt><code>argument</code></dt> * <dd>Arbitrary data that will be passed back to the success and failure handlers.</dd> * </dl> * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID, or null if response found in cache. */ sendRequest : function(oRequest, oCallback, oCaller) { // First look in cache var oCachedResponse = this.getCachedResponse(oRequest, oCallback, oCaller); if(oCachedResponse) { DS.issueCallback(oCallback,[oRequest,oCachedResponse],false,oCaller); return null; } // Not in cache, so forward request to live data return this.makeConnection(oRequest, oCallback, oCaller); }, /** * Overridable default method generates a unique transaction ID and passes * the live data reference directly to the handleResponse function. This * method should be implemented by subclasses to achieve more complex behavior * or to access remote data. * * @method makeConnection * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID. */ makeConnection : function(oRequest, oCallback, oCaller) { var tId = DS._nTransactionId++; this.fireEvent("requestEvent", {tId:tId, request:oRequest,callback:oCallback,caller:oCaller}); /* accounts for the following cases: YAHOO.util.DataSourceBase.TYPE_UNKNOWN YAHOO.util.DataSourceBase.TYPE_JSARRAY YAHOO.util.DataSourceBase.TYPE_JSON YAHOO.util.DataSourceBase.TYPE_HTMLTABLE YAHOO.util.DataSourceBase.TYPE_XML YAHOO.util.DataSourceBase.TYPE_TEXT */ var oRawResponse = this.liveData; this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); return tId; }, /** * Receives raw data response and type converts to XML, JSON, etc as necessary. * Forwards oFullResponse to appropriate parsing function to get turned into * oParsedResponse. Calls doBeforeCallback() and adds oParsedResponse to * the cache when appropriate before calling issueCallback(). * * The oParsedResponse object literal has the following properties: * <dl> * <dd><dt>tId {Number}</dt> Unique transaction ID</dd> * <dd><dt>results {Array}</dt> Array of parsed data results</dd> * <dd><dt>meta {Object}</dt> Object literal of meta values</dd> * <dd><dt>error {Boolean}</dt> (optional) True if there was an error</dd> * <dd><dt>cached {Boolean}</dt> (optional) True if response was cached</dd> * </dl> * * @method handleResponse * @param oRequest {Object} Request object * @param oRawResponse {Object} The raw response from the live database. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @param tId {Number} Transaction ID. */ handleResponse : function(oRequest, oRawResponse, oCallback, oCaller, tId) { this.fireEvent("responseEvent", {tId:tId, request:oRequest, response:oRawResponse, callback:oCallback, caller:oCaller}); var xhr = (this.dataType == DS.TYPE_XHR) ? true : false; var oParsedResponse = null; var oFullResponse = oRawResponse; // Try to sniff data type if it has not been defined if(this.responseType === DS.TYPE_UNKNOWN) { var ctype = (oRawResponse && oRawResponse.getResponseHeader) ? oRawResponse.getResponseHeader["Content-Type"] : null; if(ctype) { // xml if(ctype.indexOf("text/xml") > -1) { this.responseType = DS.TYPE_XML; } else if(ctype.indexOf("application/json") > -1) { // json this.responseType = DS.TYPE_JSON; } else if(ctype.indexOf("text/plain") > -1) { // text this.responseType = DS.TYPE_TEXT; } } else { if(YAHOO.lang.isArray(oRawResponse)) { // array this.responseType = DS.TYPE_JSARRAY; } // xml else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) { this.responseType = DS.TYPE_XML; } else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table this.responseType = DS.TYPE_HTMLTABLE; } else if(YAHOO.lang.isObject(oRawResponse)) { // json this.responseType = DS.TYPE_JSON; } else if(YAHOO.lang.isString(oRawResponse)) { // text this.responseType = DS.TYPE_TEXT; } } } switch(this.responseType) { case DS.TYPE_JSARRAY: if(xhr && oRawResponse && oRawResponse.responseText) { oFullResponse = oRawResponse.responseText; } try { // Convert to JS array if it's a string if(lang.isString(oFullResponse)) { var parseArgs = [oFullResponse].concat(this.parseJSONArgs); // Check for YUI JSON Util if(lang.JSON) { oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs); } // Look for JSON parsers using an API similar to json2.js else if(window.JSON && JSON.parse) { oFullResponse = JSON.parse.apply(JSON,parseArgs); } // Look for JSON parsers using an API similar to json.js else if(oFullResponse.parseJSON) { oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1)); } // No JSON lib found so parse the string else { // Trim leading spaces while (oFullResponse.length > 0 && (oFullResponse.charAt(0) != "{") && (oFullResponse.charAt(0) != "[")) { oFullResponse = oFullResponse.substring(1, oFullResponse.length); } if(oFullResponse.length > 0) { // Strip extraneous stuff at the end var arrayEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}")); oFullResponse = oFullResponse.substring(0,arrayEnd+1); // Turn the string into an object literal... // ...eval is necessary here oFullResponse = eval("(" + oFullResponse + ")"); } } } } catch(e1) { } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseArrayData(oRequest, oFullResponse); break; case DS.TYPE_JSON: if(xhr && oRawResponse && oRawResponse.responseText) { oFullResponse = oRawResponse.responseText; } try { // Convert to JSON object if it's a string if(lang.isString(oFullResponse)) { var parseArgs = [oFullResponse].concat(this.parseJSONArgs); // Check for YUI JSON Util if(lang.JSON) { oFullResponse = lang.JSON.parse.apply(lang.JSON,parseArgs); } // Look for JSON parsers using an API similar to json2.js else if(window.JSON && JSON.parse) { oFullResponse = JSON.parse.apply(JSON,parseArgs); } // Look for JSON parsers using an API similar to json.js else if(oFullResponse.parseJSON) { oFullResponse = oFullResponse.parseJSON.apply(oFullResponse,parseArgs.slice(1)); } // No JSON lib found so parse the string else { // Trim leading spaces while (oFullResponse.length > 0 && (oFullResponse.charAt(0) != "{") && (oFullResponse.charAt(0) != "[")) { oFullResponse = oFullResponse.substring(1, oFullResponse.length); } if(oFullResponse.length > 0) { // Strip extraneous stuff at the end var objEnd = Math.max(oFullResponse.lastIndexOf("]"),oFullResponse.lastIndexOf("}")); oFullResponse = oFullResponse.substring(0,objEnd+1); // Turn the string into an object literal... // ...eval is necessary here oFullResponse = eval("(" + oFullResponse + ")"); } } } } catch(e) { } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseJSONData(oRequest, oFullResponse); break; case DS.TYPE_HTMLTABLE: if(xhr && oRawResponse.responseText) { var el = document.createElement('div'); el.innerHTML = oRawResponse.responseText; oFullResponse = el.getElementsByTagName('table')[0]; } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseHTMLTableData(oRequest, oFullResponse); break; case DS.TYPE_XML: if(xhr && oRawResponse.responseXML) { oFullResponse = oRawResponse.responseXML; } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseXMLData(oRequest, oFullResponse); break; case DS.TYPE_TEXT: if(xhr && lang.isString(oRawResponse.responseText)) { oFullResponse = oRawResponse.responseText; } oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseTextData(oRequest, oFullResponse); break; default: oFullResponse = this.doBeforeParseData(oRequest, oFullResponse, oCallback); oParsedResponse = this.parseData(oRequest, oFullResponse); break; } // Clean up for consistent signature oParsedResponse = oParsedResponse || {}; if(!oParsedResponse.results) { oParsedResponse.results = []; } if(!oParsedResponse.meta) { oParsedResponse.meta = {}; } // Success if(oParsedResponse && !oParsedResponse.error) { // Last chance to touch the raw response or the parsed response oParsedResponse = this.doBeforeCallback(oRequest, oFullResponse, oParsedResponse, oCallback); this.fireEvent("responseParseEvent", {request:oRequest, response:oParsedResponse, callback:oCallback, caller:oCaller}); // Cache the response this.addToCache(oRequest, oParsedResponse); } // Error else { // Be sure the error flag is on oParsedResponse.error = true; this.fireEvent("dataErrorEvent", {request:oRequest, response: oRawResponse, callback:oCallback, caller:oCaller, message:DS.ERROR_DATANULL}); } // Send the response back to the caller oParsedResponse.tId = tId; DS.issueCallback(oCallback,[oRequest,oParsedResponse],oParsedResponse.error,oCaller); }, /** * Overridable method gives implementers access to the original full response * before the data gets parsed. Implementers should take care not to return an * unparsable or otherwise invalid response. * * @method doBeforeParseData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full response from the live database. * @param oCallback {Object} The callback object. * @return {Object} Full response for parsing. */ doBeforeParseData : function(oRequest, oFullResponse, oCallback) { return oFullResponse; }, /** * Overridable method gives implementers access to the original full response and * the parsed response (parsed against the given schema) before the data * is added to the cache (if applicable) and then sent back to callback function. * This is your chance to access the raw response and/or populate the parsed * response with any custom data. * * @method doBeforeCallback * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full response from the live database. * @param oParsedResponse {Object} The parsed response to return to calling object. * @param oCallback {Object} The callback object. * @return {Object} Parsed response object. */ doBeforeCallback : function(oRequest, oFullResponse, oParsedResponse, oCallback) { return oParsedResponse; }, /** * Overridable method parses data of generic RESPONSE_TYPE into a response object. * * @method parseData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full Array from the live database. * @return {Object} Parsed response object with the following properties:<br> * - results {Array} Array of parsed data results<br> * - meta {Object} Object literal of meta values<br> * - error {Boolean} (optional) True if there was an error<br> */ parseData : function(oRequest, oFullResponse) { if(lang.isValue(oFullResponse)) { var oParsedResponse = {results:oFullResponse,meta:{}}; return oParsedResponse; } return null; }, /** * Overridable method parses Array data into a response object. * * @method parseArrayData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full Array from the live database. * @return {Object} Parsed response object with the following properties:<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseArrayData : function(oRequest, oFullResponse) { if(lang.isArray(oFullResponse)) { var results = [], i, j, rec, field, data; // Parse for fields if(lang.isArray(this.responseSchema.fields)) { var fields = this.responseSchema.fields; for (i = fields.length - 1; i >= 0; --i) { if (typeof fields[i] !== 'object') { fields[i] = { key : fields[i] }; } } var parsers = {}, p; for (i = fields.length - 1; i >= 0; --i) { p = (typeof fields[i].parser === 'function' ? fields[i].parser : DS.Parser[fields[i].parser+'']) || fields[i].converter; if (p) { parsers[fields[i].key] = p; } } var arrType = lang.isArray(oFullResponse[0]); for(i=oFullResponse.length-1; i>-1; i--) { var oResult = {}; rec = oFullResponse[i]; if (typeof rec === 'object') { for(j=fields.length-1; j>-1; j--) { field = fields[j]; data = arrType ? rec[j] : rec[field.key]; if (parsers[field.key]) { data = parsers[field.key].call(this,data); } // Safety measure if(data === undefined) { data = null; } oResult[field.key] = data; } } else if (lang.isString(rec)) { for(j=fields.length-1; j>-1; j--) { field = fields[j]; data = rec; if (parsers[field.key]) { data = parsers[field.key].call(this,data); } // Safety measure if(data === undefined) { data = null; } oResult[field.key] = data; } } results[i] = oResult; } } // Return entire data set else { results = oFullResponse; } var oParsedResponse = {results:results}; return oParsedResponse; } return null; }, /** * Overridable method parses plain text data into a response object. * * @method parseTextData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full text response from the live database. * @return {Object} Parsed response object with the following properties:<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseTextData : function(oRequest, oFullResponse) { if(lang.isString(oFullResponse)) { if(lang.isString(this.responseSchema.recordDelim) && lang.isString(this.responseSchema.fieldDelim)) { var oParsedResponse = {results:[]}; var recDelim = this.responseSchema.recordDelim; var fieldDelim = this.responseSchema.fieldDelim; if(oFullResponse.length > 0) { // Delete the last line delimiter at the end of the data if it exists var newLength = oFullResponse.length-recDelim.length; if(oFullResponse.substr(newLength) == recDelim) { oFullResponse = oFullResponse.substr(0, newLength); } if(oFullResponse.length > 0) { // Split along record delimiter to get an array of strings var recordsarray = oFullResponse.split(recDelim); // Cycle through each record for(var i = 0, len = recordsarray.length, recIdx = 0; i < len; ++i) { var bError = false, sRecord = recordsarray[i]; if (lang.isString(sRecord) && (sRecord.length > 0)) { // Split each record along field delimiter to get data var fielddataarray = recordsarray[i].split(fieldDelim); var oResult = {}; // Filter for fields data if(lang.isArray(this.responseSchema.fields)) { var fields = this.responseSchema.fields; for(var j=fields.length-1; j>-1; j--) { try { // Remove quotation marks from edges, if applicable var data = fielddataarray[j]; if (lang.isString(data)) { if(data.charAt(0) == "\"") { data = data.substr(1); } if(data.charAt(data.length-1) == "\"") { data = data.substr(0,data.length-1); } var field = fields[j]; var key = (lang.isValue(field.key)) ? field.key : field; // Backward compatibility if(!field.parser && field.converter) { field.parser = field.converter; } var parser = (typeof field.parser === 'function') ? field.parser : DS.Parser[field.parser+'']; if(parser) { data = parser.call(this, data); } // Safety measure if(data === undefined) { data = null; } oResult[key] = data; } else { bError = true; } } catch(e) { bError = true; } } } // No fields defined so pass along all data as an array else { oResult = fielddataarray; } if(!bError) { oParsedResponse.results[recIdx++] = oResult; } } } } } return oParsedResponse; } } return null; }, /** * Overridable method parses XML data for one result into an object literal. * * @method parseXMLResult * @param result {XML} XML for one result. * @return {Object} Object literal of data for one result. */ parseXMLResult : function(result) { var oResult = {}, schema = this.responseSchema; try { // Loop through each data field in each result using the schema for(var m = schema.fields.length-1; m >= 0 ; m--) { var field = schema.fields[m]; var key = (lang.isValue(field.key)) ? field.key : field; var data = null; // Values may be held in an attribute... var xmlAttr = result.attributes.getNamedItem(key); if(xmlAttr) { data = xmlAttr.value; } // ...or in a node else { var xmlNode = result.getElementsByTagName(key); if(xmlNode && xmlNode.item(0)) { var item = xmlNode.item(0); // For IE, then DOM... data = (item) ? ((item.text) ? item.text : (item.textContent) ? item.textContent : null) : null; // ...then fallback, but check for multiple child nodes if(!data) { var datapieces = []; for(var j=0, len=item.childNodes.length; j<len; j++) { if(item.childNodes[j].nodeValue) { datapieces[datapieces.length] = item.childNodes[j].nodeValue; } } if(datapieces.length > 0) { data = datapieces.join(""); } } } } // Safety net if(data === null) { data = ""; } // Backward compatibility if(!field.parser && field.converter) { field.parser = field.converter; } var parser = (typeof field.parser === 'function') ? field.parser : DS.Parser[field.parser+'']; if(parser) { data = parser.call(this, data); } // Safety measure if(data === undefined) { data = null; } oResult[key] = data; } } catch(e) { } return oResult; }, /** * Overridable method parses XML data into a response object. * * @method parseXMLData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full XML response from the live database. * @return {Object} Parsed response object with the following properties<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseXMLData : function(oRequest, oFullResponse) { var bError = false, schema = this.responseSchema, oParsedResponse = {meta:{}}, xmlList = null, metaNode = schema.metaNode, metaLocators = schema.metaFields || {}, i,k,loc,v; // In case oFullResponse is something funky try { xmlList = (schema.resultNode) ? oFullResponse.getElementsByTagName(schema.resultNode) : null; // Pull any meta identified metaNode = metaNode ? oFullResponse.getElementsByTagName(metaNode)[0] : oFullResponse; if (metaNode) { for (k in metaLocators) { if (lang.hasOwnProperty(metaLocators, k)) { loc = metaLocators[k]; // Look for a node v = metaNode.getElementsByTagName(loc)[0]; if (v) { v = v.firstChild.nodeValue; } else { // Look for an attribute v = metaNode.attributes.getNamedItem(loc); if (v) { v = v.value; } } if (lang.isValue(v)) { oParsedResponse.meta[k] = v; } } } } } catch(e) { } if(!xmlList || !lang.isArray(schema.fields)) { bError = true; } // Loop through each result else { oParsedResponse.results = []; for(i = xmlList.length-1; i >= 0 ; --i) { var oResult = this.parseXMLResult(xmlList.item(i)); // Capture each array of values into an array of results oParsedResponse.results[i] = oResult; } } if(bError) { oParsedResponse.error = true; } else { } return oParsedResponse; }, /** * Overridable method parses JSON data into a response object. * * @method parseJSONData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full JSON from the live database. * @return {Object} Parsed response object with the following properties<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseJSONData : function(oRequest, oFullResponse) { var oParsedResponse = {results:[],meta:{}}; if(lang.isObject(oFullResponse) && this.responseSchema.resultsList) { var schema = this.responseSchema, fields = schema.fields, resultsList = oFullResponse, results = [], metaFields = schema.metaFields || {}, fieldParsers = [], fieldPaths = [], simpleFields = [], bError = false, i,len,j,v,key,parser,path; // Function to convert the schema's fields into walk paths var buildPath = function (needle) { var path = null, keys = [], i = 0; if (needle) { // Strip the ["string keys"] and [1] array indexes needle = needle. replace(/\[(['"])(.*?)\1\]/g, function (x,$1,$2) {keys[i]=$2;return '.@'+(i++);}). replace(/\[(\d+)\]/g, function (x,$1) {keys[i]=parseInt($1,10)|0;return '.@'+(i++);}). replace(/^\./,''); // remove leading dot // If the cleaned needle contains invalid characters, the // path is invalid if (!/[^\w\.\$@]/.test(needle)) { path = needle.split('.'); for (i=path.length-1; i >= 0; --i) { if (path[i].charAt(0) === '@') { path[i] = keys[parseInt(path[i].substr(1),10)]; } } } else { } } return path; }; // Function to walk a path and return the pot of gold var walkPath = function (path, origin) { var v=origin,i=0,len=path.length; for (;i<len && v;++i) { v = v[path[i]]; } return v; }; // Parse the response // Step 1. Pull the resultsList from oFullResponse (default assumes // oFullResponse IS the resultsList) path = buildPath(schema.resultsList); if (path) { resultsList = walkPath(path, oFullResponse); if (resultsList === undefined) { bError = true; } } else { bError = true; } if (!resultsList) { resultsList = []; } if (!lang.isArray(resultsList)) { resultsList = [resultsList]; } if (!bError) { // Step 2. Parse out field data if identified if(schema.fields) { var field; // Build the field parser map and location paths for (i=0, len=fields.length; i<len; i++) { field = fields[i]; key = field.key || field; parser = ((typeof field.parser === 'function') ? field.parser : DS.Parser[field.parser+'']) || field.converter; path = buildPath(key); if (parser) { fieldParsers[fieldParsers.length] = {key:key,parser:parser}; } if (path) { if (path.length > 1) { fieldPaths[fieldPaths.length] = {key:key,path:path}; } else { simpleFields[simpleFields.length] = {key:key,path:path[0]}; } } else { } } // Process the results, flattening the records and/or applying parsers if needed for (i = resultsList.length - 1; i >= 0; --i) { var r = resultsList[i], rec = {}; if(r) { for (j = simpleFields.length - 1; j >= 0; --j) { // Bug 1777850: data might be held in an array rec[simpleFields[j].key] = (r[simpleFields[j].path] !== undefined) ? r[simpleFields[j].path] : r[j]; } for (j = fieldPaths.length - 1; j >= 0; --j) { rec[fieldPaths[j].key] = walkPath(fieldPaths[j].path,r); } for (j = fieldParsers.length - 1; j >= 0; --j) { var p = fieldParsers[j].key; rec[p] = fieldParsers[j].parser(rec[p]); if (rec[p] === undefined) { rec[p] = null; } } } results[i] = rec; } } else { results = resultsList; } for (key in metaFields) { if (lang.hasOwnProperty(metaFields,key)) { path = buildPath(metaFields[key]); if (path) { v = walkPath(path, oFullResponse); oParsedResponse.meta[key] = v; } } } } else { oParsedResponse.error = true; } oParsedResponse.results = results; } else { oParsedResponse.error = true; } return oParsedResponse; }, /** * Overridable method parses an HTML TABLE element reference into a response object. * Data is parsed out of TR elements from all TBODY elements. * * @method parseHTMLTableData * @param oRequest {Object} Request object. * @param oFullResponse {Object} The full HTML element reference from the live database. * @return {Object} Parsed response object with the following properties<br> * - results (Array) Array of parsed data results<br> * - error (Boolean) True if there was an error */ parseHTMLTableData : function(oRequest, oFullResponse) { var bError = false; var elTable = oFullResponse; var fields = this.responseSchema.fields; var oParsedResponse = {results:[]}; if(lang.isArray(fields)) { // Iterate through each TBODY for(var i=0; i<elTable.tBodies.length; i++) { var elTbody = elTable.tBodies[i]; // Iterate through each TR for(var j=elTbody.rows.length-1; j>-1; j--) { var elRow = elTbody.rows[j]; var oResult = {}; for(var k=fields.length-1; k>-1; k--) { var field = fields[k]; var key = (lang.isValue(field.key)) ? field.key : field; var data = elRow.cells[k].innerHTML; // Backward compatibility if(!field.parser && field.converter) { field.parser = field.converter; } var parser = (typeof field.parser === 'function') ? field.parser : DS.Parser[field.parser+'']; if(parser) { data = parser.call(this, data); } // Safety measure if(data === undefined) { data = null; } oResult[key] = data; } oParsedResponse.results[j] = oResult; } } } else { bError = true; } if(bError) { oParsedResponse.error = true; } else { } return oParsedResponse; } }; // DataSourceBase uses EventProvider lang.augmentProto(DS, util.EventProvider); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * LocalDataSource class for in-memory data structs including JavaScript arrays, * JavaScript object literals (JSON), XML documents, and HTML tables. * * @namespace YAHOO.util * @class YAHOO.util.LocalDataSource * @extends YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.LocalDataSource = function(oLiveData, oConfigs) { this.dataType = DS.TYPE_LOCAL; if(oLiveData) { if(YAHOO.lang.isArray(oLiveData)) { // array this.responseType = DS.TYPE_JSARRAY; } // xml else if(oLiveData.nodeType && oLiveData.nodeType == 9) { this.responseType = DS.TYPE_XML; } else if(oLiveData.nodeName && (oLiveData.nodeName.toLowerCase() == "table")) { // table this.responseType = DS.TYPE_HTMLTABLE; oLiveData = oLiveData.cloneNode(true); } else if(YAHOO.lang.isString(oLiveData)) { // text this.responseType = DS.TYPE_TEXT; } else if(YAHOO.lang.isObject(oLiveData)) { // json this.responseType = DS.TYPE_JSON; } } else { oLiveData = []; this.responseType = DS.TYPE_JSARRAY; } util.LocalDataSource.superclass.constructor.call(this, oLiveData, oConfigs); }; // LocalDataSource extends DataSourceBase lang.extend(util.LocalDataSource, DS); // Copy static members to LocalDataSource class lang.augmentObject(util.LocalDataSource, DS); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * FunctionDataSource class for JavaScript functions. * * @namespace YAHOO.util * @class YAHOO.util.FunctionDataSource * @extends YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.FunctionDataSource = function(oLiveData, oConfigs) { this.dataType = DS.TYPE_JSFUNCTION; oLiveData = oLiveData || function() {}; util.FunctionDataSource.superclass.constructor.call(this, oLiveData, oConfigs); }; // FunctionDataSource extends DataSourceBase lang.extend(util.FunctionDataSource, DS, { ///////////////////////////////////////////////////////////////////////////// // // FunctionDataSource public properties // ///////////////////////////////////////////////////////////////////////////// /** * Context in which to execute the function. By default, is the DataSource * instance itself. If set, the function will receive the DataSource instance * as an additional argument. * * @property scope * @type Object * @default null */ scope : null, ///////////////////////////////////////////////////////////////////////////// // // FunctionDataSource public methods // ///////////////////////////////////////////////////////////////////////////// /** * Overriding method passes query to a function. The returned response is then * forwarded to the handleResponse function. * * @method makeConnection * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID. */ makeConnection : function(oRequest, oCallback, oCaller) { var tId = DS._nTransactionId++; this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); // Pass the request in as a parameter and // forward the return value to the handler var oRawResponse = (this.scope) ? this.liveData.call(this.scope, oRequest, this) : this.liveData(oRequest); // Try to sniff data type if it has not been defined if(this.responseType === DS.TYPE_UNKNOWN) { if(YAHOO.lang.isArray(oRawResponse)) { // array this.responseType = DS.TYPE_JSARRAY; } // xml else if(oRawResponse && oRawResponse.nodeType && oRawResponse.nodeType == 9) { this.responseType = DS.TYPE_XML; } else if(oRawResponse && oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table this.responseType = DS.TYPE_HTMLTABLE; } else if(YAHOO.lang.isObject(oRawResponse)) { // json this.responseType = DS.TYPE_JSON; } else if(YAHOO.lang.isString(oRawResponse)) { // text this.responseType = DS.TYPE_TEXT; } } this.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); return tId; } }); // Copy static members to FunctionDataSource class lang.augmentObject(util.FunctionDataSource, DS); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * ScriptNodeDataSource class for accessing remote data via the YUI Get Utility. * * @namespace YAHOO.util * @class YAHOO.util.ScriptNodeDataSource * @extends YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.ScriptNodeDataSource = function(oLiveData, oConfigs) { this.dataType = DS.TYPE_SCRIPTNODE; oLiveData = oLiveData || ""; util.ScriptNodeDataSource.superclass.constructor.call(this, oLiveData, oConfigs); }; // ScriptNodeDataSource extends DataSourceBase lang.extend(util.ScriptNodeDataSource, DS, { ///////////////////////////////////////////////////////////////////////////// // // ScriptNodeDataSource public properties // ///////////////////////////////////////////////////////////////////////////// /** * Alias to YUI Get Utility, to allow implementers to use a custom class. * * @property getUtility * @type Object * @default YAHOO.util.Get */ getUtility : util.Get, /** * Defines request/response management in the following manner: * <dl> * <!--<dt>queueRequests</dt> * <dd>If a request is already in progress, wait until response is returned before sending the next request.</dd> * <dt>cancelStaleRequests</dt> * <dd>If a request is already in progress, cancel it before sending the next request.</dd>--> * <dt>ignoreStaleResponses</dt> * <dd>Send all requests, but handle only the response for the most recently sent request.</dd> * <dt>allowAll</dt> * <dd>Send all requests and handle all responses.</dd> * </dl> * * @property asyncMode * @type String * @default "allowAll" */ asyncMode : "allowAll", /** * Callback string parameter name sent to the remote script. By default, * requests are sent to * &#60;URI&#62;?&#60;scriptCallbackParam&#62;=callbackFunction * * @property scriptCallbackParam * @type String * @default "callback" */ scriptCallbackParam : "callback", ///////////////////////////////////////////////////////////////////////////// // // ScriptNodeDataSource public methods // ///////////////////////////////////////////////////////////////////////////// /** * Creates a request callback that gets appended to the script URI. Implementers * can customize this string to match their server's query syntax. * * @method generateRequestCallback * @return {String} String fragment that gets appended to script URI that * specifies the callback function */ generateRequestCallback : function(id) { return "&" + this.scriptCallbackParam + "=YAHOO.util.ScriptNodeDataSource.callbacks["+id+"]" ; }, /** * Overridable method gives implementers access to modify the URI before the dynamic * script node gets inserted. Implementers should take care not to return an * invalid URI. * * @method doBeforeGetScriptNode * @param {String} URI to the script * @return {String} URI to the script */ doBeforeGetScriptNode : function(sUri) { return sUri; }, /** * Overriding method passes query to Get Utility. The returned * response is then forwarded to the handleResponse function. * * @method makeConnection * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID. */ makeConnection : function(oRequest, oCallback, oCaller) { var tId = DS._nTransactionId++; this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); // If there are no global pending requests, it is safe to purge global callback stack and global counter if(util.ScriptNodeDataSource._nPending === 0) { util.ScriptNodeDataSource.callbacks = []; util.ScriptNodeDataSource._nId = 0; } // ID for this request var id = util.ScriptNodeDataSource._nId; util.ScriptNodeDataSource._nId++; // Dynamically add handler function with a closure to the callback stack var oSelf = this; util.ScriptNodeDataSource.callbacks[id] = function(oRawResponse) { if((oSelf.asyncMode !== "ignoreStaleResponses")|| (id === util.ScriptNodeDataSource.callbacks.length-1)) { // Must ignore stale responses // Try to sniff data type if it has not been defined if(oSelf.responseType === DS.TYPE_UNKNOWN) { if(YAHOO.lang.isArray(oRawResponse)) { // array oSelf.responseType = DS.TYPE_JSARRAY; } // xml else if(oRawResponse.nodeType && oRawResponse.nodeType == 9) { oSelf.responseType = DS.TYPE_XML; } else if(oRawResponse.nodeName && (oRawResponse.nodeName.toLowerCase() == "table")) { // table oSelf.responseType = DS.TYPE_HTMLTABLE; } else if(YAHOO.lang.isObject(oRawResponse)) { // json oSelf.responseType = DS.TYPE_JSON; } else if(YAHOO.lang.isString(oRawResponse)) { // text oSelf.responseType = DS.TYPE_TEXT; } } oSelf.handleResponse(oRequest, oRawResponse, oCallback, oCaller, tId); } else { } delete util.ScriptNodeDataSource.callbacks[id]; }; // We are now creating a request util.ScriptNodeDataSource._nPending++; var sUri = this.liveData + oRequest + this.generateRequestCallback(id); sUri = this.doBeforeGetScriptNode(sUri); this.getUtility.script(sUri, {autopurge: true, onsuccess: util.ScriptNodeDataSource._bumpPendingDown, onfail: util.ScriptNodeDataSource._bumpPendingDown}); return tId; } }); // Copy static members to ScriptNodeDataSource class lang.augmentObject(util.ScriptNodeDataSource, DS); // Copy static members to ScriptNodeDataSource class lang.augmentObject(util.ScriptNodeDataSource, { ///////////////////////////////////////////////////////////////////////////// // // ScriptNodeDataSource private static properties // ///////////////////////////////////////////////////////////////////////////// /** * Unique ID to track requests. * * @property _nId * @type Number * @private * @static */ _nId : 0, /** * Counter for pending requests. When this is 0, it is safe to purge callbacks * array. * * @property _nPending * @type Number * @private * @static */ _nPending : 0, /** * Global array of callback functions, one for each request sent. * * @property callbacks * @type Function[] * @static */ callbacks : [] }); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * XHRDataSource class for accessing remote data via the YUI Connection Manager * Utility * * @namespace YAHOO.util * @class YAHOO.util.XHRDataSource * @extends YAHOO.util.DataSourceBase * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.XHRDataSource = function(oLiveData, oConfigs) { this.dataType = DS.TYPE_XHR; this.connMgr = this.connMgr || util.Connect; oLiveData = oLiveData || ""; util.XHRDataSource.superclass.constructor.call(this, oLiveData, oConfigs); }; // XHRDataSource extends DataSourceBase lang.extend(util.XHRDataSource, DS, { ///////////////////////////////////////////////////////////////////////////// // // XHRDataSource public properties // ///////////////////////////////////////////////////////////////////////////// /** * Alias to YUI Connection Manager, to allow implementers to use a custom class. * * @property connMgr * @type Object * @default YAHOO.util.Connect */ connMgr: null, /** * Defines request/response management in the following manner: * <dl> * <dt>queueRequests</dt> * <dd>If a request is already in progress, wait until response is returned * before sending the next request.</dd> * * <dt>cancelStaleRequests</dt> * <dd>If a request is already in progress, cancel it before sending the next * request.</dd> * * <dt>ignoreStaleResponses</dt> * <dd>Send all requests, but handle only the response for the most recently * sent request.</dd> * * <dt>allowAll</dt> * <dd>Send all requests and handle all responses.</dd> * * </dl> * * @property connXhrMode * @type String * @default "allowAll" */ connXhrMode: "allowAll", /** * True if data is to be sent via POST. By default, data will be sent via GET. * * @property connMethodPost * @type Boolean * @default false */ connMethodPost: false, /** * The connection timeout defines how many milliseconds the XHR connection will * wait for a server response. Any non-zero value will enable the Connection Manager's * Auto-Abort feature. * * @property connTimeout * @type Number * @default 0 */ connTimeout: 0, ///////////////////////////////////////////////////////////////////////////// // // XHRDataSource public methods // ///////////////////////////////////////////////////////////////////////////// /** * Overriding method passes query to Connection Manager. The returned * response is then forwarded to the handleResponse function. * * @method makeConnection * @param oRequest {Object} Request object. * @param oCallback {Object} Callback object literal. * @param oCaller {Object} (deprecated) Use oCallback.scope. * @return {Number} Transaction ID. */ makeConnection : function(oRequest, oCallback, oCaller) { var oRawResponse = null; var tId = DS._nTransactionId++; this.fireEvent("requestEvent", {tId:tId,request:oRequest,callback:oCallback,caller:oCaller}); // Set up the callback object and // pass the request in as a URL query and // forward the response to the handler var oSelf = this; var oConnMgr = this.connMgr; var oQueue = this._oQueue; /** * Define Connection Manager success handler * * @method _xhrSuccess * @param oResponse {Object} HTTPXMLRequest object * @private */ var _xhrSuccess = function(oResponse) { // If response ID does not match last made request ID, // silently fail and wait for the next response if(oResponse && (this.connXhrMode == "ignoreStaleResponses") && (oResponse.tId != oQueue.conn.tId)) { return null; } // Error if no response else if(!oResponse) { this.fireEvent("dataErrorEvent", {request:oRequest, callback:oCallback, caller:oCaller, message:DS.ERROR_DATANULL}); // Send error response back to the caller with the error flag on DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller); return null; } // Forward to handler else { // Try to sniff data type if it has not been defined if(this.responseType === DS.TYPE_UNKNOWN) { var ctype = (oResponse.getResponseHeader) ? oResponse.getResponseHeader["Content-Type"] : null; if(ctype) { // xml if(ctype.indexOf("text/xml") > -1) { this.responseType = DS.TYPE_XML; } else if(ctype.indexOf("application/json") > -1) { // json this.responseType = DS.TYPE_JSON; } else if(ctype.indexOf("text/plain") > -1) { // text this.responseType = DS.TYPE_TEXT; } } } this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId); } }; /** * Define Connection Manager failure handler * * @method _xhrFailure * @param oResponse {Object} HTTPXMLRequest object * @private */ var _xhrFailure = function(oResponse) { this.fireEvent("dataErrorEvent", {request:oRequest, callback:oCallback, caller:oCaller, message:DS.ERROR_DATAINVALID}); // Backward compatibility if(lang.isString(this.liveData) && lang.isString(oRequest) && (this.liveData.lastIndexOf("?") !== this.liveData.length-1) && (oRequest.indexOf("?") !== 0)){ } // Send failure response back to the caller with the error flag on oResponse = oResponse || {}; oResponse.error = true; DS.issueCallback(oCallback,[oRequest,oResponse],true, oCaller); return null; }; /** * Define Connection Manager callback object * * @property _xhrCallback * @param oResponse {Object} HTTPXMLRequest object * @private */ var _xhrCallback = { success:_xhrSuccess, failure:_xhrFailure, scope: this }; // Apply Connection Manager timeout if(lang.isNumber(this.connTimeout)) { _xhrCallback.timeout = this.connTimeout; } // Cancel stale requests if(this.connXhrMode == "cancelStaleRequests") { // Look in queue for stale requests if(oQueue.conn) { if(oConnMgr.abort) { oConnMgr.abort(oQueue.conn); oQueue.conn = null; } else { } } } // Get ready to send the request URL if(oConnMgr && oConnMgr.asyncRequest) { var sLiveData = this.liveData; var isPost = this.connMethodPost; var sMethod = (isPost) ? "POST" : "GET"; // Validate request var sUri = (isPost || !lang.isValue(oRequest)) ? sLiveData : sLiveData+oRequest; var sRequest = (isPost) ? oRequest : null; // Send the request right away if(this.connXhrMode != "queueRequests") { oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest); } // Queue up then send the request else { // Found a request already in progress if(oQueue.conn) { var allRequests = oQueue.requests; // Add request to queue allRequests.push({request:oRequest, callback:_xhrCallback}); // Interval needs to be started if(!oQueue.interval) { oQueue.interval = setInterval(function() { // Connection is in progress if(oConnMgr.isCallInProgress(oQueue.conn)) { return; } else { // Send next request if(allRequests.length > 0) { // Validate request sUri = (isPost || !lang.isValue(allRequests[0].request)) ? sLiveData : sLiveData+allRequests[0].request; sRequest = (isPost) ? allRequests[0].request : null; oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, allRequests[0].callback, sRequest); // Remove request from queue allRequests.shift(); } // No more requests else { clearInterval(oQueue.interval); oQueue.interval = null; } } }, 50); } } // Nothing is in progress else { oQueue.conn = oConnMgr.asyncRequest(sMethod, sUri, _xhrCallback, sRequest); } } } else { // Send null response back to the caller with the error flag on DS.issueCallback(oCallback,[oRequest,{error:true}],true,oCaller); } return tId; } }); // Copy static members to XHRDataSource class lang.augmentObject(util.XHRDataSource, DS); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * Factory class for creating a BaseDataSource subclass instance. The sublcass is * determined by oLiveData's type, unless the dataType config is explicitly passed in. * * @namespace YAHOO.util * @class YAHOO.util.DataSource * @constructor * @param oLiveData {HTMLElement} Pointer to live data. * @param oConfigs {object} (optional) Object literal of configuration values. */ util.DataSource = function(oLiveData, oConfigs) { oConfigs = oConfigs || {}; // Point to one of the subclasses, first by dataType if given, then by sniffing oLiveData type. var dataType = oConfigs.dataType; if(dataType) { if(dataType == DS.TYPE_LOCAL) { lang.augmentObject(util.DataSource, util.LocalDataSource); return new util.LocalDataSource(oLiveData, oConfigs); } else if(dataType == DS.TYPE_XHR) { lang.augmentObject(util.DataSource, util.XHRDataSource); return new util.XHRDataSource(oLiveData, oConfigs); } else if(dataType == DS.TYPE_SCRIPTNODE) { lang.augmentObject(util.DataSource, util.ScriptNodeDataSource); return new util.ScriptNodeDataSource(oLiveData, oConfigs); } else if(dataType == DS.TYPE_JSFUNCTION) { lang.augmentObject(util.DataSource, util.FunctionDataSource); return new util.FunctionDataSource(oLiveData, oConfigs); } } if(YAHOO.lang.isString(oLiveData)) { // strings default to xhr lang.augmentObject(util.DataSource, util.XHRDataSource); return new util.XHRDataSource(oLiveData, oConfigs); } else if(YAHOO.lang.isFunction(oLiveData)) { lang.augmentObject(util.DataSource, util.FunctionDataSource); return new util.FunctionDataSource(oLiveData, oConfigs); } else { // ultimate default is local lang.augmentObject(util.DataSource, util.LocalDataSource); return new util.LocalDataSource(oLiveData, oConfigs); } }; // Copy static members to DataSource class lang.augmentObject(util.DataSource, DS); })(); /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ /** * The static Number class provides helper functions to deal with data of type * Number. * * @namespace YAHOO.util * @requires yahoo * @class Number * @static */ YAHOO.util.Number = { /** * Takes a native JavaScript Number and formats to string for display to user. * * @method format * @param nData {Number} Number. * @param oConfig {Object} (Optional) Optional configuration values: * <dl> * <dt>prefix {String}</dd> * <dd>String prepended before each number, like a currency designator "$"</dd> * <dt>decimalPlaces {Number}</dd> * <dd>Number of decimal places to round.</dd> * <dt>decimalSeparator {String}</dd> * <dd>Decimal separator</dd> * <dt>thousandsSeparator {String}</dd> * <dd>Thousands separator</dd> * <dt>suffix {String}</dd> * <dd>String appended after each number, like " items" (note the space)</dd> * </dl> * @return {String} Formatted number for display. Note, the following values * return as "": null, undefined, NaN, "". */ format : function(nData, oConfig) { var lang = YAHOO.lang; if(!lang.isValue(nData) || (nData === "")) { return ""; } oConfig = oConfig || {}; if(!lang.isNumber(nData)) { nData *= 1; } if(lang.isNumber(nData)) { var bNegative = (nData < 0); var sOutput = nData + ""; var sDecimalSeparator = (oConfig.decimalSeparator) ? oConfig.decimalSeparator : "."; var nDotIndex; // Manage decimals if(lang.isNumber(oConfig.decimalPlaces)) { // Round to the correct decimal place var nDecimalPlaces = oConfig.decimalPlaces; var nDecimal = Math.pow(10, nDecimalPlaces); sOutput = Math.round(nData*nDecimal)/nDecimal + ""; nDotIndex = sOutput.lastIndexOf("."); if(nDecimalPlaces > 0) { // Add the decimal separator if(nDotIndex < 0) { sOutput += sDecimalSeparator; nDotIndex = sOutput.length-1; } // Replace the "." else if(sDecimalSeparator !== "."){ sOutput = sOutput.replace(".",sDecimalSeparator); } // Add missing zeros while((sOutput.length - 1 - nDotIndex) < nDecimalPlaces) { sOutput += "0"; } } } // Add the thousands separator if(oConfig.thousandsSeparator) { var sThousandsSeparator = oConfig.thousandsSeparator; nDotIndex = sOutput.lastIndexOf(sDecimalSeparator); nDotIndex = (nDotIndex > -1) ? nDotIndex : sOutput.length; var sNewOutput = sOutput.substring(nDotIndex); var nCount = -1; for (var i=nDotIndex; i>0; i--) { nCount++; if ((nCount%3 === 0) && (i !== nDotIndex) && (!bNegative || (i > 1))) { sNewOutput = sThousandsSeparator + sNewOutput; } sNewOutput = sOutput.charAt(i-1) + sNewOutput; } sOutput = sNewOutput; } // Prepend prefix sOutput = (oConfig.prefix) ? oConfig.prefix + sOutput : sOutput; // Append suffix sOutput = (oConfig.suffix) ? sOutput + oConfig.suffix : sOutput; return sOutput; } // Still not a Number, just return unaltered else { return nData; } } }; /****************************************************************************/ /****************************************************************************/ /****************************************************************************/ (function () { var xPad=function (x, pad, r) { if(typeof r === 'undefined') { r=10; } for( ; parseInt(x, 10)<r && r>1; r/=10) { x = pad.toString() + x; } return x.toString(); }; /** * The static Date class provides helper functions to deal with data of type Date. * * @namespace YAHOO.util * @requires yahoo * @class Date * @static */ var Dt = { formats: { a: function (d, l) { return l.a[d.getDay()]; }, A: function (d, l) { return l.A[d.getDay()]; }, b: function (d, l) { return l.b[d.getMonth()]; }, B: function (d, l) { return l.B[d.getMonth()]; }, C: function (d) { return xPad(parseInt(d.getFullYear()/100, 10), 0); }, d: ['getDate', '0'], e: ['getDate', ' '], g: function (d) { return xPad(parseInt(Dt.formats.G(d)%100, 10), 0); }, G: function (d) { var y = d.getFullYear(); var V = parseInt(Dt.formats.V(d), 10); var W = parseInt(Dt.formats.W(d), 10); if(W > V) { y++; } else if(W===0 && V>=52) { y--; } return y; }, H: ['getHours', '0'], I: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, 0); }, j: function (d) { var gmd_1 = new Date('' + d.getFullYear() + '/1/1 GMT'); var gmdate = new Date('' + d.getFullYear() + '/' + (d.getMonth()+1) + '/' + d.getDate() + ' GMT'); var ms = gmdate - gmd_1; var doy = parseInt(ms/60000/60/24, 10)+1; return xPad(doy, 0, 100); }, k: ['getHours', ' '], l: function (d) { var I=d.getHours()%12; return xPad(I===0?12:I, ' '); }, m: function (d) { return xPad(d.getMonth()+1, 0); }, M: ['getMinutes', '0'], p: function (d, l) { return l.p[d.getHours() >= 12 ? 1 : 0 ]; }, P: function (d, l) { return l.P[d.getHours() >= 12 ? 1 : 0 ]; }, s: function (d, l) { return parseInt(d.getTime()/1000, 10); }, S: ['getSeconds', '0'], u: function (d) { var dow = d.getDay(); return dow===0?7:dow; }, U: function (d) { var doy = parseInt(Dt.formats.j(d), 10); var rdow = 6-d.getDay(); var woy = parseInt((doy+rdow)/7, 10); return xPad(woy, 0); }, V: function (d) { var woy = parseInt(Dt.formats.W(d), 10); var dow1_1 = (new Date('' + d.getFullYear() + '/1/1')).getDay(); // First week is 01 and not 00 as in the case of %U and %W, // so we add 1 to the final result except if day 1 of the year // is a Monday (then %W returns 01). // We also need to subtract 1 if the day 1 of the year is // Friday-Sunday, so the resulting equation becomes: var idow = woy + (dow1_1 > 4 || dow1_1 <= 1 ? 0 : 1); if(idow === 53 && (new Date('' + d.getFullYear() + '/12/31')).getDay() < 4) { idow = 1; } else if(idow === 0) { idow = Dt.formats.V(new Date('' + (d.getFullYear()-1) + '/12/31')); } return xPad(idow, 0); }, w: 'getDay', W: function (d) { var doy = parseInt(Dt.formats.j(d), 10); var rdow = 7-Dt.formats.u(d); var woy = parseInt((doy+rdow)/7, 10); return xPad(woy, 0, 10); }, y: function (d) { return xPad(d.getFullYear()%100, 0); }, Y: 'getFullYear', z: function (d) { var o = d.getTimezoneOffset(); var H = xPad(parseInt(Math.abs(o/60), 10), 0); var M = xPad(Math.abs(o%60), 0); return (o>0?'-':'+') + H + M; }, Z: function (d) { var tz = d.toString().replace(/^.*:\d\d( GMT[+-]\d+)? \(?([A-Za-z ]+)\)?\d*$/, '$2').replace(/[a-z ]/g, ''); if(tz.length > 4) { tz = Dt.formats.z(d); } return tz; }, '%': function (d) { return '%'; } }, aggregates: { c: 'locale', D: '%m/%d/%y', F: '%Y-%m-%d', h: '%b', n: '\n', r: 'locale', R: '%H:%M', t: '\t', T: '%H:%M:%S', x: 'locale', X: 'locale' //'+': '%a %b %e %T %Z %Y' }, /** * Takes a native JavaScript Date and formats to string for display to user. * * @method format * @param oDate {Date} Date. * @param oConfig {Object} (Optional) Object literal of configuration values: * <dl> * <dt>format &lt;String&gt;</dt> * <dd> * <p> * Any strftime string is supported, such as "%I:%M:%S %p". strftime has several format specifiers defined by the Open group at * <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html</a> * </p> * <p> * PHP added a few of its own, defined at <a href="http://www.php.net/strftime">http://www.php.net/strftime</a> * </p> * <p> * This javascript implementation supports all the PHP specifiers and a few more. The full list is below: * </p> * <dl> * <dt>%a</dt> <dd>abbreviated weekday name according to the current locale</dd> * <dt>%A</dt> <dd>full weekday name according to the current locale</dd> * <dt>%b</dt> <dd>abbreviated month name according to the current locale</dd> * <dt>%B</dt> <dd>full month name according to the current locale</dd> * <dt>%c</dt> <dd>preferred date and time representation for the current locale</dd> * <dt>%C</dt> <dd>century number (the year divided by 100 and truncated to an integer, range 00 to 99)</dd> * <dt>%d</dt> <dd>day of the month as a decimal number (range 01 to 31)</dd> * <dt>%D</dt> <dd>same as %m/%d/%y</dd> * <dt>%e</dt> <dd>day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31')</dd> * <dt>%F</dt> <dd>same as %Y-%m-%d (ISO 8601 date format)</dd> * <dt>%g</dt> <dd>like %G, but without the century</dd> * <dt>%G</dt> <dd>The 4-digit year corresponding to the ISO week number</dd> * <dt>%h</dt> <dd>same as %b</dd> * <dt>%H</dt> <dd>hour as a decimal number using a 24-hour clock (range 00 to 23)</dd> * <dt>%I</dt> <dd>hour as a decimal number using a 12-hour clock (range 01 to 12)</dd> * <dt>%j</dt> <dd>day of the year as a decimal number (range 001 to 366)</dd> * <dt>%k</dt> <dd>hour as a decimal number using a 24-hour clock (range 0 to 23); single digits are preceded by a blank. (See also %H.)</dd> * <dt>%l</dt> <dd>hour as a decimal number using a 12-hour clock (range 1 to 12); single digits are preceded by a blank. (See also %I.) </dd> * <dt>%m</dt> <dd>month as a decimal number (range 01 to 12)</dd> * <dt>%M</dt> <dd>minute as a decimal number</dd> * <dt>%n</dt> <dd>newline character</dd> * <dt>%p</dt> <dd>either `AM' or `PM' according to the given time value, or the corresponding strings for the current locale</dd> * <dt>%P</dt> <dd>like %p, but lower case</dd> * <dt>%r</dt> <dd>time in a.m. and p.m. notation equal to %I:%M:%S %p</dd> * <dt>%R</dt> <dd>time in 24 hour notation equal to %H:%M</dd> * <dt>%s</dt> <dd>number of seconds since the Epoch, ie, since 1970-01-01 00:00:00 UTC</dd> * <dt>%S</dt> <dd>second as a decimal number</dd> * <dt>%t</dt> <dd>tab character</dd> * <dt>%T</dt> <dd>current time, equal to %H:%M:%S</dd> * <dt>%u</dt> <dd>weekday as a decimal number [1,7], with 1 representing Monday</dd> * <dt>%U</dt> <dd>week number of the current year as a decimal number, starting with the * first Sunday as the first day of the first week</dd> * <dt>%V</dt> <dd>The ISO 8601:1988 week number of the current year as a decimal number, * range 01 to 53, where week 1 is the first week that has at least 4 days * in the current year, and with Monday as the first day of the week.</dd> * <dt>%w</dt> <dd>day of the week as a decimal, Sunday being 0</dd> * <dt>%W</dt> <dd>week number of the current year as a decimal number, starting with the * first Monday as the first day of the first week</dd> * <dt>%x</dt> <dd>preferred date representation for the current locale without the time</dd> * <dt>%X</dt> <dd>preferred time representation for the current locale without the date</dd> * <dt>%y</dt> <dd>year as a decimal number without a century (range 00 to 99)</dd> * <dt>%Y</dt> <dd>year as a decimal number including the century</dd> * <dt>%z</dt> <dd>numerical time zone representation</dd> * <dt>%Z</dt> <dd>time zone name or abbreviation</dd> * <dt>%%</dt> <dd>a literal `%' character</dd> * </dl> * </dd> * </dl> * @param sLocale {String} (Optional) The locale to use when displaying days of week, * months of the year, and other locale specific strings. The following locales are * built in: * <dl> * <dt>en</dt> * <dd>English</dd> * <dt>en-US</dt> * <dd>US English</dd> * <dt>en-GB</dt> * <dd>British English</dd> * <dt>en-AU</dt> * <dd>Australian English (identical to British English)</dd> * </dl> * More locales may be added by subclassing of YAHOO.util.DateLocale. * See YAHOO.util.DateLocale for more information. * @return {String} Formatted date for display. * @sa YAHOO.util.DateLocale */ format : function (oDate, oConfig, sLocale) { oConfig = oConfig || {}; if(!(oDate instanceof Date)) { return YAHOO.lang.isValue(oDate) ? oDate : ""; } var format = oConfig.format || "%m/%d/%Y"; // Be backwards compatible, support strings that are // exactly equal to YYYY/MM/DD, DD/MM/YYYY and MM/DD/YYYY if(format === 'YYYY/MM/DD') { format = '%Y/%m/%d'; } else if(format === 'DD/MM/YYYY') { format = '%d/%m/%Y'; } else if(format === 'MM/DD/YYYY') { format = '%m/%d/%Y'; } // end backwards compatibility block sLocale = sLocale || "en"; // Make sure we have a definition for the requested locale, or default to en. if(!(sLocale in YAHOO.util.DateLocale)) { if(sLocale.replace(/-[a-zA-Z]+$/, '') in YAHOO.util.DateLocale) { sLocale = sLocale.replace(/-[a-zA-Z]+$/, ''); } else { sLocale = "en"; } } var aLocale = YAHOO.util.DateLocale[sLocale]; var replace_aggs = function (m0, m1) { var f = Dt.aggregates[m1]; return (f === 'locale' ? aLocale[m1] : f); }; var replace_formats = function (m0, m1) { var f = Dt.formats[m1]; if(typeof f === 'string') { // string => built in date function return oDate[f](); } else if(typeof f === 'function') { // function => our own function return f.call(oDate, oDate, aLocale); } else if(typeof f === 'object' && typeof f[0] === 'string') { // built in function with padding return xPad(oDate[f[0]](), f[1]); } else { return m1; } }; // First replace aggregates (run in a loop because an agg may be made up of other aggs) while(format.match(/%[cDFhnrRtTxX]/)) { format = format.replace(/%([cDFhnrRtTxX])/g, replace_aggs); } // Now replace formats (do not run in a loop otherwise %%a will be replace with the value of %a) var str = format.replace(/%([aAbBCdegGHIjklmMpPsSuUVwWyYzZ%])/g, replace_formats); replace_aggs = replace_formats = undefined; return str; } }; YAHOO.namespace("YAHOO.util"); YAHOO.util.Date = Dt; /** * The DateLocale class is a container and base class for all * localised date strings used by YAHOO.util.Date. It is used * internally, but may be extended to provide new date localisations. * * To create your own DateLocale, follow these steps: * <ol> * <li>Find an existing locale that matches closely with your needs</li> * <li>Use this as your base class. Use YAHOO.util.DateLocale if nothing * matches.</li> * <li>Create your own class as an extension of the base class using * YAHOO.lang.merge, and add your own localisations where needed.</li> * </ol> * See the YAHOO.util.DateLocale['en-US'] and YAHOO.util.DateLocale['en-GB'] * classes which extend YAHOO.util.DateLocale['en']. * * For example, to implement locales for French french and Canadian french, * we would do the following: * <ol> * <li>For French french, we have no existing similar locale, so use * YAHOO.util.DateLocale as the base, and extend it: * <pre> * YAHOO.util.DateLocale['fr'] = YAHOO.lang.merge(YAHOO.util.DateLocale, { * a: ['dim', 'lun', 'mar', 'mer', 'jeu', 'ven', 'sam'], * A: ['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'], * b: ['jan', 'f&eacute;v', 'mar', 'avr', 'mai', 'jun', 'jui', 'ao&ucirc;', 'sep', 'oct', 'nov', 'd&eacute;c'], * B: ['janvier', 'f&eacute;vrier', 'mars', 'avril', 'mai', 'juin', 'juillet', 'ao&ucirc;t', 'septembre', 'octobre', 'novembre', 'd&eacute;cembre'], * c: '%a %d %b %Y %T %Z', * p: ['', ''], * P: ['', ''], * x: '%d.%m.%Y', * X: '%T' * }); * </pre> * </li> * <li>For Canadian french, we start with French french and change the meaning of \%x: * <pre> * YAHOO.util.DateLocale['fr-CA'] = YAHOO.lang.merge(YAHOO.util.DateLocale['fr'], { * x: '%Y-%m-%d' * }); * </pre> * </li> * </ol> * * With that, you can use your new locales: * <pre> * var d = new Date("2008/04/22"); * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr"); * </pre> * will return: * <pre> * mardi, 22 avril == 22.04.2008 * </pre> * And * <pre> * YAHOO.util.Date.format(d, {format: "%A, %d %B == %x"}, "fr-CA"); * </pre> * Will return: * <pre> * mardi, 22 avril == 2008-04-22 * </pre> * @namespace YAHOO.util * @requires yahoo * @class DateLocale */ YAHOO.util.DateLocale = { a: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], A: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], b: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], B: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], c: '%a %d %b %Y %T %Z', p: ['AM', 'PM'], P: ['am', 'pm'], r: '%I:%M:%S %p', x: '%d/%m/%y', X: '%T' }; YAHOO.util.DateLocale['en'] = YAHOO.lang.merge(YAHOO.util.DateLocale, {}); YAHOO.util.DateLocale['en-US'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], { c: '%a %d %b %Y %I:%M:%S %p %Z', x: '%m/%d/%Y', X: '%I:%M:%S %p' }); YAHOO.util.DateLocale['en-GB'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en'], { r: '%l:%M:%S %P %Z' }); YAHOO.util.DateLocale['en-AU'] = YAHOO.lang.merge(YAHOO.util.DateLocale['en']); })(); YAHOO.register("datasource", YAHOO.util.DataSource, {version: "2.7.0", build: "1799"});
// --------- This code has been automatically generated !!! Wed Jul 22 2015 13:15:45 GMT+0000 (UTC) /** * @module opcua.address_space.types */ var doDebug = false; var assert = require("better-assert"); var util = require("util"); var _ = require("underscore"); var makeNodeId = require("../lib/datamodel/nodeid").makeNodeId; var schema_helpers = require("../lib/misc/factories_schema_helpers"); var extract_all_fields = schema_helpers.extract_all_fields; var resolve_schema_field_types = schema_helpers.resolve_schema_field_types; var initialize_field = schema_helpers.initialize_field; var initialize_field_array = schema_helpers.initialize_field_array; var check_options_correctness_against_schema = schema_helpers.check_options_correctness_against_schema; var _defaultTypeMap = require("../lib/misc/factories_builtin_types")._defaultTypeMap; var ec= require("../lib/misc/encode_decode"); var encodeArray= ec.encodeArray; var decodeArray= ec.decodeArray; var makeExpandedNodeId= ec.makeExpandedNodeId; var generate_new_id = require("../lib/misc/factories").generate_new_id; var _enumerations = require("../lib/misc/factories_enumerations")._private._enumerations; var schema = require("../schemas/ActivateSessionResponse_schema").ActivateSessionResponse_Schema; var ResponseHeader= require("./_auto_generated_ResponseHeader").ResponseHeader; var DiagnosticInfo= require("./_auto_generated_DiagnosticInfo").DiagnosticInfo; var BaseUAObject = require("../lib/misc/factories_baseobject").BaseUAObject; /** * Activates a session with the server. * * @class ActivateSessionResponse * @constructor * @extends BaseUAObject * @param options {Object} * @param [options.responseHeader] {ResponseHeader} A standard header included in all responses returned by servers. * @param [options.serverNonce] {ByteString} A random number generated by the server. * @param [options.results] {StatusCode[]} Any errors during validation of the software certificates. * @param [options.diagnosticInfos] {DiagnosticInfo[]} The diagnostics associated with the software certificates results. */ function ActivateSessionResponse(options) { options = options || {}; /* istanbul ignore next */ if (doDebug) { check_options_correctness_against_schema(this,schema,options); } var self = this; assert(this instanceof BaseUAObject); // ' keyword "new" is required for constructor call') resolve_schema_field_types(schema); BaseUAObject.call(this,options); /** * A standard header included in all responses returned by servers. * @property responseHeader * @type {ResponseHeader} */ self.responseHeader = new ResponseHeader( options.responseHeader); /** * A random number generated by the server. * @property serverNonce * @type {ByteString} */ self.serverNonce = initialize_field(schema.fields[1], options.serverNonce); /** * Any errors during validation of the software certificates. * @property results * @type {StatusCode[]} */ self.results = initialize_field_array(schema.fields[2], options.results); /** * The diagnostics associated with the software certificates results. * @property diagnosticInfos * @type {DiagnosticInfo[]} */ self.diagnosticInfos = []; if(options.diagnosticInfos) { assert(_.isArray(options.diagnosticInfos)); self.diagnosticInfos = options.diagnosticInfos.map(function(e){ return new DiagnosticInfo(e);}); } // Object.preventExtensions(self); } util.inherits(ActivateSessionResponse,BaseUAObject); ActivateSessionResponse.prototype.encodingDefaultBinary =makeExpandedNodeId(470,0); ActivateSessionResponse.prototype._schema = schema; var encode_ByteString = _defaultTypeMap.ByteString.encode; var decode_ByteString = _defaultTypeMap.ByteString.decode; var encode_StatusCode = _defaultTypeMap.StatusCode.encode; var decode_StatusCode = _defaultTypeMap.StatusCode.decode; /** * encode the object into a binary stream * @method encode * * @param stream {BinaryStream} */ ActivateSessionResponse.prototype.encode = function(stream,options) { // call base class implementation first BaseUAObject.prototype.encode.call(this,stream,options); this.responseHeader.encode(stream,options); encode_ByteString(this.serverNonce,stream); encodeArray(this.results, stream, encode_StatusCode); encodeArray(this.diagnosticInfos,stream,function(obj,stream){ obj.encode(stream,options); }); }; ActivateSessionResponse.prototype.decode = function(stream,options) { // call base class implementation first BaseUAObject.prototype.decode.call(this,stream,options); this.responseHeader.decode(stream,options); this.serverNonce = decode_ByteString(stream,options); this.results = decodeArray(stream, decode_StatusCode); this.diagnosticInfos = decodeArray(stream, function(stream) { var obj = new DiagnosticInfo(); obj.decode(stream,options); return obj; }); }; ActivateSessionResponse.possibleFields = function() { return [ "responseHeader", "serverNonce", "results", "diagnosticInfos" ]; }(); exports.ActivateSessionResponse = ActivateSessionResponse; var register_class_definition = require("../lib/misc/factories_factories").register_class_definition; register_class_definition("ActivateSessionResponse",ActivateSessionResponse);
var Tween = { linear: function (t, b, c, d){ return c*t/d + b; }, easeIn: function(t, b, c, d){ return c*(t/=d)*t + b; }, easeOut: function(t, b, c, d){ return -c *(t/=d)*(t-2) + b; }, easeBoth: function(t, b, c, d){ if ((t/=d/2) < 1) { return c/2*t*t + b; } return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInStrong: function(t, b, c, d){ return c*(t/=d)*t*t*t + b; }, easeOutStrong: function(t, b, c, d){ return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeBothStrong: function(t, b, c, d){ if ((t/=d/2) < 1) { return c/2*t*t*t*t + b; } return -c/2 * ((t-=2)*t*t*t - 2) + b; }, elasticIn: function(t, b, c, d, a, p){ if (t === 0) { return b; } if ( (t /= d) == 1 ) { return b+c; } if (!p) { p=d*0.3; } if (!a || a < Math.abs(c)) { a = c; var s = p/4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, elasticOut: function(t, b, c, d, a, p){ if (t === 0) { return b; } if ( (t /= d) == 1 ) { return b+c; } if (!p) { p=d*0.3; } if (!a || a < Math.abs(c)) { a = c; var s = p / 4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, elasticBoth: function(t, b, c, d, a, p){ if (t === 0) { return b; } if ( (t /= d/2) == 2 ) { return b+c; } if (!p) { p = d*(0.3*1.5); } if ( !a || a < Math.abs(c) ) { a = c; var s = p/4; } else { var s = p/(2*Math.PI) * Math.asin (c/a); } if (t < 1) { return - 0.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; } return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*0.5 + c + b; }, backIn: function(t, b, c, d, s){ if (typeof s == 'undefined') { s = 1.70158; } return c*(t/=d)*t*((s+1)*t - s) + b; }, backOut: function(t, b, c, d, s){ if (typeof s == 'undefined') { s = 2.70158; //回缩的距离 } return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, backBoth: function(t, b, c, d, s){ if (typeof s == 'undefined') { s = 1.70158; } if ((t /= d/2 ) < 1) { return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; } return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, bounceIn: function(t, b, c, d){ return c - Tween['bounceOut'](d-t, 0, c, d) + b; }, bounceOut: function(t, b, c, d){ if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + 0.75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + 0.9375) + b; } return c*(7.5625*(t-=(2.625/2.75))*t + 0.984375) + b; }, bounceBoth: function(t, b, c, d){ if (t < d/2) { return Tween['bounceIn'](t*2, 0, c, d) * 0.5 + b; } return Tween['bounceOut'](t*2-d, 0, c, d) * 0.5 + c*0.5 + b; } }; function css(element, attr , val){ if(arguments.length == 2){ var val = getComputedStyle(element)[attr]; if(attr=='opacity'){ val = Math.round(val*100); } return parseFloat(val); } if(attr == "opacity") { element.style.opacity= val/100; } else { element.style[attr]= val + "px"; } } function MTween(init){ var t = 0; var b = {}; var c = {}; var d = init.time / 20; for(var s in init.target){ b[s] = css(init.el, s); c[s] = init.target[s] - b[s]; } clearInterval(init.el.timer); init.el.timer = setInterval( function(){ t++; if(t>d){ clearInterval(init.el.timer); init.callBack&&init.callBack.call(init.el); } else { init.callIn&&init.callIn.call(init.el); for(var s in b){ var val = (Tween[init.type](t,b[s],c[s],d)).toFixed(2); css(init.el, s, val); } } }, 20 ); }
/** * Configuration data goes here. */ var sessions = require("client-sessions"); var conf = module.exports = { SITE_SECRET: getFromEnv('SITE_SECRET'), REDIS_HOST: getFromEnv('REDIS_HOST'), REDIS_PORT: getFromEnv('REDIS_PORT'), PORT: getFromEnv('PORT'), API_BASE: '/api/v1/' }; conf.signedCookie = sessions({ cookieName: 'runner.auth', requestKey: 'session', secret: conf.SITE_SECRET, duration: 24 * 60 * 60 * 1000, activeDuration: 1000 * 60 * 15, cookie: { httpOnly: true } }); conf.mysql = { host: getFromEnv('MYSQL_HOST'), database: getFromEnv('MYSQL_DB'), user: getFromEnv('MYSQL_USER'), password: getFromEnv('MYSQL_PASS') }; conf.postgres = { user: getFromEnv('POSTGRES_USER'), database: getFromEnv('POSTGRES_DB'), port: getFromEnv('POSTGRES_PORT'), host: getFromEnv('POSTGRES_HOST'), password: getFromEnv('POSTGRES_PASSWORD') }; function getFromEnv(key){ if(!(key in process.env)){ throw new Error ('Environment Variable ' + key + ' not present. Server will not starts.'); } return process.env[key]; };
const fns = { toSuperlative: require('./toSuperlative'), toComparative: require('./toComparative'), } /** conjugate an adjective into other forms */ const conjugate = function (w) { let res = {} // 'greatest' let sup = fns.toSuperlative(w) if (sup) { res.Superlative = sup } // 'greater' let comp = fns.toComparative(w) if (comp) { res.Comparative = comp } return res } module.exports = conjugate
module.exports = { ModalButton: require('./Modal/ModalButton'), ModalButtons: require('./Modal/ModalButtons'), ModalInner: require('./Modal/ModalInner'), ModalNoButttons: require('./Modal/ModalNoButttons'), ModalText: require('./Modal/ModalText'), ModalTextInput: require('./Modal/ModalTextInput'), ModalTextInputDouble: require('./Modal/ModalTextInputDouble'), ModalTitle: require('./Modal/ModalTitle'), };
define( /** * @class Control * @inheritable */ function (require) { var lib = require('../common/lib'); var blend = require('./blend'); var runtime = require('./runtime'); var isRuntimeEnv = true;//main.inRuntime();//runtime.isRuntimeEnv&&runtime.isRuntimeEnv(); function Control(options) { options = options || {}; if (!this.id && !options.id) { this.id = lib.getUniqueID(); } this.main = options.main ? options.main : this.initMain(options); this.initOptions(options); blend.register(this); //this.fire('init'); } Control.prototype = { constructor: Control, nativeObj : {}, currentStates:{}, /** * 事件存储数组 * @private * @property {Object} _listener */ _listener : {}, /** * 组件的类型 * * @cfg {String} type */ //type : "layerGroup", /** * 组件的id * * @cfg {String} id */ //id : "layerGroup", /** * 获取当前组件的类型 */ getType: function () { //layout, layer, component, navbar return this.type || 'control'; }, /** * @protected * 初始化所有options */ initOptions: function (options) { options = options || {}; this.setProperties(options); }, /** * 初始化Main元素并返回 * @returns {Object} DOM */ initMain: function () { var main = document.createElement('div'); main.setAttribute('data-blend', this.getType()); main.setAttribute('data-blend-id', this.id); //console.log(main.outerHTML); return main; }, /** * 渲染Control,可以是DOM也可以是Native,一般来说,子控件不继承此方法,而是实现paint方法 */ render: function () { //created, webviewready, pageonload, disposed this.fire('beforerender'); // 为控件主元素添加id if (!this.main.id) { this.main.id = lib.getUniqueID(); } //子控件实现这个 if(this.paint()){ this.fire('afterrender'); }else{ this.fire('renderfailed'); } return this.main; }, paint: function () { }, appendTo: function (DOM) { this.main.appendChild(DOM) }, insertBefore: function (DOMorControl) { this.main.parentNode.insertBefore(DOMorControl,this.main) }, /** * 把自己从dom中移除,包括事件,但不销毁自身实例 */ dispose: function () { this.fire('beforedestory'); try{ if(isRuntimeEnv){ runtime[this.type].destroy( this.id ); }else{ //TODO } }catch(e){ } this.fire('afterdestory'); }, /** * 清除所有DOM Events */ clearDOMEvents : function(){ }, /** * 销毁自身 */ destroy: function () { this.dispose(); blend.cancel(this); }, /** * * 获取属性 * @param {string} name 属性名 */ get: function (name) { var method = this['get' + lib.toPascal(name)]; if (typeof method == 'function') { return method.call(this); } return this[name]; }, /** * 设置控件的属性值 * * @param {string} name 属性名 * @param {Mixed} value 属性值 */ set: function (name, value) { var method = this['set' + lib.toPascal(name)]; if (typeof method == 'function') { return method.call(this, value); } var property = {}; property[name] = value; this.setProperties(property); }, /** * 设置属性 */ setProperties: function (properties) { //todo: 可能某些属性发生变化,要重新渲染页面或者调起runtime lib.extend(this, properties); }, /** * 禁用控件 */ disable: function () { this.addState('disabled'); }, /** * 启用控件 */ enable: function () { this.removeState('disabled'); }, /** * 判断控件是否不可用 */ isDisabled: function () { return this.hasState('disabled'); }, /** * 显示控件 */ in: function () { this.removeState('hidden'); this.fire("show"); }, /** * 隐藏控件 */ out: function () { this.addState('hidden'); this.fire("hide"); }, /** * 切换控件的显隐状态 */ toggle: function () { this[this.isHidden() ? 'in' : 'out'](); }, /** * 判断控件是否隐藏 */ isHidden: function () { return this.hasState('hidden'); }, /** * 为控件添加状态 * * @param {string} state 状态名 */ addState: function (state) { if (!this.hasState(state)) { } }, /** * 移除控件的状态 * * @param {String} state 状态名 */ removeState: function (state) { if (this.hasState(state)) { } }, /** * 开关控件的状态 * @param {String} state 状态名 */ toggleState: function (state) { var methodName = this.hasState(state) ? 'removeState' : 'addState'; this[methodName](state); }, /** * 判断当前控件是否处于某状态 * @param {String} state 状态名 * @returns Boolean */ hasState: function (state) { return !!this.currentStates[state]; }, /** * 注册事件 * @param {string} type 事件名字 * @param {Function} callback 绑定的回调函数 */ on : function(type, callback){ var t = this; if(!t._listener[type]){ t._listener[type] = []; } t._listener[type].push(callback); }, /** * 解绑事件 * @param {string} type 事件名字 * @param {Function} callback 绑定的回调函数 */ off: function(type, callback){ var events = this._listener[type]; if (!events) { return; } if(!callback) { delete this._listener[type]; return; } events.splice(types.indexOf(callback), 1); if (!events.length){ delete this._listener[type]; } }, /** * 触发事件 * @param {string} type 事件名字 * @param {Array} argAry 传给事件的参数 * @param {Object} context 事件的this指针 */ fire: function(type, argAry, context){ if (!type) { throw new Error('未指定事件名'); } var events = this._listener[type]; context = context || this; if (events){ for (var i = 0, len = events.length;i<len;i++){ events[i].apply(context, argAry); } } // 触发直接挂在对象上的方法 var handler = this['on' + type]; if (typeof handler === 'function') { handler.call(this, event); } return event; } }; return Control; } );
'use strict'; angular.module('crossfitApp') .factory('AlertService', function ($timeout, $sce,$translate) { var exports = { factory: factory, add: addAlert, closeAlert: closeAlert, closeAlertByIndex: closeAlertByIndex, clear: clear, get: get, success: success, error: error, info: info, warning : warning }, alertId = 0, // unique id for each alert. Starts from 0. alerts = [], timeout = 5000; // default timeout function clear() { alerts = []; } function get() { return alerts; } function success(msg, params) { this.add({ type: "success", msg: msg, params: params, timeout: timeout }); } function error(msg, params) { this.add({ type: "danger", msg: msg, params: params, timeout: timeout }); } function warning(msg, params) { this.add({ type: "warning", msg: msg, params: params, timeout: timeout }); } function info(msg, params) { this.add({ type: "info", msg: msg, params: params, timeout: timeout }); } function factory(alertOptions) { return alerts.push({ type: alertOptions.type, msg: $sce.trustAsHtml(alertOptions.msg), id: alertOptions.alertId, timeout: alertOptions.timeout, close: function () { return exports.closeAlert(this.id); } }); } function addAlert(alertOptions) { alertOptions.alertId = alertId++; alertOptions.msg = $translate.instant(alertOptions.msg, alertOptions.params); var that = this; this.factory(alertOptions); if (alertOptions.timeout && alertOptions.timeout > 0) { $timeout(function () { that.closeAlert(alertOptions.alertId); }, alertOptions.timeout); } } function closeAlert(id) { return this.closeAlertByIndex(alerts.map(function(e) { return e.id; }).indexOf(id)); } function closeAlertByIndex(index) { return alerts.splice(index, 1); } return exports; });
import React from 'react' import Relay from 'react-relay' import DeletePostMutation from '../mutations/DeletePostMutation' class Post extends React.Component { static propTypes = { post: React.PropTypes.object, viewer: React.PropTypes.object, } render () { return ( <div className='pa3 bg-black-05 ma3'> <div className='w-100' style={{ backgroundImage: `url(${this.props.post.imageUrl})`, backgroundSize: 'cover', paddingBottom: '100%', }} /> <div className='pt3'> {this.props.post.description}&nbsp; <span className='red f6 pointer dim' onClick={this.handleDelete}>Delete</span> </div> </div> ) } handleDelete = () => { const viewerId = this.props.viewer.id const postId = this.props.post.id Relay.Store.commitUpdate(new DeletePostMutation({viewerId, postId})) } } export default Relay.createContainer(Post, { fragments: { post: () => Relay.QL` fragment on Post { id imageUrl description } `, viewer: () => Relay.QL` fragment on Viewer { id } `, }, })
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import { Link, browserHistory } from 'react-router'; import SplitDropdown from 'components/dropdown/split'; import NavBar, { NAVBAR_HOME } from 'components/navbar'; import { USER_BOOKMARK } from 'services/auth/constants'; import { PAPER_LIST_FETCH, PAPER_LIST_UPDATE_FILTERS, PAPER_LIST_UPDATE_PAGINATION } from './api/constants'; import HomeList from './components/list'; import HomeFilters from './components/filters'; import NoUserState from './components/no-user'; import HomeEmptyState from './components/empty-state'; import SearchBar from './components/search-bar'; import './scene.scss'; const mapDispatchToProps = dispatch => ({ fetchPapers: () => dispatch({ type: PAPER_LIST_FETCH }), onBookmark: (paperId, bookmark) => dispatch({ type: USER_BOOKMARK, paperId, bookmark }), onFilterChange: (key, value) => dispatch({ type: PAPER_LIST_UPDATE_FILTERS, key, value }), onOffsetChange: offset => dispatch({ type: PAPER_LIST_UPDATE_PAGINATION, key: 'offset', value: offset }), }); const mapStateToProps = state => ({ facets: state.home.get('facets'), filters: state.home.get('filters'), pagination: state.home.get('pagination'), papers: state.home.get('papers'), user: state.auth, }); class HomeScene extends PureComponent { static propTypes = { facets: ImmutablePropTypes.map.isRequired, filters: ImmutablePropTypes.map.isRequired, fetchPapers: PropTypes.func.isRequired, onBookmark: PropTypes.func.isRequired, onFilterChange: PropTypes.func.isRequired, onOffsetChange: PropTypes.func.isRequired, pagination: ImmutablePropTypes.map.isRequired, papers: ImmutablePropTypes.list.isRequired, user: ImmutablePropTypes.map.isRequired, }; constructor(props) { super(props); this.props.fetchPapers(); } renderScene() { const { facets, filters, onBookmark, onFilterChange, onOffsetChange, pagination, papers, user } = this.props; if (!user.getIn(['token', 'token'])) { return <NoUserState />; } if (user.getIn(['user', 'id']) && (!user.getIn(['user', 'canSee']) || user.getIn(['user', 'canSee']).size === 0)) { return <HomeEmptyState />; } return ( <div> <SearchBar /> <div className="HomeView__Content row"> <HomeFilters className="col-md-3" facets={facets} filters={filters} onFilterChange={onFilterChange} /> <HomeList className="col-md-9" pagination={pagination} papers={papers} onBookmark={onBookmark} onOffsetChange={onOffsetChange} user={user} /> </div> </div> ); } render() { const { user } = this.props; return ( <div> <NavBar activeTab={NAVBAR_HOME}> {user.getIn(['token', 'token']) && ( <SplitDropdown btnStyle="inverse-primary" onClick={() => browserHistory.push('/papers/new')} menu={[ <Link key="cancel" className="btn dropdown-item" to="/imports"> Import </Link>, ]} title="New" /> )} </NavBar> <div className="HomeScene container">{this.renderScene()}</div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(HomeScene);
const helpers = require('../../helpers') module.exports = { command: 'get <resultId>', desc: 'Fetch a single test result.', builder: {}, handler: async function (argv) { const client = helpers.getClient(argv) const result = await client.getTestResult(argv.resultId) if (argv.json) { helpers.printJson(result) } else { helpers.print({ message: result.name, id: result._id, passing: result.passing, }) } process.exit(0) }, }
var fm = require('../') var fs = require('fs') var path = require('path') var test = require('tape') test('var fm = require("front-matter")', function (t) { t.equal(typeof fm, 'function') t.end() }) test('fm(string) - parse yaml delinetead by `---`', function (t) { fs.readFile( path.resolve(__dirname, '../examples/dashes-seperator.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') var content = fm(data) t.ok(content.attributes, 'should have `attributes` key') t.equal(content.attributes.title, 'Three dashes marks the spot') t.equal(content.attributes.tags.length, 3) t.ok(content.body, 'should have a `body` key') t.ok(content.body.match("don't break"), 'should match body') t.ok(content.body.match('---'), 'should match body') t.ok(content.body.match("Also this shouldn't be a problem"), 'should match body') t.end() }) }) test('fm(string) - parse yaml delinetead by `= yaml =`', function (t) { fs.readFile( path.resolve(__dirname, '../examples/yaml-seperator.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') var content = fm(data) var meta = content.attributes var body = content.body t.equal(meta.title, "I couldn't think of a better name") t.equal(meta.description, 'Just an example of using `= yaml =`') t.ok(body.match('Plays nice with markdown syntax highlighting'), 'should match body') t.end() }) }) test('fm(string) - parse yaml ended by `...`', function (t) { fs.readFile( path.resolve(__dirname, '../examples/dots-ending.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') var content = fm(data) var meta = content.attributes var body = content.body t.equal(meta.title, 'Example with dots document ending') t.equal(meta.description, 'Just an example of using `...`') t.ok(body.match("It shouldn't break with ..."), 'should match body') t.end() }) }) test('fm(string) - string missing front-matter', function (t) { var content = fm('No front matter here') t.equal(content.body, 'No front matter here') t.end() }) test('fm(string) - string missing body', function (t) { fs.readFile( path.resolve(__dirname, '../examples/missing-body.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') var content = fm(data) t.equal(content.attributes.title, 'Three dashes marks the spot') t.equal(content.attributes.tags.length, 3) t.equal(content.body, '') t.end() }) }) test('fm(string) - wrapped test in yaml', function (t) { fs.readFile( path.resolve(__dirname, '../examples/wrapped-text.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') var content = fm(data) var folded = [ 'There once was a man from Darjeeling', 'Who got on a bus bound for Ealing', ' It said on the door', ' "Please don\'t spit on the floor"', 'So he carefully spat on the ceiling\n' ].join('\n') t.equal(content.attributes['folded-text'], folded) t.ok(content.body.match('Some crazy stuff going on up there'), 'should match body') t.end() }) }) test('fm(string) - strings with byte order mark', function (t) { fs.readFile( path.resolve(__dirname, '../examples/bom.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') var content = fm(data) t.equal(content.attributes.title, "Relax guy, I'm not hiding any BOMs") t.end() }) }) test('fm(string) - no front matter, markdown with hr', function (t) { fs.readFile( path.resolve(__dirname, '../examples/no-front-matter.md'), 'utf8', function (err, data) { t.error(err, 'read should not error') var content = fm(data) t.equal(content.body, data) t.end() }) }) test('fm(string) - complex yaml', function (t) { fs.readFile( path.resolve(__dirname, '../examples/complex-yaml.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') var content = fm(data) t.ok(content.attributes, 'should have `attributes` key') t.equal(content.attributes.title, 'This is a title!') t.equal(content.attributes.contact, null) t.equal(content.attributes.match.toString(), '/pattern/gim') t.end() }) }) test('fm.test(string) - yaml seperator', function (t) { fs.readFile( path.resolve(__dirname, '../examples/yaml-seperator.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') t.equal(fm.test(data), true) t.end() }) }) test('fm.test(string) - dashes seperator', function (t) { fs.readFile( path.resolve(__dirname, '../examples/dashes-seperator.md'), 'utf8', function (err, data) { t.error(err, 'read(...) should not error') t.equal(fm.test(data), true) t.end() }) }) test('fm.test(string) - no front-matter', function (t) { t.equal(fm.test('no front matter here'), false) t.end() }) test('Supports live updating', function (t) { var seperator = '---' var string = '' for (var i = 0; i < seperator.length; i++) { string += seperator[i] try { fm(string) } catch (e) { t.error(e) } } string += '\n' string += 'foo: bar' var content = fm(string) t.same(content, { attributes: {}, body: string }) string += '\n---\n' content = fm(string) t.same(content, { attributes: { foo: 'bar' }, body: '' }) t.end() })
define([ 'underscore', 'text!templates/grid-docs.html', 'text!pages/grid-options-shiftSelect.html', 'dobygrid' ], function (_, template, page, DobyGrid) { "use strict"; return Backbone.DobyView.extend({ events: function () { return _.extend({}, Backbone.DobyView.prototype.events, { "change #option-value": "changeOption" }); }, initialize: function () { var html = _.template(template)({page: page}); this.$el.append(html); }, render: function () { var columns = [{ id: 'id', field: 'id', name: 'ID', removable: true, width: 15 }, { id: 'name', field: 'name', name: 'Name', removable: true }, { id: 'age', field: 'age', name: 'Age', removable: true, width: 15 }]; this.grid = new DobyGrid({ columns: columns, data: [{ id: 1, data: { id: 1, name: "Abraham", age: 20 } }, { id: 2, data: { id: 2, name: "Bobby", age: 20 } }, { id: 3, data: { id: 3, name: "James", age: 21 } }, { id: 4, data: { id: 4, name: "Steve", age: 30 } }], rowHeight: 35 }).appendTo('#demo-grid'); }, changeOption: function (event) { // Get value var value = $(event.currentTarget).val(); // Set value this.grid.setOptions({shiftSelect: value === 'false' ? false : true}); } }); });
// @flow import { SET_CURRENCY } from "../constants"; import type { Action } from "../actions"; type State = Object; export default function currencyReducer(state: State = { "value": "$", "label": "USD" }, action: Action) { if (action.type === SET_CURRENCY) { return action.currency; } return state; }
import JoinAllLink from './JoinAllLink.svelte'; import getElementById from '../../common/getElementById'; function mountApp(newGroup) { return new JoinAllLink({ anchor: newGroup, target: newGroup.parentNode, }); } export default function injectJoinAllLink() { const newGroup = getElementById('notification-guild-group'); if (newGroup) { mountApp(newGroup); } }
describe('view entity events', function() { 'use strict'; beforeEach(function() { this.model = new Backbone.Model(); this.collection = new Backbone.Collection(); this.fooStub = this.sinon.stub(); this.barStub = this.sinon.stub(); this.modelEventsStub = this.sinon.stub().returns({'foo': this.fooStub}); this.collectionEventsStub = this.sinon.stub().returns({'bar': this.barStub}); }); describe('when a view has string-based model and collection event configuration', function() { beforeEach(function() { this.fooOneStub = this.sinon.stub(); this.fooTwoStub = this.sinon.stub(); this.barOneStub = this.sinon.stub(); this.barTwoStub = this.sinon.stub(); this.View = Marionette.View.extend({ modelEvents : {'foo': 'fooOne fooTwo'}, collectionEvents : {'bar': 'barOne barTwo'}, fooOne: this.fooOneStub, fooTwo: this.fooTwoStub, barOne: this.barOneStub, barTwo: this.barTwoStub }); this.view = new this.View({ model : this.model, collection : this.collection }); }); it('should wire up model events', function() { this.model.trigger('foo'); expect(this.fooOneStub).to.have.been.calledOnce; expect(this.fooTwoStub).to.have.been.calledOnce; }); it('should wire up collection events', function() { this.collection.trigger('bar'); expect(this.barOneStub).to.have.been.calledOnce; expect(this.barTwoStub).to.have.been.calledOnce; }); }); describe('when a view has function-based model and collection event configuration', function() { beforeEach(function() { this.View = Marionette.View.extend({ modelEvents : {'foo': this.fooStub}, collectionEvents : {'bar': this.barStub} }); this.view = new this.View({ model : this.model, collection : this.collection }); }); it('should wire up model events', function() { this.model.trigger('foo'); expect(this.fooStub).to.have.been.calledOnce; }); it('should wire up collection events', function() { this.collection.trigger('bar'); expect(this.barStub).to.have.been.calledOnce; }); }); describe('when a view has model event config with a specified handler method that doesnt exist', function() { beforeEach(function() { var suite = this; this.View = Marionette.View.extend({ modelEvents: {foo: 'doesNotExist'}, model: this.model }); this.getBadViewInstance = function() { return new suite.View(); }; }); it('should error when method doesnt exist', function() { expect(this.getBadViewInstance).to.throw('Method "doesNotExist" was configured as an event handler, but does not exist.'); }); }); describe('when configuring entity events with a function', function() { beforeEach(function() { this.View = Marionette.View.extend({ modelEvents : this.modelEventsStub, collectionEvents : this.collectionEventsStub }); this.view = new this.View({ model : this.model, collection : this.collection }); }); it('should trigger the model event', function() { this.view.model.trigger('foo'); expect(this.fooStub).to.have.been.calledOnce; }); it('should trigger the collection event', function() { this.view.collection.trigger('bar'); expect(this.barStub).to.have.been.calledOnce; }); }); describe('when undelegating events on a view', function() { beforeEach(function() { this.View = Marionette.View.extend({ modelEvents : {'foo': 'foo'}, collectionEvents : {'bar': 'bar'}, foo: this.fooStub, bar: this.barStub }); this.view = new this.View({ model : this.model, collection : this.collection }); this.sinon.spy(this.view, 'undelegateEvents'); this.view.undelegateEvents(); this.model.trigger('foo'); this.collection.trigger('bar'); }); it('should undelegate the model events', function() { expect(this.fooStub).not.to.have.been.calledOnce; }); it('should undelegate the collection events', function() { expect(this.barStub).not.to.have.been.calledOnce; }); it('should return the view', function() { expect(this.view.undelegateEvents).to.have.returned(this.view); }); }); describe('when undelegating events on a view, delegating them again, and then triggering a model event', function() { beforeEach(function() { this.View = Marionette.View.extend({ modelEvents : {'foo': 'foo'}, collectionEvents : {'bar': 'bar'}, foo: this.fooStub, bar: this.barStub }); this.view = new this.View({ model : this.model, collection : this.collection }); this.view.undelegateEvents(); this.sinon.spy(this.view, 'delegateEvents'); this.view.delegateEvents(); }); it('should fire the model event once', function() { this.model.trigger('foo'); expect(this.fooStub).to.have.been.calledOnce; }); it('should fire the collection event once', function() { this.collection.trigger('bar'); expect(this.barStub).to.have.been.calledOnce; }); it('should return the view from delegateEvents', function() { expect(this.view.delegateEvents).to.have.returned(this.view); }); }); describe('when LayoutView bound to modelEvent replaces region with new view', function() { beforeEach(function() { this.LayoutView = Marionette.LayoutView.extend({ template: _.template('<div id="child"></div>'), regions: {child: '#child'}, modelEvents: {'baz': 'foo'}, foo: this.fooStub }); this.ItemView = Marionette.ItemView.extend({ template: _.template('bar'), modelEvents: {'baz': 'bar'}, bar: this.barStub }); this.layoutView = new this.LayoutView({model: this.model}); this.itemViewOne = new this.ItemView({model: this.model}); this.itemViewTwo = new this.ItemView({model: this.model}); this.layoutView.render(); this.layoutView.child.show(this.itemViewOne); this.layoutView.child.show(this.itemViewTwo); this.model.trigger('baz'); }); it('should leave the layoutView\'s modelEvent binded', function() { expect(this.fooStub).to.have.been.calledOnce; }); it('should unbind the previous child view\'s modelEvents', function() { expect(this.barStub).to.have.been.calledOnce; }); }); });
import { fromJS } from 'immutable'; import createReducer from 'utils/createReducer'; import { SET_COMPANY_DATA, SET_COMPANY_STATUS, } from '../actions/timeAndSalaryCompany'; import fetchingStatus from '../constants/status'; const preloadedState = fromJS({ companyName: null, data: null, status: fetchingStatus.UNFETCHED, error: null, }); export default createReducer(preloadedState, { [SET_COMPANY_DATA]: (state, { companyName, data, status, error }) => state .set('data', fromJS(data)) .set('status', status) .set('error', error) .set('companyName', companyName), [SET_COMPANY_STATUS]: (state, { status }) => state.set('status', status), });
import moment from 'moment' import _ from 'lodash' import { fromJS } from 'immutable' import $ from 'zepto-modules' import Jed from 'jed' import { SyncApp, User } from '../app/Api' import { Files, Transfers } from '../app/Api' import { int, translations } from '../common' import Uploader from '../uploader' import Growl from '../components/growl' import * as DownloadsActions from '../downloads/Actions' export const SYNCAPP_STATUS_STOPPED = 'stopped' export const SYNCAPP_STATUS_SYNCING = 'syncing' export const SYNCAPP_STATUS_UPTODATE = 'up-to-date' export const GET_CONFIG_SUCCESS = 'GET_CONFIG_SUCCESS' export function GetConfig() { return (dispatch, getState) => { SyncApp .Config() .then(response => { dispatch({ type: GET_CONFIG_SUCCESS, config: response.body, }) dispatch(Authenticate()) dispatch(GetSourceFolder( response.body['download-from'] )) }) } } export const AUTHENTICATE_USER = 'AUTHENTICATE_USER' export const APP_READY = 'APP_READY' export function Authenticate() { return (dispatch, getState) => { const config = getState().getIn([ 'app', 'config', ]) window.token = config.get('oauth2-token') if (!token) { return dispatch(GrantAccess()) } User .Get() .then(response => { let user = response.body.info // get language file InitInternalization(user.settings.locale || 'en') .then(() => { dispatch({ type: AUTHENTICATE_USER, user, }) dispatch({ type: APP_READY, ready: true, }) }) }) .catch(err => { if (err && err.error_type === 'invalid_grant') { return dispatch(GrantAccess()) } }) } } export function GrantAccess() { return (dispatch, getState) => { const oauth = getState().getIn([ 'app', 'oauth', ]) window.location.href = '' window.location.replace(`https://put.io/v2/oauth2/authenticate?client_id=${oauth.get('id')}&response_type=token&redirect_uri=${oauth.get('callback')}`) } } export function SaveToken(token) { return (dispatch, getState) => { SyncApp .SetConfig({ 'oauth2-token': token, }) .then(response => { window.location.href = '/welcome' }) } } export const GET_SOURCEFOLDER_SUCCESS = 'GET_SOURCEFOLDER_SUCCESS' export function GetSourceFolder(id) { return (dispatch, getState) => { const config = getState().getIn([ 'app', 'config', ]) Files .Query(id, { breadcrumbs: true, }) .then(response => { let breadcrumbs = response.body.breadcrumbs.map(b => ({ id: b[0], name: b[1], })) breadcrumbs.push({ id: response.body.parent.id, name: response.body.parent.name, }) let source = _.map(breadcrumbs, b => { return b.name }).join('/') dispatch({ type: GET_SOURCEFOLDER_SUCCESS, source: parseInt(id), sourceStr: `/${source}`, }) }) } } export function InitInternalization(locale) { return new Promise((resolve, reject) => { $.ajax({ type: 'GET', url: `/statics/locale/${locale}.json`, dataType: 'json', timeout: 1000, error: resolve, success: data => { moment.locale(locale); int.init(data); resolve() }, }) }) } export const SET_PROCESSING = 'SET_PROCESSING' export function SetProcessing(processing) { return (dispatch, getState) => { dispatch({ type: SET_PROCESSING, processing, }) } } export function Logout() { return (dispatch, getState) => { const appId = getState().getIn([ 'app', 'oauth', 'id', ]) User.Revoke(appId) .then(response => { User.Logout() .then(response => { dispatch(GrantAccess()) }) }) } } export function HandlePaste(e) { return (dispatch, getState) => { let text if (window.clipboardData && window.clipboardData.getData) { text = window.clipboardData.getData('Text'); } else if (e.clipboardData && e.clipboardData.getData) { text = e.clipboardData.getData('text/plain'); } if (text.match(/magnet:\?xt=urn/i) === null && text.match(/^https?.*$/ig) === null) { return } dispatch(SetProcessing(true)) dispatch(StartTransfers(text)) } } export const ANALYSIS_SUCCESS = 'ANALYSIS_SUCCESS' export function StartTransfers(text) { return (dispatch, getState) => { const links = _.compact(text.split('\n')) if (!links.length) { Growl.Show({ message: translations.new_transfer_no_link_error(), scope: Growl.SCOPE.ERROR, timeout: 2, }) return dispatch(SetProcessing(false)) } Transfers .Analysis(links) .then(response => { let eFiles = _.filter(response.body.ret, f => f.error) let hasError = (eFiles.length === response.body.ret.length) let someError = (eFiles.length && eFiles.length < response.body.ret.length) if (hasError) { Growl.Show({ message: translations.new_transfer_invalid_link_error(), scope: Growl.SCOPE.ERROR, timeout: 2, }) return dispatch(SetProcessing(false)) } if (someError) { Growl.Show({ message: 'Some of the hashes couldn\'t add', scope: Growl.SCOPE.ERROR, timeout: 2, }) } const files = _.chain(response.body.ret) .filter(f => !f.error) .map(f => ({ id: f.url, name: f.name, size: f.file_size, email_when_complete: false, type: 'magnet', _source: f, })) .value() dispatch(StartFetching(files)) }) .catch(err => { dispatch(SetProcessing(false)) }) } } export function StartFetching(files) { return (dispatch, getState) => { const magnets = fromJS(files) .map(m => ({ url: m.get('id'), email_when_complete: m.get('email_when_complete'), extract: m.get('extract'), save_parent_id: 0, })).toJS() Transfers .StartFetching(magnets) .then(response => { Growl.Show({ message: translations.new_transfer_success_message(), scope: Growl.SCOPE.SUCCESS, timeout: 2, }) dispatch(SetProcessing(false)) }) .catch(err => { dispatch(SetProcessing(false)) }) } } export function OnFileDrop(files) { return (dispatch, getState) => { dispatch(SetProcessing(true)) let uploader = new Uploader() _.each(files, f => { uploader.add(f, 0) }) uploader.start() .then(() => { dispatch(SetProcessing(false)) Growl.Show({ message: translations.app_drag_drop_success(), scope: Growl.SCOPE.SUCCESS, timeout: 3, }) }) .catch(err => { dispatch(SetProcessing(false)) Growl.Show({ message: translations.app_drag_drop_error(), scope: Growl.SCOPE.ERROR, timeout: 3, }) }) } }
(function() { var data, keys, students, chart = document.querySelector(".chart") ; function drawGraphic(containerWidth) { chart.innerHTML = ""; var x, y, adm, color, dates, xAxis, yAxis, line, legend, revenue, enrollment, margin = { top: 16, right: 16, bottom: 32 , left: 64 }, width = calculateWidth(), mobile = (width <= 320), ratio = (mobile) ? { width: 1, height: 2 } : { width: 3, height: 2 }, height = calculateHeight() ; // Helper functions for chart dimensions // --------------------------------------------------------------------------- function marginWidth() { return margin.left + margin.right; } function marginHeight() { return margin.top + margin.bottom; } function calculateWidth() { if (!containerWidth) { var containerWidth = +chart.offsetWidth; } return Math.ceil(containerWidth - marginWidth()); } function calculateHeight() { return Math.ceil(width * ratio.height / ratio.width) - marginHeight(); } // Data source and header container (Title, description, legend and adjustment button) // --------------------------------------------------------------------------- d3.select(".header").style({ "margin-left": "7px", "margin-right": "7px" }); d3.select(".data-source").style({ "margin-left": "7px", "margin-right": "7px" }); // Legend // --------------------------------------------------------------------------- legend = d3.select(".legend svg") .attr("width", width) .attr("height", (mobile) ? marginHeight() * 1.75 : marginHeight()) .style("margin-top", "8px"); d3.selectAll(".key-group") .attr("transform", function(d, i) { var x, y; if (mobile) { x = 0; y = i } else { x = (i <= 2) ? 0 : width / 2; y = (i <= 2) ? i : i - 3; } return "translate(" + x + "," + (y * 16 + 16) + ")"; }); // Scales, axes // --------------------------------------------------------------------------- dates = data[0].revenue.map(function(d) { return d.date; }); // x scale by year x = d3.time.scale() .range([0, width]) .domain(d3.extent(dates)); // y scale by revenue y = d3.scale.linear() .range([height, 0]) .domain([ 0, d3.max(data, function(d) { return d3.max(d.revenue, function(r) { return r.adjusted; }) }) ]); // y scale by enrollment adm = d3.scale.linear() .range([height / 2, 0]) .domain(d3.extent(students, function(d) { return d.enrollment; })); // lines excluding enrollment color = d3.scale.ordinal() .domain(keys) .range(["#0060ae", "#0060ae", "#0060ae", "#8dbd45", "#df2027"]); xAxis = d3.svg.axis() .scale(x) .orient("bottom") .tickValues(dates.filter(function(d, i) { return (mobile) ? !(i % 4) : !(i % 2); })) .tickFormat(d3.time.format("%Y")); yAxis = d3.svg.axis() .scale(y) .tickFormat(function(d) { return "$" + d3.format(".2s")(d); }) .tickSize(-width, 0, 0) .orient("left"); aAxis = d3.svg.axis() .scale(adm) .orient("left") .tickSize(-width, 0, 0) .ticks(4); // svg setup // --------------------------------------------------------------------------- revenue = d3.select(chart).append("svg") .attr("width", width + marginWidth()) .attr("height", height + marginHeight()) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); revenue.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + height + ")") .call(xAxis); revenue.append("g") .attr("class", "y axis") .call(yAxis); d3.select(".y.axis .tick").remove(); // Removes first tick mark enrollment = d3.select(chart).append("svg") .attr("width", width + marginWidth()) .attr("height", height / 2 + marginHeight()) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); enrollment.append("g") .attr("class", "a axis") .call(aAxis); // y axis labels d3.select(".y.axis") .append("text") .attr("class", "label") .attr("transform", "rotate(-90)") .attr("text-anchor", "middle") .attr("x", -height / 2) .attr("y", -margin.left * .8) .text("Revenue"); d3.select(".a.axis") .append("text") .attr("class", "label") .attr("transform", "rotate(-90)") .attr("text-anchor", "middle") .attr("x", -height / 4) .attr("y", -margin.left * .8) .text("Enrollment"); // Revenue line graphs // --------------------------------------------------------------------------- line = d3.svg.line() .x(function(d) { return x(d.date); }) .y(function(d) { return y(d.unadjusted); }); revenue.selectAll("g.revenue-source") .data(data) .enter().append("g") .attr("class", "revenue-source"); d3.selectAll("g.revenue-source").append("path") .attr("class", "line") .attr("d", function(d) { return line(d.revenue); }) .attr("stroke-dasharray", function(d) { switch (d.name) { case "Property tax": return "5,5"; case "Sales tax": return "0.9"; default: return false; } }) .style("stroke", function(d) { return color(d.name); }); // Button click resets line y with CPI adjustments // Changes button text d3.select("#adjustment").on("click", function() { var button = this; if (button.innerHTML == "Reset to nominal") { line.y(function(d) { return y(d.unadjusted); }); button.innerHTML = "Adjust for inflation"; } else { line.y(function(d) { return y(d.adjusted); }); button.innerHTML = "Reset to nominal"; } d3.selectAll(".revenue-source .line") .transition() .delay(100) .duration(500) .attr("d", function(d) { return line(d.revenue); }); }); // Enrollment line graph // --------------------------------------------------------------------------- enrollment.append("path") .datum(students) .attr("class", "line") .attr("d", d3.svg.line() .x(function(d) { return x(d.date); }) .y(function(d) { return adm(d.enrollment); })); } // End of drawGraphic() // Adjusts for inflation using CPI-U for South region // http://data.bls.gov/pdq/SurveyOutputServlet?series_id=CUUR0300SA0,CUUS0300SA0 // --------------------------------------------------------------------------- function adjustForInflation(amount, current, previous) { var cpi = { 1998: 158.9, 1999: 162.0, 2000: 167.2, 2001: 171.1, 2002: 173.3, 2003: 177.3, 2004: 181.8, 2005: 188.3, 2006: 194.7, 2007: 200.361, 2008: 208.681, 2009: 207.845, 2010: 211.338, 2011: 218.618, 2012: 223.242, 2013: 226.721, 2014: 230.552, 2015: 230.147 }; return amount * cpi[previous] / cpi[current]; }; // Load and map data // --------------------------------------------------------------------------- d3.csv("data.csv", function(error, csv) { if (error) throw error; keys = d3.keys(csv[0]).filter(function(key) { return key != "year" && key != "adm"; }); data = keys.map(function(key) { return { name: key, revenue: csv.map(function(row) { return { date: d3.time.format("%Y%m%d").parse(row.year + "0630"), unadjusted: +row[key], adjusted: Math.round(adjustForInflation(row[key], row.year, 2015)) }; }) }; }); students = csv.map(function(row) { return { date: d3.time.format("%Y%m%d").parse(row.year + "0630"), enrollment: +row.adm }; }); console.log(students); new pym.Child({ renderCallback: drawGraphic }); }); })()
const mongoose = require('mongoose') const ping = require("net-ping") const schedule = require("node-schedule"); const stateSchema = require('./State') const logSchema = require('./Log') var nodemailer = require('nodemailer') var smtpTransport = require('nodemailer-smtp-transport') /*mongoose.connect('mongodb://127.0.0.1:27017/monitor', { useMongoClient: true }); mongoose.Promise = global.Promise;*/ var State = mongoose.model("State", stateSchema); var Log = mongoose.model("Log", logSchema); var session = ping.createSession(); var transporter = nodemailer.createTransport(smtpTransport({ host: 'smtp.kagoya.net', auth: { user: '', pass: '' } })) var mailOptions = (element, address) => ({ from: '', to: '', subject: element + ' ' + 'server is down!', text: 'The' + ' ' + element + ' ' + 'with ip address of' + ' ' + address + ' ' + 'is not responding!' }) /*var mailOptions = { from: 'chickenruntest@gmail.com', to: 'h-zhang@junction.tokyo', subject: 'Sending Email using Node.js', text: 'That was easy!' }*/ var rule = new schedule.RecurrenceRule(); rule.minute = new schedule.Range(0, 59, 1); var mission = schedule.scheduleJob(rule, function() { State.find(async(err, target) => { if (err) { console.log(target + " : " + error.toString()); } else { target.forEach(async(element, index) => { session.pingHost(element.ip_address, function(error, target, sent, rcvd) { var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + ": " + error.toString()); /*transporter.sendMail(mailOptions(element.server_name, element.ip_address), function(error, info) { if (error) { console.log(error); } else { console.log('Email sent: ' + info.response); } })*/ State.findOneAndUpdate({ "server_name": element.server_name, }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": element.ip_address, "pors": element.port, "server_name": element.server_name, "port": element.port, "jp_name": element.jp_name, "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) } else { console.log(target + ": Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": element.server_name, }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { /*if (!doc) { doc = new State({ ip_address: element.ip_address, server_name: element.server_name, jp_name: element.jp_name, state: "green" }); doc.save(function(err) { if (err) console.log(err); }) }*/ } }) } }) }) } }) /*for (let i = 0; i < targets.length; i++) { session.pingHost(targets[i], function(error, target, sent, rcvd) { switch (targets[i]) { case "192.168.1.20": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + " : " + error.toString()); State.findOneAndUpdate({ "server_name": "JT-CTI", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "JT-CTI", "jp_name": "JT-CTI", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + " : Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "JT-CTI", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "JT-CTI", jp_name: "JT-CTI", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.1.100": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + ": " + error.toString()); State.findOneAndUpdate({ "server_name": "JT-MAIN", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "JT-MAIN", "jp_name": "JT-MAIN", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + ": Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "JT-MAIN", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "JT-MAIN", jp_name: "JT-MAIN", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.2.20": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + " : " + error.toString()); State.findOneAndUpdate({ "server_name": "MG-CTI", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "MG-CTI", "jp_name": "MG-CTI", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + " : Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "MG-CTI", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "MG-CTI", jp_name: "MG-CTI", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.2.100": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + ": " + error.toString()); State.findOneAndUpdate({ "server_name": "MG-MAIN", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "MG-MAIN", "jp_name": "MG-MAIN", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + ": Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "MG-MAIN", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "MG-MAIN", jp_name: "MG-MAIN", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.3.20": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + " : " + error.toString()); State.findOneAndUpdate({ "server_name": "OSAKA-CTI", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "OSAKA-CTI", "jp_name": "大阪-CTI", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + " : Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "OSAKA-CTI", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "OSAKA-CTI", jp_name: "大阪-CTI", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.3.100": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + ": " + error.toString()); State.findOneAndUpdate({ "server_name": "OSAKA-MAIN", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "OSAKA-MAIN", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + ": Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "OSAKA-MAIN", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "OSAKA-MAIN", jp_name: "大阪-MAIN", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.5.20": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + " : " + error.toString()); State.findOneAndUpdate({ "server_name": "MATSUMOTO-CTI", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "MATSUMOTO-CTI", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + " : Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "MATSUMOTO-CTI", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "MATSUMOTO-CTI", jp_name: "松本-CTI", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.5.100": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + ": " + error.toString()); State.findOneAndUpdate({ "server_name": "MATSUMOTO-MAIN", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "MATSUMOTO-MAIN", "jp_name": "松本-MAIN", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + ": Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "MATSUMOTO-MAIN", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "MATSUMOTO-MAIN", jp_name: "松本-MAIN", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.6.20": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + " : " + error.toString()); State.findOneAndUpdate({ "server_name": "KANAZAWA-CTI", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "KANAZAWA-CTI", "jp_name": "金沢-CTI", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + " : Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "KANAZAWA-CTI", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "KANAZAWA-CTI", jp_name: "金沢-CTI", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.6.100": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + ": " + error.toString()); State.findOneAndUpdate({ "server_name": "KANAZAWA-MAIN", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "KANAZAWA-MAIN", "jp_name": "金沢-MAIN", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + ": Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "KANAZAWA-MAIN", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "KANAZAWA-MAIN", jp_name: "金沢-MAIN", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.7.20": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + " : " + error.toString()); State.findOneAndUpdate({ "server_name": "KUMAMOTO-CTI", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "KUMAMOTO-CTI", "jp_name": "熊本-CTI", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + " : Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "KUMAMOTO-CTI", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "KUMAMOTO-CTI", jp_name: "熊本-CTI", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } case "192.168.7.100": var ms = rcvd - sent; if (ms < 10) { ms = "0" + ms; } if (error) { console.log(target + ": " + error.toString()); State.findOneAndUpdate({ "server_name": "KUMAMOTO-MAIN", }, { "$set": { "state": "red" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) Log.create({ "ip_address": targets[i], "server_name": "KUMAMOTO-MAIN", "jp_name": "熊本-MAIN", "state": "red" }, function(err, doc) { if (err) { console.log(err.toString()); } else { } }) break; } else { console.log(target + ": Alive(ms=" + ms + ")" + " " + new Date().toLocaleString().replace('/T/', '').replace('/\../+', '')); State.findOneAndUpdate({ "server_name": "KUMAMOTO-MAIN", }, { "$set": { "state": "green" } }, function(err, doc) { if (err) { console.log(err.toString()); } else { if (!doc) { doc = new State({ ip_address: targets[i], server_name: "KUMAMOTO-MAIN", jp_name: "熊本-MAIN", state: "green" }); doc.save(function(err) { if (err) console.log(err); }) } } }) break; } } }) }*/ }) module.exports = mission
(function(){ 'use strict'; angular.module('app', []); })();
'use strict'; // Declare app level module which depends on views, and components angular.module('myApp', [ 'ngRoute', 'myApp.main' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/main'}); }]);
var a00446 = [ [ "CDC_BUFFER_MAX", "a00446.html#a5ac8c9377f90d6ce3044f81f900a54fe", null ], [ "CDC_DEVICES_MAX", "a00446.html#a08b6c05184266dc4d5c8727bb9c1c754", null ], [ "atcacdc_t", "a00446.html#a2df85bfd309840b4c9a5087e053d4811", null ], [ "cdc_device_t", "a00446.html#a99ee56102171adcbcecb8a78fb9fa895", null ] ];
var Readable = require('stream').Readable var split = require('split') var BRANCH_HEADER_REGEX = /^branch\.(oid|head|upstream|ab) (.*)$/ var AHEAD_BEHIND_REGEX = /^\+(\d+) -(\d+)$/ var CHANGED_REGEX = /^([.MADRCUT]{2}) ([NS][.C][.M][.U]) (\d+) (\d+) (\d+) ([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/ var RENAMED_COPIED_REGEX = /^([.MADRCUT]{2}) ([NS][.C][.M][.U]) (\d+) (\d+) (\d+) ([0-9a-f]{40}) ([0-9a-f]{40}) ([RC]\d+) (.*)$/ var UNMERGED_REGEX = /^([.MADRCUT]{2}) ([NS][.C][.M][.U]) (\d+) (\d+) (\d+) (\d+) ([0-9a-f]{40}) ([0-9a-f]{40}) ([0-9a-f]{40}) (.*)$/ function parse(str, limit) { return new Promise(function (resolve, reject) { var count = 0 var result = { branch: { aheadBehind: { ahead: null, behind: null } }, changedEntries: [], untrackedEntries: [], renamedEntries: [], unmergedEntries: [], ignoredEntries: [], } var context = { inProgressRenameOrCopy: null, } var s = new Readable s.push(str) s.push(null) var resolved = false s.pipe(split('\000')) .on('data', function (line) { if (resolved || (limit && count > limit)) return try { var addedNewEntry = parseLine(line, result, context) if (addedNewEntry) count++ } catch (err) { resolved || reject(err) resolved = true } }) .on('error', function (err) { resolved || reject(err) resolved = true }) .on('end', function() { resolved || resolve(result) resolved = true }) }) } function parseLine(line, result, context) { if (!line.length) return var first = line[0]; var rest = line.substr(2) switch (first) { case '#': parseHeader(rest, result) return false case '1': parseChangedEntry(rest, result) return true case '2': var entry = parseRenamedOrCopiedEntry(rest, result) context.inProgressRenameOrCopy = { entry: entry } return false case 'u': parseUnmergedEntry(rest, result) return true case '?': parseUntrackedEntry(rest, result) return true case '!': parseIgnoredEntry(rest, result) return true default: if (context.inProgressRenameOrCopy) { context.inProgressRenameOrCopy.entry.origFilePath = line context.inProgressRenameOrCopy = null return true } else { throw new Error('Bad entry: ' + line) } } } function parseHeader(line, result) { var match = line.match(BRANCH_HEADER_REGEX) if (match) { var field = match[1] var data = match[2] if (field === 'ab') { field = 'aheadBehind' data = parseAheadBehind(data) } result.branch[field] = data } else { // unknown header; ignore } } function parseAheadBehind(ab) { var match = ab.match(AHEAD_BEHIND_REGEX) if (match) { return { ahead: parseInt(match[1], 10), behind: parseInt(match[2], 10) } } else { throw new Error('Invalid ahead/behind string: ' + ab) } } function parseChangedEntry(line, result) { var match = line.match(CHANGED_REGEX) var entry = { filePath: match[8], stagedStatus: match[1][0] === '.' ? null : match[1][0], unstagedStatus: match[1][1] === '.' ? null : match[1][1], submodule: { isSubmodule: match[2][0] === 'S' }, fileModes: { head: match[3], index: match[4], worktree: match[5], }, headSha: match[6], indexSha: match[7], } if (entry.submodule.isSubmodule) { Object.assign(entry.submodule, { commitChanged: match[2][1] !== '.', trackedChanges: match[2][2] !== '.', untrackedChanges: match[2][3] !== '.', }) } result.changedEntries.push(entry) return entry } function parseRenamedOrCopiedEntry(line, result) { var match = line.match(RENAMED_COPIED_REGEX) var entry = { filePath: match[9], origFilePath: null, stagedStatus: match[1][0] === '.' ? null : match[1][0], unstagedStatus: match[1][1] === '.' ? null : match[1][1], submodule: { isSubmodule: match[2][0] === 'S' }, fileModes: { head: match[3], index: match[4], worktree: match[5], }, headSha: match[6], indexSha: match[7], similarity: { type: match[8][0], score: parseInt(match[8].substr(1), 10), }, } if (entry.submodule.isSubmodule) { Object.assign(entry.submodule, { commitChanged: match[2][1] !== '.', trackedChanges: match[2][2] !== '.', untrackedChanges: match[2][3] !== '.', }) } result.renamedEntries.push(entry) return entry } function parseUnmergedEntry(line, result) { var match = line.match(UNMERGED_REGEX) var entry = { filePath: match[10], stagedStatus: match[1][0] === '.' ? null : match[1][0], unstagedStatus: match[1][1] === '.' ? null : match[1][1], submodule: { isSubmodule: match[2][0] === 'S' }, fileModes: { stage1: match[3], stage2: match[4], stage3: match[5], worktree: match[6], }, stage1Sha: match[7], stage2Sha: match[8], stage3Sha: match[9], } if (entry.submodule.isSubmodule) { Object.assign(entry.submodule, { commitChanged: match[2][1] !== '.', trackedChanges: match[2][2] !== '.', untrackedChanges: match[2][3] !== '.', }) } result.unmergedEntries.push(entry) return entry } function parseUntrackedEntry(line, result) { var entry = { filePath: line, } result.untrackedEntries.push(entry) return entry } function parseIgnoredEntry(line, result) { var entry = { filePath: line, } result.ignoredEntries.push(entry) return entry } module.exports = { parse: parse }
import { RX_ARRAY_NOTATION } from '../constants/regex' import { identity } from './identity' import { isArray, isNull, isObject, isUndefinedOrNull } from './inspect' /** * Get property defined by dot/array notation in string, returns undefined if not found * * @link https://gist.github.com/jeneg/9767afdcca45601ea44930ea03e0febf#gistcomment-1935901 * * @param {Object} obj * @param {string|Array} path * @return {*} */ export const getRaw = (obj, path, defaultValue = undefined) => { // Handle array of path values path = isArray(path) ? path.join('.') : path // If no path or no object passed if (!path || !isObject(obj)) { return defaultValue } // Handle edge case where user has dot(s) in top-level item field key // See https://github.com/bootstrap-vue/bootstrap-vue/issues/2762 // Switched to `in` operator vs `hasOwnProperty` to handle obj.prototype getters // https://github.com/bootstrap-vue/bootstrap-vue/issues/3463 if (path in obj) { return obj[path] } // Handle string array notation (numeric indices only) path = String(path).replace(RX_ARRAY_NOTATION, '.$1') const steps = path.split('.').filter(identity) // Handle case where someone passes a string of only dots if (steps.length === 0) { return defaultValue } // Traverse path in object to find result // Switched to `in` operator vs `hasOwnProperty` to handle obj.prototype getters // https://github.com/bootstrap-vue/bootstrap-vue/issues/3463 return steps.every(step => isObject(obj) && step in obj && !isUndefinedOrNull((obj = obj[step]))) ? obj : isNull(obj) ? null : defaultValue } /** * Get property defined by dot/array notation in string. * * @link https://gist.github.com/jeneg/9767afdcca45601ea44930ea03e0febf#gistcomment-1935901 * * @param {Object} obj * @param {string|Array} path * @param {*} defaultValue (optional) * @return {*} */ export const get = (obj, path, defaultValue = null) => { const value = getRaw(obj, path) return isUndefinedOrNull(value) ? defaultValue : value }
'use strict' let Audio = require('../') let t = require('tape') let AudioBuffer = require('audio-buffer') // TODO: test if is online/offline t('audio.offset', t => { let a1 = Audio({rate: 22000}) t.equal(a1.offset(1.2), 22000 * 1.2) let a2 = Audio() t.equal(a2.offset(-1.2), -44100 * 1.2) t.end() }) t('audio.time', t => { let a1 = Audio({rate: 22000}) t.equal(a1.time(22000), 1) let a2 = Audio() t.equal(a2.time(-1.2), -1.2 / 44100) t.end() }) t.skip('Audio.isAudio', t => { // let a1 = Audio(1000) // t.ok(Audio.isAudio(a1)) // t.notOk(Audio.isAudio()) // t.notOk(Audio.isAudio(new AudioBuffer({length: 1024}))) // t.end() }) t('Audio.equal', t => { let a1 = Audio({length: 1000}) let a2 = Audio({length: 1000}) let a3 = Audio({length: 1001}) let a4 = Audio({length: 1000}).write(1) let a5 = Audio.from(Audio({length: 500}).write(1), Audio({length: 500}).write(1)) t.ok(Audio.equal(a1, a2)) t.notOk(Audio.equal(a2, a3)) t.notOk(Audio.equal(a2, a4)) t.ok(Audio.equal(a4, a5)) t.ok(Audio.equal(a1, Audio({length: 1000}), a2)) t.notOk(Audio.equal(a1, Audio({length: 1000}), a3)) t.end() }) t.skip('audio.serialize', t => { }) t.skip('toArray default', t => { let a = Audio(.5) let arr = a.toArray() t.ok(Array.isArray(arr)) t.equal(arr.length, 22050) t.equal(arr[0], 0) t.end() }) t.skip('toArray uint8 interleaved', t => { let a = Audio(.5, 2) let arr = a.toArray('uint8 interleaved') t.ok(ArrayBuffer.isView(arr)) t.equal(arr.length, 22050*2) t.equal(arr[0], 127) t.end() })
import expect from 'expect'; import dataAdapter from '../src/data-adapter.js'; describe('data-adapter', function() { it('should create an array of objects when passing an array of relative paths', function() { expect( dataAdapter( [ 'http://some.domain.com/image1.jpg', { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' } ], 'myfolder' ) ).toEqual([{ host: 'some.domain.com', path: '/image1.jpg', fileName: `${process.cwd()}/myfolder/image1.jpg` }, { host: 'someother.domain.com', path: '/image2.jpg', fileName: `${process.cwd()}/myfolder/image2_renamed.jpg` }]); }); it('should create an array of objects when passing an array of absolute paths', function() { expect( dataAdapter( [ 'http://some.domain.com/image1.jpg', { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' } ], '/myfolder' ) ).toEqual([{ host: 'some.domain.com', path: '/image1.jpg', fileName: '/myfolder/image1.jpg' }, { host: 'someother.domain.com', path: '/image2.jpg', fileName: '/myfolder/image2_renamed.jpg' }]); }); it('should create an array of objects without providing the savePath parameter', function() { expect( dataAdapter( [ 'http://some.domain.com/image1.jpg', { url: 'http://someother.domain.com/image2.jpg', name: 'image2_renamed.jpg' } ] ) ).toEqual([{ host: 'some.domain.com', path: '/image1.jpg', fileName: `${process.cwd()}/image1.jpg` }, { host: 'someother.domain.com', path: '/image2.jpg', fileName: `${process.cwd()}/image2_renamed.jpg` }]); }); it('should use original image name if name property is unset or empty', function() { expect( dataAdapter( [ { url: 'http://some.domain.com/image1.jpg', name: '' }, { url: 'http://someother.domain.com/image2.jpg' } ], 'myfolder' ) ).toEqual([{ host: 'some.domain.com', path: '/image1.jpg', fileName: `${process.cwd()}/myfolder/image1.jpg` }, { host: 'someother.domain.com', path: '/image2.jpg', fileName: `${process.cwd()}/myfolder/image2.jpg` }]); }); it('should create an array without duplicates', function() { expect( dataAdapter( [ 'http://some.domain.com/image1.jpg', 'http://some.domain.com/image1.jpg', 'http://some.domain.com/image1.jpg', 'http://some.domain.com/image2.jpg' ], 'myfolder' ) ).toEqual([ { host: 'some.domain.com', path: '/image1.jpg', fileName: `${process.cwd()}/myfolder/image1.jpg` }, { host: 'some.domain.com', path: '/image2.jpg', fileName: `${process.cwd()}/myfolder/image2.jpg` } ]); }); });
'use strict'; var bootstrap = require('./bootstrap'); bootstrap.app.env = process.env; bootstrap.app.rootPath = process.env.PWD; bootstrap.app.config = require('./config.json'); bootstrap.start();
const CaseClass = require('../utility.js').CaseClass; class NumberExpression extends CaseClass { constructor(number) { super('NumberExpression'); this.number = number; } doCase(fn) { return fn(this.number); } } class IdExpression extends CaseClass { constructor(id) { super('IdExpression'); this.id = id; } doCase(fn) { return fn(this.id); } } class StringExpression extends CaseClass { constructor(string) { super('StringExpression'); this.string = string; } doCase(fn) { return fn(this.string); } } class ArrayExpression extends CaseClass { constructor(expressions) { super('ArrayExpression'); this.expressions = expressions; } doCase(fn) { return fn(this.expressions); } } class ObjectExpression extends CaseClass { constructor(bindings) { super('ObjectExpression'); this.bindings = bindings; } doCase(fn) { return fn(this.bindings); } } class ObjectBinding extends CaseClass { constructor(leftExpr, rightExpr) { super('ObjectBinding'); this.member = leftExpr; this.value = rightExpr; } doCase(fn) { return fn(this.member, this.value); } } class IdBinding extends CaseClass { constructor(idExpr) { super('IdBinding'); this.member = idExpr; } doCase(fn) { return fn(this.member); } } class MemberRenaming extends CaseClass { constructor(member, name) { super('MemberRenaming'); this.member = member; this.name = name; } doCase(fn) { return fn(this.member, this.name); } } class SingleMember extends CaseClass { constructor(member) { super('SingleMember'); this.member = member; } doCase(fn) { return fn(this.member); } } class ObjectDestructure extends CaseClass { constructor(members) { super('ObjectDestructure'); this.members = members; } doCase(fn) { return fn(this.members); } } class ArrayDestructure extends CaseClass { constructor(members) { super('ArrayDestructure'); this.members = members; } doCase(fn) { return fn(this.members); } } class ArrowList extends CaseClass { constructor(parameters) { super('ArrowList'); this.parameters = parameters; } doCase(fn) { return fn(this.parameters); } } class ArrowExpression extends CaseClass { constructor(signature, body) { super('ArrowExpression'); this.signature = signature; this.body = body; } doCase(fn) { return fn(this.signature, this.body); } } class DoBindingStatement extends CaseClass { constructor(idExpr, doExpr) { super('DoBindingStatement'); this.id = idExpr; this.expr = doExpr; } doCase(fn) { return fn(this.id, this.expr); } } class VarBindingExpression extends CaseClass { constructor(lValue, doExpr) { super('VarBindingExpression'); this.lValue = lValue; this.expr = doExpr; } doCase(fn) { return fn(this.lValue, this.expr); } } class DoBlock extends CaseClass { constructor(monad, statements, isAst = false) { super('DoBlock'); this.monad = monad; this.statements = statements; this.isAst = isAst; } doCase(fn) { return fn(this.monad, this.statements, this.isAst); } } class AstExpr extends CaseClass { constructor(lang, expr) { super('AstExpr'); this.lang = lang; this.expr = expr; } doCase(fn) { return fn(this.lang, this.expr); } } function AstBlock(inner) { return inner.case({ DoBlock: (m, s, a) => new DoBlock(m, s, true), AstExpr: _ => inner, }); } class BinaryOperatorExpression extends CaseClass { constructor(op, left, right) { super('BinaryOperatorExpression'); this.op = op; this.left = left; this.right = right; } doCase(fn) { return fn(this.op, this.left, this.right); } } class UnaryOperatorExpression extends CaseClass { constructor(op, expr) { super('UnaryOperatorExpression'); this.op = op; this.expr = expr; } doCase(fn) { return fn(this.op, this.expr); } } class BooleanExpression extends CaseClass { constructor(bool) { super('BooleanExpression'); this.bool = bool; } doCase(fn) { return fn(this.bool); } } class IfElseBlock extends CaseClass { constructor(cond, tBranch, fBranch) { super('IfElseBlock'); this.cond = cond; this.tBranch = tBranch; this.fBranch = fBranch; } doCase(fn) { return fn(this.cond, this.tBranch, this.fBranch); } } module.exports = { BooleanExpression: bool => new BooleanExpression(bool), NumberExpression: num => new NumberExpression(num), IdExpression: id => new IdExpression(id), StringExpression: str => new StringExpression(str), ArrayExpression: exprs => new ArrayExpression(exprs), ObjectExpression: bindings => new ObjectExpression(bindings), ObjectBinding: left => right => new ObjectBinding(left, right), IdBinding: id => new IdBinding(id), SingleMember: id => new SingleMember(id), MemberRenaming: left => right => new MemberRenaming(left, right), ObjectDestructure: renamings => new ObjectDestructure(renamings), ArrayDestructure: ids => new ArrayDestructure(ids), ArrowList: params => new ArrowList(params), ArrowExpression: sig => body => new ArrowExpression(sig, body), DoBlock: monad => statements => new DoBlock(monad, statements), VarBindingExpression: lvalue => expr => new VarBindingExpression(lvalue, expr), DoBindingStatement: id => expr => new DoBindingStatement(id, expr), BinaryOperatorExpression: o => l => r => new BinaryOperatorExpression(o, l, r), UnaryOperatorExpression: o => e => new UnaryOperatorExpression(o, e), IfElseBlock: c => t => f => new IfElseBlock(c, t, f), AstExpr: i => e => new AstExpr(i, e), AstBlock };
/*global module:false*/ module.exports = function (config) { 'use strict'; config.set({ autoWatch: false, basePath: '../', frameworks: ['jasmine'], jasmineNodeOpts: { defaultTimeoutInterval: 30000, isVerbose: true, showColors: true, includeStackTrace: true }, browserNoActivityTimeout: 30000, files: [ // bower:js 'bower_components/angular/angular.js', 'bower_components/angular-route/angular-route.js', 'bower_components/jquery/dist/jquery.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/es5-shim/es5-shim.js', // endbower 'app/js/app.js', 'app/js/**/*.js', 'app/views/*.html', 'test/unit/**/*.js', {pattern: 'src/images/*', watched: false, included: false, served: true} ], exclude: [], port: 9001, browsers: [ 'PhantomJS' ], plugins: [ 'karma-phantomjs-launcher', 'karma-jasmine', 'karma-coverage', 'karma-junit-reporter', 'karma-ng-html2js-preprocessor' ], singleRun: false, colors: true, logLevel: config.LOG_INFO, proxies: { '/_karma_/images/': '/base/src/images/' }, urlRoot: '_karma_', reporters: ['progress', 'coverage', 'junit'], preprocessors: { 'app/js/{,*/}*.js': ['coverage'], 'app/views/*.html': ['ng-html2js'] }, coverageReporter: { dir: 'test-results', reporters: [ {type: 'cobertura', subdir: '.'}, {type: 'html', subdir: 'html'} ] }, junitReporter: { outputDir: 'test-results', outputFile: 'unit-test-results.xml', suite: '' }, ngHtml2JsPreprocessor: { cacheIdFromPath: function (filepath) { return filepath.replace('app', '..'); }, moduleName: 'templates' } }); };
import dateUtils from 'date-utils'; import fs from 'fs'; export function initialize(callback){ fs.readFile(`${__dirname}/config.json`, { encoding: 'utf8' }, (err, config) => { callback(JSON.parse(config)); }); } export function sendWeather(client, fromNumber, toNumber, location) { const date = (new Date()).toFormat('DDD MMM D'); client.messages.create({ from: fromNumber, to: toNumber, body: `Weather forecast for ${location.name} on ${date}.`, mediaUrl: buildURL(location), }, (err, message) => { if (err){ console.error('Got error sending weather:', err); } else { console.log('Sent weather:', message.sid) } }); } function buildURL({lat, long, zcode}) { return `http://forecast.weather.gov/meteograms/Plotter.php?` + `lat=${lat}&lon=${long}&wfo=MTR&zcode=${zcode}&gset=18&gdiff=3&unit=0&tinfo=PY8&ahour=0&` + `pcmd=11011111111000100000000000000000000000000000000000000000000&lg=en&indu=1!1!1!&` + `dd=&bw=&hrspan=30&pqpfhr=6&psnwhr=6`; }
import { Mongo } from 'meteor/mongo'; import SimpleSchema from 'simpl-schema'; import { SchemaHelpers } from '../schema_helpers.js'; /** * Status Metrics - track the health of the system */ export const SystemHealthMetric = new SimpleSchema({ key : { type: String }, title : { type: String }, type : { type : String, optional: true }, isHealthy : { type : Boolean, defaultValue: false }, detail : { type : Object, blackbox: true, optional: true }, // Auto track last updated lastUpdated: { type : Date, autoValue: SchemaHelpers.autoValueDateModified } }); export const SystemHealthMetrics = new Mongo.Collection('system_health_metrics'); SystemHealthMetrics.attachSchema(SystemHealthMetric); // These are server side only SystemHealthMetrics.deny({ remove () { return true; }, insert () { return true; }, update () { return true; } }); SystemHealthMetrics.helpers({});
/* @flow */ 'use strict' import { Map, List, fromJS } from 'immutable' import { SET_FILTER_COMPONENT_OPEN_STATUS, SET_FILTER_COMPONENT_MENU_STATE, RESET_FILTER_COMPONENT_STATE, CLOSE_FILTER_COMPONENT, OVERLAY_CLOSED, SET_FILTER, FILTER_SEARCH_RESULT, RESET_FILTERS, } from '../actions' import { NAME_TYPE, EMAIL_TYPE, DESCRIPTION_TYPE, OPENING_TIMESTAMP_TYPE, CLOSING_TIMESTAMP_TYPE, EMPLOYEE_TYPE, OPEN_STATUS_TYPE, LOCATION_TYPE, } from '../actions/types' export const initialState = Map({ open: false, selectedFilterMenu: 'root', filterSearchQuery: '', filterSearchQueryResults: List.of(), timestamp: Map({ from: 0, to: 0, }), }) export default function(state: Map = initialState, action) { switch (action.type) { case SET_FILTER_COMPONENT_OPEN_STATUS: return state.set('open', action.payload) case SET_FILTER_COMPONENT_MENU_STATE: return state.set('selectedFilterMenu', action.payload) case RESET_FILTERS: case CLOSE_FILTER_COMPONENT: case OVERLAY_CLOSED: return initialState case RESET_FILTER_COMPONENT_STATE: return initialState.set('open', true) case SET_FILTER: switch (action.payload.type) { case OPENING_TIMESTAMP_TYPE: case CLOSING_TIMESTAMP_TYPE: return state.setIn(['timestamp', action.payload.timestampType], action.payload.value) default: return state } case FILTER_SEARCH_RESULT: switch (action.payload.type) { case NAME_TYPE: case EMAIL_TYPE: case EMPLOYEE_TYPE: case LOCATION_TYPE: return state.set('filterSearchQuery', action.payload.term) .set('filterSearchQueryResults', fromJS(action.payload.results)) default: return state } default: return state } }
Accounts.onCreateUser((options, user) => { const superuser = options.superuser || false; const simulationId = options.simulationId || null; user.superuser = superuser; user.simulationId = simulationId; if (options.profile) { user.profile = options.profile; } return user; }); Meteor.startup(() => { if(Meteor.users.find().count() === 0) { const superuser = Meteor.settings.superuser; Accounts.createUser({ username: superuser.login, password: superuser.password, superuser: true, }); } });
version https://git-lfs.github.com/spec/v1 oid sha256:dab1f8d6f5e3da06dbdc309a5ffc69906304948b18b9149abb4801126191a00d size 3360
version https://git-lfs.github.com/spec/v1 oid sha256:a91d45feedec9e236857f4f5cb0a4806f9621f7610d33b0301f5d591fb3465b7 size 5151
Page({ data: { }, onLoad() { console.log(666) }, pay() { wx.scanCode({ success: (res) => { console.log(res) } }) } })
'use strict'; var assert = require('assert'); var lz = require('./'); describe('leading-zero', function(){ it('should return the number with the correct number of leading zeros', function(){ assert.equal(lz(48, 5), '0000048'); assert.equal(lz(-48897,1), '-048897'); }); });
/* * jQuery FlexSlider v2.2.0 * Copyright 2012 WooThemes * Contributing Author: Tyler Smith */ (function (e) { e.flexslider = function (t, n) { var r = e(t); r.vars = e.extend({}, e.flexslider.defaults, n); var i = r.vars.namespace, s = window.navigator && window.navigator.msPointerEnabled && window.MSGesture, o = ("ontouchstart" in window || s || window.DocumentTouch && document instanceof DocumentTouch) && r.vars.touch, u = "click touchend MSPointerUp", a = "", f, l = r.vars.direction === "vertical", c = r.vars.reverse, h = r.vars.itemWidth > 0, p = r.vars.animation === "fade", d = r.vars.asNavFor !== "", v = {}, m = !0; e.data(t, "flexslider", r); v = { init: function () { r.animating = !1; r.currentSlide = parseInt(r.vars.startAt ? r.vars.startAt : 0); isNaN(r.currentSlide) && (r.currentSlide = 0); r.animatingTo = r.currentSlide; r.atEnd = r.currentSlide === 0 || r.currentSlide === r.last; r.containerSelector = r.vars.selector.substr(0, r.vars.selector.search(" ")); r.slides = e(r.vars.selector, r); r.container = e(r.containerSelector, r); r.count = r.slides.length; r.syncExists = e(r.vars.sync).length > 0; r.vars.animation === "slide" && (r.vars.animation = "swing"); r.prop = l ? "top" : "marginLeft"; r.args = {}; r.manualPause = !1; r.stopped = !1; r.started = !1; r.startTimeout = null; r.transitions = !r.vars.video && !p && r.vars.useCSS && function () { var e = document.createElement("div"), t = ["perspectiveProperty", "WebkitPerspective", "MozPerspective", "OPerspective", "msPerspective"]; for (var n in t) if (e.style[t[n]] !== undefined) { r.pfx = t[n].replace("Perspective", "").toLowerCase(); r.prop = "-" + r.pfx + "-transform"; return !0 } return !1 }(); r.vars.controlsContainer !== "" && (r.controlsContainer = e(r.vars.controlsContainer).length > 0 && e(r.vars.controlsContainer)); r.vars.manualControls !== "" && (r.manualControls = e(r.vars.manualControls).length > 0 && e(r.vars.manualControls)); if (r.vars.randomize) { r.slides.sort(function () { return Math.round(Math.random()) - .5 }); r.container.empty().append(r.slides) } r.doMath(); r.setup("init"); r.vars.controlNav && v.controlNav.setup(); r.vars.directionNav && v.directionNav.setup(); r.vars.keyboard && (e(r.containerSelector).length === 1 || r.vars.multipleKeyboard) && e(document).bind("keyup", function (e) { var t = e.keyCode; if (!r.animating && (t === 39 || t === 37)) { var n = t === 39 ? r.getTarget("next") : t === 37 ? r.getTarget("prev") : !1; r.flexAnimate(n, r.vars.pauseOnAction) } }); r.vars.mousewheel && r.bind("mousewheel", function (e, t, n, i) { e.preventDefault(); var s = t < 0 ? r.getTarget("next") : r.getTarget("prev"); r.flexAnimate(s, r.vars.pauseOnAction) }); r.vars.pausePlay && v.pausePlay.setup(); r.vars.slideshow && r.vars.pauseInvisible && v.pauseInvisible.init(); if (r.vars.slideshow) { r.vars.pauseOnHover && r.hover(function () { !r.manualPlay && !r.manualPause && r.pause() }, function () { !r.manualPause && !r.manualPlay && !r.stopped && r.play() }); if (!r.vars.pauseInvisible || !v.pauseInvisible.isHidden()) r.vars.initDelay > 0 ? r.startTimeout = setTimeout(r.play, r.vars.initDelay) : r.play() } d && v.asNav.setup(); o && r.vars.touch && v.touch(); (!p || p && r.vars.smoothHeight) && e(window).bind("resize orientationchange focus", v.resize); r.find("img").attr("draggable", "false"); setTimeout(function () { r.vars.start(r) }, 200) }, asNav: { setup: function () { r.asNav = !0; r.animatingTo = Math.floor(r.currentSlide / r.move); r.currentItem = r.currentSlide; r.slides.removeClass(i + "active-slide").eq(r.currentItem).addClass(i + "active-slide"); if (!s) r.slides.click(function (t) { t.preventDefault(); var n = e(this), s = n.index(), o = n.offset().left - e(r).scrollLeft(); if (o <= 0 && n.hasClass(i + "active-slide")) r.flexAnimate(r.getTarget("prev"), !0); else if (!e(r.vars.asNavFor).data("flexslider").animating && !n.hasClass(i + "active-slide")) { r.direction = r.currentItem < s ? "next" : "prev"; r.flexAnimate(s, r.vars.pauseOnAction, !1, !0, !0) } }); else { t._slider = r; r.slides.each(function () { var t = this; t._gesture = new MSGesture; t._gesture.target = t; t.addEventListener("MSPointerDown", function (e) { e.preventDefault(); e.currentTarget._gesture && e.currentTarget._gesture.addPointer(e.pointerId) }, !1); t.addEventListener("MSGestureTap", function (t) { t.preventDefault(); var n = e(this), i = n.index(); if (!e(r.vars.asNavFor).data("flexslider").animating && !n.hasClass("active")) { r.direction = r.currentItem < i ? "next" : "prev"; r.flexAnimate(i, r.vars.pauseOnAction, !1, !0, !0) } }) }) } } }, controlNav: { setup: function () { r.manualControls ? v.controlNav.setupManual() : v.controlNav.setupPaging() }, setupPaging: function () { var t = r.vars.controlNav === "thumbnails" ? "control-thumbs" : "control-paging", n = 1, s, o; r.controlNavScaffold = e('<ol class="' + i + "control-nav " + i + t + '"></ol>'); if (r.pagingCount > 1) for (var f = 0; f < r.pagingCount; f++) { o = r.slides.eq(f); s = r.vars.controlNav === "thumbnails" ? '<img src="' + o.attr("data-thumb") + '"/>' : "<a>" + n + "</a>"; if ("thumbnails" === r.vars.controlNav && !0 === r.vars.thumbCaptions) { var l = o.attr("data-thumbcaption"); "" != l && undefined != l && (s += '<span class="' + i + 'caption">' + l + "</span>") } r.controlNavScaffold.append("<li>" + s + "</li>"); n++ } r.controlsContainer ? e(r.controlsContainer).append(r.controlNavScaffold) : r.append(r.controlNavScaffold); v.controlNav.set(); v.controlNav.active(); r.controlNavScaffold.delegate("a, img", u, function (t) { t.preventDefault(); if (a === "" || a === t.type) { var n = e(this), s = r.controlNav.index(n); if (!n.hasClass(i + "active")) { r.direction = s > r.currentSlide ? "next" : "prev"; r.flexAnimate(s, r.vars.pauseOnAction) } } a === "" && (a = t.type); v.setToClearWatchedEvent() }) }, setupManual: function () { r.controlNav = r.manualControls; v.controlNav.active(); r.controlNav.bind(u, function (t) { t.preventDefault(); if (a === "" || a === t.type) { var n = e(this), s = r.controlNav.index(n); if (!n.hasClass(i + "active")) { s > r.currentSlide ? r.direction = "next" : r.direction = "prev"; r.flexAnimate(s, r.vars.pauseOnAction) } } a === "" && (a = t.type); v.setToClearWatchedEvent() }) }, set: function () { var t = r.vars.controlNav === "thumbnails" ? "img" : "a"; r.controlNav = e("." + i + "control-nav li " + t, r.controlsContainer ? r.controlsContainer : r) }, active: function () { r.controlNav.removeClass(i + "active").eq(r.animatingTo).addClass(i + "active") }, update: function (t, n) { r.pagingCount > 1 && t === "add" ? r.controlNavScaffold.append(e("<li><a>" + r.count + "</a></li>")) : r.pagingCount === 1 ? r.controlNavScaffold.find("li").remove() : r.controlNav.eq(n).closest("li").remove(); v.controlNav.set(); r.pagingCount > 1 && r.pagingCount !== r.controlNav.length ? r.update(n, t) : v.controlNav.active() } }, directionNav: { setup: function () { var t = e('<ul class="' + i + 'direction-nav"><li><a class="' + i + 'prev" href="#">' + r.vars.prevText + '</a></li><li><a class="' + i + 'next" href="#">' + r.vars.nextText + "</a></li></ul>"); if (r.controlsContainer) { e(r.controlsContainer).append(t); r.directionNav = e("." + i + "direction-nav li a", r.controlsContainer) } else { r.append(t); r.directionNav = e("." + i + "direction-nav li a", r) } v.directionNav.update(); r.directionNav.bind(u, function (t) { t.preventDefault(); var n; if (a === "" || a === t.type) { n = e(this).hasClass(i + "next") ? r.getTarget("next") : r.getTarget("prev"); r.flexAnimate(n, r.vars.pauseOnAction) } a === "" && (a = t.type); v.setToClearWatchedEvent() }) }, update: function () { var e = i + "disabled"; r.pagingCount === 1 ? r.directionNav.addClass(e).attr("tabindex", "-1") : r.vars.animationLoop ? r.directionNav.removeClass(e).removeAttr("tabindex") : r.animatingTo === 0 ? r.directionNav.removeClass(e).filter("." + i + "prev").addClass(e).attr("tabindex", "-1") : r.animatingTo === r.last ? r.directionNav.removeClass(e).filter("." + i + "next").addClass(e).attr("tabindex", "-1") : r.directionNav.removeClass(e).removeAttr("tabindex") } }, pausePlay: { setup: function () { var t = e('<div class="' + i + 'pauseplay"><a></a></div>'); if (r.controlsContainer) { r.controlsContainer.append(t); r.pausePlay = e("." + i + "pauseplay a", r.controlsContainer) } else { r.append(t); r.pausePlay = e("." + i + "pauseplay a", r) } v.pausePlay.update(r.vars.slideshow ? i + "pause" : i + "play"); r.pausePlay.bind(u, function (t) { t.preventDefault(); if (a === "" || a === t.type) if (e(this).hasClass(i + "pause")) { r.manualPause = !0; r.manualPlay = !1; r.pause() } else { r.manualPause = !1; r.manualPlay = !0; r.play() } a === "" && (a = t.type); v.setToClearWatchedEvent() }) }, update: function (e) { e === "play" ? r.pausePlay.removeClass(i + "pause").addClass(i + "play").html(r.vars.playText) : r.pausePlay.removeClass(i + "play").addClass(i + "pause").html(r.vars.pauseText) } }, touch: function () { var e, n, i, o, u, a, f = !1, d = 0, v = 0, m = 0; if (!s) { t.addEventListener("touchstart", g, !1); function g(s) { if (r.animating) s.preventDefault(); else if (window.navigator.msPointerEnabled || s.touches.length === 1) { r.pause(); o = l ? r.h : r.w; a = Number(new Date); d = s.touches[0].pageX; v = s.touches[0].pageY; i = h && c && r.animatingTo === r.last ? 0 : h && c ? r.limit - (r.itemW + r.vars.itemMargin) * r.move * r.animatingTo : h && r.currentSlide === r.last ? r.limit : h ? (r.itemW + r.vars.itemMargin) * r.move * r.currentSlide : c ? (r.last - r.currentSlide + r.cloneOffset) * o : (r.currentSlide + r.cloneOffset) * o; e = l ? v : d; n = l ? d : v; t.addEventListener("touchmove", y, !1); t.addEventListener("touchend", b, !1) } } function y(t) { d = t.touches[0].pageX; v = t.touches[0].pageY; u = l ? e - v : e - d; f = l ? Math.abs(u) < Math.abs(d - n) : Math.abs(u) < Math.abs(v - n); var s = 500; if (!f || Number(new Date) - a > s) { t.preventDefault(); if (!p && r.transitions) { r.vars.animationLoop || (u /= r.currentSlide === 0 && u < 0 || r.currentSlide === r.last && u > 0 ? Math.abs(u) / o + 2 : 1); r.setProps(i + u, "setTouch") } } } function b(s) { t.removeEventListener("touchmove", y, !1); if (r.animatingTo === r.currentSlide && !f && u !== null) { var l = c ? -u : u, h = l > 0 ? r.getTarget("next") : r.getTarget("prev"); r.canAdvance(h) && (Number(new Date) - a < 550 && Math.abs(l) > 50 || Math.abs(l) > o / 2) ? r.flexAnimate(h, r.vars.pauseOnAction) : p || r.flexAnimate(r.currentSlide, r.vars.pauseOnAction, !0) } t.removeEventListener("touchend", b, !1); e = null; n = null; u = null; i = null } } else { t.style.msTouchAction = "none"; t._gesture = new MSGesture; t._gesture.target = t; t.addEventListener("MSPointerDown", w, !1); t._slider = r; t.addEventListener("MSGestureChange", E, !1); t.addEventListener("MSGestureEnd", S, !1); function w(e) { e.stopPropagation(); if (r.animating) e.preventDefault(); else { r.pause(); t._gesture.addPointer(e.pointerId); m = 0; o = l ? r.h : r.w; a = Number(new Date); i = h && c && r.animatingTo === r.last ? 0 : h && c ? r.limit - (r.itemW + r.vars.itemMargin) * r.move * r.animatingTo : h && r.currentSlide === r.last ? r.limit : h ? (r.itemW + r.vars.itemMargin) * r.move * r.currentSlide : c ? (r.last - r.currentSlide + r.cloneOffset) * o : (r.currentSlide + r.cloneOffset) * o } } function E(e) { e.stopPropagation(); var n = e.target._slider; if (!n) return; var r = -e.translationX, s = -e.translationY; m += l ? s : r; u = m; f = l ? Math.abs(m) < Math.abs(-r) : Math.abs(m) < Math.abs(-s); if (e.detail === e.MSGESTURE_FLAG_INERTIA) { setImmediate(function () { t._gesture.stop() }); return } if (!f || Number(new Date) - a > 500) { e.preventDefault(); if (!p && n.transitions) { n.vars.animationLoop || (u = m / (n.currentSlide === 0 && m < 0 || n.currentSlide === n.last && m > 0 ? Math.abs(m) / o + 2 : 1)); n.setProps(i + u, "setTouch") } } } function S(t) { t.stopPropagation(); var r = t.target._slider; if (!r) return; if (r.animatingTo === r.currentSlide && !f && u !== null) { var s = c ? -u : u, l = s > 0 ? r.getTarget("next") : r.getTarget("prev"); r.canAdvance(l) && (Number(new Date) - a < 550 && Math.abs(s) > 50 || Math.abs(s) > o / 2) ? r.flexAnimate(l, r.vars.pauseOnAction) : p || r.flexAnimate(r.currentSlide, r.vars.pauseOnAction, !0) } e = null; n = null; u = null; i = null; m = 0 } } }, resize: function () { if (!r.animating && r.is(":visible")) { h || r.doMath(); if (p) v.smoothHeight(); else if (h) { r.slides.width(r.computedW); r.update(r.pagingCount); r.setProps() } else if (l) { r.viewport.height(r.h); r.setProps(r.h, "setTotal") } else { r.vars.smoothHeight && v.smoothHeight(); r.newSlides.width(r.computedW); r.setProps(r.computedW, "setTotal") } } }, smoothHeight: function (e) { if (!l || p) { var t = p ? r : r.viewport; e ? t.animate({ height: r.slides.eq(r.animatingTo).height() }, e) : t.height(r.slides.eq(r.animatingTo).height()) } }, sync: function (t) { var n = e(r.vars.sync).data("flexslider"), i = r.animatingTo; switch (t) { case "animate": n.flexAnimate(i, r.vars.pauseOnAction, !1, !0); break; case "play": !n.playing && !n.asNav && n.play(); break; case "pause": n.pause() } }, pauseInvisible: { visProp: null, init: function () { var e = ["webkit", "moz", "ms", "o"]; if ("hidden" in document) return "hidden"; for (var t = 0; t < e.length; t++) e[t] + "Hidden" in document && (v.pauseInvisible.visProp = e[t] + "Hidden"); if (v.pauseInvisible.visProp) { var n = v.pauseInvisible.visProp.replace(/[H|h]idden/, "") + "visibilitychange"; document.addEventListener(n, function () { v.pauseInvisible.isHidden() ? r.startTimeout ? clearTimeout(r.startTimeout) : r.pause() : r.started ? r.play() : r.vars.initDelay > 0 ? setTimeout(r.play, r.vars.initDelay) : r.play() }) } }, isHidden: function () { return document[v.pauseInvisible.visProp] || !1 } }, setToClearWatchedEvent: function () { clearTimeout(f); f = setTimeout(function () { a = "" }, 3e3) } }; r.flexAnimate = function (t, n, s, u, a) { !r.vars.animationLoop && t !== r.currentSlide && (r.direction = t > r.currentSlide ? "next" : "prev"); d && r.pagingCount === 1 && (r.direction = r.currentItem < t ? "next" : "prev"); if (!r.animating && (r.canAdvance(t, a) || s) && r.is(":visible")) { if (d && u) { var f = e(r.vars.asNavFor).data("flexslider"); r.atEnd = t === 0 || t === r.count - 1; f.flexAnimate(t, !0, !1, !0, a); r.direction = r.currentItem < t ? "next" : "prev"; f.direction = r.direction; if (Math.ceil((t + 1) / r.visible) - 1 === r.currentSlide || t === 0) { r.currentItem = t; r.slides.removeClass(i + "active-slide").eq(t).addClass(i + "active-slide"); return !1 } r.currentItem = t; r.slides.removeClass(i + "active-slide").eq(t).addClass(i + "active-slide"); t = Math.floor(t / r.visible) } r.animating = !0; r.animatingTo = t; n && r.pause(); r.vars.before(r); r.syncExists && !a && v.sync("animate"); r.vars.controlNav && v.controlNav.active(); h || r.slides.removeClass(i + "active-slide").eq(t).addClass(i + "active-slide"); r.atEnd = t === 0 || t === r.last; r.vars.directionNav && v.directionNav.update(); if (t === r.last) { r.vars.end(r); r.vars.animationLoop || r.pause() } if (!p) { var m = l ? r.slides.filter(":first").height() : r.computedW, g, y, b; if (h) { g = r.vars.itemMargin; b = (r.itemW + g) * r.move * r.animatingTo; y = b > r.limit && r.visible !== 1 ? r.limit : b } else r.currentSlide === 0 && t === r.count - 1 && r.vars.animationLoop && r.direction !== "next" ? y = c ? (r.count + r.cloneOffset) * m : 0 : r.currentSlide === r.last && t === 0 && r.vars.animationLoop && r.direction !== "prev" ? y = c ? 0 : (r.count + 1) * m : y = c ? (r.count - 1 - t + r.cloneOffset) * m : (t + r.cloneOffset) * m; r.setProps(y, "", r.vars.animationSpeed); if (r.transitions) { if (!r.vars.animationLoop || !r.atEnd) { r.animating = !1; r.currentSlide = r.animatingTo } r.container.unbind("webkitTransitionEnd transitionend"); r.container.bind("webkitTransitionEnd transitionend", function () { r.wrapup(m) }) } else r.container.animate(r.args, r.vars.animationSpeed, r.vars.easing, function () { r.wrapup(m) }) } else if (!o) { r.slides.eq(r.currentSlide).css({ zIndex: 1 }).animate({ opacity: 0 }, r.vars.animationSpeed, r.vars.easing); r.slides.eq(t).css({ zIndex: 2 }).animate({ opacity: 1 }, r.vars.animationSpeed, r.vars.easing, r.wrapup) } else { r.slides.eq(r.currentSlide).css({ opacity: 0, zIndex: 1 }); r.slides.eq(t).css({ opacity: 1, zIndex: 2 }); r.wrapup(m) } r.vars.smoothHeight && v.smoothHeight(r.vars.animationSpeed) } }; r.wrapup = function (e) { !p && !h && (r.currentSlide === 0 && r.animatingTo === r.last && r.vars.animationLoop ? r.setProps(e, "jumpEnd") : r.currentSlide === r.last && r.animatingTo === 0 && r.vars.animationLoop && r.setProps(e, "jumpStart")); r.animating = !1; r.currentSlide = r.animatingTo; r.vars.after(r) }; r.animateSlides = function () { !r.animating && m && r.flexAnimate(r.getTarget("next")) }; r.pause = function () { clearInterval(r.animatedSlides); r.animatedSlides = null; r.playing = !1; r.vars.pausePlay && v.pausePlay.update("play"); r.syncExists && v.sync("pause") }; r.play = function () { r.playing && clearInterval(r.animatedSlides); r.animatedSlides = r.animatedSlides || setInterval(r.animateSlides, r.vars.slideshowSpeed); r.started = r.playing = !0; r.vars.pausePlay && v.pausePlay.update("pause"); r.syncExists && v.sync("play") }; r.stop = function () { r.pause(); r.stopped = !0 }; r.canAdvance = function (e, t) { var n = d ? r.pagingCount - 1 : r.last; return t ? !0 : d && r.currentItem === r.count - 1 && e === 0 && r.direction === "prev" ? !0 : d && r.currentItem === 0 && e === r.pagingCount - 1 && r.direction !== "next" ? !1 : e === r.currentSlide && !d ? !1 : r.vars.animationLoop ? !0 : r.atEnd && r.currentSlide === 0 && e === n && r.direction !== "next" ? !1 : r.atEnd && r.currentSlide === n && e === 0 && r.direction === "next" ? !1 : !0 }; r.getTarget = function (e) { r.direction = e; return e === "next" ? r.currentSlide === r.last ? 0 : r.currentSlide + 1 : r.currentSlide === 0 ? r.last : r.currentSlide - 1 }; r.setProps = function (e, t, n) { var i = function () { var n = e ? e : (r.itemW + r.vars.itemMargin) * r.move * r.animatingTo, i = function () { if (h) return t === "setTouch" ? e : c && r.animatingTo === r.last ? 0 : c ? r.limit - (r.itemW + r.vars.itemMargin) * r.move * r.animatingTo : r.animatingTo === r.last ? r.limit : n; switch (t) { case "setTotal": return c ? (r.count - 1 - r.currentSlide + r.cloneOffset) * e : (r.currentSlide + r.cloneOffset) * e; case "setTouch": return c ? e : e; case "jumpEnd": return c ? e : r.count * e; case "jumpStart": return c ? r.count * e : e; default: return e } }(); return i * -1 + "px" }(); if (r.transitions) { i = l ? "translate3d(0," + i + ",0)" : "translate3d(" + i + ",0,0)"; n = n !== undefined ? n / 1e3 + "s" : "0s"; r.container.css("-" + r.pfx + "-transition-duration", n) } r.args[r.prop] = i; (r.transitions || n === undefined) && r.container.css(r.args) }; r.setup = function (t) { if (!p) { var n, s; if (t === "init") { r.viewport = e('<div class="' + i + 'viewport"></div>').css({ overflow: "hidden", position: "relative" }).appendTo(r).append(r.container); r.cloneCount = 0; r.cloneOffset = 0; if (c) { s = e.makeArray(r.slides).reverse(); r.slides = e(s); r.container.empty().append(r.slides) } } if (r.vars.animationLoop && !h) { r.cloneCount = 2; r.cloneOffset = 1; t !== "init" && r.container.find(".clone").remove(); r.container.append(r.slides.first().clone().addClass("clone").attr("aria-hidden", "true")).prepend(r.slides.last().clone().addClass("clone").attr("aria-hidden", "true")) } r.newSlides = e(r.vars.selector, r); n = c ? r.count - 1 - r.currentSlide + r.cloneOffset : r.currentSlide + r.cloneOffset; if (l && !h) { r.container.height((r.count + r.cloneCount) * 200 + "%").css("position", "absolute").width("100%"); setTimeout(function () { r.newSlides.css({ display: "block" }); r.doMath(); r.viewport.height(r.h); r.setProps(n * r.h, "init") }, t === "init" ? 100 : 0) } else { r.container.width((r.count + r.cloneCount) * 200 + "%"); r.setProps(n * r.computedW, "init"); setTimeout(function () { r.doMath(); r.newSlides.css({ width: r.computedW, "float": "left", display: "block" }); r.vars.smoothHeight && v.smoothHeight() }, t === "init" ? 100 : 0) } } else { r.slides.css({ width: "100%", "float": "left", marginRight: "-100%", position: "relative" }); t === "init" && (o ? r.slides.css({ opacity: 0, display: "block", webkitTransition: "opacity " + r.vars.animationSpeed / 1e3 + "s ease", zIndex: 1 }).eq(r.currentSlide).css({ opacity: 1, zIndex: 2 }) : r.slides.css({ opacity: 0, display: "block", zIndex: 1 }).eq(r.currentSlide).css({ zIndex: 2 }).animate({ opacity: 1 }, r.vars.animationSpeed, r.vars.easing)); r.vars.smoothHeight && v.smoothHeight() } h || r.slides.removeClass(i + "active-slide").eq(r.currentSlide).addClass(i + "active-slide") }; r.doMath = function () { var e = r.slides.first(), t = r.vars.itemMargin, n = r.vars.minItems, i = r.vars.maxItems; r.w = r.viewport === undefined ? r.width() : r.viewport.width(); r.h = e.height(); r.boxPadding = e.outerWidth() - e.width(); if (h) { r.itemT = r.vars.itemWidth + t; r.minW = n ? n * r.itemT : r.w; r.maxW = i ? i * r.itemT - t : r.w; r.itemW = r.minW > r.w ? (r.w - t * (n - 1)) / n : r.maxW < r.w ? (r.w - t * (i - 1)) / i : r.vars.itemWidth > r.w ? r.w : r.vars.itemWidth; r.visible = Math.floor(r.w / r.itemW); r.move = r.vars.move > 0 && r.vars.move < r.visible ? r.vars.move : r.visible; r.pagingCount = Math.ceil((r.count - r.visible) / r.move + 1); r.last = r.pagingCount - 1; r.limit = r.pagingCount === 1 ? 0 : r.vars.itemWidth > r.w ? r.itemW * (r.count - 1) + t * (r.count - 1) : (r.itemW + t) * r.count - r.w - t } else { r.itemW = r.w; r.pagingCount = r.count; r.last = r.count - 1 } r.computedW = r.itemW - r.boxPadding }; r.update = function (e, t) { r.doMath(); if (!h) { e < r.currentSlide ? r.currentSlide += 1 : e <= r.currentSlide && e !== 0 && (r.currentSlide -= 1); r.animatingTo = r.currentSlide } if (r.vars.controlNav && !r.manualControls) if (t === "add" && !h || r.pagingCount > r.controlNav.length) v.controlNav.update("add"); else if (t === "remove" && !h || r.pagingCount < r.controlNav.length) { if (h && r.currentSlide > r.last) { r.currentSlide -= 1; r.animatingTo -= 1 } v.controlNav.update("remove", r.last) } r.vars.directionNav && v.directionNav.update() }; r.addSlide = function (t, n) { var i = e(t); r.count += 1; r.last = r.count - 1; l && c ? n !== undefined ? r.slides.eq(r.count - n).after(i) : r.container.prepend(i) : n !== undefined ? r.slides.eq(n).before(i) : r.container.append(i); r.update(n, "add"); r.slides = e(r.vars.selector + ":not(.clone)", r); r.setup(); r.vars.added(r) }; r.removeSlide = function (t) { var n = isNaN(t) ? r.slides.index(e(t)) : t; r.count -= 1; r.last = r.count - 1; isNaN(t) ? e(t, r.slides).remove() : l && c ? r.slides.eq(r.last).remove() : r.slides.eq(t).remove(); r.doMath(); r.update(n, "remove"); r.slides = e(r.vars.selector + ":not(.clone)", r); r.setup(); r.vars.removed(r) }; v.init() }; e(window).blur(function (e) { focused = !1 }).focus(function (e) { focused = !0 }); e.flexslider.defaults = { namespace: "flex-", selector: ".slides > li", animation: "fade", easing: "swing", direction: "horizontal", reverse: !1, animationLoop: !0, smoothHeight: !1, startAt: 0, slideshow: !0, slideshowSpeed: 7e3, animationSpeed: 600, initDelay: 0, randomize: !1, thumbCaptions: !1, pauseOnAction: !0, pauseOnHover: !1, pauseInvisible: !0, useCSS: !0, touch: !0, video: !1, controlNav: !0, directionNav: !0, prevText: "Previous", nextText: "Next", keyboard: !0, multipleKeyboard: !1, mousewheel: !1, pausePlay: !1, pauseText: "Pause", playText: "Play", controlsContainer: "", manualControls: "", sync: "", asNavFor: "", itemWidth: 0, itemMargin: 0, minItems: 1, maxItems: 0, move: 0, allowOneSlide: !0, start: function () {}, before: function () {}, after: function () {}, end: function () {}, added: function () {}, removed: function () {} }; e.fn.flexslider = function (t) { t === undefined && (t = {}); if (typeof t == "object") return this.each(function () { var n = e(this), r = t.selector ? t.selector : ".slides > li", i = n.find(r); if (i.length === 1 && t.allowOneSlide === !0 || i.length === 0) { i.fadeIn(400); t.start && t.start(n) } else n.data("flexslider") === undefined && new e.flexslider(this, t) }); var n = e(this).data("flexslider"); switch (t) { case "play": n.play(); break; case "pause": n.pause(); break; case "stop": n.stop(); break; case "next": n.flexAnimate(n.getTarget("next"), !0); break; case "prev": case "previous": n.flexAnimate(n.getTarget("prev"), !0); break; default: typeof t == "number" && n.flexAnimate(t, !0) } } })(jQuery);
'use strict'; const resultsStorage = require('../lib/support/resultsStorage'); const moment = require('moment'); const path = require('path'); const expect = require('chai').expect; const timestamp = moment(); const timestampString = timestamp.format('YYYY-MM-DD-HH-mm-ss'); function createManager(url, outputFolder) { return resultsStorage(url, timestamp, outputFolder).storageManager; } describe('storageManager', function() { describe('#rootPathFromUrl', function() { it('should create path from url', function() { const storageManager = createManager('http://www.foo.bar'); const path = storageManager.rootPathFromUrl('http://www.foo.bar/x/y/z.html'); expect(path).to.equal('../../../../../'); }); it('should create path from url with query string', function() { const storageManager = createManager('http://www.foo.bar'); const path = storageManager.rootPathFromUrl('http://www.foo.bar/x/y/z?foo=bar'); expect(path).to.equal('../../../../../../'); }); }); describe('#getBaseDir', function() { it('should create base dir with default output folder', function() { const storageManager = createManager('http://www.foo.bar'); expect(storageManager.getBaseDir()).to.equal(path.resolve('sitespeed-result', 'www.foo.bar', timestampString)); }); it('should create base dir with custom output folder', function() { const storageManager = createManager('http://www.foo.bar', '/tmp/sitespeed.io/foo'); expect(storageManager.getBaseDir()).to.equal('/tmp/sitespeed.io/foo'); }); }); describe('#getStoragePrefix', function() { it('should create prefix with default output folder', function() { const storageManager = createManager('http://www.foo.bar'); expect(storageManager.getStoragePrefix()).to.equal(path.join('www.foo.bar', timestampString)); }); it('should create prefix with custom output folder', function() { const storageManager = createManager('http://www.foo.bar', '/tmp/sitespeed.io/foo'); expect(storageManager.getStoragePrefix()).to.equal('foo'); }); }); });
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) const store=new Vuex.Store({ state:{ isLoading:false,//是否登陆 loadingAnimate:false, //是否显示登陆动画 }, getter:{}, mutations:{ updateLoadingState(state,flag){ state.isLoading=flag }, updateLoadingAnimate(state,flag){ state.loadingAnimate=flag } }, actions:{ onLoading(context,flag){ context.commit("updateLoadingState",flag); }, showAnimate(context,flag) { context.commit("updateLoadingAnimate",flag); } }, modules:{} }) export default store
import { moduleForModel, test } from 'ember-qunit'; moduleForModel('message-header', 'Unit | Model | MessageHeader', { needs: [ 'model:meta', 'model:narrative', 'model:resource', 'model:extension', 'model:coding', 'model:message-header-destination', 'model:reference', 'model:message-header-source', 'model:codeable-concept', 'model:message-header-response' ] }); test('it exists', function(assert) { const model = this.subject(); assert.ok(!!model); });
/** * Copyright (c) 2013-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+relay * @format */ 'use strict'; require('configureForRelayOSS'); const RelayClassic_DEPRECATED = require('RelayClassic_DEPRECATED'); const RelayQuery = require('../RelayQuery'); const RelayTestUtils = require('RelayTestUtils'); describe('RelayQueryFragment', () => { const {getNode} = RelayTestUtils; let fragment; beforeEach(() => { jest.resetModules(); expect.extend(RelayTestUtils.matchers); const subfrag = RelayClassic_DEPRECATED.QL` fragment on StreetAddress { city } `; const frag = RelayClassic_DEPRECATED.QL` fragment on StreetAddress { country ${subfrag} } `; fragment = getNode(frag); }); it('does not equal non-fragments', () => { const query = getNode( RelayClassic_DEPRECATED.QL` query { me { firstName } } `, ); const field = query.getChildren()[0]; expect(fragment.equals(query)).toBe(false); expect(fragment.equals(field)).toBe(false); }); it('does not equal different fragment', () => { const fragment2 = getNode( RelayClassic_DEPRECATED.QL` fragment on StreetAddress { country } `, ); expect(fragment.equals(fragment2)).toBe(false); expect(fragment2.equals(fragment)).toBe(false); }); it('does not return a source composite hash for un-cloned fragments', () => { expect(fragment.getSourceCompositeHash()).toBe(null); }); it('does not equal equivalent fragments with a different structure', () => { expect(fragment.equals(fragment)).toBe(true); // invert the fields between outer/inner fragments const subfrag = RelayClassic_DEPRECATED.QL` fragment on StreetAddress { country } `; const fragment2 = getNode( RelayClassic_DEPRECATED.QL` fragment on StreetAddress { city ${subfrag} } `, ); expect(fragment.equals(fragment2)).toBe(false); expect(fragment2.equals(fragment)).toBe(false); }); it('equals fragments with the same structure', () => { expect(fragment.equals(fragment)).toBe(true); const subfrag = RelayClassic_DEPRECATED.QL` fragment on StreetAddress { city } `; const fragment2 = getNode( RelayClassic_DEPRECATED.QL` fragment on StreetAddress { country ${subfrag} } `, ); expect(fragment.equals(fragment2)).toBe(true); expect(fragment2.equals(fragment)).toBe(true); }); it('equals fragments with different names', () => { // NOTE: Two fragments in the same scope will have different names. const fragment1 = getNode( RelayClassic_DEPRECATED.QL`fragment on Node { id }`, ); const fragment2 = getNode( RelayClassic_DEPRECATED.QL`fragment on Node { id }`, ); expect(fragment1.equals(fragment2)).toBe(true); expect(fragment2.equals(fragment1)).toBe(true); }); it('returns metadata', () => { const node = RelayClassic_DEPRECATED.QL` fragment on StreetAddress { country } `; fragment = getNode(node); expect(fragment.getDebugName()).toBe('RelayQueryFragmentRelayQL'); expect(fragment.getType()).toBe('StreetAddress'); }); it('returns children', () => { const children = fragment.getChildren(); expect(children.length).toBe(2); expect(children[0].getSchemaName()).toBe('country'); expect(children[1].getDebugName()).toBe('RelayQueryFragmentRelayQL'); }); it('returns same object when cloning with same children', () => { const children = fragment.getChildren(); expect(fragment.clone(children)).toBe(fragment); expect(fragment.clone(children.map(c => c))).toBe(fragment); }); it('returns the source composite hash for cloned fragments', () => { const query = getNode( RelayClassic_DEPRECATED.QL` fragment on StreetAddress { country city } `, ); const clone = fragment.clone([query.getChildren()[0]]); expect(clone.getSourceCompositeHash()).toBe(fragment.getCompositeHash()); }); it('returns null when cloning without children', () => { expect(fragment.clone([])).toBe(null); expect(fragment.clone([null])).toBe(null); }); it('clones with updated children', () => { const query = getNode( RelayClassic_DEPRECATED.QL` fragment on StreetAddress { country city } `, ); const clone = fragment.clone([query.getChildren()[0]]); expect(clone.getChildren().length).toBe(1); expect(clone.getChildren()[0].getSchemaName()).toBe('country'); expect(clone.getFieldByStorageKey('city')).toBe(undefined); }); it('is not a ref query dependency', () => { expect(fragment.isRefQueryDependency()).toBe(false); }); it('is not generated', () => { expect(fragment.isGenerated()).toBe(false); }); it('creates nodes', () => { const fragmentRQL = RelayClassic_DEPRECATED.QL` fragment on StreetAddress { city } `; fragment = getNode(fragmentRQL); const node = fragment.createNode(fragmentRQL); expect(node instanceof RelayQuery.Fragment).toBe(true); expect(node.getType()).toBe('StreetAddress'); expect(node.getRoute()).toBe(fragment.getRoute()); expect(node.getVariables()).toBe(fragment.getVariables()); }); it('returns directives', () => { fragment = getNode( RelayClassic_DEPRECATED.QL` fragment on Story @include(if: $cond) { feedback } `, {cond: true}, ); expect(fragment.getDirectives()).toEqual([ { args: [{name: 'if', value: true}], name: 'include', }, ]); }); describe('canHaveSubselections()', () => { it('returns true', () => { // fragment with children expect(fragment.canHaveSubselections()).toBe(true); // fragment without children expect( getNode( RelayClassic_DEPRECATED.QL`fragment on Viewer { ${null} }`, ).canHaveSubselections(), ).toBe(true); }); }); describe('variables argument of @relay directive', () => { it('maps listed variables', () => { const query = getNode( RelayClassic_DEPRECATED.QL` fragment on User { ... on User @relay(variables: ["inner"]) { profilePicture(size: $inner) } } `, {inner: 100}, ); const frag = query.getChildren()[1]; expect(frag instanceof RelayQuery.Fragment).toBe(true); expect(frag.getVariables()).toEqual({inner: 100}); }); it('filters non-listed variables', () => { const query = getNode( RelayClassic_DEPRECATED.QL` fragment on User { ... on User @relay(variables: []) { profilePicture(size: $inner) } } `, {inner: 100}, ); const frag = query.getChildren()[1]; expect(frag instanceof RelayQuery.Fragment).toBe(true); expect(frag.getVariables()).toEqual({}); }); }); });
var SOFR = {} || SOFR; SOFR.addFileReader = function() { var fileReaderButton = SO.menu.appendChild( document.createElement( 'div' ) ); fileReaderButton.innerHTML = '<a href=# onclick=SO.toggleDialogs(SOFR.FileReader); ><p class=button >' + '<i class="fa fa-file-image-o"></i> File Reader...' + '</p></a>'; SOFR.FileReader = SO.container.appendChild( document.createElement( 'div' ) ); SOFR.FileReader.style.cssText = 'display: none; background-color: #ccc; opacity: 0.9; padding: 0 20px 20px; ' + 'bottom: 0; height: 100px; left: 0; margin: auto; position: absolute; right: 0; top: 0; width: 450px; '; SOFR.FileReader.innerHTML = '<div>' + '<p>' + '<input type=file id=inpFile ><br>' + '<div id=divData></div>' '</p>' + '<p style=text-align:right; >' + '<a class=button href=JavaScript:SO.toggleDialogs(); >Close</a> ' + '</p>' + '</div>'; inpFile.onchange = function() { SOFR.readFile( this ); }; }; SOFR.readFile = function( that) { SO.toggleDialogs(); SOFR.frame = 0; SOFR.heights = []; var data, lines, length; if ( that.files && that.files[0]){ var reader = new FileReader(); reader.onload = function ( event ) { data = event.target.result; divData.innerHTML = data.substr( 1000, 1000 ); lines = data.split(/\n/); length = lines.length; var sep = ','; for ( var i = 0; i < length; i++ ) { SOFR.heights.push( lines[i].split( sep ) ); } divFrames.innerHTML = 'Frames Read: ' + length; divElevations.innerHTML = 'Elevations/frame: ' + SOFR.heights[ 0 ].length; SOFR.startTime = new Date(); SO.updateFrame(); }; reader.readAsText( that.files[0] ); /* reader.onloadend = function( event ) { arrayBuffer = event.target.result; var elevations = new Float32Array( arrayBuffer ); divData.innerHTML = elevations.length; console.log( elevations ); }; // var blob = file.slice(start, stop + 1); reader.readAsArrayBuffer( that.files[0] ); */ } };
//base test describe("arc object",function(){ it("should not be null",function(){ expect(arc.not.toBeNull(); }); });
import SaveButton from './../../components/layout/Settings/SaveButton'; import {connect} from 'react-redux'; import {aboutClick} from './../..//actions/funcs/settings'; const mapStateToProps = () => { return { title: 'Save Changes to About Me' }; }; const mapDispatchToProps = (dispatch) => { return { onClickFunction: () => dispatch(aboutClick()) }; }; export default connect(mapStateToProps, mapDispatchToProps)(SaveButton);
Date.prototype.addDays=function(d){return new Date(this.valueOf()+864E5*d);}; //snippet from http://stackoverflow.com/questions/563406/add-days-to-datetime function DateDiff(date1, date2) { //snippet from http://stackoverflow.com/questions/7763327/how-to-calculate-date-difference-in-javascript date1.setHours(0); date1.setMinutes(0, 0, 0); date2.setHours(0); date2.setMinutes(0, 0, 0); var datediff = Math.abs(date1.getTime() - date2.getTime()); // difference return parseInt(datediff / (24 * 60 * 60 * 1000), 10); //Convert values days and return value } function calculateConception() { var datum = new Date(document.getElementById("inpdate").value) console.log("Input " + datum); var geburtstermin = datum.addDays(277); document.getElementById("outdate").innerHTML = geburtstermin.getDate() + "." + geburtstermin.getMonth() + "." + geburtstermin.getFullYear(); var heute = new Date(); var schwangerschaftstage = DateDiff(datum,heute); var ssw = Math.ceil(schwangerschaftstage / 7); if (ssw > 45) { ssw = "Fehler"; } document.getElementById("outssw").innerHTML = ssw; };
import React, { Component } from 'react'; import applicationStore from 'focus-core/application/built-in-store'; /** * HeaderContent component. */ class HeaderContent extends Component { /** Display name. */ static displayName = 'HeaderContent'; /** * Constructor. * @param {object} props Props. */ constructor(props) { super(props); this.state = this._getStateFromStore(); this._handleComponentChange = this._handleComponentChange.bind(this); } /** @inheriteddoc */ componentWillMount() { applicationStore.addCartridgeComponentChangeListener(this._handleComponentChange); } /** @inheriteddoc */ componentWillUnmount() { applicationStore.removeCartridgeComponentChangeListener(this._handleComponentChange); } /** * Read the component state from the connected stores. * @return {object} - The new state. */ _getStateFromStore() { return { cartridgeComponent: applicationStore.getCartridgeComponent() || { component: 'div', props: {} } }; } /** * Handle the component change cb. */ _handleComponentChange() { this.setState(this._getStateFromStore()); } /** @inheritdoc */ render() { const { cartridgeComponent: { component: Component, props } } = this.state; return ( <div data-focus='header-content'> <Component {...props} /> </div> ); } } export default HeaderContent;
var sudoBlock = require('sudo-block'); var autostart = require('../lib/actions/autostart') var daemon = require('../lib/actions/daemon') // Checking if hotel is being installed using 'sudo npm' // ~/.hotel should not be created as root sudoBlock( '\n' + ' To complete install, please run:\n' + ' hotel autostart && hotel start\n' ) console.log() autostart.create() console.log() daemon.start() console.log() console.log(' To uninstall: npm rm -g hotel') console.log()
/* jshint -W117, -W030 */ describe('customers', function() { describe('state', function() { var controller; var views = { customers: 'app/customers/customers.html', customerdetail: 'app/customers/customer-detail.html' }; beforeEach(function() { module('app.customers', bard.fakeToastr); bard.inject(this, '$location', '$rootScope', '$state', '$templateCache'); }); beforeEach(function() { $templateCache.put(views.customers, ''); $templateCache.put(views.customerdetail, ''); }); it('should map state customer.list to url /customer/list ', function() { expect($state.href('customer.list', {})).to.equal('/customer/list'); }); it('should map state customer.detail to url /customer/:id ', function() { expect($state.href('customer.detail', {id: 7})).to.equal('/customer/7'); }); it('should map /customers route to customers View template', function() { expect($state.get('customer.list').templateUrl).to.equal(views.customers); }); it('should map /customer.details route to customers View template', function() { expect($state.get('customer.detail').templateUrl).to.equal(views.customerdetail); }); it('of customer.list should work with $state.go', function() { $state.go('customer.list'); $rootScope.$apply(); expect($state.is('customer.list')); }); }); });
'use strict'; /*! * Collection * https://github.com/kobezzza/Collection * * Released under the MIT license * https://github.com/kobezzza/Collection/blob/master/LICENSE */ import { Collection } from '../core'; import { isFunction, isArray, isNumber, iterators } from '../helpers/types'; import { byLink, splice } from '../helpers/link'; import { any } from '../helpers/gcc'; /** * Removes elements from the collection by the specified condition/link * * @see Collection.prototype.forEach * @param {($$CollectionFilter|$$CollectionBase|$$CollectionLink)=} [opt_filter] - link, function filter or an array of functions * @param {?$$CollectionBase=} [opt_params] - additional parameters * @return {($$CollectionReport|!Promise<$$CollectionReport>)} */ Collection.prototype.remove = function (opt_filter, opt_params) { let p = opt_params || {}; if ( !isFunction(opt_filter) && ( isArray(opt_filter) && !isFunction(opt_filter[1]) || opt_filter != null && typeof opt_filter !== 'object' ) ) { return byLink(this.data, opt_filter, {delete: true}); } if (!isArray(opt_filter) && !isFunction(opt_filter)) { p = opt_filter || p; opt_filter = null; } this._initParams(p, opt_filter); p = any(Object.assign(Object.create(this.p), p)); const isRealArray = p.type === 'array' && isArray(this.data); if (iterators[p.type]) { throw new TypeError('Incorrect data type'); } const mult = p.mult !== false, res = []; if (mult) { p.result = res; } else { p.result = { notFound: true, result: false, key: undefined, value: undefined }; } let fn; switch (p.type) { case 'map': fn = (value, key, data) => { data.delete(key); const o = { result: !data.has(key), key, value }; if (mult) { res.push(o); } else { p.result = o; } }; break; case 'set': fn = (value, key, data) => { data.delete(value); const o = { result: !data.has(value), key: null, value }; if (mult) { res.push(o); } else { p.result = o; } }; break; case 'array': if (p.reverse) { fn = (value, key, data) => { if (isRealArray) { data.splice(key, 1); } else { splice.call(data, key, 1); } const o = { result: data[key] !== value, key, value }; if (mult) { res.push(o); } else { p.result = o; } }; } else { let rm = 0; if (p.live) { fn = (value, key, data, ctx) => { if (isRealArray) { data.splice(key, 1); } else { splice.call(data, key, 1); } ctx.i(-1); const o = { result: data[key] !== value, key: key + rm, value }; if (mult) { res.push(o); } else { p.result = o; } rm++; }; } else { fn = (value, key, data, ctx) => { const ln = ctx.length(); const f = (length) => { if (isRealArray) { data.splice(key, 1); } else { splice.call(data, key, 1); } ctx.i(-1); const o = { result: data[key] !== value, key: key + rm, value }; if (mult) { res.push(o); } else { p.result = o; } if (++rm === length) { return ctx.break; } }; if (isNumber(ln)) { f(ln); } else { return ctx.wait(ln).then(f); } }; } } break; default: fn = (value, key, data) => { delete data[key]; const o = { result: key in data === false, key, value }; if (mult) { res.push(o); } else { p.result = o; } }; } const returnVal = any(this.forEach(any(fn), p)); if (returnVal !== this) { return returnVal; } return p.result; };
var port = process.env.PORT || 3000; r_port = 6379, r_host = "localhost", server = require('http').createServer(), io = require('socket.io').listen(server), crypto = require('crypto'), redis = require('redis'); // Avatar config //var avatar_url = "http://cdn.libravatar.org/avatar/"; var avatar_url = "http://www.gravatar.com/avatar/"; var avatar_404 = ['mm', 'identicon', 'monsterid', 'wavatar', 'retro']; var socks = {}, users_key = "jqchat:users", user_key = "jqchat:user:", chat_key = "jqchat:chat:"; function Uid() { this.id = ++Uid.lastid; } Uid.lastid = 0; //Handle users io.sockets.on('connection', function (socket) { // Connection to redis var r = redis.createClient(r_port, r_host); // Event received by new user socket.on('join', function (recv, fn) { if (!recv.user) { socket.emit('custom_error', { message: 'User not found or invalid' }); return; } // Wheter if user is logged r.sismember(users_key, recv.user, function(err, reply) { if (reply) { socket.emit('custom_error', { message: 'The user '+ recv.user +' is already logged' }); return; } }); // If there is users online, send the list of them r.smembers(users_key, function(err, reply) { if (reply.length > 0) { getAllUsers(r, reply, function(users) { socket.emit('chat', JSON.stringify( { 'action': 'usrlist', 'user': users } )); }); } }); // Set new uid uid = new Uid(); socket.user = recv.user; my_avatar = get_avatar_url(socket.user); r.sadd([users_key, socket.user], function(err, reply) {}); // Add the new data user r.hmset(user_key + socket.user, 'uid', Uid.lastid, 'user', socket.user, 'name', recv.name, 'status', 'online', 'avatar', my_avatar); socks[socket.user] = {'socket': socket} // Send new user is connected to everyone r.hgetall(user_key + socket.user, function(err, data) { socket.broadcast.emit('chat', JSON.stringify( {'action': 'newuser', 'user': data} )); if (typeof fn !== 'undefined') fn(JSON.stringify( {'login': 'successful', 'my_settings': data} )); }); }); // Event received when user want change his status socket.on('user_status', function (recv) { r.sismember(users_key, socket.user, function(err, reply) { r.hset(user_key + socket.user, "status", recv.status, function(err, reply) { r.hgetall(user_key + socket.user, function(err, data) { socket.broadcast.emit('chat', JSON.stringify( {'action': 'user_status', 'user': data} )); }); }); }); }); // Event received when user is typing socket.on('user_typing', function (recv) { var id = socks[recv.user].socket.id; r.hgetall(user_key + socket.user, function(err, data) { io.sockets.socket(id).emit('chat', JSON.stringify( {'action': 'user_typing', 'data': data} )); }); }); // Event received when user send message to another socket.on('message', function (recv, fn) { r.hgetall(user_key + socket.user, function(err, data) { var d = new Date(), id = socks[recv.user].socket.id, msg = {'msg': recv.msg, 'user': data}, log = {"msg": recv.msg, "date": d }, key = chat_key + data.user + "_" + recv.user; r.rpush([key , JSON.stringify(log)], function(err, reply) { if (typeof fn !== 'undefined') fn(JSON.stringify( {'ack': 'true', 'date': d} )); io.sockets.socket(id).emit('chat', JSON.stringify( {'action': 'message', 'data': msg, 'date': d} )); }); }); }); // Event received when user has disconnected socket.on('disconnect', function () { r.srem([users_key, socket.user], function(err, reply) { if (reply) { r.hgetall(user_key + socket.user, function(err, data) { r.del(user_key + socket.user, function(err, reply) { socket.broadcast.emit('chat', JSON.stringify( {'action': 'disconnect', 'user': data} )); delete socks[socket.user]; }); }); } }); }); }); //Listen to the server port server.listen(port, function () { var addr = server.address(); console.log('jqchat listening on ' + addr.address + addr.port); }); function getAllUsers(r, reply, callback) { var users = {}; for (var i = 0; i < reply.length; i++) { (function(i) { r.hgetall(user_key + reply[i], function(err, data) { users[data['user']] = data; if (i == (reply.length - 1)) callback(users); }); })(i); } } // Generate url for avatar purpose function get_avatar_url(user) { var mymd5 = crypto.createHash('md5').update(user); var rand = random(0, avatar_404.length); var end = '?d=' + avatar_404[rand]; return avatar_url + mymd5.digest("hex") + "/" + end } function random(low, high) { return Math.floor(Math.random() * (high - low) + low); }
// merlin.js // Import Backbone if it isnt already in place var Backbone = this.Backbone; if (!Backbone){ if(typeof exports !== 'undefined'){ Backbone = require('backbone'); } } // Import Underscore if it isnt already in place var _ = this._; if (!_){ if(typeof exports !== 'undefined'){ _ = require('underscore'); } } // Initialise the Merlin namespace Backbone.Merlin = { // shamelessly lifted from Coffeescript's compiler // extends: function(child, parent) { // 'use strict'; // var __hasProp = {}.hasOwnProperty; // for (var key in parent) { // if (__hasProp.call(parent, key)) { // child[key] = parent[key]; // } // } // function Ctor() { this.constructor = child; } // Ctor.prototype = parent.prototype; // child.prototype = new Ctor(); // child._super = parent.prototype; // return child; // } };
import virtualDom from 'virtual-dom'; import makeTag from './make-tag'; import $$ from 'slot'; import CellMode from './cell-mode'; import { sprintf } from 'sprintf-js'; var VNode = virtualDom.VNode; var VText = virtualDom.VText; class Hook { constructor(cell) { this.cell = cell; this.ondblclick = function (cell) { return function () { cell.ondblclick(); }; }(cell); this.onclick = function (cell) { return function () { cell.select(); }; }(cell); } hook(el) { this.cell.el = el; el.addEventListener('dblclick', this.ondblclick); el.addEventListener('click', this.onclick); } unhook(el) { el.removeEventListener('dblclick', this.ondblclick); el.removeEventListener('click', this.onclick); el = null; } } let stringifyStyle = function (style) { if (typeof style === 'object') { let s = ''; for (let k in style) { let v = style[k]; k = k.replace(/[A-Z]/g, function (s) { return '-' + s.toLowerCase(); }).replace(/^_/, ''); s += `${k}: ${v};`; } style = s; } return style; }; class EditorHook { constructor(cell, onChangeCb) { this.moveCaretAtEnd = function moveCaretAtEnd(e) { var temp_value = e.target.value; e.target.value = ''; e.target.value = temp_value; }; this.cell = cell; this.onChangeCb = onChangeCb; let editor = this; this.onkeydown = function onkeydown(e) { if (e.keyCode == 27 || e.keyCode == 13) { e.stopPropagation(); e.currentTarget.blur(); return false; } }; this.onblur = function onblur() { editor.onChangeCb(cell, this.value); }; } hook(el) { this.el = el; el.onfocus = this.moveCaretAtEnd; el.addEventListener('keydown', this.onkeydown); el.addEventListener('blur', this.onblur); } unhook(el) { el.onfocus = null; el.removeEventListener('keydown', this.onkeydown); el.removeEventListener('blur', this.onblur); el = null; } } /** * Cell actually represent a vnode slot, it may display as any cell (determined * by leftmost column and topmost row) * */ class Cell { /** * @constructor * * @param {SmartGrid} - sg * @param {row} - the row of the cell in vnode grid * @param {col} - the column of the cell in vnode grid * */ constructor(sg, row, col) { this.sg = sg; this.row = row; this.col = col; this.hook = new Hook(this); this.editorHook = new EditorHook(this, function (cell, val) { let that = this; if ((cell.def && cell.def.val) != val) { let validate = (cell.def || {}).__validate; Promise.resolve(validate? validate.apply(cell, [val]): null) .then(function () { let def = Object.assign(cell.def || {}, { val }); cell.sg.setCellDef(cell.tag, def); // why reset all the slots? since modify a value of a cell will affect // many other cells, and we can't know the affection unless we reset // all the slots, for example, in a grid // [ // ['1', '=A1+2'], // ['2'], // ] // if we change definition of 'B1' to '0', then the slot of 'A1' // will be revoked, however in this grid // [ // ['1', '=A1+2'], // ['=A1*2'] // ] // if we change definition of 'B1' to '0', slot of 'A1' will not be // revoked, since 'B1' depends on 'A1' // // reset will reuse existing slots if possible, so we don't need to // recreate the whole grid (which is a very expensive operation) cell.sg.dataSlotManager.reset(); cell.def = cell.sg.getCellDef(cell.tag); cell.$$envSlot = cell.sg.getCellSlot(cell.tag); let slots = [cell.sg.$$focusedCell]; if (cell.$$envSlot) { slots.push(cell.$$envSlot); } cell.$$view.connect(slots, cell._vf).refresh(null, true); cell.def.__onchange && cell.def.__onchange.apply(cell); }, function () { that.el.value = ''; }); } cell.sg.$$focusedCell.patch({ mode: CellMode.SELECTED }); return false; }); this.tag = makeTag(this.row, this.col); this.mode = CellMode.DEFAULT; this._vf = function (cell) { return function _vf([focusedCell, val], initiators) { // if: // 1. only the focusedCell change // 2. I am not the unfocused or focused one // this wave of change has nothing todo with me let newMode = (focusedCell && focusedCell.tag === cell.tag)? focusedCell.mode: CellMode.DEFAULT; if (this.value && initiators && initiators.length == 1 && initiators[0].id == cell.sg.$$focusedCell.id) { if (cell.mode == newMode) { return this.value; } } cell.mode = newMode; if (val === void 0) { val = cell.def && cell.def.val || ''; } return cell.def && cell.def.__makeVNode? cell.def.__makeVNode(cell, val): cell.makeVNode(val); }; }(this); this.$$view = $$(null, `cell-${row}-${col}`); this.resetView(0, 0); } makeVNode(val) { let className = ['cell', this.tag]; if (this.def && this.def.readonly) { className.push('readonly'); } if (this.def && this.def.class) { className = className.concat(this.def.class); } let selected = this.mode == CellMode.SELECTED; if (selected) { className.push('selected'); } let editing = this.mode == CellMode.EDIT; if (editing) { className.push('editing'); } let properties = function (cell) { let title = (cell.def && cell.def.title); if (!title) { let d = {}; for (let k in cell.def) { if (!k.startsWith('__')) { d[k] = cell.def[k]; } } title = JSON.stringify(d, null, 2); } return { attributes: { class: className.join(' '), style: stringifyStyle(cell.def? cell.def.style: {}), title, }, hook: cell.hook, }; }(this); let ret = new VNode('div', properties, [ this.makeContentVnode(this.def, val, editing), this.makeEditorVnode(this.def, editing), ]); // reset the input element's value, since VNode won't reset value // for you return ret; } resetView(topmostRow, leftmostCol) { this.tag = makeTag(this.row + topmostRow, this.col + leftmostCol); this.def = this.sg.getCellDef(this.tag); this.$$envSlot = this.sg.getCellSlot(this.tag); let slots = [this.sg.$$focusedCell]; this.$$envSlot && slots.push(this.$$envSlot); this.$$view.connect(slots, this._vf); } makeEditorVnode(def, editing) { // it could be more sophisticated let properties = { hook: this.editorHook, value: (def && def.val) || '', attributes: { class: 'editor', type: 'text', style: editing? '': 'display: none', } }; return new VNode('input', properties); } makeContentVnode(def, val, editing) { // it could be more sophisticated val = String(val || ''); if (val && def && def.format) { val = sprintf(def.format, val); } let colWidth = this.sg.resetColWidth(this.col + this.sg.$$leftmostCol.val(), val.length); let style = { width: colWidth + 'rem', }; if (editing) { style.display = 'none'; } let properties = { attributes: { class: 'content', style: stringifyStyle(style), } }; if (val == '') { // 全角空格 val = '\u3000'; } return new VNode('div', properties, [new VText(val)]); } select() { let focusedCell = this.sg.$$focusedCell; if (focusedCell && focusedCell.tag == this.tag) { return; } this.sg.$$focusedCell.val({ tag: this.tag, row: this.row + this.sg.$$topmostRow.val(), col: this.col + this.sg.$$leftmostCol.val(), mode: CellMode.SELECTED, }); } ondblclick() { let def = this.def; if ((def && def.readonly)) { return; } this.sg.$$focusedCell.val({ tag: this.tag, row: this.row + this.sg.$$topmostRow.val(), col: this.col + this.sg.$$leftmostCol.val(), mode: CellMode.EDIT, }); } } export default Cell;
/* * .json : JSON * .hjson : hjson, (http://hjson.org) * .yaml, .yml: YAML * .conf : HOCON (https://github.com/typesafehub/config/blob/master/HOCON.md) */ const JSON_EXTNAME = ['.json']; const HJSON_EXTNAME = ['.hjson']; const YAML_EXTNAME = ['.yaml', '.yml']; const HOCON_EXTNAME = ['.conf', '.hocon']; const SUPPORT_FORMATS = JSON_EXTNAME .concat(HJSON_EXTNAME) .concat(YAML_EXTNAME) .concat(HOCON_EXTNAME); const SUPPORT_CONFIG_EXTNAME = SUPPORT_FORMATS.map(extname => `config${extname}`); class Format { static isCollectFormatExtname(extname) { return SUPPORT_FORMATS.indexOf(extname) >= 0; } static isCollectConfigPostfix(filename) { return SUPPORT_CONFIG_EXTNAME .map(postfix => filename.indexOf(postfix) >= 0) .reduce((left, right) => left || right); } static isInExtname(extnames, extname) { return extnames .map(format => format.indexOf(extname) >= 0) .reduce((left, right) => left || right); } static isJSONExtname(extname) { return Format.isInExtname(JSON_EXTNAME, extname); } static isHJSONExtname(extname) { return Format.isInExtname(HJSON_EXTNAME, extname); } static isYAMLExtname(extname) { return Format.isInExtname(YAML_EXTNAME, extname); } static isHOCONExtname(extname) { return Format.isInExtname(HOCON_EXTNAME, extname); } static removePostfix(filename) { return [filename].concat(SUPPORT_CONFIG_EXTNAME) .reduce((resultFileName, extname) => resultFileName.replace(extname, '')) .replace('.config', ''); } } module.exports = Format;
game.PlayScreen = me.ScreenObject.extend({ /** * action to perform on state change */ onResetEvent: function() { me.device.watchDeviceOrientation(); me.device.watchAccelerometer(); // clear the background me.game.world.addChild(new me.ColorLayer("background", "#000000", 0)); // renderable to display device information me.game.world.addChild(new (me.Renderable.extend({ init: function() { this._super(me.Renderable, 'init', [0, 0, 100, 200]); this.font = new me.Font('arial', '24px', "white"); }, update: function() { return true; }, draw: function(renderer) { this.font.draw(renderer, "Gamma: " + me.device.gamma, 10, 0); this.font.draw(renderer, "Beta: " + me.device.beta, 10, 30); this.font.draw(renderer, "Alpha: " + me.device.alpha, 10, 60); this.font.draw(renderer, "X: " + me.device.accelerationX, 10, 90); this.font.draw(renderer, "Y: " + me.device.accelerationY, 10, 120); this.font.draw(renderer, "Z: " + me.device.accelerationZ, 10, 150); this.font.draw(renderer, "orientation: " + me.device.orientation + " degrees", 10, 180); } })), 1); }, /** * action to perform when leaving this screen (state change) */ onDestroyEvent: function() { me.device.unwatchDeviceOrientation(); me.device.unwatchAccelerometer(); } });
'use strict'; var i2c = require('i2c-bus').openSync(1), avr = require('./avr'), count = 0; function toCelcius(rawValue) { var voltage = rawValue * 3.3; voltage /= 1024.0; var temperatureC = (voltage - 0.5) * 100; return temperatureC; } i2c.writeByteSync(avr.ADDR, avr.A0_MODE, avr.ANALOG); i2c.writeByteSync(avr.ADDR, avr.A1_MODE, avr.ANALOG); i2c.writeByteSync(avr.ADDR, avr.A2_MODE, avr.ANALOG); i2c.writeByteSync(avr.ADDR, avr.A3_MODE, avr.ANALOG); setInterval(function () { var rawTemp, rawLdr, half, full; rawTemp = i2c.readWordSync(avr.ADDR, avr.A0_VALUE); rawLdr = i2c.readWordSync(avr.ADDR, avr.A1_VALUE); half = i2c.readWordSync(avr.ADDR, avr.A2_VALUE); full = i2c.readWordSync(avr.ADDR, avr.A3_VALUE); console.log(++count + ': ' + rawTemp.toString(16) + ' ' + toCelcius(rawTemp) + ', ' + rawLdr.toString(16) + ', ' + half.toString(16) + ', ' + full.toString(16)); }, 100);
import Plugin from "./../Plugin"; import Util from "./../Util"; export default class RateLimiter extends Plugin { static get plugin() { return { name: "RateLimiter", description: "Automatically ignore spamming users", help: "", visibility: Plugin.Visibility.HIDDEN, type: Plugin.Type.PROXY }; } lastMessages = {}; spamInterval = 1000; oldThreshold = 60; // Reject messages older than this many seconds proxy(eventName, message) { const now = (new Date()).getTime(); const author = message.from.id; const lastMessage = this.lastMessages[author]; // Skip old messages when "catching up" if ((Math.round(now / 1000) - message.date) > this.oldThreshold) return Promise.reject(); // The difference is in milliseconds. if (lastMessage && ((now - lastMessage) < this.spamInterval)) { this.log.verbose("Rejecting message from " + Util.buildPrettyUserName(message.from)); return Promise.reject(); } this.lastMessages[author] = now; return Promise.resolve(); } }
const join = require('path').join // $FlowFixMe const esprima = require('esprima') class AstParser { parser: any sourceType: string constructor (parser: any = esprima, sourceType: string = 'module') { this.parser = parser this.sourceType = 'module' } parse (filePath: string, text: string) { const ast: Array<any> = this.parser.parse(text, { sourceType: this.sourceType }).body return { imports: extractImports(filePath, ast), exports: extractExports(ast) } } } function extractImports (filePath: string, ast: Array<any>) { const imports = {} ast.filter(isImport) .forEach(importAst => { const source = importAst.source.value const sourcePath = resolvePath(filePath, source) imports[sourcePath] = importAst.specifiers.length === 0 ? source.substr(source.indexOf('./') + 2) : importAst.specifiers[0].local.name }) return imports } function extractExports (ast: Array<any>) { const exports = {} ast.filter(isExport) .forEach(exportAst => { switch (exportAst.constructor.name) { case 'ExportAllDeclaration': exports.all = exportAst.source.value break case 'ExportDefaultDeclaration': exports.default = exportAst.declaration.name break case 'ExportNamedDeclaration': exports.named = [] exportAst.specifiers.forEach(specifier => { exports.named.push(specifier.exported.name) }) break } }) return exports } function resolvePath (filePath: string, source: string) { const stripFilePath = filePath.substr(0, filePath.lastIndexOf('/')) return `${join(stripFilePath, source)}.js` } function isImport (statement: any) { return statement.type === 'ImportDeclaration' } function isExport (statement: any) { return statement.type === 'ExportAllDeclaration' || statement.type === 'ExportDefaultDeclaration' || statement.type === 'ExportNamedDeclaration' } module.exports = AstParser
import Ember from 'ember'; import config from './config/environment'; const Router = Ember.Router.extend({ location: config.locationType, rootURL: config.rootURL }); Router.map(function() { this.mount('ember-blog-engine', {as: 'blog'}); }); export default Router;
const _ = require('lodash'); const { authenticate } = require('feathers-authentication').hooks; const commonHooks = require('feathers-hooks-common'); const { restrictToOwner } = require('feathers-authentication-hooks'); const verifyHooks = require('feathers-authentication-management').hooks; const { isEnabled, setDefaultRole, setFirstUserToRole, sendVerificationEmail, hasPermissionsBoolean, preventDisabledAdmin, loopItems, } = require('../../hooks'); const { hashPassword } = require('feathers-authentication-local').hooks; const restrict = [ authenticate('jwt'), isEnabled(), commonHooks.unless( hasPermissionsBoolean('manageUsers'), restrictToOwner({ idField: '_id', ownerField: '_id' }) ) ]; function setUserInitials(item) { if(item.name) { item.initials = _.get(item, 'name', '') .match(/\b(\w)/g) .join('') .slice(0, 2) .toUpperCase(); } } const schema = { include: [{ service: 'roles', nameAs: 'access', parentField: 'role', childField: 'role', provider: undefined }], }; const serializeSchema = { computed: { permissions: (item, hook) => _.get(item, 'access.permissions'), }, exclude: ['access', '_include'] }; module.exports = { before: { all: [], find: [ authenticate('jwt'), isEnabled(), ], get: [ authenticate('jwt'), isEnabled(), ], create: [ hashPassword(), verifyHooks.addVerification(), setDefaultRole(), setFirstUserToRole({ role: 'admin' }), preventDisabledAdmin(), loopItems(setUserInitials) ], update: [ commonHooks.disallow('external') ], patch: [ ...restrict, commonHooks.iff(commonHooks.isProvider('external'), commonHooks.preventChanges( 'email', 'isVerified', 'verifyToken', 'verifyShortToken', 'verifyExpires', 'verifyChanges', 'resetToken', 'resetShortToken', 'resetExpires' )), preventDisabledAdmin(), loopItems(setUserInitials) ], remove: [ ...restrict ] }, after: { all: [ commonHooks.when( hook => hook.params.provider, commonHooks.discard('password', '_computed', 'verifyExpires', 'resetExpires', 'verifyChanges') ), commonHooks.populate({ schema }), commonHooks.serialize(serializeSchema), ], find: [ ], get: [ ], create: [ sendVerificationEmail(), verifyHooks.removeVerification(), ], update: [ ], patch: [ ], remove: [ ] }, error: { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] } };
//Module with variables and methods for config build process module.exports = function () { //Main config variables with final distribution names (you can change them) var appScriptsFile = 'app.js'; var appStylesFile = 'app.css'; var appTemplatesFile = 'templates.js'; var appLanguagesFile = 'languages.js'; var vendorScriptsFile = 'vendor.js'; var vendorStylesFile = 'vendor.css'; var distributionAppFolder = 'dist'; var distributionAssetsFolder = 'dist/assets'; var mainModule = 'app'; var templatesFolder = 'templates'; //Main class config for app and vendor assets from a dev process (you cannot change them) var AppConfig = function () { var directFiles = ['public/**/*', 'app/index.html']; var appAssets = { scripts: ['app/app.js', 'app/modules/**/*.js', 'app/**/*.js', '!app/locales/**/*.js'], styles: 'app/styles/**/*.css', sassStyles: 'app/styles/**/*.scss', lessStyles: 'app/styles/**/*.less', templates: 'app/templates/**/*.html', languages: 'app/locales/**/*.js' }; var vendorAssets = { scripts: [], styles: [] }; this.importScript = function (file) { vendorAssets.scripts.push(file); }; this.importStyle = function (file) { vendorAssets.styles.push(file); }; this.getDirectFiles = function () { return directFiles; }; this.getAssets = function () { return { app: appAssets, vendor: vendorAssets } } }; //The main point where you can start importing new vendor / bower / node dependencies for JS and CSS. var app = new AppConfig(); app.importScript('bower_components/angular/angular.min.js'); app.importScript('bower_components/angular-ui-router/release/angular-ui-router.min.js'); app.importScript('bower_components/angular-restmod/dist/angular-restmod-bundle.min.js'); app.importScript('bower_components/satellizer/satellizer.min.js'); app.importScript('bower_components/angular-translate/angular-translate.min.js'); app.importScript('bower_components/angular-cookies/angular-cookies.min.js'); app.importScript('bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.min.js'); app.importScript('bower_components/angular-translate-storage-local/angular-translate-storage-local.min.js'); //Returning module object return { assets: app.getAssets(), directFiles: app.getDirectFiles(), appScriptsFile: appScriptsFile, appStylesFile: appStylesFile, appTemplatesFile: appTemplatesFile, appLanguagesFile: appLanguagesFile, vendorScriptsFile: vendorScriptsFile, vendorStylesFile: vendorStylesFile, distributionAppFolder: distributionAppFolder, distributionAssetsFolder: distributionAssetsFolder, mainModule: mainModule, templatesFolder: templatesFolder }; };
import {Component, View, For} from 'angular2/angular2'; import {Inject} from 'angular2/di'; import {AlbumService} from 'components/album/service'; import {RouterService} from 'components/router/service'; @Component({ selector: 'album-list', services: [AlbumService, RouterService] }) @View({ templateUrl: 'components/album/list.html', directives: [For] }) export class AlbumList { albumService:AlbumService; routerService:RouterService; constructor() { console.log('component AlbumList mounted'); this.albumService = AlbumService.getInstance(); this.routerService = RouterService.getInstance(); } show(item2) { this.albumService.select(item2); this.routerService.displayAlbumShow(); } }
version https://git-lfs.github.com/spec/v1 oid sha256:5ab3e41ede67febf40554edc869bcbdf2988519e4257d9aba7a2d88b8ee14cd2 size 6729
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><circle cx="12" cy="17" r="4" /><path d="M12 3C8.1 3 4.56 4.59 2 7.15l5 5c1.28-1.28 3.05-2.08 5-2.08s3.72.79 5 2.07l5-5C19.44 4.59 15.9 3 12 3z" /></React.Fragment> , 'CompassCalibrationSharp');
function Ambiente(){} function iniciar() { this.canvas = document.getElementById('canvas'); this.contexto = this.canvas.getContext('2d'); this.bola = new Bola(50, '#0000ff'); this.bola.x = 50; this.bola.y = 70; this.bola.vx = 55 / 60; this.bola.vy = 0; this.bola.ax = 0; this.bola.ay = 0.8 / 60; this.bloco = new Bloco(160, 30, "red"); setInterval(this.emCadaPasso, 1000 / 60); // 60 fps } function emCadaPasso() { if(this.bola.x <= 160){ this.bola.x += this.bola.vx; } else{ if(this.bola.dentroLimiteDireito(this.canvas)){ this.bola.x += this.bola.vx; } else { this.bola.vx = -this.bola.vx * 0.8; this.bola.vy *= 0.95; } if (this.bola.dentroLimiteInferior(this.canvas)) { this.bola.y += this.bola.vy; this.bola.vy += this.bola.ay; } else { this.bola.vy = -this.bola.vy * 0.8; this.bola.vx *= 0.95; } } this.limparCanvas(); this.bola.desenhar(this.contexto); // desenhe a bola this.bloco.desenhar(this.contexto); } function limparCanvas(){ this.contexto.clearRect(0, 0, this.canvas.width, this.canvas.height); } Ambiente.prototype.iniciar = iniciar; Ambiente.prototype.emCadaPasso = emCadaPasso; Ambiente.prototype.limparCanvas = limparCanvas;