code stringlengths 2 1.05M |
|---|
Slot = function()
{
}
Slot.prototype.fired = function(value)
{
}
signal = new Athena.Signals.Signal();
slot = new Slot();
CHECK(signal.disconnected, "signal.disconnected");
signal.connect(slot, slot.fired);
CHECK(!signal.disconnected, "!signal.disconnected");
signal.disconnect(slot, slot.fired);
CHECK(signal.disconnected, "signal.disconnected");
|
var util = require('util');
var colors = require('./colors');
// wow what a clusterfuck
var parseOptions = function(plugin, message, opt) {
if (!opt) opt = {};
if (typeof plugin === 'object') {
opt = plugin;
} else if (message instanceof Error) {
opt.message = message;
opt.plugin = plugin;
} else if (typeof message === 'object') {
opt = message;
opt.plugin = plugin;
} else if (typeof opt === 'object') {
opt.plugin = plugin;
opt.message = message;
}
return opt;
};
function PluginError(plugin, message, opt) {
if (!(this instanceof PluginError)) throw new Error('Call PluginError using new');
Error.call(this);
var options = parseOptions(plugin, message, opt);
this.plugin = options.plugin;
this.showStack = options.showStack;
// if message is an Error grab crap off it
if (options.message instanceof Error) {
this.name = options.message.name;
this.message = options.message.message;
this.fileName = options.message.fileName;
this.lineNumber = options.message.lineNumber;
this.stack = options.message.stack;
} else { // else check options obj
this.name = options.name;
this.message = options.message;
this.fileName = options.fileName;
this.lineNumber = options.lineNumber;
this.stack = options.stack;
}
// defaults
if (!this.name) this.name = 'Error';
// TODO: figure out why this explodes mocha
if (!this.stack) Error.captureStackTrace(this, arguments.callee || this.constructor);
if (!this.plugin) throw new Error('Missing plugin name');
if (!this.message) throw new Error('Missing error message');
}
util.inherits(PluginError, Error);
PluginError.prototype.toString = function () {
var sig = '['+colors.green('gulp')+'] '+this.name+' in plugin \''+colors.cyan(this.plugin)+'\'';
var msg = this.showStack ? (this._stack || this.stack) : this.message;
return sig+': '+msg;
};
module.exports = PluginError; |
description('Test to make sure we push down inline styles properly.');
if (window.internals)
internals.settings.setEditingBehavior('win');
var testContainer = document.createElement("div");
testContainer.contentEditable = true;
document.body.appendChild(testContainer);
function testSingleToggle(toggleCommand, selector, initialContents, expectedContents)
{
testContainer.innerHTML = initialContents;
var selected = selector(testContainer);
document.execCommand('styleWithCSS', false, 'false');
document.execCommand(toggleCommand, false, null);
var action = toggleCommand + ' on ' + selected + ' of ' + initialContents + " yields " + testContainer.innerHTML;
if (testContainer.innerHTML == expectedContents)
testPassed(action);
else
testFailed(action + ", expected " + expectedContents);
}
function selectFirstWord(container) {
window.getSelection().setPosition(container, 0);
window.getSelection().modify('extend', 'forward', 'word');
return 'first word';
}
function selectLastWord(container) {
window.getSelection().setPosition(container, container.childNodes.length);
window.getSelection().modify('extend', 'backward', 'word');
return 'last word';
}
testSingleToggle("bold", selectFirstWord, '<b><ul><li><b>a</b></li></ul></b>', '<ul><li>a</li></ul>');
testSingleToggle("bold", selectFirstWord, '<b><ul><li>hello</li><li>world</li></ul></b>', '<ul><li>hello</li><li style="font-weight: bold;">world</li></ul>');
testSingleToggle("bold", selectLastWord, '<ul><li>hello</li><li style="font-weight: bold;">world</li></ul>', '<ul><li>hello</li><li>world</li></ul>');
testSingleToggle("bold", selectFirstWord, '<b><ul><li>hello world</li><li>webkit</li></ul></b>', '<ul><li>hello <b>world</b></li><li style="font-weight: bold;">webkit</li></ul>');
testSingleToggle("italic", selectFirstWord, '<i><ul><li><i>a</i></li></ul></i>', '<ul><li>a</li></ul>');
testSingleToggle("italic", selectFirstWord, '<i><ul><li>hello</li><li>world</li></ul></i>', '<ul><li>hello</li><li style="font-style: italic;">world</li></ul>');
testSingleToggle("italic", selectLastWord, '<ul><li>hello</li><li style="font-style: italic;">world</li></ul>', '<ul><li>hello</li><li>world</li></ul>');
testSingleToggle("italic", selectFirstWord, '<i><ul><li>hello world</li><li>webkit</li></ul></i>', '<ul><li>hello <i>world</i></li><li style="font-style: italic;">webkit</li></ul>');
testSingleToggle("underline", selectFirstWord, '<u><ul><li><u>a</u></li></ul></u>', '<ul><li>a</li></ul>');
testSingleToggle("underline", selectFirstWord, '<u><ul><li>hello</li><li>world</li></ul></u>', '<ul><li>hello</li><li style="text-decoration-line: underline;">world</li></ul>');
testSingleToggle("underline", selectLastWord, '<ul><li>hello</li><li style="text-decoration: underline;">world</li></ul>', '<ul><li>hello</li><li>world</li></ul>');
testSingleToggle("underline", selectFirstWord, '<u><ul><li>hello world</li><li>webkit</li></ul></u>', '<ul><li>hello <u>world</u></li><li style="text-decoration-line: underline;">webkit</li></ul>');
testSingleToggle("strikethrough", selectFirstWord, '<strike><ul><li><strike>a</strike></li></ul></strike>', '<ul><li>a</li></ul>');
testSingleToggle("strikethrough", selectFirstWord, '<strike><ul><li>hello</li><li>world</li></ul></strike>', '<ul><li>hello</li><li style="text-decoration-line: line-through;">world</li></ul>');
testSingleToggle("strikethrough", selectLastWord, '<ul><li>hello</li><li style="text-decoration: line-through;">world</li></ul>', '<ul><li>hello</li><li>world</li></ul>');
testSingleToggle("strikethrough", selectFirstWord, '<strike><ul><li>hello world</li><li>webkit</li></ul></strike>', '<ul><li>hello <strike>world</strike></li><li style="text-decoration-line: line-through;">webkit</li></ul>');
document.body.removeChild(testContainer);
var successfullyParsed = true;
|
/* jshint esversion: 6 */
var robot = require('../..');
var targetpractice = require('targetpractice/index.js');
var os = require('os');
robot.setMouseDelay(100);
var target, elements;
describe('Integration/Keyboard', () => {
beforeEach(done => {
target = targetpractice.start();
target.once('elements', message => {
elements = message;
done();
});
});
afterEach(() => {
targetpractice.stop();
target = null;
});
it('types', done => {
const stringToType = 'hello world';
// Currently Target Practice waits for the "user" to finish typing before sending the event.
target.once('type', element => {
expect(element.id).toEqual('input_1');
expect(element.text).toEqual(stringToType);
done();
});
const input_1 = elements.input_1;
robot.moveMouse(input_1.x, input_1.y);
robot.mouseClick();
robot.typeString(stringToType);
});
});
|
// ==UserScript==
// @name PortsSyndLinks
// @namespace https://github.com/MyRequiem/comfortablePlayingInGW
// @description На страницах списков ближайших/прошедших боев за порты добавляет знаки синдикатов, являющиеся ссылками на их онлайн.
// @id comfortablePlayingInGW@MyRequiem
// @updateURL https://raw.githubusercontent.com/MyRequiem/comfortablePlayingInGW/master/separatedScripts/PortsSyndLinks/portsSyndLinks.meta.js
// @downloadURL https://raw.githubusercontent.com/MyRequiem/comfortablePlayingInGW/master/separatedScripts/PortsSyndLinks/portsSyndLinks.user.js
// @include https://*gwars.ru/object.php?id=*
// @grant none
// @license MIT
// @version 1.07-140820
// @author MyRequiem [https://www.gwars.ru/info.php?id=2095458]
// ==/UserScript==
/*global unsafeWindow */
/*jslint browser: true, maxlen: 80, vars: true, plusplus: true, regexp: true */
/*eslint-env browser */
/*eslint no-useless-escape: 'warn', linebreak-style: ['error', 'unix'],
quotes: ['error', 'single'], semi: ['error', 'always'],
eqeqeq: 'error', curly: 'error'
*/
/*jscs:disable requireMultipleVarDecl, requireVarDeclFirst */
/*jscs:disable disallowKeywords, disallowDanglingUnderscores */
/*jscs:disable validateIndentation */
(function () {
'use strict';
/**
* @class PortsSyndLinks
* @constructor
*/
var PortsSyndLinks = function () {
/**
* @property root
* @type {Object}
*/
this.root = this.getRoot();
/**
* @property doc
* @type {Object}
*/
this.doc = this.root.document;
/**
* @property loc
* @type {String}
*/
this.loc = this.root.location.href;
};
/**
* @lends PortsSyndLinks.prototype
*/
PortsSyndLinks.prototype = {
/**
* @method getRoot
* @return {Object}
*/
getRoot: function () {
var rt = typeof unsafeWindow;
return rt !== 'undefined' ? unsafeWindow : window;
},
/**
* @method init
*/
init: function () {
var table = this.doc.querySelector('td>table.simplewhitebg');
if (table) {
var syndLinks = table.querySelectorAll('a[href*="&page="]'),
link,
sign,
reg,
i;
for (i = 0; i < syndLinks.length; i++) {
link = syndLinks[i];
reg = /&sid=(\d+)$/.exec(link.href);
if (reg) {
sign = this.doc.createElement('a');
sign.setAttribute('href', 'https://www.gwars.ru/' +
'syndicate.php?id=' + reg[1] + '&page=online');
sign.setAttribute('target', '_blank');
sign.setAttribute('style', 'margin-right: 2px;');
sign.innerHTML = '<img src="https://images.gwars.ru/' +
'img/synds/' + reg[1] + '.gif" width="20" ' +
'height="14" border="0" alt="img" />';
link.parentNode.insertBefore(sign, link);
}
}
}
}
};
new PortsSyndLinks().init();
}());
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var auth_service_1 = require('./auth.service');
var HomeComponent = (function () {
function HomeComponent(auth) {
this.auth = auth;
this.userName = localStorage.getItem('userName');
console.log(auth);
}
HomeComponent = __decorate([
core_1.Component({
selector: 'home',
templateUrl: 'app/home.template.html',
styleUrls: ['app/home.component.css']
}),
__metadata('design:paramtypes', [auth_service_1.Auth])
], HomeComponent);
return HomeComponent;
}());
exports.HomeComponent = HomeComponent;
//# sourceMappingURL=home.component.js.map |
window.pdfMake = window.pdfMake || {}; window.pdfMake.fonts = {"Lusitana":{"bold":"Lusitana-Bold.ttf","normal":"Lusitana-Regular.ttf","italics":"Lusitana-Regular.ttf","bolditalics":"Lusitana-Bold.ttf"}}; |
module.exports = {
verbose: false,
ignoreFiles: [
'web-ext-config.js',
],
build: {
overwriteDest: true,
},
};
|
const path = require('path');
const _ = require('lodash');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
// Common configuration chunk to be used on all bundles
// webtask (webtask.js), and normal (node.js) bundles
const defaultConfig = {
context: path.resolve(__dirname, '../src'),
output: {
path: path.join(__dirname, '../dist'),
libraryTarget: 'commonjs2'
},
module: {
loaders: [{
test: /\.js$/,
loader: 'babel',
include: path.join(__dirname, '../src')
}, {
test: /\.json$/,
loader: 'json'
}]
},
externals: [nodeExternals({
whitelist: ['replacestream']
})],
target: 'node',
debug: true,
devtool: 'inline-source-map',
stats: {
colors: true
}
};
// Configuration for the webtask bundle (webtask.js)
const indexConfig = _.merge({}, defaultConfig, {
entry: ['./webtask'],
output: {
filename: 'webtask.js'
}
});
// Configuration for the normal bundle (node.js)
const runConfig = _.merge({}, defaultConfig, {
entry: ['./node'],
output: {
filename: 'node.js'
}
});
module.exports = [indexConfig, runConfig];
|
// xHasStyleSelector r1, Copyright 2006-2007 Ivan Pepelnjak (www.zaplana.net)
// Part of X, a Cross-Browser Javascript Library, Distributed under the terms of the GNU LGPL
// xHasStyleSelector(styleSelectorString)
// checks whether any of the stylesheets attached to the document contain the definition of the specified
// style selector (simple string matching at the moment)
//
// returns:
// undefined - style sheet scripting not supported by the browser
// true/false - found/not found
function xHasStyleSelector(ss) {
if (! xHasStyleSheets()) return undefined ;
function testSelector(cr) {
return cr.selectorText.indexOf(ss) >= 0;
}
return xTraverseDocumentStyleSheets(testSelector);
}
|
import ItemofHome from '../index';
import expect from 'expect';
import { shallow } from 'enzyme';
import React from 'react';
describe('<ItemofHome />', () => {
it('should render its children', () => {
const children = (<h1>TEST</h1>);
const renderedComponent = shallow(
<ItemofHome>
{children}
</ItemofHome>
);
expect(renderedComponent.contains(children)).toEqual(true);
});
});
|
7.0-alpha1:be1b10a0d82c31417054606bc6827bf2c606b1b1c7a1ee1e05d010e4a7f25c4c
7.0-alpha2:be1b10a0d82c31417054606bc6827bf2c606b1b1c7a1ee1e05d010e4a7f25c4c
7.0-alpha3:be1b10a0d82c31417054606bc6827bf2c606b1b1c7a1ee1e05d010e4a7f25c4c
7.0-alpha4:41e5c41b37aae49d5c2f404e7a98e7244a4bba10b938fd401b8fcb3ef228f04f
7.0-alpha5:41e5c41b37aae49d5c2f404e7a98e7244a4bba10b938fd401b8fcb3ef228f04f
7.0-alpha6:41e5c41b37aae49d5c2f404e7a98e7244a4bba10b938fd401b8fcb3ef228f04f
7.0-alpha7:41e5c41b37aae49d5c2f404e7a98e7244a4bba10b938fd401b8fcb3ef228f04f
7.0-beta1:41e5c41b37aae49d5c2f404e7a98e7244a4bba10b938fd401b8fcb3ef228f04f
7.0-beta2:41e5c41b37aae49d5c2f404e7a98e7244a4bba10b938fd401b8fcb3ef228f04f
7.0-beta3:a7085dd108894be7bc3c1f2bc830691adcefefa1e3c7e491180bec87ba9f2858
7.1:1cefb619e1193bdde0af01257fc9198b041b215d656f01c1b41fe974b646a994
7.2:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.3:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.4:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.5:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.6:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.7:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.8:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.9:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.10:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.11:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.12:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.13:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.14:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.15:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.16:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.17:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.18:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.19:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.20:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.21:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.22:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.23:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.24:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.25:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.26:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.27:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.28:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.29:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.30:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.31:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.32:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.33:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.34:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.35:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.36:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.37:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.38:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.39:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.40:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.41:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.42:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.43:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.44:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.50:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.51:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.52:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.53:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.54:9314c5b6b9c4e657a1dd69df84d3697950bd909115cda522377a172568944f58
7.0:a7085dd108894be7bc3c1f2bc830691adcefefa1e3c7e491180bec87ba9f2858
|
'use strict'
const request = jest.genMockFromModule('request')
request.defaults = jest.fn(() => ({
get: jest.fn((opts, callback) => callback(null, {}, {})),
post: jest.fn((opts, callback) => callback(null, {}, {})),
put: jest.fn((opts, callback) => callback(null, {}, {})),
delete: jest.fn((opts, callback) => callback(null, {}, {})),
}))
module.exports = request
|
"use strict";
describe("NexusCtrl", function () {
var nexusController;
var $scope;
var $rootScope;
var $location = jasmine.createSpyObj("$location", ["path"]);
var partyService = jasmine.createSpyObj("partyService", ["getPartyInitD"]);
beforeEach(module("EnctrPwr.Ctrls"));
beforeEach(module(function($provide) {
$provide.value("$location", $location);
$provide.value("PartyService", partyService);
}));
beforeEach(inject(function(
_$rootScope_,
$controller) {
$rootScope = _$rootScope_;
$scope = _$rootScope_.$new();
nexusController = $controller("NexusController", {
$scope: $scope,
$rootScope: $rootScope,
$location: $location,
PartyService: partyService
});
}));
}); |
const EventEmitter = require('events').EventEmitter;
const util = require('util');
const randomstring = require('randomstring');
const RequestMessage = require('./messages').Request;
const ResponseDecoder = require('./messages/decoders').ResponseDecoder;
const url = require('url');
const defaultTracer = require('./tracer');
const reconnect = require('reconnect-net');
const reconnectTls = require('reconnect-tls');
const disyuntor = require('disyuntor');
const ms = require('ms');
const _ = require('lodash');
const DEFAULT_PROTOCOL = 'baas';
const DEFAULT_PORT = 9485;
const DEFAULT_HOST = 'localhost';
const lib_map = {
'baas': reconnect,
'baass': reconnectTls
};
function parseURI (uri) {
const parsed = url.parse(uri);
return {
host: parsed.hostname,
port: parseInt(parsed.port || DEFAULT_PORT, 10),
protocol: parsed.protocol.slice(0, -1)
};
}
function BaaSClient (options, done) {
options = options || {};
EventEmitter.call(this);
if (typeof options === 'string') {
options = parseURI(options);
} else if (options.uri || options.url) {
options = _.extend(options, parseURI(options.uri || options.url));
} else {
options.protocol = options.protocol || DEFAULT_PROTOCOL;
options.port = options.port || DEFAULT_PORT;
options.host = options.host || DEFAULT_HOST;
}
options.tracer = options.tracer || defaultTracer;
this._socketLib = lib_map[options.protocol];
if (!this._socketLib) {
throw new Error('unknown protocol ' + options.protocol);
}
this._options = options;
this._requestCount = 0;
if (typeof this._options.requestTimeout === 'undefined') {
this._options.requestTimeout = ms('2s');
}
this._pendingRequests = 0;
this._sendRequestSafe = disyuntor(this._sendRequest.bind(this), _.extend({
name: 'baas.client',
timeout: options.requestTimeout,
onTrip: (err) => {
this.emit('breaker_error', err);
}
}, options.breaker || {} ));
this.connect(done);
}
util.inherits(BaaSClient, EventEmitter);
BaaSClient.prototype.connect = function (done) {
const options = this._options;
const client = this;
this.socket = this._socketLib(function (stream) {
stream.pipe(ResponseDecoder()).on('data', function (response) {
client.emit('response', response);
client.emit('response_' + response.request_id, response);
});
client.stream = stream;
client.emit('ready');
}).once('connect', function () {
client.emit('connect');
}).on('close', function (err) {
client.emit('close', err);
}).on('error', function (err) {
if (err === 'DEPTH_ZERO_SELF_SIGNED_CERT' && options.rejectUnauthorized === false) {
return;
}
client.emit('error', err);
}).connect(options.port, options.address || options.hostname || options.host, {
rejectUnauthorized: options.rejectUnauthorized
});
client.once('ready', done || _.noop);
};
/**
* Signatures
*
* hash('password', (err, hash))
* hash('password', 'salt', (err, hash))
* hash('password', { span: span }, (err, hash))
*/
BaaSClient.prototype.hash = function (password, salt, callback) {
var options = {};
//Salt is keep for api-level compatibility with node-bcrypt
//but is enforced in the backend.
if (typeof salt === 'function') {
callback = salt;
} else if (typeof salt === 'object') {
options = salt;
}
if (!password) {
return setImmediate(callback, new Error('password is required'));
}
const request = {
'password': password,
'operation': RequestMessage.Operation.HASH,
'span': options.span
};
this._sendRequestSafe(request, (err, response) => {
callback(err, response && response.hash);
});
};
/**
* Signatures
*
* compare('password', 'hash', (err, hash))
* compare('password', 'hash', { span: span }, (err, hash))
*/
BaaSClient.prototype.compare = function (password, hash, options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
options = options || {};
if (!password) {
return setImmediate(callback, new Error('password is required'));
}
if (!hash) {
return setImmediate(callback, new Error('hash is required'));
}
var request = {
'password': password,
'hash': hash,
'operation': RequestMessage.Operation.COMPARE,
'span': options.span
};
this._sendRequestSafe(request, (err, response) => {
callback(err, response && response.success);
});
};
BaaSClient.prototype._sendRequest = function (params, callback) {
if (!callback) {
return setImmediate(callback, new Error('callback is required'));
}
if (!this.stream || !this.stream.writable) {
return setImmediate(callback, new Error('The socket is closed.'));
}
var request;
try {
request = RequestMessage.create(_.extend({
'id': randomstring.generate(7)
}, params));
let err = RequestMessage.verify(request);
if (err) {
throw new Error(err);
}
} catch (err) {
return callback(err);
}
const tracer = this._options.tracer;
const operation = params.operation === RequestMessage.Operation.COMPARE ? 'compare' : 'hash';
const spanOptions = params.span ? { childOf: params.span } : undefined;
const span = tracer.startSpan(operation, spanOptions);
span.setTag(tracer.Tags.SPAN_KIND, tracer.Tags.SPAN_KIND_RPC_CLIENT);
span.setTag(tracer.Tags.PEER_ADDRESS, this._options.host);
span.setTag(tracer.Tags.PEER_PORT, this._options.port);
span.setTag('request.id', request.id);
tracer.inject(span, tracer.FORMAT_AUTH0_BINARY, (context) => request.trace_context = context);
this._requestCount++;
this._pendingRequests++;
this.once('response_' + request.id, (response) => {
this._pendingRequests--;
if (this._pendingRequests === 0) {
this.emit('drain');
}
if (response.busy) {
span.setTag(tracer.Tags.ERROR, true);
span.finish();
return callback(new Error('baas server is busy'));
}
span.finish();
callback(null, response);
});
this.stream.write(RequestMessage.encodeDelimited(request).finish());
};
BaaSClient.prototype.disconnect = function () {
this.socket.disconnect();
};
module.exports = BaaSClient;
|
/*! AdminLTE app.js
* ================
* Main JS application file for AdminLTE v2. This file
* should be included in all pages. It controls some layout
* options and implements exclusive AdminLTE plugins.
*
* @Author Almsaeed Studio
* @Support <http://www.almsaeedstudio.com>
* @Email <support@almsaeedstudio.com>
* @version 2.3.0
* @license MIT <http://opensource.org/licenses/MIT>
*/
//Make sure jQuery has been loaded before app.js
if (typeof jQuery === "undefined") {
throw new Error("AdminLTE requires jQuery");
}
/* AdminLTE
*
* @type Object
* @description $.AdminLTE is the main object for the template's app.
* It's used for implementing functions and options related
* to the template. Keeping everything wrapped in an object
* prevents conflict with other plugins and is a better
* way to organize our code.
*/
$.AdminLTE = {};
/* --------------------
* - AdminLTE Options -
* --------------------
* Modify these options to suit your implementation
*/
$.AdminLTE.options = {
//Add slimscroll to navbar menus
//This requires you to load the slimscroll plugin
//in every page before app.js
navbarMenuSlimscroll: true,
navbarMenuSlimscrollWidth: "3px", //The width of the scroll bar
navbarMenuHeight: "200px", //The height of the inner menu
//General animation speed for JS animated elements such as box collapse/expand and
//sidebar treeview slide up/down. This options accepts an integer as milliseconds,
//'fast', 'normal', or 'slow'
animationSpeed: 500,
//Sidebar push menu toggle button selector
sidebarToggleSelector: "[data-toggle='offcanvas']",
//Activate sidebar push menu
sidebarPushMenu: true,
//Activate sidebar slimscroll if the fixed layout is set (requires SlimScroll Plugin)
sidebarSlimScroll: true,
//Enable sidebar expand on hover effect for sidebar mini
//This option is forced to true if both the fixed layout and sidebar mini
//are used together
sidebarExpandOnHover: false,
//BoxRefresh Plugin
enableBoxRefresh: true,
//Bootstrap.js tooltip
enableBSToppltip: true,
BSTooltipSelector: "[data-toggle='tooltip']",
//Enable Fast Click. Fastclick.js creates a more
//native touch experience with touch devices. If you
//choose to enable the plugin, make sure you load the script
//before AdminLTE's app.js
enableFastclick: true,
//Control Sidebar Options
enableControlSidebar: true,
controlSidebarOptions: {
//Which button should trigger the open/close event
toggleBtnSelector: "[data-toggle='control-sidebar']",
//The sidebar selector
selector: ".control-sidebar",
//Enable slide over content
slide: true
},
//Box Widget Plugin. Enable this plugin
//to allow boxes to be collapsed and/or removed
enableBoxWidget: true,
//Box Widget plugin options
boxWidgetOptions: {
boxWidgetIcons: {
//Collapse icon
collapse: 'fa-minus',
//Open icon
open: 'fa-plus',
//Remove icon
remove: 'fa-times'
},
boxWidgetSelectors: {
//Remove button selector
remove: '[data-widget="remove"]',
//Collapse button selector
collapse: '[data-widget="collapse"]'
}
},
//Direct Chat plugin options
directChat: {
//Enable direct chat by default
enable: true,
//The button to open and close the chat contacts pane
contactToggleSelector: '[data-widget="chat-pane-toggle"]'
},
//Define the set of colors to use globally around the website
colors: {
lightBlue: "#3c8dbc",
red: "#f56954",
green: "#00a65a",
aqua: "#00c0ef",
yellow: "#f39c12",
blue: "#0073b7",
navy: "#001F3F",
teal: "#39CCCC",
olive: "#3D9970",
lime: "#01FF70",
orange: "#FF851B",
fuchsia: "#F012BE",
purple: "#8E24AA",
maroon: "#D81B60",
black: "#222222",
gray: "#d2d6de"
},
//The standard screen sizes that bootstrap uses.
//If you change these in the variables.less file, change
//them here too.
screenSizes: {
xs: 480,
sm: 768,
md: 992,
lg: 1200
}
};
/* ------------------
* - Implementation -
* ------------------
* The next block of code implements AdminLTE's
* functions and plugins as specified by the
* options above.
*/
$(function () {
"use strict";
//Fix for IE page transitions
$("body").removeClass("hold-transition");
//Extend options if external options exist
if (typeof AdminLTEOptions !== "undefined") {
$.extend(true,
$.AdminLTE.options,
AdminLTEOptions);
}
//Easy access to options
var o = $.AdminLTE.options;
//Set up the object
_init();
//Activate the layout maker
$.AdminLTE.layout.activate();
//Enable control sidebar
if (o.enableControlSidebar) {
$.AdminLTE.controlSidebar.activate();
}
//Add slimscroll to navbar dropdown
if (o.navbarMenuSlimscroll && typeof $.fn.slimscroll != 'undefined') {
$(".navbar .menu").slimscroll({
height: o.navbarMenuHeight,
alwaysVisible: false,
size: o.navbarMenuSlimscrollWidth
}).css("width", "100%");
}
//Activate Bootstrap tooltip
if (o.enableBSToppltip) {
$('body').tooltip({
selector: o.BSTooltipSelector
});
}
//Activate box widget
if (o.enableBoxWidget) {
$.AdminLTE.boxWidget.activate();
}
//Activate fast click
if (o.enableFastclick && typeof FastClick != 'undefined') {
FastClick.attach(document.body);
}
//Activate direct chat widget
if (o.directChat.enable) {
$(document).on('click', o.directChat.contactToggleSelector, function () {
var box = $(this).parents('.direct-chat').first();
box.toggleClass('direct-chat-contacts-open');
});
}
/*
* INITIALIZE BUTTON TOGGLE
* ------------------------
*/
$('.btn-group[data-toggle="btn-toggle"]').each(function () {
var group = $(this);
$(this).find(".btn").on('click', function (e) {
group.find(".btn.active").removeClass("active");
$(this).addClass("active");
e.preventDefault();
});
});
});
/* ----------------------------------
* - Initialize the AdminLTE Object -
* ----------------------------------
* All AdminLTE functions are implemented below.
*/
function _init() {
'use strict';
/* Layout
* ======
* Fixes the layout height in case min-height fails.
*
* @type Object
* @usage $.AdminLTE.layout.activate()
* $.AdminLTE.layout.fix()
* $.AdminLTE.layout.fixSidebar()
*/
$.AdminLTE.layout = {
activate: function () {
var _this = this;
_this.fix();
_this.fixSidebar();
$(window, ".wrapper").resize(function () {
_this.fix();
_this.fixSidebar();
});
},
fix: function () {
//Get window height and the wrapper height
var neg = $('.main-header').outerHeight() + $('.main-footer').outerHeight();
var window_height = $(window).height();
var sidebar_height = $(".sidebar").height();
//Set the min-height of the content and sidebar based on the
//the height of the document.
if ($("body").hasClass("fixed")) {
$(".content-wrapper, .right-side").css('min-height', window_height - $('.main-footer').outerHeight());
} else {
var postSetWidth;
if (window_height >= sidebar_height) {
$(".content-wrapper, .right-side").css('min-height', window_height - neg);
postSetWidth = window_height - neg;
} else {
$(".content-wrapper, .right-side").css('min-height', sidebar_height);
postSetWidth = sidebar_height;
}
//Fix for the control sidebar height
var controlSidebar = $($.AdminLTE.options.controlSidebarOptions.selector);
if (typeof controlSidebar !== "undefined") {
if (controlSidebar.height() > postSetWidth)
$(".content-wrapper, .right-side").css('min-height', controlSidebar.height());
}
}
},
fixSidebar: function () {
//Make sure the body tag has the .fixed class
if (!$("body").hasClass("fixed")) {
if (typeof $.fn.slimScroll != 'undefined') {
$(".sidebar").slimScroll({destroy: true}).height("auto");
}
return;
} else if (typeof $.fn.slimScroll == 'undefined' && window.console) {
window.console.error("Error: the fixed layout requires the slimscroll plugin!");
}
//Enable slimscroll for fixed layout
if ($.AdminLTE.options.sidebarSlimScroll) {
if (typeof $.fn.slimScroll != 'undefined') {
//Destroy if it exists
$(".sidebar").slimScroll({destroy: true}).height("auto");
//Add slimscroll
$(".sidebar").slimscroll({
height: ($(window).height() - $(".main-header").height()) + "px",
color: "rgba(0,0,0,0.2)",
size: "3px"
});
}
}
}
};
/* ControlSidebar
* ==============
* Adds functionality to the right sidebar
*
* @type Object
* @usage $.AdminLTE.controlSidebar.activate(options)
*/
$.AdminLTE.controlSidebar = {
//instantiate the object
activate: function () {
//Get the object
var _this = this;
//Update options
var o = $.AdminLTE.options.controlSidebarOptions;
//Get the sidebar
var sidebar = $(o.selector);
//The toggle button
var btn = $(o.toggleBtnSelector);
//Listen to the click event
btn.on('click', function (e) {
e.preventDefault();
//If the sidebar is not open
if (!sidebar.hasClass('control-sidebar-open')
&& !$('body').hasClass('control-sidebar-open')) {
//Open the sidebar
_this.open(sidebar, o.slide);
} else {
_this.close(sidebar, o.slide);
}
});
//If the body has a boxed layout, fix the sidebar bg position
var bg = $(".control-sidebar-bg");
_this._fix(bg);
//If the body has a fixed layout, make the control sidebar fixed
if ($('body').hasClass('fixed')) {
_this._fixForFixed(sidebar);
} else {
//If the content height is less than the sidebar's height, force max height
if ($('.content-wrapper, .right-side').height() < sidebar.height()) {
_this._fixForContent(sidebar);
}
}
},
//Open the control sidebar
open: function (sidebar, slide) {
//Slide over content
if (slide) {
sidebar.addClass('control-sidebar-open');
} else {
//Push the content by adding the open class to the body instead
//of the sidebar itself
$('body').addClass('control-sidebar-open');
}
},
//Close the control sidebar
close: function (sidebar, slide) {
if (slide) {
sidebar.removeClass('control-sidebar-open');
} else {
$('body').removeClass('control-sidebar-open');
}
},
_fix: function (sidebar) {
var _this = this;
if ($("body").hasClass('layout-boxed')) {
sidebar.css('position', 'absolute');
sidebar.height($(".wrapper").height());
$(window).resize(function () {
_this._fix(sidebar);
});
} else {
sidebar.css({
'position': 'fixed',
'height': 'auto'
});
}
},
_fixForFixed: function (sidebar) {
sidebar.css({
'position': 'fixed',
'max-height': '100%',
'overflow': 'auto',
'padding-bottom': '50px'
});
},
_fixForContent: function (sidebar) {
$(".content-wrapper, .right-side").css('min-height', sidebar.height());
}
};
/* BoxWidget
* =========
* BoxWidget is a plugin to handle collapsing and
* removing boxes from the screen.
*
* @type Object
* @usage $.AdminLTE.boxWidget.activate()
* Set all your options in the main $.AdminLTE.options object
*/
$.AdminLTE.boxWidget = {
selectors: $.AdminLTE.options.boxWidgetOptions.boxWidgetSelectors,
icons: $.AdminLTE.options.boxWidgetOptions.boxWidgetIcons,
animationSpeed: $.AdminLTE.options.animationSpeed,
activate: function (_box) {
var _this = this;
if (!_box) {
_box = document; // activate all boxes per default
}
//Listen for collapse event triggers
$(_box).on('click', _this.selectors.collapse, function (e) {
e.preventDefault();
_this.collapse($(this));
});
//Listen for remove event triggers
$(_box).on('click', _this.selectors.remove, function (e) {
e.preventDefault();
_this.remove($(this));
});
},
collapse: function (element) {
var _this = this;
//Find the box parent
var box = element.parents(".box").first();
//Find the body and the footer
var box_content = box.find("> .box-body, > .box-footer, > form >.box-body, > form > .box-footer");
if (!box.hasClass("collapsed-box")) {
//Convert minus into plus
element.children(":first")
.removeClass(_this.icons.collapse)
.addClass(_this.icons.open);
//Hide the content
box_content.slideUp(_this.animationSpeed, function () {
box.addClass("collapsed-box");
});
} else {
//Convert plus into minus
element.children(":first")
.removeClass(_this.icons.open)
.addClass(_this.icons.collapse);
//Show the content
box_content.slideDown(_this.animationSpeed, function () {
box.removeClass("collapsed-box");
});
}
},
remove: function (element) {
//Find the box parent
var box = element.parents(".box").first();
box.slideUp(this.animationSpeed);
}
};
}
/* ------------------
* - Custom Plugins -
* ------------------
* All custom plugins are defined below.
*/
/*
* BOX REFRESH BUTTON
* ------------------
* This is a custom plugin to use with the component BOX. It allows you to add
* a refresh button to the box. It converts the box's state to a loading state.
*
* @type plugin
* @usage $("#box-widget").boxRefresh( options );
*/
(function ($) {
"use strict";
$.fn.boxRefresh = function (options) {
// Render options
var settings = $.extend({
//Refresh button selector
trigger: ".refresh-btn",
//File source to be loaded (e.g: ajax/src.php)
source: "",
//Callbacks
onLoadStart: function (box) {
return box;
}, //Right after the button has been clicked
onLoadDone: function (box) {
return box;
} //When the source has been loaded
}, options);
//The overlay
var overlay = $('<div class="overlay"><div class="fa fa-refresh fa-spin"></div></div>');
return this.each(function () {
//if a source is specified
if (settings.source === "") {
if (window.console) {
window.console.log("Please specify a source first - boxRefresh()");
}
return;
}
//the box
var box = $(this);
//the button
var rBtn = box.find(settings.trigger).first();
//On trigger click
rBtn.on('click', function (e) {
e.preventDefault();
//Add loading overlay
start(box);
//Perform ajax call
box.find(".box-body").load(settings.source, function () {
done(box);
});
});
});
function start(box) {
//Add overlay and loading img
box.append(overlay);
settings.onLoadStart.call(box);
}
function done(box) {
//Remove overlay and loading img
box.find(overlay).remove();
settings.onLoadDone.call(box);
}
};
})(jQuery);
/*
* EXPLICIT BOX ACTIVATION
* -----------------------
* This is a custom plugin to use with the component BOX. It allows you to activate
* a box inserted in the DOM after the app.js was loaded.
*
* @type plugin
* @usage $("#box-widget").activateBox();
*/
(function ($) {
'use strict';
$.fn.activateBox = function () {
$.AdminLTE.boxWidget.activate(this);
};
})(jQuery);
/*
* TODO LIST CUSTOM PLUGIN
* -----------------------
* This plugin depends on iCheck plugin for checkbox and radio inputs
*
* @type plugin
* @usage $("#todo-widget").todolist( options );
*/
(function ($) {
'use strict';
$.fn.todolist = function (options) {
// Render options
var settings = $.extend({
//When the user checks the input
onCheck: function (ele) {
return ele;
},
//When the user unchecks the input
onUncheck: function (ele) {
return ele;
}
}, options);
return this.each(function () {
if (typeof $.fn.iCheck != 'undefined') {
$('input', this).on('ifChecked', function () {
var ele = $(this).parents("li").first();
ele.toggleClass("done");
settings.onCheck.call(ele);
});
$('input', this).on('ifUnchecked', function () {
var ele = $(this).parents("li").first();
ele.toggleClass("done");
settings.onUncheck.call(ele);
});
} else {
$('input', this).on('change', function () {
var ele = $(this).parents("li").first();
ele.toggleClass("done");
if ($('input', ele).is(":checked")) {
settings.onCheck.call(ele);
} else {
settings.onUncheck.call(ele);
}
});
}
});
};
}(jQuery)); |
//flow.js
module.exports = function (less) {
var checkArg = require("./argumentChecker");
var True = less.tree.Keyword.True,
False = less.tree.Keyword.False,
Quoted = less.tree.Quoted;
function getFunction(funcName) {
return less.functions.functionRegistry.get(funcName.value);
}
function getListValue(maybeList) {
var value = Array.isArray(maybeList.value) ?
maybeList.value : Array(maybeList);
return value;
}
return {
isfunction: function (funcName) {
if (checkArg(funcName, Quoted)) {
return !!getFunction(funcName) ? True : False;
}
else {
throw {
type: "Argument",
message: "isfunction(arg): requires a string argument"
};
}
},
type: function (node) {
if (node) {
return new Quoted('"' + node.type + '"', node.type, false);
}
else {
throw {
type: "Argument",
message: "type(arg): requires an argument"
}
}
},
call: function (funcName /*args, args, args*/) {
if (checkArg(funcName, Quoted)) {
var func = getFunction(funcName);
var args = Array.prototype.slice.call(arguments, 1);
if (func) {
return func.apply(null, args);
}
else {
throw {
type: "Argument",
message: "call(): function argument is not registered"
}
}
}
else {
throw {
type: "Argument",
message: "call(): function name must be string"
}
}
},
apply: function (funcName, list) {
if (checkArg(funcName, Quoted)) {
var func = getFunction(funcName);
var args = getListValue(list);
if (func) {
return func.apply(null, args);
}
else {
throw {
type: "Argument",
message: "apply(): function argument is not registered"
}
}
}
else {
throw {
type: "Argument",
message: "apply(): function name must be string"
}
}
},
if: function (isTrue, left, right) {
if (arguments.length < 3) {
throw {
type: "Argument",
message: "if(): requires at least 3 arguments"
}
}
else if (isTrue.type === True.type && isTrue.value === True.value) {
return left;
}
else {
return right;
}
}
};
};
|
import AuthenticatedRoute from 'ghost/routes/authenticated';
import CurrentUserSettings from 'ghost/mixins/current-user-settings';
import PaginationRouteMixin from 'ghost/mixins/pagination-route';
var TagsRoute,
paginationSettings;
paginationSettings = {
page: 1,
include: 'post_count',
limit: 15
};
TagsRoute = AuthenticatedRoute.extend(CurrentUserSettings, PaginationRouteMixin, {
titleToken: '设置 - 标签管理',
beforeModel: function (transition) {
this._super(transition);
return this.get('session.user')
.then(this.transitionAuthor());
},
model: function () {
this.store.unloadAll('tag');
return this.store.filter('tag', paginationSettings, function (tag) {
return !tag.get('isNew');
});
},
setupController: function (controller, model) {
this._super(controller, model);
this.setupPagination(paginationSettings);
},
renderTemplate: function (controller, model) {
this._super(controller, model);
this.render('settings/tags/settings-menu', {
into: 'application',
outlet: 'settings-menu'
});
},
deactivate: function () {
this.controller.send('resetPagination');
}
});
export default TagsRoute;
|
/*!
* jQuery scrolldeck plugin
* Original author: @paulvonschrottky
* Further changes, comments: @paulvonschrottky
* Licensed under the MIT license
*
* This plugin depends on the great jquery.mousewheel.min.js plugin found at
* https://plugins.jquery.com/mousewheel/
*
* A jQuery plugin to produce a scroll deck similar to 'http://bradywilliams.co/'.
* The idea is that instead of scrolling vertically through a tall website, each
* page slides up from the bottom of the screen and 'docks' on top of the
* previous page.
*
* Create pages like this and call this function in document ready, that's all.
*
* <div class="page">Page 1</div>
* <div class="page">Page 2</div>
* <div class="page">Page 3</div>
*
*/
;(function($) {
$.fn.scrolldeck = function(options) {
// Defaults.
var pluginName,
settings = $.extend({
debug: false,
}, options);
// Hide scrollbars caused by offscreen pages.
$('body').css({
'overflow' : 'hidden',
'margin' : '0',
});
// Add our CSS to the pages.
this.css({
'position': 'absolute',
'width': '100%',
'height': '100%',
});
// Mark the first page as the current page (i.e. the page that is filling up the entire screen).
this.first().addClass('current');
// Hide beneath the bottom of the screen all pages except for the first.
this.not('.current').each(function (index, page) {
$(page).offset({
top: window.innerHeight,
left: 0,
});
});
// Add a scroll listener to the pages so we know when the user scrolls and so
// we can slide the pages up (or down).
var pages = this; // A reference to the pages.
this.on('mousewheel', function(event) {
if (settings.debug) {
console.log(event.deltaX, event.deltaY, event.deltaFactor);
}
// Get the next page to be displayed and its current y position.
var nextPage = $(pages).filter('.current').next();
var nextPageY = $(nextPage).offset().top;
// If the new position would be off the top of the screen, snap the page to the top of the screen.
// Else, if the new position would be past the bottom of the screen, snap the page to the bottom of the screen.
var newNextPageY = nextPageY + event.deltaY * event.deltaFactor;
if (newNextPageY < 0) {
newNextPageY = 0;
// Also, mark the next page as the current page.
if ($(nextPage).is(':last-of-type') == false) {
$(nextPage).prev().removeClass('current');
$(nextPage).addClass('current');
}
} else if (newNextPageY > window.innerHeight) {
newNextPageY = window.innerHeight;
// Also, mark the previous page as the current page.
if ($(nextPage).prev().is(':first-of-type') == false) {
$(nextPage).prev().removeClass('current');
$(nextPage).prev().prev().addClass('current');
}
}
// Scroll the next page up by the user's scrolling distance.
$(nextPage).offset({
top: newNextPageY,
left: 0,
});
});
};
}(jQuery));
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.csUnflip = csUnflip;
var _csFlip = require("./csFlip");
function csUnflip(i) {
// flip the value if it is negative
return i < 0 ? (0, _csFlip.csFlip)(i) : i;
} |
for(let i = 1;i<=7;i++){
for(let j = 1;j<=i;j++)
process.stdout.write('#');
process.stdout.write('\n\t');
}
|
'use strict';
var redux = require('./redux.js');
function thunk (store) {
return function (dispatch) {
return function (action) {
if (typeof action === 'function') {
return action(store.dispatch, store.getState);
}
return dispatch(action);
}
}
}
var createStoreSubstitute = redux.applyMiddleware(
thunk
)(redux.createStore);
function reducer (state, action) {
if (action.type === 'one') return 'one';
return 'none';
}
function actionCreator () { return { type:'two' }; }
var store = createStoreSubstitute(reducer, 'start');
function asyncStuff (item) {
return function (dispatch,getState) {
process.nextTick(function () {
dispatch(actionCreator);
});
};
}
store.dispatch(asyncStuff());
console.log(store.getState());
// -> 'start'
process.nextTick(() => {
console.log(store.getState());
// -> 'none'
});
|
import UAlert from './UAlert'
export {
UAlert
}
|
version https://git-lfs.github.com/spec/v1
oid sha256:a745fd15eddb892ba2c09bf54fda941ffbd65373190f5fa20ad70e390d5f1d44
size 65441
|
'use strict';
const roundRobin = require('../../lib/assignment/roundrobin');
const _ = require('lodash');
const should = require('should');
describe('Round Robin Assignment', function () {
const topicPartition = {
'RebalanceTopic': [
'0',
'1',
'2'
],
'RebalanceTest': [
'0',
'1',
'2'
]
};
it('should have required fields', function () {
roundRobin.should.have.property('assign').which.is.a.Function;
roundRobin.name.should.be.eql('roundrobin');
roundRobin.version.should.be.eql(0);
});
it('should distribute two topics three partitions to two consumers ', function (done) {
const groupMembers = [
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer1'
},
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer2'
}
];
roundRobin.assign(topicPartition, groupMembers, function (error, assignment) {
should(error).be.empty;
const consumer1 = _.head(assignment);
consumer1.memberId.should.eql('consumer1');
Object.keys(consumer1.topicPartitions).should.eql(['RebalanceTopic', 'RebalanceTest']);
consumer1.topicPartitions['RebalanceTest'].should.eql(['1']);
consumer1.topicPartitions['RebalanceTopic'].should.eql(['0', '2']);
const consumer2 = _.last(assignment);
consumer2.memberId.should.eql('consumer2');
Object.keys(consumer2.topicPartitions).should.eql(['RebalanceTopic', 'RebalanceTest']);
consumer2.topicPartitions['RebalanceTest'].should.eql(['0', '2']);
consumer2.topicPartitions['RebalanceTopic'].should.eql(['1']);
done();
});
});
it('should distribute two topics three partitions to three consumers', function (done) {
const groupMembers = [
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer1'
},
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer3'
},
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer2'
}
];
roundRobin.assign(topicPartition, groupMembers, function (error, assignment) {
should(error).be.empty;
assignment = _.sortBy(assignment, 'memberId');
const consumer1 = _.head(assignment);
consumer1.memberId.should.eql('consumer1');
Object.keys(consumer1.topicPartitions).should.eql(['RebalanceTopic', 'RebalanceTest']);
consumer1.topicPartitions['RebalanceTest'].should.eql(['0']);
consumer1.topicPartitions['RebalanceTopic'].should.eql(['0']);
const consumer2 = assignment[1];
consumer2.memberId.should.eql('consumer2');
Object.keys(consumer2.topicPartitions).should.eql(['RebalanceTopic', 'RebalanceTest']);
consumer2.topicPartitions['RebalanceTest'].should.eql(['1']);
consumer2.topicPartitions['RebalanceTopic'].should.eql(['1']);
const consumer3 = _.last(assignment);
consumer3.memberId.should.eql('consumer3');
Object.keys(consumer3.topicPartitions).should.eql(['RebalanceTopic', 'RebalanceTest']);
consumer3.topicPartitions['RebalanceTest'].should.eql(['2']);
consumer3.topicPartitions['RebalanceTopic'].should.eql(['2']);
done();
});
});
it('should distribute two topics three partitions to four consumers', function (done) {
const groupMembers = [
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer1'
},
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer3'
},
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer2'
},
{
'subscription': [
'RebalanceTopic',
'RebalanceTest'
],
'version': 0,
'id': 'consumer4'
}
];
roundRobin.assign(topicPartition, groupMembers, function (error, assignment) {
should(error).be.empty;
assignment = _.sortBy(assignment, 'memberId');
const consumer1 = _.head(assignment);
consumer1.memberId.should.eql('consumer1');
Object.keys(consumer1.topicPartitions).should.eql(['RebalanceTopic', 'RebalanceTest']);
consumer1.topicPartitions['RebalanceTest'].should.eql(['1']);
consumer1.topicPartitions['RebalanceTopic'].should.eql(['0']);
const consumer2 = assignment[1];
consumer2.memberId.should.eql('consumer2');
Object.keys(consumer2.topicPartitions).should.eql(['RebalanceTopic', 'RebalanceTest']);
consumer2.topicPartitions['RebalanceTest'].should.eql(['2']);
consumer2.topicPartitions['RebalanceTopic'].should.eql(['1']);
const consumer3 = assignment[2];
consumer3.memberId.should.eql('consumer3');
Object.keys(consumer3.topicPartitions).should.eql(['RebalanceTopic']);
consumer3.topicPartitions['RebalanceTopic'].should.eql(['2']);
const consumer4 = _.last(assignment);
consumer4.memberId.should.eql('consumer4');
Object.keys(consumer4.topicPartitions).should.eql(['RebalanceTest']);
done();
});
});
});
|
import {Task} from '../../../src/models/Task';
describe('the Task', () => {
var task;
describe('no default values', () => {
beforeEach(() => {
task = new Task();
});
it('has empty title', () => {
expect(task.title).toBe('');
});
it('has empty category', () => {
expect(task.category).toBe('');
});
it('has no start time', () => {
expect(task.startTime).toBeUndefined();
});
});
describe('with default values', () => {
beforeEach(() => {
task = new Task('default', 'values');
});
it('has a default title', () => {
expect(task.title).toBe('default');
});
it('has a default category', () => {
expect(task.category).toBe('values');
});
});
describe('when starting a task', () => {
var startTime;
beforeEach(() => {
var oldDate = Date;
spyOn(window, 'Date').and.callFake(() => {
startTime = new oldDate('2015-01-01 00:00:00');
return startTime;
});
task = new Task('Starting task', 'Starters');
task.start();
});
it('has a start time', () => {
expect(task.startTime).toBeDefined();
expect(task.startTime).toBe(startTime);
});
});
describe('when stopping a task', () => {
var startTime, stopTime;
beforeEach(() => {
var oldDate = Date;
spyOn(window, 'Date').and.callFake(() => {
stopTime = new oldDate('2015-01-01 01:00:00');
startTime = new oldDate('2015-01-01 00:00:00');
return stopTime;
});
task = new Task('Stopping task', 'Stoppers');
task.startTime = startTime;
task.stop();
});
it('has a stop time', () => {
expect(task.stopTime).toBeDefined();
expect(task.stopTime).toBe(stopTime);
});
it('has a duration', () => {
expect(task.duration).toBeDefined();
expect(task.duration).toBe(3600);
});
it('is finished', () => {
expect(task.isFinished).toBe(true);
});
});
describe('when task is running', () => {
beforeEach(() => {
var oldDate = Date;
spyOn(window, 'Date').and.callFake(() => {
return new oldDate('2015-01-01 00:01:00:001');
});
task = new Task('Running task');
task.startTime = new oldDate('2015-01-01 00:00:00');
});
it('has a duration', () => {
expect(task.duration).toBe(60);
});
it('is not finished', () => {
expect(task.isFinished).toBe(false);
});
});
describe('when using the parsing function', () => {
var task;
beforeEach(() => {
var taskProperties = {
'id': "2964248c-84a8-40dd-a55d-bddad68bc11a",
'title': 'Title',
'category': 'Category',
'startTime': new Date('2015-01-01 00:00:00'),
'stopTime': new Date('2015-01-01 01:00:00').toISOString()
};
task = Task.parse(taskProperties);
});
it('sets the correct ID', () => {
expect(task.id).toBe("2964248c-84a8-40dd-a55d-bddad68bc11a");
});
it('sets the correct title', () => {
expect(task.title).toBe('Title');
});
it('sets the correct category', () => {
expect(task.category).toBe('Category');
});
it('sets the correct start time', () => {
expect(task.startTime.toISOString()).toBe(new Date('2015-01-01 00:00:00').toISOString());
});
it('sets the correct stop time', () => {
expect(task.stopTime.toISOString()).toBe(new Date('2015-01-01 01:00:00').toISOString());
});
});
}); |
import NumberValidator from './-base';
export default NumberValidator.extend({
validationKey: 'gte'
});
|
/*
* mimesis,
* Boostrap da Aplicacao
*
* https://github.com/cleberar/mimesis
*
* Copyright (c) 2013 Cleber Rodrigues
* Licensed under the MIT license.
*/
var util = require('util');
var verbose = false;
// obtendo agrumentos passados por linha de comando
var args = process.argv.slice(2);
args.forEach(function (argument) {
if (argument == "--verbose") {
verbose = true;
}
});
// gerenciamento de entrada de dados
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (text) {
console.log('Digite quit para sair, ou pressione CRTL + C');
// se foi digitado quit, para o processo
if (text === 'quit\n' || text === 'quit\r\n') {
console.log('\nhasta la vista baby');
process.exit();
}
});
console.log('Para parar pressione (Enter) e digite quit para sair, ou pressione CRTL + C');
console.log("\n\n");
var mimesis = require('./mimesis.js');
mimesis.loading(verbose); |
let i = "I1";
let k = "K1";
global.i = "GI";
global.j = "GJ";
global.k = "GK";
(function() {
let j = "J1";
{
let i = "I2";
eval(`let j = "J2";
k += "+1";
debugger;
k += "-1";
console.log(i, j, k, this);`);
}
(0, eval)(`let j = "J3";
k += "+2";
debugger;
k += "-2";
console.log(i, j);`);
new Function(
"j",
`let i = "I3";
k += "+3";
debugger;
k += "-3";
console.log(i, j, k, this);`
).call(this, "JF");
(function(k) {
eval(`let j = "J4";
debugger;
console.log(i, j, k, this);`);
(0, eval)(`let j = "J5";
debugger;
console.log(i, j, k)`);
}.call(this, "KL"));
}.call({ obj: "OBJ" }));
|
'use strict';
angular.module('bestInBlackApp')
.config(['$stateProvider', function ($stateProvider) {
$stateProvider
.state('login', {
url: '/login',
templateUrl: 'app/account/login/login.html',
controller: 'LoginCtrl'
})
.state('signup', {
url: '/signup',
templateUrl: 'app/account/signup/signup.html',
controller: 'SignupCtrl'
})
.state('settings', {
url: '/settings',
templateUrl: 'app/account/settings/settings.html',
controller: 'SettingsCtrl',
authenticate: true
});
}]);
|
var userTable = mysqlcrud.table('user', {/*options*/});
// Destroy data.
userTable.destroy(3, function (err, result) {
/**...**/
}); |
jui.defineUI("ui.autocomplete", [ "jquery", "util.base", "ui.dropdown" ], function($, _, dropdown) {
/**
* @class ui.autocomplete
* Auto complete component that shows a list of keywords containing the input value when inputting a string in a text box
*
* @extends core
* @requires jquery
* @requires util.base
* @requires ui.dropdown
*/
var UI = function() {
var ddUi = null, target = null,
words = [], list = [];
function createDropdown(self, words) {
if(words.length == 0) {
if(ddUi) ddUi.hide();
return;
} else {
if(ddUi) $(ddUi.root).remove();
}
var pos = $(self.root).offset(),
$ddObj = $(self.tpl.words({ words: words }));
$("body").append($ddObj);
ddUi = dropdown($ddObj, {
keydown: true,
width: $(self.root).outerWidth(),
left: pos.left,
top: pos.top + $(self.root).outerHeight(),
event: {
change: function(data, e) {
$(target).val(data.text);
self.emit("change", [ data.text, e ]);
}
}
});
ddUi.show();
}
function getFilteredWords(word) {
var result = [];
if(word != "") {
for(var i = 0; i < words.length; i++) {
var origin = words[i],
a = words[i].toLowerCase(),
b = word.toLowerCase();
if(a.indexOf(b) != -1) {
result.push(origin);
}
}
}
return result;
}
function setEventKeyup(self) {
self.addEvent(target, "keyup", function(e) {
if(e.which == 38 || e.which == 40 || e.which == 13) return;
list = getFilteredWords($(this).val());
createDropdown(self, list);
return false;
});
}
this.init = function() {
var opts = this.options;
// 타겟 엘리먼트 설정
target = (opts.target == null) ? this.root : $(this.root).find(opts.target);
// 키-업 이벤트 설정
setEventKeyup(this);
// 단어 업데이트
this.update(opts.words);
}
/**
* @method update
* Updates words subject to autofill
*
* @param {Array} words
*/
this.update = function(newWords) {
words = newWords;
}
/**
* @method close
* Close the active drop-down
*
*/
this.close = function() {
if(ddUi) ddUi.hide();
}
/**
* @method list
* Gets filtered words subject to autofill
*
* @return {Array} words
*/
this.list = function() {
return list;
}
}
UI.setup = function() {
return {
/**
* @cfg {String/DOMElement} [target=null]
* Designates a target selector when an autofill route is not a target
*/
target: null,
/**
* @cfg {Array} words
* Designates words subject to autofill
*/
words: []
}
}
/**
* @event change
* Event that occurs when you click on a dropdown that shows a word list
*
* @param {String} word Changed word
*/
return UI;
}); |
'use strict';
/* jshint mocha:true, expr:true */
var expect = require('chai').expect;
describe('Asset', function () {
var Asset = require('./asset');
function noop() {
// Do nothing...
}
it('is accessible', function () {
expect(Asset).to.be.defined;
});
it('is a constructor', function () {
expect(Asset).to.be.a('function');
expect (new Asset('foo/bar/baz.ext')).to.be.instanceOf(Asset);
});
describe('constructor', function () {
it('throws if no path is provided', function () {
function initWithoutPath() {
return new Asset();
}
expect(initWithoutPath).to.throw;
});
});
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////
describe('instance', function () {
var asset;
function runCallbackSuccess(r, cb) {
if (arguments.length === 1) {
cb = r;
}
cb(null, true);
}
function runCallbackError(r, cb) {
if (arguments.length === 1) {
cb = r;
}
cb(new Error('FAIL'));
}
beforeEach(function () {
asset = new Asset('some/path.ext');
asset._load = runCallbackSuccess;
asset._install = runCallbackSuccess;
asset._uninstall = runCallbackSuccess;
asset._unload = runCallbackSuccess;
});
it('is an Asset', function () {
expect(asset).to.be.instanceOf(Asset);
});
it('is an EventEmitter', function () {
var EventEmitter = require('eventemitter2').EventEmitter2;
expect(asset).to.be.instanceOf(EventEmitter);
});
////////////////////////////////////////////////////////////////////////////
describe('#isLoaded()', function () {
it('is a function', function () {
expect(asset.isLoaded).to.be.a('function');
});
it('returns false if not loaded', function () {
expect(asset.isLoaded()).to.be.false;
});
it('returns true if loaded', function (done) {
expect(asset.isLoaded()).to.be.false;
asset.load(function (err) {
if (!err) {
expect(asset.isLoaded()).to.be.true;
}
done(err);
});
});
it('returns false if failed to load', function (done) {
asset._load = runCallbackError;
// Just to prevent the 'error' event special case
asset.on('error', noop);
expect(asset.isLoaded()).to.be.false;
asset.load(function (err) {
expect(err).to.be.defined;
expect(err.message).to.equal('FAIL');
done();
});
});
it('returns false while loading', function (done) {
expect(asset.isLoaded(), 'Not loaded at start').to.be.false;
asset.load(done);
expect(asset.isLoading(), 'Loading').to.be.true;
expect(asset.isLoaded(), 'Not loaded while loading').to.be.false;
});
}); // #isLoaded()
////////////////////////////////////////////////////////////////////////////
describe('#isLoading()', function () {
it('is a function', function () {
expect(asset.isLoading).to.be.a('function');
});
it('returns true while loading', function (done) {
expect(asset.isLoading()).to.be.false;
asset.load(done);
expect(asset.isLoading()).to.be.true;
});
it('returns false before load starts', function () {
expect(asset.isLoaded()).to.be.false;
expect(asset.isLoading()).to.be.false;
});
it('returns false after the asset is loaded', function (done) {
expect(asset.isLoading()).to.be.false;
asset.load(function () {
expect(asset.isLoaded()).to.be.true;
expect(asset.isLoading()).to.be.false;
done();
});
});
it('returns false after failing to load', function (done) {
asset._load = runCallbackError;
asset.on('error', noop);
expect(asset.isLoading()).to.be.false;
asset.load(function (err) {
expect(err).to.not.be.null;
expect(asset.isLoading()).to.be.false;
done();
});
});
}); // #isLoading()
////////////////////////////////////////////////////////////////////////////
describe('#isUnloading()', function () {
beforeEach(function (done) {
asset.load(done);
});
it('is a function', function () {
expect(asset.isUnloading).to.be.a('function');
});
it('returns true while unloading', function (done) {
expect(asset.isUnloading()).to.be.false;
asset.unload(done);
expect(asset.isUnloading()).to.be.true;
});
it('returns false before unload starts');
it('returns false if content is not loaded');
it('returns false when unloaded');
}); // #isUnloading()
////////////////////////////////////////////////////////////////////////////
describe('#isInstalling()', function () {
it('is a function');
it('returns true while installing');
it('returns false before installation starts');
it('returns false when installed');
it('returns false if not installed');
}); // #isInstalling()
////////////////////////////////////////////////////////////////////////////
describe('#isInstalled()', function () {
it('is a function');
it('returns true if installed');
it('returns false if not installed');
}); // #isInstalled()
////////////////////////////////////////////////////////////////////////////
describe('#isUninstalling()', function () {
it('is a function');
it('returns true while uninstalling');
it('returns false before uninstall starts');
it('returns false when uninstalled');
}); // #isUninstalling()
////////////////////////////////////////////////////////////////////////////
describe('#load()', function () {
it('is a function');
}); // #load()
////////////////////////////////////////////////////////////////////////////
describe('#unload()', function () {
it('is a function');
}); // #unload()
////////////////////////////////////////////////////////////////////////////
describe('#install()', function () {
it('is a function');
}); // #install()
////////////////////////////////////////////////////////////////////////////
describe('#uninstall()', function () {
it('is a function');
}); // #uninstall()
////////////////////////////////////////////////////////////////////////////
describe('#unload()', function () {
it('is a function');
}); // #unload()
});
}); |
var server = require('webserver').create(),
system = require('system'),
fs = require('fs'),
port = system.env.PORT || 23156;
var service = server.listen(port, function(request, response) {
if (request.method == 'POST' && request.post.url) {
var url = request.post.url;
var formdata = request.post.formdata;
if (formdata != undefined) {
post_page(url, formdata, function(properties) {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.write(properties)
response.close();
})
} else {
request_page(url, function(properties) {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.write(properties)
response.close();
})
}
} else {
response.statusCode = 200;
response.setHeader('Content-Type', 'text/html; charset=utf-8');
response.write(fs.read('index.html'));
response.close();
}
});
if (service) console.log("server started - http://localhost:" + server.port);
function request_page(url, callback) {
var page = new WebPage();
page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36';
page.settings.resourceTimeout = 10000
page.onLoadStarted = function() {
console.log('loading:' + url);
};
page.onLoadFinished = function(status) {
console.log('loaded:' + url);
setTimeout(function() {
callback(page.content);
page.close();
}, 2000) //时间太短的话会出现渲染不出来的情况
};
page.open(url);
}
function post_page(url, fdata, callback) {
console.log("post page")
var page = new WebPage();
page.settings.userAgent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36';
page.settings.resourceTimeout = 10000
page.onLoadStarted = function() {
console.log('loading:' + url);
};
page.onLoadFinished = function(status) {
console.log('loaded:' + url);
setTimeout(function() {
callback(page.content);
page.close();
}, 2000) //时间太短的话会出现渲染不出来的情况
};
// page.open(url, 'post', data);
page.open(url,'post',fdata)
}
|
var expect = require('chai').expect
var setStatus = require('../../src/control/set_status')
var StreamTest = require('streamtest')
describe('set_target', () => {
StreamTest.versions.forEach(function (version) {
describe('for ' + version + ' streams', function () {
it('Should set file status', (done) => {
StreamTest[version].fromObjects([{
file: 'file',
doc: {
files: {}
},
status: 'status',
machine: 'machine'
}]).pipe(setStatus()).pipe(StreamTest[version].toObjects((error, objects) => {
expect(objects).to.containSubset([{
doc: {
files: {
machine: {
file: 'status'
}
}
}
}])
done(error)
}))
})
})
})
})
|
/*
* MelonJS Game Engine
* Copyright (C) 2011 - 2014 Olivier Biot, Jason Oster, Aaron McLeod
* http://www.melonjs.org
*
* a simple debug panel plugin
* usage : me.plugin.register(debugPanel, "debug");
*
* you can then use me.plugin.debug.show() or me.plugin.debug.hide()
* to show or hide the panel, or press respectively the "S" and "H" keys.
*
* note :
* Heap Memory information is available under Chrome when using
* the "--enable-memory-info" parameter to launch Chrome
*/
(function($) {
// ensure that me.debug is defined
me.debug = me.debug || {};
/**
* @class
* @public
* @extends me.plugin.Base
* @memberOf me
* @constructor
*/
debugPanel = me.plugin.Base.extend(
/** @scope me.debug.Panel.prototype */
{
/** @private */
init : function(showKey, hideKey) {
// call the super constructor
this._super(me.plugin.Base, 'init');
// minimum melonJS version expected
this.version = "1.1.0";
// to hold the debug options
// clickable rect area
this.area = {};
// panel position and size
this.rect = null;
// for z ordering
// make it ridiculously high
this.z = Infinity;
// visibility flag
this.visible = false;
// frame update time in ms
this.frameUpdateTime = 0;
// frame draw time in ms
this.frameDrawTime = 0;
this.rect = new me.Rect(0, 0, me.video.renderer.getWidth(), 35);
// set the object GUID value
this.GUID = "debug-" + me.utils.createGUID();
// set the object entity name
this.name = "me.debugPanel";
// persistent
this.isPersistent = true;
// a floating object
this.floating = true;
// renderable
this.isRenderable = true;
// always update, even when not visible
this.alwaysUpdate = true;
// create a default font, with fixed char width
var s = 10;
this.mod = 1;
if(me.game.viewport.width < 500) {
s = 7;
this.mod = 0.7;
}
this.font = new me.Font('courier', s, 'white');
// clickable areas
this.area.renderHitBox = new me.Rect(160,5,15,15);
this.area.renderVelocity = new me.Rect(165,18,15,15);
this.area.renderQuadTree = new me.Rect(270,5,15,15);
//this.area.renderCollisionMap = new me.Rect(270,18,15,15);
// some internal string/length
this.help_str = "(s)how/(h)ide";
this.help_str_len = this.font.measureText(me.video.renderer.getContext(), this.help_str).width;
this.fps_str_len = this.font.measureText(me.video.renderer.getContext(), "00/00 fps").width;
this.memoryPositionX = this.font.measureText(me.video.renderer.getContext(), "Draw : ").width * 2.2 + 310 * this.mod;
// enable the FPS counter
me.debug.displayFPS = true;
// bind the "S" and "H" keys
me.input.bindKey(showKey || me.input.KEY.S, "show", false, false);
me.input.bindKey(hideKey || me.input.KEY.H, "hide", false, false);
// add some keyboard shortcuts
var self = this;
this.keyHandler = me.event.subscribe(me.event.KEYDOWN, function (action, keyCode, edge) {
if (action === "show") {
self.show();
} else if (action === "hide") {
self.hide();
}
});
// memory heap sample points
this.samples = [];
//patch patch patch !
this.patchSystemFn();
// make it visible
this.show();
},
/**
* patch system fn to draw debug information
*/
patchSystemFn : function() {
// add a few new debug flag (if not yet defined)
me.debug.renderHitBox = me.debug.renderHitBox || false;
me.debug.renderVelocity = me.debug.renderVelocity || false;
me.debug.renderQuadTree = me.debug.renderQuadTree || false;
var _this = this;
// patch timer.js
me.plugin.patch(me.timer, "update", function (time) {
// call the original me.timer.update function
this._patched(time);
// call the FPS counter
me.timer.countFPS();
});
// patch me.game.update
me.plugin.patch(me.game, 'update', function(time) {
var frameUpdateStartTime = window.performance.now();
this._patched(time);
// calculate the update time
_this.frameUpdateTime = window.performance.now() - frameUpdateStartTime;
});
// patch me.game.draw
me.plugin.patch(me.game, 'draw', function() {
var frameDrawStartTime = window.performance.now();
this._patched();
// calculate the drawing time
_this.frameDrawTime = window.performance.now() - frameDrawStartTime;
});
// patch sprite.js
me.plugin.patch(me.Sprite, "draw", function (renderer) {
// call the original me.Sprite function
this._patched(renderer);
// draw the sprite rectangle
if (me.debug.renderHitBox) {
renderer.strokeRect(this.left, this.top, this.width, this.height, "green");
}
});
// patch entities.js
me.plugin.patch(me.Entity, "draw", function (renderer) {
// call the original me.game.draw function
this._patched(renderer);
// check if debug mode is enabled
if (me.debug.renderHitBox) {
renderer.save();
// draw the bounding rect shape
this.getBounds().draw(renderer, "orange");
renderer.translate(this.pos.x, this.pos.y);
if (this.body.shapes.length) {
// TODO : support multiple shapes
this.body.getShape().draw(renderer, "red");
}
renderer.restore();
}
if (me.debug.renderVelocity) {
// draw entity current velocity
var x = ~~(this.pos.x + this.hWidth);
var y = ~~(this.pos.y + this.hHeight);
// TODO: This will also be tricky for WebGL.
var context = renderer.getContext();
context.strokeStyle = "blue";
context.lineWidth = 1;
context.beginPath();
context.moveTo(x, y);
context.lineTo(
x + ~~(this.body.vel.x * this.hWidth),
y + ~~(this.body.vel.y * this.hHeight)
);
context.stroke();
}
});
},
/**
* show the debug panel
*/
show : function() {
if (!this.visible) {
// register a mouse event for the checkboxes
me.input.registerPointerEvent('pointerdown', this.rect, this.onClick.bind(this), true);
// add the debug panel to the game world
me.game.world.addChild(this, Infinity);
// mark it as visible
this.visible = true;
}
},
/**
* hide the debug panel
*/
hide : function() {
if (this.visible) {
// release the mouse event for the checkboxes
me.input.releasePointerEvent('pointerdown', this.rect);
// remove the debug panel from the game world
me.game.world.removeChild(this);
// mark it as invisible
this.visible = false;
}
},
/** @private */
update : function() {
if (me.input.isKeyPressed('show')) {
this.show();
}
else if (me.input.isKeyPressed('hide')) {
this.hide();
}
return true;
},
/**
* @private
*/
getBounds : function() {
return this.rect;
},
/** @private */
onClick : function(e) {
// check the clickable areas
if (this.area.renderHitBox.containsPoint(e.gameX, e.gameY)) {
me.debug.renderHitBox = !me.debug.renderHitBox;
}
else if (this.area.renderVelocity.containsPoint(e.gameX, e.gameY)) {
// does nothing for now, since velocity is
// rendered together with hitboxes (is a global debug flag required?)
me.debug.renderVelocity = !me.debug.renderVelocity;
}
else if (this.area.renderQuadTree.containsPoint(e.gameX, e.gameY)) {
me.debug.renderQuadTree = !me.debug.renderQuadTree;
}
// force repaint
me.game.repaint();
},
/** @private */
drawQuadTreeNode : function (renderer, node) {
var bounds = node.bounds;
// draw the current bounds
if( node.nodes.length === 0) {
// cap the alpha value to 0.4 maximum
var _alpha = (node.objects.length * 0.4) / me.collision.maxChildren;
if (_alpha > 0.0) {
renderer.setGlobalAlpha(_alpha);
renderer.fillRect(bounds.pos.x, bounds.pos.y, bounds.width, bounds.height, "red");
}
} else {
//has subnodes? drawQuadtree them!
for( var i=0;i<node.nodes.length;i=i+1 ) {
this.drawQuadTreeNode( renderer, node.nodes[ i ] );
}
}
},
/** @private */
drawQuadTree : function (renderer) {
// save the current globalAlpha value
var _alpha = renderer.globalAlpha();
renderer.translate(-me.game.viewport.pos.x, -me.game.viewport.pos.y);
this.drawQuadTreeNode(renderer, me.collision.quadTree);
renderer.translate(me.game.viewport.pos.x, me.game.viewport.pos.y);
renderer.setGlobalAlpha(_alpha);
},
/** @private */
drawMemoryGraph : function (renderer, endX) {
if (window.performance && window.performance.memory) {
var context = renderer.getContext();
var usedHeap = Number.prototype.round(window.performance.memory.usedJSHeapSize/1048576, 2);
var totalHeap = Number.prototype.round(window.performance.memory.totalJSHeapSize/1048576, 2);
var len = endX - this.memoryPositionX;
// remove the first item
this.samples.shift();
// add a new sample (25 is the height of the graph)
this.samples[len] = (usedHeap / totalHeap) * 25;
// draw the graph
for (var x = len; x >= 0; x--) {
var where = endX - (len - x);
context.beginPath();
context.strokeStyle = "lightblue";
context.moveTo(where, 30 * this.mod);
context.lineTo(where, (30 - (this.samples[x] || 0)) * this.mod);
context.stroke();
}
// display the current value
this.font.draw(context, "Heap : " + usedHeap + '/' + totalHeap + ' MB', this.memoryPositionX, 5 * this.mod);
} else {
// Heap Memory information not available
this.font.draw(renderer.getContext(), "Heap : ??/?? MB", this.memoryPositionX, 5 * this.mod);
}
},
/** @private */
draw : function(renderer) {
renderer.save();
// draw the QuadTree (before the panel)
if (me.debug.renderQuadTree === true) {
this.drawQuadTree(renderer);
}
// draw the panel
renderer.setGlobalAlpha(0.5);
renderer.fillRect(this.rect.left, this.rect.top,
this.rect.width, this.rect.height, "black");
renderer.setGlobalAlpha(1.0);
var context = renderer.getContext();
// # entities / draw
this.font.draw(context, "#objects : " + me.game.world.children.length, 5 * this.mod, 5 * this.mod);
this.font.draw(context, "#draws : " + me.game.world.drawCount, 5 * this.mod, 18 * this.mod);
// debug checkboxes
this.font.draw(context, "?hitbox ["+ (me.debug.renderHitBox?"x":" ") +"]", 100 * this.mod, 5 * this.mod);
this.font.draw(context, "?velocity ["+ (me.debug.renderVelocity?"x":" ") +"]", 100 * this.mod, 18 * this.mod);
this.font.draw(context, "?QuadTree ["+ (me.debug.renderQuadTree?"x":" ") +"]", 200 * this.mod, 5 * this.mod);
//this.font.draw(context, "?col. layer ["+ (me.debug.renderCollisionMap?"x":" ") +"]", 200 * this.mod, 18 * this.mod);
// draw the update duration
this.font.draw(context, "Update : " + this.frameUpdateTime.toFixed(2) + " ms", 310 * this.mod, 5 * this.mod);
// draw the draw duration
this.font.draw(context, "Draw : " + (this.frameDrawTime).toFixed(2) + " ms", 310 * this.mod, 18 * this.mod);
// draw the memory heap usage
var endX = this.rect.width - 25;
this.drawMemoryGraph(renderer, endX - this.help_str_len);
// some help string
this.font.draw(context, this.help_str, endX - this.help_str_len, 18 * this.mod);
//fps counter
var fps_str = "" + me.timer.fps + "/" + me.sys.fps + " fps";
this.font.draw(context, fps_str, this.rect.width - this.fps_str_len - 5, 5 * this.mod);
renderer.restore();
},
/** @private */
onDestroyEvent : function() {
// hide the panel
this.hide();
// unbind keys event
me.input.unbindKey(me.input.KEY.S);
me.input.unbindKey(me.input.KEY.H);
me.event.unsubscribe(this.keyHandler);
}
});
/*---------------------------------------------------------*/
// END END END
/*---------------------------------------------------------*/
})(window);
|
lychee.define('lychee.game.Loop').includes([
'lychee.Events'
]).supports(function(lychee, global) {
if (typeof setInterval === 'function') {
return true;
}
return false;
}).exports(function(lychee, global) {
var _instances = [];
var _listeners = {
interval: function() {
for (var i = 0, l = _instances.length; i < l; i++) {
var instance = _instances[i];
var clock = Date.now() - instance.__clock.start;
instance._updateLoop(clock);
instance._renderLoop(clock);
}
}
};
(function(callsPerSecond) {
var interval = typeof setInterval === 'function';
if (interval === true) {
global.setInterval(_listeners.interval, callsPerSecond);
}
if (lychee.debug === true) {
var methods = [];
if (interval) methods.push('setInterval');
if (methods.length === 0) methods.push('NONE');
console.log('lychee.game.Loop: Supported interval methods are ' + methods.join(', '));
}
})(1000 / 60);
var _timeoutId = 0,
_intervalId = 0;
var Class = function(data) {
var settings = lychee.extend({}, data);
this.__timeouts = {};
this.__intervals = {};
this.__state = 'running';
lychee.Events.call(this, 'loop');
var ok = this.reset(settings.update, settings.render);
if (ok === true) {
_instances.push(this);
}
settings = null;
};
Class.prototype = {
/*
* PUBLIC API
*/
reset: function(updateFps, renderFps) {
updateFps = typeof updateFps === 'number' ? updateFps : 0;
renderFps = typeof renderFps === 'number' ? renderFps : 0;
if (updateFps < 0) updateFps = 0;
if (renderFps < 0) renderFps = 0;
if (updateFps === 0 && renderFps === 0) {
return false;
}
this.__clock = {
start: Date.now(),
update: 0,
render: 0
};
this.__ms = {};
if (updateFps > 0) this.__ms.update = 1000 / updateFps;
if (renderFps > 0) this.__ms.render = 1000 / updateFps;
this.__updateFps = updateFps;
this.__renderFps = renderFps;
return true;
},
start: function() {
this.__state = 'running';
},
stop: function() {
this.__state = 'stopped';
},
timeout: function(delta, callback, scope) {
delta = typeof delta === 'number' ? delta : null;
callback = callback instanceof Function ? callback : null;
scope = scope !== undefined ? scope : global;
if (delta === null || callback === null) {
return null;
}
var id = _timeoutId++;
this.__timeouts[id] = {
start: this.__clock.update + delta,
callback: callback,
scope: scope
};
var that = this;
return {
clear: function() {
that.__timeouts[id] = null;
}
};
},
interval: function(delta, callback, scope) {
delta = typeof delta === 'number' ? delta : null;
callback = callback instanceof Function ? callback : null;
scope = scope !== undefined ? scope : global;
if (delta === null || callback === null) {
return null;
}
var id = _intervalId++;
this.__intervals[id] = {
start: this.__clock.update + delta,
delta: delta,
step: 0,
callback: callback,
scope: scope
};
var that = this;
return {
clear: function() {
that.__intervals[id] = null;
}
};
},
isRunning: function() {
return this.__state === 'running';
},
/*
* PROTECTED API
*/
_renderLoop: function(clock) {
if (this.__state !== 'running') return;
var delta = clock - this.__clock.render;
if (delta >= this.__ms.render) {
this.trigger('render', [ clock, delta ]);
this.__clock.render = clock;
}
},
_updateLoop: function(clock) {
if (this.__state !== 'running') return;
var delta = clock - this.__clock.update;
if (delta >= this.__ms.update) {
this.trigger('update', [ clock, delta ]);
this.__clock.update = clock;
}
var data;
for (var iId in this.__intervals) {
data = this.__intervals[iId];
// Skip cleared intervals
if (data === null) continue;
var curStep = Math.floor((clock - data.start) / data.delta);
if (curStep > data.step) {
data.step = curStep;
data.callback.call(data.scope, clock - data.start, curStep);
}
}
for (var tId in this.__timeouts) {
data = this.__timeouts[tId];
// Skip cleared timeouts
if (data === null) continue;
if (clock >= data.start) {
this.__timeouts[tId] = null;
data.callback.call(data.scope, clock);
}
}
}
};
return Class;
});
|
console.log('testing reserve_with_timeout');
var assert = require('assert');
var helper = require('./helper');
helper.bind(function(conn, data) {
if(String(data) == 'reserve-with-timeout 2\r\n') {
conn.write("RESERVED 9 4\r\ntest\r\n");
}
}, true);
var client = helper.getClient();
var success = false;
var error = false;
client.reserve_with_timeout(2).onSuccess(function(data) {
assert.ok(data);
success = true;
client.disconnect();
});
client.addListener('error', function() {
error = true;
});
process.addListener('exit', function() {
assert.ok(!error);
assert.ok(success);
console.log('test passed');
});
|
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var core_1 = require("@angular/core");
var TriStateCheckboxDemo = (function () {
function TriStateCheckboxDemo() {
}
return TriStateCheckboxDemo;
}());
TriStateCheckboxDemo = __decorate([
core_1.Component({
templateUrl: './tristatecheckboxdemo.html',
})
], TriStateCheckboxDemo);
exports.TriStateCheckboxDemo = TriStateCheckboxDemo;
//# sourceMappingURL=tristatecheckboxdemo.js.map |
'use strict';
const assert = require('assert');
const normalizeHandlers = require('../lib/normalize-handlers');
describe('normalizeHandlers', () => {
it('is a function', () => {
assert.equal(typeof normalizeHandlers, 'function');
});
it('throws when called without an object', () => {
assert.throws(
() => normalizeHandlers(),
Error,
'Handlers must be an object with HTTP methods as keys.'
);
});
it('throws when called with an object with an unknown HTTP method as a key', () => {
assert.throws(
() => normalizeHandlers({ blah: [] }),
Error,
'Unknown method: blah'
);
});
it('throws when called with an object with the same HTTP method twice', () => {
assert.throws(
() => normalizeHandlers({ get: [], GET: [] }),
Error,
'A method can only be used once: GET'
);
});
it('throws when called with a callbacks list which is not an array', () => {
assert.throws(
() => normalizeHandlers({ get: 'blah' }),
Error,
'A method can only be used once: GET'
);
});
it('returns an new object with upper-cased HTTP method name', () => {
const getHandlers = [];
const postHandlers = [];
const original = { get: getHandlers, POST: postHandlers };
const normalized = normalizeHandlers(original);
assert.notEqual(original, normalized);
assert.deepEqual(normalized, {
GET: getHandlers,
POST: postHandlers
});
});
});
|
import {coverage} from "../src/punctuate-coverage"
import assert from "power-assert"
describe("punctuate-coverage", function () {
describe("#coverage", function () {
it("should return object", function () {
var results = coverage([__dirname + "/fixtures/README.md"]);
assert(results.files.length > 0);
assert.equal(typeof results.files[0].source, "object");
assert.equal(typeof results.files[0].filename, "string");
});
});
}); |
const test = require('blue-tape');
const fetch = require('node-fetch');
const _ = require('lodash');
const fixture = require('../../fixtures/symptom');
const IO = require('socket.io-client');
const assertOk = (t) => {
return (res) => {
return t.ok(res.ok, 'statusCode is 2xx');
}
};
const unwrapJSON = (res) => {
return res.json()
.then(json => json.result);
}
const unwrapOldVal = (res) => {
return res.json()
.then(json => json.old_val);
}
const getJSON = (suffix) => {
return fetch(url+suffix)
.then(unwrapJSON);
}
const url = 'http://localhost:'+process.env.PORT;
const sender = method => suffix => data => {
return fetch(url+suffix, {
method: method,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify( data )
});
};
const poster = sender('post');
const putter = sender('put');
const deleter = suffix => () => {
return fetch(url+suffix, {
method: 'delete',
headers: {
'Accept': 'application/json',
}
});
};
const symptomPoster = poster('/symptoms')
const symptomCreator = times => {
return Promise.all(_.times(times, () => {
const data = fixture.valid();
return symptomPoster(data)
.then(unwrapJSON)
}));
};
const pop = data => data[0];
const singlesymptomCreator = () => symptomCreator(1).then(pop);
test('POSTing a valid sprint should return 200', (t) => {
const symptom = fixture.valid();
return symptomPoster(symptom)
.then(assertOk(t));
});
test('GET /symptoms/:id should return 200', (t) => {
return singlesymptomCreator()
.then(body => fetch(url+'/symptoms/'+body.id))
.then(assertOk(t));
});
test('GET /symptoms should return 200', (t) => {
return singlesymptomCreator()
.then(() => fetch(url+'/symptoms'))
.then(assertOk(t));
});
test('GET /symptoms should return an object with a .result property', (t) => {
return singlesymptomCreator()
.then(() => fetch(url+'/symptoms'))
.then(res => res.json())
.then(json => {
t.equal(typeof json, 'object');
t.ok(json.result);
});
});
test('GET /symptoms should accept search params in the querystring', (t) => {
return symptomCreator(2)
.then(symptoms => {
const target = Object.keys(symptoms[0]).filter(k => k != 'id')[0];
return getJSON('/symptoms?'+target+'='+symptoms[0][target])
.then(json => {
t.equal(json.length, 1);
t.equal(json[0][target], symptoms[0][target]);
});
});
});
test('GET /symptoms should not match non-property search params in the querystring', (t) => {
return symptomCreator(2)
.then(symptoms => {
return getJSON('/symptoms?foo='+symptoms[0].id)
.then(json => {
t.ok(json.length > 1);
});
});
});
test('GET /symptoms should return an array', (t) => {
return singlesymptomCreator()
.then(() => getJSON('/symptoms'))
.then(json => {
t.ok(Array.isArray(json));
});
});
test('GET /symptoms should paginate if asked', (t) => {
return symptomCreator(5)
.then(() => getJSON('/symptoms?limit=2'))
.then(json => {
t.equal(json.length, 2);
});
});
test('GET /symptoms should skip if asked', (t) => {
return symptomCreator(5)
.then(() => getJSON('/symptoms?limit=2'))
.then(first => {
t.equal(first.length, 2);
return getJSON('/symptoms?limit=2&skip=2')
.then(second => {
t.equal(second.length, 2);
t.notDeepEqual(first, second);
});
});
});
test('GET /symptoms should orderBy if asked', (t) => {
return symptomCreator(15)
.then(() => getJSON('/symptoms?orderBy=id'))
.then(results => {
const reordered = _.clone(results).sort((a, b) => {
if (a.id > b.id) return 1;
if (a.id < b.id) return -1;
return 0;
});
t.deepEqual(_.pluck(reordered, 'id'), _.pluck(results, 'id'));
});
});
test('GET /symptoms should orderBy asc if asked', (t) => {
return symptomCreator(15)
.then(() => getJSON('/symptoms?orderBy=id&order=asc'))
.then(results => {
const reordered = _.clone(results).sort((a, b) => {
if (a.id > b.id) return 1;
if (a.id < b.id) return -1;
return 0;
});
t.deepEqual(_.pluck(reordered, 'id'), _.pluck(results, 'id'));
});
});
test('GET /symptoms should orderBy desc if asked', (t) => {
return symptomCreator(15)
.then(() => getJSON('/symptoms?orderBy=id&order=desc'))
.then(results => {
const reordered = _.clone(results).sort((a, b) => {
if (a.id < b.id) return 1;
if (a.id > b.id) return -1;
return 0;
});
t.deepEqual(_.pluck(reordered, 'id'), _.pluck(results, 'id'));
});
});
test('GET /symptoms?count=true&limit=n should return n matching docs with a count of all matching docs ', (t) => {
return symptomCreator(10)
.then(() => fetch(url+'/symptoms?count=true&limit=5'))
.then(res => res.json())
.then(json => {
t.equal(json.result.length, 5);
t.ok(json.count);
t.ok(json.count > 5);
});
});
test('GET /symptoms?limit=n should return n matching docs without a count of all matching docs ', (t) => {
return symptomCreator(10)
.then(() => fetch(url+'/symptoms?limit=5'))
.then(res => res.json())
.then(json => {
t.equal(json.result.length, 5);
t.ok(!json.count);
});
});
test('GET /symptoms?count=true&result=false should return only a count with no matching docs', (t) => {
return symptomCreator(10)
.then(() => fetch(url+'/symptoms?count=true&result=false'))
.then(res => res.json())
.then(json => {
t.ok(!json.result, 'has no result');
t.ok(json.count, 'has a count');
t.ok(json.count > 5, 'count is greater than 5');
});
});
test('POSTing a valid symptom should actually persist it', (t) => {
return singlesymptomCreator()
.then(spec => {
return getJSON('/symptoms/'+spec.id)
.then((json) => {
t.equal(json.id, spec.id);
});
});
});
test('PUTing an updated symptom should actually persist it', (t) => {
return singlesymptomCreator()
.then(body => {
body.name = 'Something else';
return body
})
.then(body => putter('/symptoms/'+body.id)(body))
.then(unwrapJSON)
.then(body => getJSON('/symptoms/'+body.id))
.then((json) => {
t.equal(json.name, 'Something else');
});
});
test('DELETEing a symptom should return 200', (t) => {
return singlesymptomCreator()
.then(body => deleter('/symptoms/'+body.id)())
.then(assertOk(t));
});
test('DELETEing a symptom should actually delete it', (t) => {
return singlesymptomCreator()
.then(body => deleter('/symptoms/'+body.id)())
.then(unwrapOldVal)
.then(body => fetch(url+'/symptoms/'+body.id))
.then(res => {
t.equal(res.status, 404);
});
});
test('opening a websocket connection to a symptom should return it', (t) => {
return singlesymptomCreator()
.then(body => {
return new Promise(resolve => {
const io = IO(url+'/symptoms', {query: 'id='+body.id, forceNew: true});
io.on('record', data => {
resolve(data.new_val);
io.disconnect();
});
})
.then(data => {
t.deepEqual(data, body);
});
});
});
test('opening a websocket connection to symptoms should return all of them', (t) => {
return symptomCreator(2)
.then(body => {
return new Promise(resolve => {
const io = IO(url+'/symptoms', {forceNew: true});
var count = 0;
io.on('record', () => {
count++;
if (count > 1) {
resolve();
io.disconnect();
}
});
});
});
});
test('opening a websocket connection to symptoms should return changed documents', (t) => {
return singlesymptomCreator()
.then(body => {
return new Promise(resolve => {
const io = IO(url+'/symptoms', {forceNew: true});
io.on('state', data => {
if (data.state === 'ready') {
const target = _.assign({}, body, {name: 'ohai'});
io.on('record', data => {
t.deepEqual(data.new_val, target);
t.notDeepEqual(data.new_val, body);
io.disconnect();
resolve();
});
putter('/symptoms/'+body.id)(target)
};
});
});
});
});
test('websockets should accept the same filter params as GET requests', (t) => {
return symptomCreator(2)
.then(symptoms => {
const target = symptoms[0];
const targetKey = Object.keys(target).filter(k => k !== 'id')[0];
return new Promise(resolve => {
const query = [targetKey].reduce((r, k) => {
r[k] = target[k];
return r;
}, {});
const io = IO(url+'/symptoms', {query: query, forceNew: true});
io.on('record', data => {
t.deepEqual(data.new_val, target);
});
io.on('state', data => {
if (data.state != 'ready') return;
io.disconnect();
t.end();
});
});
});
});
test('websockets should accept the same limit param as GET requests', (t) => {
return symptomCreator(2)
.then(() => {
return new Promise(resolve => {
const io = IO(url+'/symptoms', {query: {limit: 1}, forceNew: true});
var count = 0;
io.on('record', data => {
count++;
});
io.on('state', data => {
if (data.state != 'ready') return;
io.disconnect();
t.equal(count, 1);
t.end();
});
});
});
});
test('websockets should skip if asked', (t) => {
return symptomCreator(5)
.then(() => {
return new Promise(resolve => {
const io = IO(url+'/symptoms', {query: {limit: 1}, forceNew: true});
var first;
io.on('record', data => {
first = data;
io.disconnect();
const io2 = IO(url+'/symptoms', {query: {skip: 1}, forceNew: true});
io2.on('record', data => {
t.notDeepEqual(data, first);
io2.disconnect();
return resolve();
});
});
});
});
});
test('websockets should orderBy asc if asked', (t) => {
// The websocket API won't return its results in order, but they will be pulled from the right part of the database
return symptomCreator(15)
.then(() => {
return new Promise(resolve => {
const io = IO(url+'/symptoms', {query: {orderBy: 'id', order: 'asc'}, forceNew: true});
const results = [];
io.on('record', data => {
results.push(data.new_val);
});
io.on('state', data => {
if (data.state !== 'ready') return;
io.disconnect();
const reordered = _.clone(results).sort((a, b) => {
if (a.id > b.id) return 1;
if (a.id < b.id) return -1;
return 0;
});
return resolve(getJSON('/symptoms?orderBy=id&order=asc')
.then(json => {
t.deepEqual(_.pluck(reordered, 'id'), _.pluck(json, 'id'));
}));
});
});
});
});
test('websockets should orderBy desc if asked', (t) => {
return symptomCreator(15)
.then(() => {
return new Promise(resolve => {
const io = IO(url+'/symptoms', {query: {orderBy: 'id', order: 'desc'}, forceNew: true});
const results = [];
io.on('record', data => {
results.push(data.new_val);
});
io.on('state', data => {
if (data.state !== 'ready') return;
io.disconnect();
const reordered = _.clone(results).sort((a, b) => {
if (a.id < b.id) return 1;
if (a.id > b.id) return -1;
return 0;
});
return resolve(getJSON('/symptoms?orderBy=id&order=desc')
.then(json => {
t.deepEqual(_.pluck(reordered, 'id'), _.pluck(json, 'id'));
}));
});
});
});
});
|
(function () {
'use strict';
angular.module('app.controllers')
.controller('PaymentViewController', PaymentViewController);
PaymentViewController.$inject = ['$scope', '$state', 'PaymentService', 'EmployeeService', 'toastr', 'Util'];
function PaymentViewController ($scope, $state, PaymentService, EmployeeService, toastr, Util) {
$scope.btnLoading = false;
$scope.listEmployee = [];
$scope.model = PaymentService.attributes();
$scope.save = save;
$scope.init = init;
function save ( model ) {
if (!validateForms(model))
return;
$scope.btnLoading = true;
var payment = Object.assign({}, model);
payment.dataPagamento = Util.formatDateToLong(payment.dataPagamento);
payment.salarioFixo = payment.salarioFixo.toString().replace(/[,]/g, '.');
payment.valorTotalComissao = payment.valorTotalComissao.toString().replace(/[,]/g, '.');
PaymentService.update(payment, setSave);
}
function setSave (response, message) {
$scope.btnLoading = false;
if (!response || !response.data || response.status !== 200) {
toastr.error('Não foi possível concluir a sua solicitação, por favor tente mais tarde!', 'Atenção!');
return;
}
if (response.data.tipoErro) {
toastr.error(response.data.mensagem, 'Atenção!');
return;
}
toastr.success('Salvo com sucesso!', 'Atenção!');
$state.go('app.payment.index');
}
function init () {
if (!$state.params.id) {
$state.go('app.product.index');
toastr.warning('Por favor selecione um item valido!', 'Atenção!');
return;
}
EmployeeService.getAll(setEmployee);
PaymentService.getById($state.params.id, setById);
}
function validateForms (model) {
if (!model.funcionario || !model.funcionario.id) {
toastr.error('O campo Funcionario é obrigatorio!', 'Atenção');
return false;
}
if (!model.dataPagamento) {
toastr.error('O campo Data Pagamento é obrigatorio!', 'Atenção');
return false;
}
if (!model.salarioFixo) {
toastr.error('O campo Salario Fixo é obrigatorio!', 'Atenção');
return false;
}
return true;
}
function setEmployee (response, message) {
if (!response || !response.data) {
toastr.error('Não foi possivel concluir a sua solicitação!', 'Atenção');
return;
}
$scope.listEmployee = response.data || [];
}
function setById (response, message) {
if (!response || !response.data) {
toastr.error('Não foi possivel concluir a sua solicitação!', 'Atenção');
return;
}
var data = response.data;
$scope.model = {
id : data.id || null,
dataPagamento : data.dataPagamento ? Util.formatLongToDate(data.dataPagamento) : null,
salarioFixo : data.salarioFixo ? data.salarioFixo.toString().replace('.', ',') : null,
valorTotalComissao : data.valorTotalComissao ? data.valorTotalComissao.toString().replace('.', ',') : null,
funcionario : {
id : data.funcionario.id ? data.funcionario.id : null
}
};
}
}
})();
|
const a = "hello", b = "world", c = 1234;
export { a, b, c };
export { a as foo, b as bar };
export let pi = Math.PI;
export const tau = 2 * pi;
export * from "util";
export { format } from "util";
export { format as lol, inspect as derp } from "util";
export otherDefault from "other-lib";
export {};
|
'use strict';
import ContainerView from './views/containerView.js';
import ZoomableElementsView from './views/zoomableElementsView.js';
import ZoomView from './views/zoomView.js';
import CodeView from './views/codeView.js';
import * as helper from './helper.js';
export default class ExplorableDomInspector {
constructor(originalDom, inspectorDom) {
this._originalDom = originalDom;
this._inspectorDom = inspectorDom;
this._currentView = null;
}
showView(viewType) {
// Switch to specified view
this._switchView(viewType);
}
handleChangedPath() {
// Keep current view when switching to new file
if(this._currentView) {
this._switchView(this._currentView.getViewType(), true);
}
}
hideView(switchView=false, switchFile=false) {
// Disable navigation bar buttons
this._disablePreviousHierarchyButton(true);
this._disableNextHierarchyButton(true);
this._disableHideViewButton(true);
// Reset changes
if(switchFile) {
// Do not need to set opacity or delete elements because the content gets overwritten anyway
this._currentView = null;
return;
}
if(this._currentView) {
// Delete elements created by the current view and reset opacity
this._setOpacity('1');
this._currentView.deleteElements();
if(!switchView) {
// Reset the hierarchy information, filter, and currentView because no new view will be shown
this._currentView = null;
this._updateHierarchyInformation(true);
this._updateTagSelect(true);
}
}
}
showPreviousHierarchyLevel() {
this._currentView.showHierarchyLevel(this._currentView.getShowedLevel() - 1);
this.filterTag();
this._updateHierarchyInformation();
this._disableNextHierarchyButton(false);
if(this._currentView.getShowedLevel() === 0) {
this._disablePreviousHierarchyButton(true);
}
}
showNextHierarchyLevel() {
this._currentView.showHierarchyLevel(this._currentView.getShowedLevel() + 1);
this.filterTag();
this._updateHierarchyInformation();
this._disablePreviousHierarchyButton(false);
if(this._currentView.getShowedLevel() === this._currentView.getMaxNestedLevel()) {
this._disableNextHierarchyButton(true);
}
}
filterTag(tagName=null) {
if(!tagName) {
let tagSelect = this._inspectorDom.querySelector('#tagSelect');
tagName = tagSelect.options[tagSelect.selectedIndex].value;
}
if(tagName != 0) {
this._currentView.showElementsByTag(tagName);
return;
}
this._currentView.showHierarchyLevel(this._currentView.getShowedLevel());
}
_switchView(type, isNewFile=false) {
// Save hierarchy level
let hierarchyLevel = null;
if(this._currentView) {
hierarchyLevel = this._currentView.getShowedLevel();
}
// Remove current view
this.hideView(true, isNewFile);
// Create new view (create copied elements, etc.)
this._createView(type, hierarchyLevel);
// Update hierarchy level information and tagName filter
this._updateHierarchyInformation();
this._updateTagSelect();
// Make background less prominent
this._setOpacity(this._currentView.getOpacityValue());
this._disableHideViewButton(false);
// Enable hierarchy button only if there are nested elements
if(this._currentView.getMaxNestedLevel() > 0) {
this._disableNextHierarchyButton(false);
}
if(this._currentView.getShowedLevel() > 0) {
this._disablePreviousHierarchyButton(false);
}
if (this._currentView.getShowedLevel() === this._currentView.getMaxNestedLevel()) {
this._disablePreviousHierarchyButton(false);
this._disableNextHierarchyButton(true);
}
}
_createView(viewType, hierarchyLevel) {
let inspectorContent = this._originalDom.querySelector('#inspector-content');
let originalParent = this._originalDom.querySelector('#inspector-content::shadow #container-root');
let childElements = this._originalDom.querySelectorAll('#inspector-content > *');
let view;
switch (viewType) {
case 'basic':
view = ContainerView;
break;
case 'zoom':
view = ZoomView;
break;
case 'zoomableElements':
view = ZoomableElementsView;
break;
case 'code':
view = CodeView;
break;
default:
view = ContainerView;
}
this._currentView = new view(inspectorContent, originalParent, childElements, hierarchyLevel);
}
/*
Template helper functions for enabeling/disabeling buttons, setting the opacity, and
updating the hierarchy and tagSelect information
*/
_disablePreviousHierarchyButton(expr) {
this._inspectorDom.querySelector('#previousHierarchyLevelButton').disabled = expr;
}
_disableNextHierarchyButton(expr) {
this._inspectorDom.querySelector('#nextHierarchyLevelButton').disabled = expr;
}
_disableHideViewButton(expr) {
this._inspectorDom.querySelector('#hideViewButton').disabled = expr;
}
_setOpacity(value) {
if (this._currentView) {
let wrapper = this._originalDom.querySelector('#inspector-content > #wrap--original');
if(wrapper) {
wrapper.style.opacity = value;
}
}
}
_updateHierarchyInformation(setDefault=false) {
if (setDefault) {
this._inspectorDom.querySelector('#hierarchyLevel').innerText = '- / -';
return;
}
let currentLvl = this._currentView.getShowedLevel() + 1;
let maxLvl = this._currentView.getMaxNestedLevel() + 1;
this._inspectorDom.querySelector('#hierarchyLevel').innerText = currentLvl + ' / ' + maxLvl;
}
_updateTagSelect(setDefault=false) {
let select = this._inspectorDom.querySelector('#tagSelect');
// Clear select
select.innerHTML = '';
// Add default option
let defaultOpt = document.createElement('option');
defaultOpt.value = 0;
defaultOpt.innerHTML = '-';
if (setDefault) {
select.disabled = true;
}
select.appendChild(defaultOpt);
if (!setDefault) {
select.disabled = false;
// Add tagName options
let allTags = this._currentView.getTagNames();
let tags = allTags.filter((element, index, self) => index == self.indexOf(element));
for (let i = 0; i < tags.length; i++) {
let opt = document.createElement('option');
opt.value = tags[i];
opt.innerHTML = tags[i];
select.appendChild(opt);
}
}
}
}
|
import React, { Component } from 'react'
import './CoreLayout.less'
import ScrollToTop from './ScrollToTop'
class CoreLayout extends Component {
render () {
const { children } = this.props
return (
<div className='core-container notransition'>
<ScrollToTop>
<div>
{children}
</div>
</ScrollToTop>
</div>
)
}
}
CoreLayout.propTypes = {
children: React.PropTypes.element.isRequired
}
export default CoreLayout
|
{
this$1.emit("error", err);
}
|
function fix(r){return Math.round(100*r)/100}function rule(r){var i=!1,n=!1,u=Number("${minLotteryAmount}"),t=Number("${discountAmount}"),e=Number("${discountRate}");return _ruleForWeixin(r,i,n,u,t,e)}function _ruleForWeixin(r,i,n,u,t,e){if(n){var f=r*e;return u>=f?"折扣金额"+u+"元以上才有折扣哦":i?fix(10*e)+"折立减"+fix(r-f)+"元,实付"+fix(f)+"元":fix(10*e)+"折立减"+fix(r-f)+"元,随机立减"+t+"元,实付"+fix(f-t)+"元"}return u>=r?"支付金额"+u+"元以上才有折扣哦":i?"您今天的3次人品已经被你用完了,实付"+r+"元":"人品爆发!本次优惠"+t+"元,实付"+fix(r-t)+"元"} |
/**
* Get the source of a page from our queue, grab a list of live match urls
* and add the urls to our queue.
*/
var projectConfig = require('../config/project.json');
var queueDriver = require('../utils/queue/' + projectConfig.queueDriver);
var LiveMatches = {
run: function() {
queueDriver.get('sourceQueue', function(msg, ch) {
var data = JSON.parse(msg.content.toString());
var parser = require('../parsers/' + data.site + '/liveMatches');
var matches = parser.getMatches(data.content);
matches.forEach(function(match) {
queueDriver.save(
'matchQueue',
JSON.stringify({
site: data.site,
match: match
})
);
});
ch.ack(msg);
});
}
}
module.exports = LiveMatches;
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class RNFacebookFirebase extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('RNFacebookFirebase', () => RNFacebookFirebase);
|
/**
* Wheel, copyright (c) 2019 - present by Arno van der Vegt
* Distributed under an MIT license: https://arnovandervegt.github.io/wheel/license.txt
**/
const path = require('../../../../shared/lib/path');
const Downloader = require('../../../program/Downloader');
const dispatcher = require('../../../lib/dispatcher').dispatcher;
const Dialog = require('../../../lib/components/Dialog').Dialog;
const ResourceLine = require('./components/ResourceLine').ResourceLine;
const SHOW_SIGNAL = 'Dialog.Download.Show';
exports.DownloadDialog = class extends Dialog {
constructor(opts) {
super(opts);
this._ev3 = opts.ev3;
this.initWindow({
showSignal: SHOW_SIGNAL,
width: 600,
height: 472,
className: 'download-dialog',
title: 'Download resources'
});
}
initWindowContent(opts) {
return [
{
className: 'flt max-w download-row',
children: [
{
innerHTML: 'Project filename:',
className: 'flt label'
},
{
ref: this.setRef('projectFilename'),
className: 'flt value'
}
]
},
{
className: 'flt max-w download-row',
children: [
{
innerHTML: 'Project description:',
className: 'flt label'
},
{
ref: this.setRef('projectDescription'),
className: 'flt value'
}
]
},
{
className: 'flt max-w download-row',
children: [
{
innerHTML: 'Remote directory:',
className: 'flt label'
},
{
ref: this.setRef('remoteDirectory'),
className: 'flt value'
}
]
},
{
className: 'flt max-w download-row',
children: [
{
innerHTML: 'Actions:',
className: 'flt label'
}
]
},
{
ref: this.setRef('text'),
className: 'abs dialog-cw dialog-l ui1-box vscroll pad download-text'
},
this.initButtons([
{
ref: this.setRef('downloadButton'),
value: 'Download',
tabIndex: 128,
onClick: this.onDownload.bind(this)
},
{
ref: this.setRef('closeButton'),
value: 'Close',
tabIndex: 129,
color: 'dark-green',
onClick: this.hide.bind(this)
}
])
];
}
initLines(resources) {
let text = this._refs.text;
while (text.childNodes.length) {
text.removeChild(text.childNodes[0]);
}
let filenames = resources.getFilenameList();
let elementByFilename = {};
new ResourceLine({
parentNode: text,
elementByFilename: elementByFilename,
elementId: 'createDirectory',
filename: 'Create directory "' + this._remoteDirectory + '"'
});
new ResourceLine({
parentNode: text,
elementByFilename: elementByFilename,
elementId: 'downloadedVM',
filename: 'Download VM'
});
new ResourceLine({
parentNode: text,
elementByFilename: elementByFilename,
elementId: 'downloadProgram',
filename: 'Download program "program.rtf"'
});
filenames.forEach(
function(filename) {
new ResourceLine({
parentNode: text,
elementByFilename: elementByFilename,
filename: filename
});
},
this
);
this._elementByFilename = elementByFilename;
}
onDownload() {
let refs = this._refs;
let elementByFilename = this._elementByFilename;
refs.downloadButton.setDisabled(true);
refs.closeButton.setDisabled(true);
new Downloader.Downloader().download({
ev3: this._ev3,
program: this._program,
resources: this._resources,
localPath: this._settings.getDocumentPath(),
remoteDirectory: this._remoteDirectory,
remotePath: '../prjs/',
onCreatedDirectory() {
elementByFilename.createDirectory.setResult(true);
},
onDownloadedVM() {
elementByFilename.downloadedVM.setResult(true);
},
onDownloadedProgram() {
elementByFilename.downloadProgram.setResult(true);
},
onDownloadedFile: function(filename, result) {
elementByFilename[filename].setResult(result);
},
onDownloadReady: function() {
refs.downloadButton.setDisabled(false);
refs.closeButton.setDisabled(false);
}
});
}
onShow(opts) {
let refs = this._refs;
this._ev3.stopPolling();
this._program = opts.program;
this._remoteDirectory = Downloader.getRemoteDirectory(opts.filename);
this._resources = opts.resources;
refs.projectDescription.innerHTML = opts.program.getTitle() || '?';
refs.projectFilename.innerHTML = path.removePath(this._settings.getDocumentPath(), opts.filename);
refs.remoteDirectory.innerHTML = this._remoteDirectory;
this.initLines(opts.resources);
this.show();
}
hide() {
this._ev3.resumePolling();
super.hide();
}
};
exports.DownloadDialog.SHOW_SIGNAL = SHOW_SIGNAL;
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
ServiceRecord = mongoose.model('ServiceRecord'),
_ = require('lodash');
/**
* Create a Service record
*/
exports.create = function(req, res) {
var serviceRecord = new ServiceRecord(req.body);
serviceRecord.user = req.user;
serviceRecord.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(serviceRecord);
}
});
};
/**
* Show the current Service record
*/
exports.read = function(req, res) {
res.jsonp(req.serviceRecord);
};
/**
* Update a Service record
*/
exports.update = function(req, res) {
var serviceRecord = req.serviceRecord ;
serviceRecord = _.extend(serviceRecord , req.body);
serviceRecord.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(serviceRecord);
}
});
};
/**
* Delete an Service record
*/
exports.delete = function(req, res) {
var serviceRecord = req.serviceRecord ;
serviceRecord.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(serviceRecord);
}
});
};
/**
* List of Service records
*/
exports.list = function(req, res) {
ServiceRecord.find().sort('-created').populate('user', 'displayName').exec(function(err, serviceRecords) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(serviceRecords);
}
});
};
/**
* Service record middleware
*/
exports.serviceRecordByID = function(req, res, next, id) {
ServiceRecord.findById(id).populate('user', 'displayName').exec(function(err, serviceRecord) {
if (err) return next(err);
if (! serviceRecord) return next(new Error('Failed to load Service record ' + id));
req.serviceRecord = serviceRecord ;
next();
});
};
/**
* Service record authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.serviceRecord.user.id !== req.user.id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
function initTask(subTask) {
var state = {};
var level;
var answer = null;
var data = {
easy: {
path: ["start","v_1","v_5","v_9","v_12","v_13","v_16","end"],
graph: {
"vertexInfo": {
"start":{tree:4},"v_1":{tree:0},"v_2":{tree:2},"v_3":{tree:0},"v_4":{tree:3},"v_5":{tree:1},"v_6":{tree:4},"v_7":{tree:1},"v_8":{tree:0},"v_9":{tree:5},"v_10":{tree:0},
"v_11":{tree:3},"v_12":{tree:3},"v_13":{tree:3},"v_14":{tree:4},"v_15":{tree:2},"v_16":{tree:4},"v_17":{tree:1},"end":{tree:3} },
"edgeInfo": {
"e_0":{},"e_1":{},"e_2":{},"e_3":{},"e_4":{},"e_5":{},"e_6":{},"e_7":{},"e_8":{},"e_9":{},"e_10":{},
"e_11":{},"e_12":{},"e_13":{},"e_14":{},"e_15":{},"e_16":{},"e_17":{},"e_18":{},"e_19":{},"e_20":{},
"e_21":{},"e_22":{},"e_23":{},"e_24":{} },
"edgeVertices": {
"e_0":["start","v_1"],"e_1":["start","v_2"],"e_2":["start","v_3"],"e_3":["start","v_4"],"e_4":["v_1","v_5"],
"e_5":["v_2","v_5"],"e_6":["v_3","v_6"],"e_7":["v_4","v_7"],"e_8":["v_7","v_10"],"e_9":["v_5","v_8"],
"e_10":["v_5","v_9"],"e_11":["v_6","v_12"],"e_12":["v_10","v_13"],"e_13":["v_8","v_11"],"e_14":["v_9","v_12"],
"e_15":["v_11","v_14"],"e_16":["v_12","v_14"],"e_17":["v_12","v_13"],"e_18":["v_13","v_15"],"e_19":["v_15","v_14"],
"e_20":["v_14","v_17"],"e_21":["v_17","end"],"e_22":["v_15","end"],"e_23":["v_13","v_16"],"e_24":["v_16","end"] },
"directed":false
},
vertexVisualInfo: {
"start":{"x":113,"y":113},
"v_1":{"x":197,"y":54},
"v_2":{"x":213,"y":134},
"v_3":{"x":218,"y":207},
"v_4":{"x":144,"y":241},
"v_5":{"x":289,"y":92},
"v_6":{"x":319,"y":208},
"v_7":{"x":220,"y":297},
"v_8":{"x":370,"y":55},
"v_9":{"x":381,"y":136},
"v_10":{"x":324,"y":315},
"v_11":{"x":459,"y":67},
"v_12":{"x":452,"y":200},
"v_13":{"x":414,"y":282},
"v_14":{"x":519,"y":132},
"v_15":{"x":531,"y":243},
"v_16":{"x":516,"y":329},
"v_17":{"x":599,"y":158},
"end":{"x":627,"y":256}
}
},
medium: {
path: ["start","v_4","v_7","v_10","v_13","v_15","v_14","v_17","end"],
hidden: [6],
graph: {
"vertexInfo": {
"start":{tree:4},"v_1":{tree:0},"v_2":{tree:2},"v_3":{tree:0},"v_4":{tree:3},"v_5":{tree:1},"v_6":{tree:4},"v_7":{tree:1},"v_8":{tree:0},"v_9":{tree:5},"v_10":{tree:0},
"v_11":{tree:3},"v_12":{tree:3},"v_13":{tree:3},"v_14":{tree:4},"v_15":{tree:2},"v_16":{tree:4},"v_17":{tree:1},"end":{tree:3} },
"edgeInfo": {
"e_0":{},"e_1":{},"e_2":{},"e_3":{},"e_4":{},"e_5":{},"e_6":{},"e_7":{},"e_8":{},"e_9":{},"e_10":{},
"e_11":{},"e_12":{},"e_13":{},"e_14":{},"e_15":{},"e_16":{},"e_17":{},"e_18":{},"e_19":{},"e_20":{},
"e_21":{},"e_22":{},"e_23":{},"e_24":{} },
"edgeVertices": {
"e_0":["start","v_1"],"e_1":["start","v_2"],"e_2":["start","v_3"],"e_3":["start","v_4"],"e_4":["v_1","v_5"],
"e_5":["v_2","v_5"],"e_6":["v_3","v_6"],"e_7":["v_4","v_7"],"e_8":["v_7","v_10"],"e_9":["v_5","v_8"],
"e_10":["v_5","v_9"],"e_11":["v_6","v_12"],"e_12":["v_10","v_13"],"e_13":["v_8","v_11"],"e_14":["v_9","v_12"],
"e_15":["v_11","v_14"],"e_16":["v_12","v_14"],"e_17":["v_12","v_13"],"e_18":["v_13","v_15"],"e_19":["v_15","v_14"],
"e_20":["v_14","v_17"],"e_21":["v_17","end"],"e_22":["v_15","end"],"e_23":["v_13","v_16"],"e_24":["v_16","end"] },
"directed":false
},
vertexVisualInfo: {
"start":{"x":113,"y":113},
"v_1":{"x":197,"y":54},
"v_2":{"x":213,"y":134},
"v_3":{"x":218,"y":207},
"v_4":{"x":144,"y":241},
"v_5":{"x":289,"y":92},
"v_6":{"x":319,"y":208},
"v_7":{"x":220,"y":297},
"v_8":{"x":370,"y":55},
"v_9":{"x":381,"y":136},
"v_10":{"x":324,"y":315},
"v_11":{"x":459,"y":67},
"v_12":{"x":452,"y":200},
"v_13":{"x":414,"y":282},
"v_14":{"x":519,"y":132},
"v_15":{"x":531,"y":243},
"v_16":{"x":516,"y":329},
"v_17":{"x":599,"y":158},
"end":{"x":627,"y":256}
}
},
hard: {
path: ["start","v_3","v_6","v_12","v_9","v_5","v_8","v_11","v_14","v_15","end"],
hidden: [2,4,6],
graph: {
"vertexInfo": {
"start":{tree:4},"v_1":{tree:0},"v_2":{tree:2},"v_3":{tree:0},"v_4":{tree:3},"v_5":{tree:1},"v_6":{tree:4},"v_7":{tree:1},"v_8":{tree:0},"v_9":{tree:5},"v_10":{tree:0},
"v_11":{tree:3},"v_12":{tree:3},"v_13":{tree:3},"v_14":{tree:4},"v_15":{tree:2},"v_16":{tree:4},"v_17":{tree:1},"end":{tree:3} },
"edgeInfo": {
"e_0":{},"e_1":{},"e_2":{},"e_3":{},"e_4":{},"e_5":{},"e_6":{},"e_7":{},"e_8":{},"e_9":{},"e_10":{},
"e_11":{},"e_12":{},"e_13":{},"e_14":{},"e_15":{},"e_16":{},"e_17":{},"e_18":{},"e_19":{},"e_20":{},
"e_21":{},"e_22":{},"e_23":{},"e_24":{} },
"edgeVertices": {
"e_0":["start","v_1"],"e_1":["start","v_2"],"e_2":["start","v_3"],"e_3":["start","v_4"],"e_4":["v_1","v_5"],
"e_5":["v_2","v_5"],"e_6":["v_3","v_6"],"e_7":["v_4","v_7"],"e_8":["v_7","v_10"],"e_9":["v_5","v_8"],
"e_10":["v_5","v_9"],"e_11":["v_6","v_12"],"e_12":["v_10","v_13"],"e_13":["v_8","v_11"],"e_14":["v_9","v_12"],
"e_15":["v_11","v_14"],"e_16":["v_12","v_14"],"e_17":["v_12","v_13"],"e_18":["v_13","v_15"],"e_19":["v_15","v_14"],
"e_20":["v_14","v_17"],"e_21":["v_17","end"],"e_22":["v_15","end"],"e_23":["v_13","v_16"],"e_24":["v_16","end"] },
"directed":false
},
vertexVisualInfo: {
"start":{"x":113,"y":113},
"v_1":{"x":197,"y":54},
"v_2":{"x":213,"y":134},
"v_3":{"x":218,"y":207},
"v_4":{"x":144,"y":241},
"v_5":{"x":289,"y":92},
"v_6":{"x":319,"y":208},
"v_7":{"x":220,"y":297},
"v_8":{"x":370,"y":55},
"v_9":{"x":381,"y":136},
"v_10":{"x":324,"y":315},
"v_11":{"x":459,"y":67},
"v_12":{"x":452,"y":200},
"v_13":{"x":414,"y":282},
"v_14":{"x":519,"y":132},
"v_15":{"x":531,"y":243},
"v_16":{"x":516,"y":329},
"v_17":{"x":599,"y":158},
"end":{"x":627,"y":256}
}
}
};
var paperPath;
var paperGraph;
var pathHeight;
var pathWidth;
var path;
var graph;
var graphMouse;
var vertexToggler;
var graphWidth = 740;
var graphHeight = 384;
var vGraph;
var graphDrawer;
var src = [];
var treeSize = 47;
var margin = 20;
var vertexAttr = {
r: treeSize/2 + 5,
stroke: "none",
fill: "white"
};
var markedVertexAttr = {
r: treeSize/2 + 5,
stroke: "black",
"stroke-width": 3,
fill: "white"
};
var edgeAttr = {
stroke: '#a05000',
"stroke-width": 5
};
var markedEdgeAttr = {
stroke: 'black',
"stroke-width": 7
};
var arrowAttr = {
width: 40,
height: 30
};
var hidden;
var buttons = [];
subTask.loadLevel = function(curLevel) {
level = curLevel;
getSrc();
path = data[level].path;
pathHeight = treeSize + margin;
pathWidth = path.length * treeSize + margin;
graph = Graph.fromJSON(JSON.stringify(data[level].graph));
hidden = (level !== "easy") ? data[level].hidden : null;
};
subTask.getStateObject = function() {
return state;
};
subTask.reloadAnswerObject = function(answerObj) {
answer = answerObj;
};
subTask.resetDisplay = function() {
initPath();
initGraph();
reloadAnswer();
};
subTask.getAnswerObject = function() {
return answer;
};
subTask.getDefaultAnswerObject = function() {
var defaultAnswer = [];
return defaultAnswer;
};
subTask.unloadLevel = function(callback) {
callback();
};
function getResultAndMessage() {
var result = { successRate: 1, message: taskStrings.success };
if(level === "easy"){
if(answer.length === 0){
result = { successRate: 0, message: taskStrings.click };
}else if(answer.length < path.length){
result = { successRate: 0, message: taskStrings.notEnoughTrees };
}else if(answer.length > path.length){
result = { successRate: 0, message: taskStrings.tooManyTrees };
}else{
for(var iNode = 0; iNode < path.length; iNode++){
if(!Beav.Array.has(answer,path[iNode])){
result = { successRate: 0, message: taskStrings.wrongTree };
break;
}
}
}
}else if(answer.length === 0){
result = { successRate: 0, message: taskStrings.clickButton };
}else if(answer.length < hidden.length){
result = { successRate: 0, message: taskStrings.missingTrees };
}else{
for(var iAns = 0; iAns < answer.length; iAns++){
var vertex = path[hidden[iAns]];
var vertexTree = graph.getVertexInfo(vertex).tree;
if(answer[iAns] !== vertexTree){
result = { successRate: 0, message: taskStrings.wrongPath };
break;
}
}
}
return result;
};
subTask.getGrade = function(callback) {
callback(getResultAndMessage());
};
function initPath() {
paperPath = subTask.raphaelFactory.create('path','path',pathWidth,pathHeight);
paperPath.rect(2,2,pathWidth-4,pathHeight-4);
for(var iTree = 0; iTree < path.length; iTree++){
var x = margin/2 + iTree*treeSize;
var y = margin/2;
var tree = graph.getVertexInfo(path[iTree]).tree;
var source = src[tree];
if(level !== "easy" && Beav.Array.has(hidden,iTree)){
var button = new Button(paperPath,x,y - 3,treeSize,treeSize + 6,"?");
buttons.push(button);
}else{
paperPath.image(source,x,y,treeSize,treeSize);
}
}
initHandlers();
};
function initGraph() {
paperGraph = subTask.raphaelFactory.create('graph','graph',graphWidth,graphHeight);
var graphDrawer = new SimpleGraphDrawer(vertexAttr,edgeAttr);
graphDrawer.setDrawVertex(drawVertex);
vGraph = new VisualGraph("vGraph", paperGraph, graph, graphDrawer, true, data[level].vertexVisualInfo);
placeArrows();
if(level === "easy"){
graphMouse = new GraphMouse("graphMouse", graph, vGraph);
vertexToggler = new VertexToggler("vTog", graph, vGraph, graphMouse, vertexToggle, true);
}
};
function initHandlers() {
if(level !== "easy"){
for(var iButton = 0; iButton < buttons.length; iButton++){
buttons[iButton].click(clickButton(iButton));
}
}
};
function drawVertex(id,info,visualInfo) {
var pos = this._getVertexPosition(visualInfo);
this.originalPositions[id] = pos;
var background = paperGraph.circle(pos.x,pos.y).attr(vertexAttr);
var tree = paperGraph.image(src[info.tree],pos.x - treeSize/2,pos.y - treeSize/2, treeSize, treeSize);
var vertex = paperGraph.set(background,tree);
this._addCustomElements(id, vertex);
return [vertex];
};
function placeArrows() {
var startPos = vGraph.getVertexVisualInfo("start");
var endPos = vGraph.getVertexVisualInfo("end");
var arrowSrc = $("#arrow").attr("src");
var x1 = startPos.x - arrowAttr.width - vertexAttr.r;
var y1 = startPos.y - arrowAttr.height/2;
var x2 = endPos.x + vertexAttr.r;
var y2 = endPos.y - arrowAttr.height/2;
paperGraph.image(arrowSrc, x1, y1).attr(arrowAttr);
paperGraph.image(arrowSrc, x2, y2).attr(arrowAttr);
};
function vertexToggle(id,selected) {
var vertex = vGraph.getRaphaelsFromID(id);
if(selected){
vertex[0].attr(markedVertexAttr);
answer.push(id);
}else{
vertex[0].attr(vertexAttr);
var index = Beav.Array.indexOf(answer,id);
answer.splice(index,1);
}
updateEdges(id,selected);
var res = getResultAndMessage();
if(res.successRate === 1){
displayHelper.validate("stay");
}
};
function updateEdges(id,selected) {
var neighbors = graph.getNeighbors(id);
for(var iNeigh = 0; iNeigh < neighbors.length; iNeigh++){
if(graph.getVertexInfo(neighbors[iNeigh]).selected){
var edgeId = graph.getEdgesBetween(id,neighbors[iNeigh])[0];
var edge = vGraph.getRaphaelsFromID(edgeId);
var newAttr = (selected) ? markedEdgeAttr : edgeAttr;
edge[0].attr(newAttr);
}
}
};
function clickButton(i) {
return function() {
var x = buttons[i].elements.rect.attrs.x;
var y = buttons[i].elements.rect.attrs.y;
if(!answer[i] && answer[i] !== 0){
answer[i] = 0;
buttons[i].elements.text.remove();
}else{
answer[i] = (answer[i] + 1)%6;
buttons[i].elements.tree.remove();
}
var tree = paperPath.image(src[answer[i]],x,y,treeSize,treeSize);
buttons[i].addElement("tree",tree);
}
}
function getSrc() {
for(var iTree = 0; iTree < 6; iTree++){
src[iTree] = $("#tree_"+(iTree+1)).attr("src")
}
};
function reloadAnswer() {
if(level === "easy"){
for(var iVert = 0; iVert < answer.length; iVert++){
var id = answer[iVert];
graph.setVertexInfo(id,{selected:true});
var vertex = vGraph.getRaphaelsFromID(id);
vertex[0].attr(markedVertexAttr);
updateEdges(id,true);
}
}else{
for(var iAns = 0; iAns < answer.length; iAns++){
var x = buttons[iAns].elements.rect.attrs.x;
var y = buttons[iAns].elements.rect.attrs.y;
var tree = paperPath.image(src[answer[iAns]],x,y,treeSize,treeSize);
buttons[iAns].elements.text.remove();
buttons[iAns].addElement("tree",tree);
}
}
};
}
initWrapper(initTask, ["easy", "medium", "hard"]);
displayHelper.useFullWidth();
|
define(['whs'], function(WHS) {
describe('EffectComposer', () => {
const world = new WHS.World({ plugins: { rendering: false } });
function describeAttribute(composer, name, dims, Value) {
describe('.' + name, done => {
it('Method', () => composer[name].set(1, 1, 1));
it('Setter', () => {
composer[name] = new Value(...(new Array(dims.length).fill(2)));
});
it('Poperties', () => {
for (let i = 0; i < dims.length; i++)
composer[name][dims.charAt(i)] = 3;
});
});
}
function testAPI(composer) {
class DummyPass extends WHS.Pass {
constructor(name) {super(name);}
render() {}
}
it('#swapBuffers', () => composer.swapBuffers());
it('#addPass', () => composer.addPass(new DummyPass('one')));
it('#getPass', () => composer.getPass('one'));
it('#getPassIndex', () => composer.getPassIndex(0));
it('#addPassAfter', () => composer.addPassAfter('one', new DummyPass('two')));
it('#insertPass', () => composer.insertPass(new DummyPass('three'), 1));
it('#removePass', () => composer.removePass('one'));
it('#render', () => composer.render(0));
it('#reset', () => composer.reset(new THREE.WebGLRenderTarget(0, 0)));
it('#setSize', () => composer.setSize(0, 0));
}
context('Automated EffectComposer tests', () => {
const composer = new WHS.EffectComposer(world.renderer, new THREE.WebGLRenderTarget(0, 0));
testAPI(composer);
});
});
});
|
// import { version } from '../../package.json';
import { Router } from 'express';
import gewesten from './gewesten';
import gemeenten from './gemeenten';
import straten from './straten';
import huisnummers from './huisnummers';
import wegobjecten from './wegobjecten';
import wegsegmenten from './wegsegmenten';
import gebouwen from './gebouwen';
import facets from './facets';
import crab from './crab';
const SorteerVeld = 0;
const TaalCode = 'nl';
const GewestId = 1;
const GemeenteId = 71;
const StraatnaamId = 7338;
const HuisnummerId = 1373962;
const IdentificatorPerceel = '11020I0449/00G000';
const IdentificatorWegobject = 53835939;
const IdentificatorWegsegment = 262050;
const IdentificatorTerreinobject = '11020_I_0449_G_000_00';
const IdentificatorGebouw = 1874906;
const Operations = {
ListTalen: { SorteerVeld },
ListGewesten: { SorteerVeld },
GetGewestByGewestIdAndTaalCode: { GewestId, TaalCode },
ListGemeentenByGewestId: { GewestId, SorteerVeld },
GetGemeenteByGemeenteId: { GemeenteId },
ListStraatnamenByGemeenteId: { GemeenteId, SorteerVeld },
GetStraatnaamByStraatnaamId: { StraatnaamId },
ListHuisnummersByStraatnaamId: { StraatnaamId, SorteerVeld },
GetHuisnummerByHuisnummerId: { HuisnummerId },
ListPercelenByHuisnummerId: { HuisnummerId },
GetPerceelByIdentificatorPerceel: { IdentificatorPerceel },
ListGebouwenByHuisnummerId: { HuisnummerId, SorteerVeld },
GetGebouwByIdentificatorGebouw: { IdentificatorGebouw },
ListTerreinobjectenByHuisnummerId: { HuisnummerId, SorteerVeld },
GetTerreinobjectByIdentificatorTerreinobject: { IdentificatorTerreinobject },
ListWegobjectenByStraatnaamId: { StraatnaamId, SorteerVeld },
GetWegobjectByIdentificatorWegobject: { IdentificatorWegobject },
ListWegsegmentenByStraatnaamId: { StraatnaamId, SorteerVeld },
GetWegsegmentByIdentificatorWegsegment: { IdentificatorWegsegment },
};
const link = (href, text) => `<a href="${href}">${text}</a>`;
const operation = ([key, value]) => link(`api/crab?operation=${key}&${parameters(value)}`, key);
const parameter = ([param, val]) => `${param}=${val}`;
const parameters = param => Object.entries(param).map(parameter).join('&');
export default ({ config, db }) => {
let api = Router();
api.use('/crab', crab({ config, db }));
api.use('/facets', facets({ config, db }));
api.use('/gewesten', gewesten({ config, db }));
api.use('/gemeenten', gemeenten({ config, db }));
api.use('/straten', straten({ config, db }));
api.use('/huisnummers', huisnummers({ config, db }));
api.use('/wegobjecten', wegobjecten({ config, db }));
api.use('/wegsegmenten', wegsegmenten({ config, db }));
api.use('/gebouwen', gebouwen({ config, db }));
api.get('/', (req, res) => res.send(Object.entries(Operations).map(operation).join('<br>')));
return api;
};
|
$(document).ready(function() {
module("_.array.builders");
test("cat", function() {
// no args
deepEqual(_.cat(), [], 'should return an empty array when given no args');
// one arg
deepEqual(_.cat([]), [], 'should concatenate one empty array');
deepEqual(_.cat([1,2,3]), [1,2,3], 'should concatenate one homogenious array');
var result = _.cat([1, "2", [3], {n: 4}]);
deepEqual(result, [1, "2", [3], {n: 4}], 'should concatenate one heterogenious array');
result = (function(){ return _.cat(arguments); })(1, 2, 3);
deepEqual(result, [1, 2, 3], 'should concatenate the arguments object');
// two args
deepEqual(_.cat([1,2,3],[4,5,6]), [1,2,3,4,5,6], 'should concatenate two arrays');
result = (function(){ return _.cat(arguments, [4,5,6]); })(1,2,3);
deepEqual(result, [1,2,3,4,5,6], 'should concatenate an array and an arguments object');
// > 2 args
var a = [1,2,3];
var b = [4,5,6];
var c = [7,8,9];
var d = [0,0,0];
deepEqual(_.cat(a,b,c), [1,2,3,4,5,6,7,8,9], 'should concatenate three arrays');
deepEqual(_.cat(a,b,c,d), [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays');
result = (function(){ return _.cat(arguments,b,c,d); }).apply(null, a);
deepEqual(result, [1,2,3,4,5,6,7,8,9,0,0,0], 'should concatenate four arrays, including an arguments object');
// heterogenious types
deepEqual(_.cat([1],2), [1,2], 'should concatenate mixed types');
deepEqual(_.cat([1],2,3), [1,2,3], 'should concatenate mixed types');
deepEqual(_.cat(1,2,3), [1,2,3], 'should concatenate mixed types');
result = (function(){ return _.cat(arguments, 4,5,6); })(1,2,3);
deepEqual(result, [1,2,3,4,5,6], 'should concatenate mixed types, including an arguments object');
});
test("cons", function() {
deepEqual(_.cons(0, []), [0], 'should insert the first arg into the array given as the second arg');
deepEqual(_.cons(1, [2]), [1,2], 'should insert the first arg into the array given as the second arg');
deepEqual(_.cons([0], [1,2,3]), [[0],1,2,3], 'should insert the first arg into the array given as the second arg');
deepEqual(_.cons(1, 2), [1,2], 'should create a pair if the second is not an array');
deepEqual(_.cons([1], 2), [[1],2], 'should create a pair if the second is not an array');
result = (function(){ return _.cons(0, arguments); })(1,2,3);
deepEqual(result, [0,1,2,3], 'should construct an array given an arguments object as the tail');
var a = [1,2,3];
var result = _.cons(0,a);
deepEqual(a, [1,2,3], 'should not modify the original tail');
});
test("chunk", function() {
var a = _.range(4);
var b = _.range(5);
var c = _.range(7);
deepEqual(_.chunk(a, 2), [[0,1],[2,3]], 'should chunk into the size given');
deepEqual(_.chunk(b, 2), [[0,1],[2,3]], 'should chunk into the size given. Extras are dropped');
var result = _.chunk(a, 2);
deepEqual(a, _.range(4), 'should not modify the original array');
deepEqual(_.chunk(c, 3, [7,8]), [[0,1,2],[3,4,5],[6,7,8]], 'should allow one to specify a padding array');
deepEqual(_.chunk(b, 3, 9), [[0,1,2],[3,4,9]], 'should allow one to specify a padding value');
deepEqual(_.chunk(a, 3, 9), [[0,1,2],[3,9,9]], 'should repeat the padding value');
deepEqual(_.chunk(a, 3, undefined), [[0,1,2],[3,undefined,undefined]], 'should allow padding with undefined');
});
test("chunkAll", function() {
var a = _.range(4);
var b = _.range(10);
deepEqual(_.chunkAll(a, 2), [[0,1],[2,3]], 'should chunk into the size given');
deepEqual(_.chunkAll(b, 4), [[0,1,2,3],[4,5,6,7],[8,9]], 'should chunk into the size given, with a small end');
var result = _.chunkAll(a, 2);
deepEqual(a, _.range(4), 'should not modify the original array');
deepEqual(_.chunkAll(b, 2, 4), [[0,1],[4,5],[8,9]], 'should chunk into the size given, with skips');
deepEqual(_.chunkAll(b, 3, 4), [[0,1,2],[4,5,6],[8,9]], 'should chunk into the size given, with skips and a small end');
});
test("mapcat", function() {
var a = [1,2,3];
var commaize = function(e) { return _.cons(e, [","]); };
deepEqual(_.mapcat(a, commaize), [1, ",", 2, ",", 3, ","], 'should return an array with all intermediate mapped arrays concatenated');
});
test("interpose", function() {
var a = [1,2,3];
var b = [1,2];
var c = [1];
deepEqual(_.interpose(a, 0), [1,0,2,0,3], 'should put the 2nd arg between the elements of the array given');
deepEqual(_.interpose(b, 0), [1,0,2], 'should put the 2nd arg between the elements of the array given');
deepEqual(_.interpose(c, 0), [1], 'should return the array given if nothing to interpose');
deepEqual(_.interpose([], 0), [], 'should return an empty array given an empty array');
var result = _.interpose(b,0);
deepEqual(b, [1,2], 'should not modify the original array');
});
test("weave", function() {
var a = [1,2,3];
var b = [1,2];
var c = ['a', 'b', 'c'];
var d = [1, [2]];
// zero
deepEqual(_.weave(), [], 'should weave zero arrays');
// one
deepEqual(_.weave([]), [], 'should weave one array');
deepEqual(_.weave([1,[2]]), [1,[2]], 'should weave one array');
// two
deepEqual(_.weave(a,b), [1,1,2,2,3], 'should weave two arrays');
deepEqual(_.weave(a,a), [1,1,2,2,3,3], 'should weave two arrays');
deepEqual(_.weave(c,a), ['a',1,'b',2,'c',3], 'should weave two arrays');
deepEqual(_.weave(a,d), [1,1,2,[2],3], 'should weave two arrays');
// > 2
deepEqual(_.weave(a,b,c), [1,1,'a',2,2,'b',3,'c'], 'should weave more than two arrays');
deepEqual(_.weave(a,b,c,d), [1,1,'a',1,2,2,'b',[2],3,'c'], 'should weave more than two arrays');
});
test("repeat", function() {
deepEqual(_.repeat(3,1), [1,1,1], 'should build an array of size n with the specified element in each slot');
deepEqual(_.repeat(0), [], 'should return an empty array if given zero and no repeat arg');
deepEqual(_.repeat(0,9999), [], 'should return an empty array if given zero and some repeat arg');
});
test("cycle", function() {
var a = [1,2,3];
deepEqual(_.cycle(3, a), [1,2,3,1,2,3,1,2,3], 'should build an array with the specified array contents repeated n times');
deepEqual(_.cycle(0, a), [], 'should return an empty array if told to repeat zero times');
deepEqual(_.cycle(-1000, a), [], 'should return an empty array if told to repeat negative times');
});
test("splitAt", function() {
var a = [1,2,3,4,5];
deepEqual(_.splitAt(a, 2), [[1,2],[3,4,5]], 'should bifurcate an array at a given index');
deepEqual(_.splitAt(a, 0), [[], [1,2,3,4,5]], 'should bifurcate an array at a given index');
deepEqual(_.splitAt(a, 5), [[1,2,3,4,5],[]], 'should bifurcate an array at a given index');
deepEqual(_.splitAt([], 5), [[],[]], 'should bifurcate an array at a given index');
});
test("iterateUntil", function() {
var dec = function(n) { return n - 1; };
var isPos = function(n) { return n > 0; };
deepEqual(_.iterateUntil(dec, isPos, 6), [5,4,3,2,1], 'should build an array, decrementing a number while positive');
});
test("takeSkipping", function() {
deepEqual(_.takeSkipping(_.range(5), 0), [], 'should take nothing if told to skip by zero');
deepEqual(_.takeSkipping(_.range(5), -1), [], 'should take nothing if told to skip by negative');
deepEqual(_.takeSkipping(_.range(5), 100), [0], 'should take first element if told to skip by big number');
deepEqual(_.takeSkipping(_.range(5), 1), [0,1,2,3,4], 'should take every element in an array');
deepEqual(_.takeSkipping(_.range(10), 2), [0,2,4,6,8], 'should take every 2nd element in an array');
});
test("reductions", function() {
var result = _.reductions([1,2,3,4,5], function(agg, n) {
return agg + n;
}, 0);
deepEqual(result, [1,3,6,10,15], 'should retain each intermediate step in a reduce');
});
test("keepIndexed", function() {
var a = ['a', 'b', 'c', 'd', 'e'];
var b = [-9, 0, 29, -7, 45, 3, -8];
var oddy = function(k, v) { return _.isOdd(k) ? v : undefined; };
var posy = function(k, v) { return _.isPositive(v) ? k : undefined; };
deepEqual(_.keepIndexed(a, _.isOdd), [false,true,false,true,false], 'runs the predciate on the index, and not the element');
deepEqual(_.keepIndexed(a, oddy), ['b', 'd'], 'keeps elements whose index passes a truthy test');
deepEqual(_.keepIndexed(b, posy), [2,4,5], 'keeps elements whose index passes a truthy test');
deepEqual(_.keepIndexed(_.range(10), oddy), [1,3,5,7,9], 'keeps elements whose index passes a truthy test');
});
test('reverseOrder', function() {
var arr = [1, 2, 3];
deepEqual(_.reverseOrder(arr), [3, 2, 1], 'returns an array whose elements are in the opposite order of the argument');
deepEqual(arr, [1, 2, 3], 'should not mutate the argument');
var throwingFn = function() { _.reverseOrder('string'); };
throws(throwingFn, TypeError, 'throws a TypeError when given a string');
var argObj = (function() { return arguments; })(1, 2, 3);
deepEqual(_.reverseOrder(argObj), [3, 2, 1], 'works with other array-like objects');
});
test('collate', function() {
var properOrder = ['red', 'orange', 'yellow', 'green', 'blue', 'indigo', 'violet'];
var itemsBare = ['green', 'yellow', 'violet', 'red', 'indigo', 'orange', 'blue'];
var itemsObj = [{'prop':'green'}, {'prop':'yellow'}, {'prop':'violet'}, {'prop':'red'}, {'prop':'indigo'}, {'prop':'orange'}, {'prop':'blue'}];
var itemsRaw = ['g', 'y', 'v', 'r', 'i', 'o', 'b'];
var rawConvertFunc = function() {
return ({
'r': 'red',
'o': 'orange',
'y': 'yellow',
'g': 'green',
'b': 'blue',
'i': 'indigo',
'v': 'violet'
})[this];
};
deepEqual(_.collate(itemsBare, properOrder), properOrder, 'returns an array of scalars whose elements are ordered according to provided lexicon');
deepEqual(_.collate(itemsObj, properOrder, 'prop'), [{'prop':'red'}, {'prop':'orange'}, {'prop':'yellow'}, {'prop':'green'}, {'prop':'blue'}, {'prop':'indigo'}, {'prop':'violet'}], 'returns an array of objects that are ordered according to provided lexicon');
deepEqual(_.collate(itemsRaw, properOrder, rawConvertFunc), ['r', 'o', 'y', 'g', 'b', 'i', 'v'], 'returns an array whose elements are sorted by derived value according to provided lexicon');
});
});
|
/**
* PublicAuthorshipGroup.js
*
* @description :: TODO: You might write a short summary of how this model works and what it represents here.
* @docs :: http://sailsjs.org/documentation/concepts/models-and-orm/models
*/
module.exports = {
attributes: {
document: {
model: 'document',
primaryKey: true
},
researchEntity: {
model: 'group',
primaryKey: true
}
},
migrate: 'safe',
tableName: 'publicauthorshipgroup',
autoUpdatedAt: false,
autoCreatedAt: false
};
|
import React from 'react';
const CurrentInfo = ({
pokemon,
calculate
}) => {
let currentInfo = {};
return (
<div className="currentInfo">
<form onSubmit={e => {
e.preventDefault();
calculate(currentInfo.heldPokemon.value,currentInfo.heldCandies.value,pokemon.candyRequired);
}}>
<label className="heldPokemonText">Current Held {pokemon.name}:
<input className="heldPokemonEntry" type="text" ref={node => {
currentInfo.heldPokemon = node;
}}/>
</label>
<label className="heldCandiesText">Current {pokemon.name} Candies Held:
<input className="heldCandiesEntry" type="text" ref={node => {
currentInfo.heldCandies = node;
}}/>
<button className="calculateButton" type="submit">
Calculate!
</button>
</label>
</form>
</div>
);
}
export default CurrentInfo;
|
/**
* 日期编辑组件。
*
* @type {class}
*
* @remark
* 根据格式化字符串不同,可以显示为日期、时间、日期时间、月度等。
*/
define(['jquery', 'core', 'ui-editor', 'ui-tool-manager', 'wDatePicker'], function ($, hsr, _super, ToolUtils) {
'use strict';
var _superMethods = _super.prototype;
/**
* 构造方法。
*
* @param {HTMLElement | jQuery} element 主元素。
* @param {object} options 配置项。
*
* @constructor
*/
function DateEditorClass(element, options) {
// 私有属性。
var self = this;
// 特权属性。
// 继承父类。
_super.call(self, element, options);
}
// 继承父类。
hsr.inherit(DateEditorClass, _super);
/***********元数据***********/
var metedata = {
/**
* 版本。
* @type {string}
* @readonly
*/
version: '@VERSION@',
/**
* 样式类。
* @type {string}
* @readonly
*/
cssClass: '@CSS_PREFIX@editor-date',
/**
* 名称。
* @type {string}
* @readonly
*/
typeName: 'DateEditor'
};
$.extend(DateEditorClass, metedata);
// 注册组件。
ToolUtils.regiest(DateEditorClass);
/***********公共(及特权)方法***********/
$.extend(DateEditorClass.prototype, metedata, {
/**
* 创建配置属性。
*
* @returns {array} 配置属性信息。
*
* @protected
*/
_createOptionProperties: function () {
return [
{ name: 'format', value: '' } // 日期格式化字符串。
];
},
/**
* 创建控件。
*
* @param {jQuery} element$ 主元素。
* @param {object} options 配置项。
*
* @protected
*/
_create: function (element$, options) {
var self = this;
_superMethods._create.call(self, element$, options);
// 必须确定格式化字符串。
if(hsr.StringUtils.isBlank(options.format)) {
options.format = self._reckonFormat(element$);
}
// 存储值的隐藏域自动生成 ID 。
var id = 'picker_date_' + hsr.UUID.random();
self._value$.attr('id', id);
// 使用 My97DatePicker 控件。
var dateOptions = {
vel: id,
dateFmt: options.format
};
self._display$.attr('onfocus', 'WdatePicker(' + JSON.stringify(dateOptions) + ')');
//self._display$.attr('onfocus', 'WdatePicker({vel: \'' + id + '\', dateFmt: \'' + options.format + '\'})');
},
/**
* 刷新控件。
*
* @param {jQuery} element$ 主元素。
* @param {object} options 配置项。
*
* @protected
*/
_refresh: function (element$, options) {
var self = this;
_superMethods._refresh.call(self, element$, options);
},
/**
* 根据元素的样式推断格式化字符串。
*/
_reckonFormat: function (element$) {
if (element$.hasClass('date')) {
return 'yyyy-MM-dd';
} else if (element$.hasClass('time')) {
return 'HH:mm:ss';
} else if (element$.hasClass('datetime')) {
return 'yyyy-MM-dd HH:mm:ss';
} else if (element$.hasClass('month')) {
return 'yyyy-MM';
} else if (element$.hasClass('year')) {
return 'yyyy';
} else {
return 'yyyy-MM-dd';
}
}
});
/***********私有方法***********/
return DateEditorClass;
}); |
var test = require('tape');
var ndarray = require('ndarray');
var zeros = require('zeros');
var lu = require('../');
var toA = require('./lib/toa.js');
test('2x2', function (t) {
var A = ndarray([ 4, 3, 6, 3 ], [ 2, 2 ]);
var L = zeros([ 2, 2 ]);
var U = zeros([ 2, 2 ]);
t.ok(lu(A, L, U));
t.deepEqual(toA(U), [ [ 1, 1.5 ], [ 0, 1 ] ], 'U');
t.deepEqual(toA(L), [ [ 4, 0 ], [ 3, -1.5 ] ], 'L');
t.end();
});
|
var eventEmitter = require('../eventEmitter')
, async = require('async')
, _ = require('lodash');
var SagaHandler = {};
SagaHandler.prototype = {
sagas: {},
initialize: function(callback) {
var self = this;
function initSaga(id, data, callback) {
var saga = new self.Saga(id);
saga.commit = function(callback) {
self.commit(this, callback);
};
self.sagas[id] = saga;
saga.load(data, callback);
}
this.repository.find({ type: this.saga }, function(err, sagas) {
if (!err) {
async.forEach(sagas, function(saga, callback) {
initSaga(saga.id, saga, callback);
}, callback);
}
});
},
defaultHandle: function(id, evt) {
var self = this;
async.waterfall([
// load saga
function(callback) {
self.loadSaga(id, callback);
},
// transition the event
function(saga, callback) {
saga.transition(evt, function(err) {
callback(err, saga);
});
},
// commit the uncommittedEvents
function(saga, callback) {
self.commit(saga, callback);
}
],
// finally
function(err) {
if (!err) {
}
});
},
commit: function(saga, callback) {
var self = this;
this.repository.get(saga.id, function(err, vm) {
vm.set('type', self.saga);
if (saga.get('destroyed')) {
vm.destroy();
} else {
vm.set(saga.toJSON());
}
self.repository.commit(vm, function(err) {
callback(err);
});
});
},
handle: function(evt) {
if (this[evt.event]) {
this[evt.event](evt);
} else {
this.defaultHandle(evt.payload.id, evt);
}
},
loadSaga: function(id, callback) {
var self = this;
var saga = this.sagas[id];
if (!saga) {
saga = new this.Saga(id);
saga.commit = function(callback) {
self.commit(this, callback);
};
this.repository.get(id, function(err, sagaData) {
self.sagas[id] = saga;
saga.load(sagaData, function(err) {
callback(err, saga);
});
});
} else {
callback(null, saga);
}
},
configure: function(fn) {
fn.call(this);
return this;
},
use: function(module) {
if (!module) return;
if (module.commit) {
this.repository = module;
}
}
};
module.exports = {
extend: function(obj) {
return _.extend(_.clone(SagaHandler.prototype), obj);
}
}; |
'use strict';
var grunt = require('grunt');
/*
======== A Handy Little Nodeunit Reference ========
https://github.com/caolan/nodeunit
Test methods:
test.expect(numAssertions)
test.done()
Test assertions:
test.ok(value, [message])
test.equal(actual, expected, [message])
test.notEqual(actual, expected, [message])
test.deepEqual(actual, expected, [message])
test.notDeepEqual(actual, expected, [message])
test.strictEqual(actual, expected, [message])
test.notStrictEqual(actual, expected, [message])
test.throws(block, [error], [message])
test.doesNotThrow(block, [error], [message])
test.ifError(value)
*/
exports.plugin_rename_from_file = {
setUp: function(done) {
// setup here if necessary
done();
},
default_options: function(test) {
var file = '35d54f6649e07b9db764998faa2bce61.jpg';
var actual = grunt.file.exists('test/expected/' + file);
var expected = grunt.file.exists('dist/images/' + file);
grunt.file.exists
test.equal(actual, expected, 'should describe what the default behavior is.');
test.done();
}
};
|
function getAllScores(){
strokeRisk();
diabetesRisk();
CKDtoKF();
reynolds();
} |
const config = require('../../config.js');
const api = require('../../lib/api.js');
const request = require('../../lib/request.js');
const storage = require('../../lib/storage.js');
Page({
data:{
regSucImg:'../../images/suc.png',
second:5
},
onReady: function() {
storage.getStorage({
key: 'openId'
}).then((ress) => {
this.setData({
openId:ress
});
request({
method: 'POST',
header: {
"content-type": "application/x-www-form-urlencoded"
},
url: api.getUrl('/security/register/getPhone'),
data: {
openId:ress
}
}).then((resp) => {
this.setData({
phone:resp.data
});
})
})
},
onLoad:function(){
this.countDown();
},
countDown:function(){
var nowsec=this.data.second;
var that=this;
if(nowsec<=0){
clearTimeout(time);
this.gotoHome();
}
else{
var time=setTimeout(function(){
that.setData({
second:--nowsec
});
that.countDown();
},1000)
}
},
gotoHome:function() {
wx.redirectTo({ url: '../account/login' });
}
});
|
Object.defineProperty(exports,"__esModule",{value:true});
var _graphqlRelay=require('graphql-relay');
var _graphql=require('graphql');
var _Ensayo=require('../model/Ensayo');var _Ensayo2=_interopRequireDefault(_Ensayo);
var _NodeInterface=require('../../../../units/urb-base-server/graphql/NodeInterface');var _NodeInterface2=_interopRequireDefault(_NodeInterface);function _interopRequireDefault(obj){return obj&&obj.__esModule?obj:{default:obj};}exports.default=
new _graphql.GraphQLObjectType({
name:'Ensayo',
interfaces:[_NodeInterface2.default],
isTypeOf:function isTypeOf(object){return object instanceof _Ensayo2.default;},
fields:{
id:(0,_graphqlRelay.globalIdField)('Ensayo'),
Ensayo_Title:{type:_graphql.GraphQLString,resolve:function resolve(obj){return obj.Ensayo_Title;}},
Ensayo_Description:{type:_graphql.GraphQLString,resolve:function resolve(obj){return obj.Ensayo_Description;}},
Ensayo_Content:{type:_graphql.GraphQLString,resolve:function resolve(obj){return obj.Ensayo_Content;}}}});
//# sourceMappingURL=EnsayoType.js.map |
// Put your own keys here
exports.twitterConsumerKey = '';
exports.twitterConsumerSecret = '';
exports.twitterToken = '';
exports.twitterTokenSecret = '';
|
var Story = require('./Story.js');
var helper = require('./Helper.js')();
module.exports = StoryFactory;
function StoryFactory(opts){
if (!(this instanceof StoryFactory)) return new StoryFactory(opts);
this.opts = helper.extend({
name: 'Story Factory',
id: 'StoryFactory'
}, opts);
this.name = opts.name;
this.id = opts.id;
return this;
}
StoryFactory.prototype.generate = function() {
return new Story(this.opts);
}; |
/* ==========================================================================
* ./webpack.config.base.js
*
* Base/Shared Webpack config
* ========================================================================== */
const path = require('path');
const webpack = require('webpack');
const cssnano = require('cssnano');
module.exports = {
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
resolve: {
root: [
path.resolve(__dirname),
path.resolve(__dirname, 'node_modules')
],
alias: {
imgsRoot: path.resolve(__dirname, 'static/images'),
blurbsRoot: path.resolve(__dirname, 'static/blurbs')
}
},
module: {
loaders: [
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
],
include: [
path.resolve(__dirname, 'static/images')
]
},
{
test: /\.json$/,
loader: 'json'
}
]
},
plugins: [
new webpack.NoErrorsPlugin()
],
postcss: [
cssnano({
safe: true,
sourcemap: true,
autoprefixer: {
add: true,
remove: true,
browsers: [
'last 3 versions',
'ie >= 8',
'> 2%'
]
},
discardComments: {
removeAll: true
}
})
]
};
|
import { LOCATION_CHANGE, NOT_FOUND } from 'constants/ActionTypes';
import { quickNavRoutes } from 'constants/navItems';
export const DEFAULT_STATE = {
previousTo: null,
previousName: null,
nextTo: null,
nextName: null,
};
export function handleLocationChange(state, { pathname }) {
let i = 0;
quickNavRoutes.some((r, index) => {
if (r.to === pathname) {
i = index;
return true;
}
return false;
});
const previous = quickNavRoutes[i - 1] || {};
const next = quickNavRoutes[i + 1] || {};
return {
previousTo: previous.to || null,
previousName: previous.primaryText || null,
nextTo: next.to || null,
nextName: next.primaryText || null,
};
}
const pathname = __CLIENT__ ? window.location.pathname : '';
const initialState = handleLocationChange(DEFAULT_STATE, { pathname });
export default function quickNavigation(state = initialState, action) {
switch (action.type) {
case NOT_FOUND:
return DEFAULT_STATE;
case LOCATION_CHANGE:
return handleLocationChange(state, action.payload);
default:
return state;
}
}
|
/**
* @module widget-myportal-legal-ng
* @name LegalController
* @author Lenin Meza <lmeza@anzen.com.mx>
*
* @description
* Legal
*/
import { E_AUTH, E_CONNECTIVITY } from "lib-bb-model-errors";
const errorMessage = (code) => ({
[E_AUTH]: "error.load.auth",
[E_CONNECTIVITY]: "error.load.connectivity",
}[code] || "error.load.unexpected");
export default function LegalController(bus, hooks, model, widget) {
const $ctrl = this;
const portal = window.b$ && window.b$.portal;
console.log("portal:", portal);
// Referrer page
let referrerPage = widget.getStringPreference("referrerPage");
if (portal.portalName === "standalone-development") {
referrerPage = "/widget-myportal-login-ng";
}
/**
* AngularJS Lifecycle hook used to initialize the controller
*
* @name LegalController#$onInit
* @returns {void}
*/
const $onInit = () => {
$ctrl.isLoading = true;
model.load()
.then(loaded => {
$ctrl.items = hooks.itemsFromModel(loaded);
})
.catch(error => {
$ctrl.error = errorMessage(error.code);
bus.publish("widget-myportal-legal-ng.load.failed", { error });
})
.then(() => { $ctrl.isLoading = false; });
bus.publish("cxp.item.loaded", {
id: widget.getId(),
});
};
const onClickBtnBack = () => {
window.location.assign(referrerPage);
};
Object.assign($ctrl, {
$onInit,
onClickBtnBack,
/**
* @description
* The value returned from {@link Hooks.processItems} hook.
* null if the items aren't loaded.
*
* @name LegalController#items
* @type {any}
*/
items: null,
/**
* @description
* Loading status
*
* @name LegalController#isLoading
* @type {boolean}
*/
isLoading: false,
/**
* @description
* The error encountered when attempting to fetch from the model
*
* @name LegalController#error
* @type {ModelError}
*/
error: null,
});
}
|
$(function () {
"use strict";
$("#menuToggle, .btn-close").on("click", function (e) {
e.preventDefault();
});
$('.dropdown-menu a').click(function(e) {
e.stopPropagation();
});
function getGridSize() {
return (Modernizr.mq('(max-width:490px)')) ? 1 :
(Modernizr.mq('(max-width:705px)')) ? 2 :
(Modernizr.mq('(max-width:768px)')) ? 3 : 4;
}
/* ---------------------------------------------------------
* Background
*/
$.backstretch([
"assets/img/background/1.jpg",
"assets/img/background/2.jpg",
"assets/img/background/3.jpg"
], {duration: 3800, fade: 1500});
/* ---------------------------------------------------------
* WOW
*/
new WOW({
mobile: false
}).init();
/* ---------------------------------------------------------
* Knob
*/
$(".dial").knob({
draw : function () {
// "tron" case
if(this.$.data('skin') == 'tron') {
var a = this.angle(this.cv) // Angle
, sa = this.startAngle // Previous start angle
, sat = this.startAngle // Start angle
, ea // Previous end angle
, eat = sat + a // End angle
, r = true;
this.g.lineWidth = this.lineWidth;
this.o.cursor
&& (sat = eat - 0.3)
&& (eat = eat + 0.3);
if (this.o.displayPrevious) {
ea = this.startAngle + this.angle(this.value);
this.o.cursor
&& (sa = ea - 0.3)
&& (ea = ea + 0.3);
this.g.beginPath();
this.g.strokeStyle = this.previousColor;
this.g.arc(this.xy, this.xy, this.radius - this.lineWidth, sa, ea, false);
this.g.stroke();
}
this.g.beginPath();
this.g.strokeStyle = r ? this.o.fgColor : this.fgColor ;
this.g.arc(this.xy, this.xy, this.radius - this.lineWidth, sat, eat, false);
this.g.stroke();
this.g.lineWidth = 2;
this.g.beginPath();
this.g.strokeStyle = this.o.fgColor;
this.g.arc(this.xy, this.xy, this.radius - this.lineWidth + 1 + this.lineWidth * 2 / 3, 0, 2 * Math.PI, false);
this.g.stroke();
return false;
}
}
});
/* ---------------------------------------------------------
* TextRotator
*/
$(".rotate").textrotator({
animation: "dissolve", // You can pick the way it animates when rotating through words. Options are dissolve (default), fade, flip, flipUp, flipCube, flipCubeUp and spin.
separator: ",", // If you don't want commas to be the separator, you can define a new separator (|, &, * etc.) by yourself using this field.
speed: 2000 // How many milliseconds until the next word show.
});
/* ---------------------------------------------------------
* Scroll arrow
*/
$("#scroll").click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1200);
return false;
}
}
});
/* ---------------------------------------------------------
* Timeline
*/
$("[data-toggle='collapse']").on("click", function(e){
e.preventDefault();
var id = $('.v-icon[data-target="' + $(this).attr("data-target") + '"]');
var icon = $(id).children("i");
if(/fa-minus/i.test($(icon).attr("class"))){
$(icon).removeClass("fa-minus").addClass("fa-plus");
}
else{
$(icon).removeClass("fa-plus").addClass("fa-minus");
}
});
/* ---------------------------------------------------------
* Twitter
*/
twitterFetcher.fetch({
"id": '345170787868762112',
"domId": '',
"maxTweets": 3,
"enableLinks": true,
"showInteraction": false,
"showUser": false,
"customCallback": function handleTweets(tweets){
var x = tweets.length,
n = 0,
tweetsHtml = '<ul class="twitterFeed">';
while(n < x) {
tweetsHtml += '<li>' + tweets[n] + '</li>';
n++;
}
tweetsHtml += '</ul>';
$('#twitterFeed').html(tweetsHtml);
$(".twitterFeed").bxSlider({
nextText: "",
prevText: ""
});
}
});
/*
* Navigation
* ----------------------------------------------------------------- */
$('#nav').affix({
offset: {
top: $('#home').height() - 80
}
});
/*
* Navbar scrolls
* ----------------------------------------------------------------- */
$(".navbar-nav").find("a").on("click", function(e){
e.preventDefault();
if($(this).attr("href") != "#"){
$.scrollTo($(this).attr("href"),1000, {offset: {left: 0, top: -80}});
}
});
/* ---------------------------------------------------------
* Portfolio
*/
var $grid = $('#portfolio-container');
$grid.imagesLoaded( function() {
$grid.shuffle({
itemSelector: '.portfolio-item',
speed: 450
});
$('#filter a').click(function (e) {
e.preventDefault();
// set active class
$('#filter a').removeClass('active');
$(this).addClass('active');
// get group name from clicked item
var groupName = $(this).attr('data-group');
// reshuffle grid
$grid.shuffle('shuffle', groupName );
});
});
/* ---------------------------------------------------------
* GITheWall
*/
$('.GITheWall').GITheWall({
nextButtonClass: 'fa fa-chevron-right',
prevButtonClass: 'fa fa-chevron-left',
closeButtonClass: 'fa fa-times',
dynamicHeight: false,
onShow: function(){
$("#portfolio-container").slideDown(300).fadeOut(300);
$(".filter-tags").slideDown(300).fadeOut(300);
$("#portfolio-more").slideDown(300).fadeOut(300);
},
onHide: function(){
$("#portfolio-container").slideUp(300).fadeIn(300);
$(".filter-tags").slideUp(300).fadeIn(300);
$("#portfolio-more").slideUp(300).fadeIn(300);
}
});
/* ---------------------------------------------------------
* CounterUp
*/
$('.counter').counterUp({
delay: 100,
time: 2000
});
/* ---------------------------------------------------------
* SignUp form
*/
$('#signupForm').bootstrapValidator({
message: 'This value is not valid',
feedbackIcons: {
valid: 'fa fa-check',
invalid: 'fa fa-times',
validating: 'fa fa-refresh'
},
submitHandler: function (validator, form, submitButton) {
var l = Ladda.create(submitButton[0]),
btnText = submitButton.children(".ladda-label");
l.start();
btnText.html("Signing up...");
$.get(form.attr('action'), form.serialize(), function(result) {
btnText.html(result.message);
}, 'json')
.always(function() {
l.stop();
validator.disableSubmitButtons(true);
});
},
fields: {
email: {
validators: {
notEmpty: {
message: 'Email cannot be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
}
}
});
/* ---------------------------------------------------------
* Contact form
*/
$('#contactForm').bootstrapValidator({
fields: {
name: {
validators: {
notEmpty: {
message: 'Name cannot be empty'
},
stringLength: {
min: 6,
max: 30,
message: 'Name must be more than 6 and less than 30 characters long'
},
regexp: {
regexp: /^[a-zA-Z\s]+$/,
message: 'Name can only consist alphabetical characters'
}
}
},
contactEmail: {
validators: {
notEmpty: {
message: 'Email cannot be empty'
},
emailAddress: {
message: 'The input is not a valid email address'
}
}
},
message: {
validators: {
notEmpty: {
message: 'Message cannot be empty'
}
}
}
},
feedbackIcons: {
valid: 'fa fa-check',
invalid: 'fa fa-times',
validating: 'fa fa-refresh'
},
submitHandler: function (validator, form, submitButton) {
var l = Ladda.create(submitButton[0]),
btnText = submitButton.children(".ladda-label");
l.start();
btnText.html("Sending...");
$.post(form.attr('action'), form.serialize(), function(result) {
if(result.sent){
btnText.html("Sent!");
}
else{
btnText.html("Error!");
}
// Reset form after 5s
setTimeout(function() {
btnText.html("Submit");
$(form[0])[0].reset();
validator.resetForm();
}, 5000);
}, 'json')
.always(function() {
l.stop();
validator.disableSubmitButtons(true);
});
},
});
}); |
var Commodity = createClass('Commodity', {
initialize: function(data){
// todo
this.name = data.name;
this.size = data.size;
}
}); |
var path = require('path');
//These get used so much, they may as well be global
global.q = require('q');
global.extend = require('extend');
global.requireAll = require('require-all');
global.express = require('express');
global._ = require('lodash');
global.http = require('http');
global.flash = require('express-flash'); //For sending temporary messages to redirects
global.fs = require('fs'); //For file system calls
global.path = require('path');
global.url = require('url');
global.moment = require('moment');
global.gm = require('gm');
global.sizeOf = require('image-size');
global.Chance = require('chance'); //For generating random names, dates, etc.
//Global configuration settings
global.settings = {
ROOT_DIR: process.cwd(),
NODE_ENV: process.env.NODE_ENV,
UPLOADS_PATH: 'public/uploads',
UPLOADS_URL_PATH: '/photos/',
LOG_PATH: 'logs/',
ADMIN_PASSWORD: 'spawncamping', //Password given by TA for bulk upload security
/*
To use this connection string, run the following commands in your localhost mysql
CREATE USER 'user'@'localhost';
GRANT ALL PRIVILEGES ON *.* TO 'user'@'localhost' WITH GRANT OPTION;
SET PASSWORD FOR 'user'@'localhost' = PASSWORD('user');
CREATE DATABASE seng_development;
*/
db: {
//NOTE!!!!!! config.json will need to be changed to reflect these changes (to perform migrations)
TABLE: 'seng_development',
USERNAME: 'user',
PASSWORD: 'user',
options: {
host: 'localhost',
port: 3306
}
}
};
//System functions/required modules
global.system = {
pathTo: function (/**..args**/) {
var args = Array.prototype.slice.call(arguments);
args.unshift(settings.ROOT_DIR);
return path.join.apply(null, args);
},
/**
* @example
* getPath('/p/a/t/h', {query: 'myquery'}) => '/p/a/t/h?query=myquery'
*
* @param path the url path
* @param [query] any query parameters to send
* @param [options] additional url options (e.g. host, port)
* @returns {string}
*/
getUrlPath: function (path, query, options) {
return url.format(_.extend({pathname: path, query: query}, options));
},
ext: requireAll(path.join(settings.ROOT_DIR, '/core/ext/')),
//Settings for performance mode
performance: {
hostname: 'localhost', //Change this to test performance on localhost
ROOT_DIR: process.cwd(), //Also change this to the path to your repository (for image upload)
protocol: 'http',
port: 8800,
pathTo: function (/**..args**/) {
var args = Array.prototype.slice.call(arguments);
args.unshift(this.ROOT_DIR);
return path.join.apply(null, args)
.replace(/\\/g,'/'); //Replace all black slashes (Windows) with forward slashes (so the path can be used on Linux)
},
/**
* @example
* If performance server host is host.com:80, then
* getPath('/p/a/t/h', {query: 'myquery'}) => 'host.com:80/p/a/t/h?query=myquery'
*
* @param path the url path
* @param [query] any query parameters to send
* @returns {string}
*/
getUrlPath: function (path, query) {
return system.getUrlPath(path, query, {hostname: this.hostname, port: this.port, protocol: this.protocol});
},
RESULTS_DIR: 'results/',
tests: {
userCreationChunkSize: 20, //Decrease this if timeouts occur during creation of followers
concurrency: {
runTest: true, //Turn on/off concurrency tests
options: {
maxSessions: 100,
step: 10
}
},
followers: {
runTest: true, //Turn on/off followers tests
options: {
numUsers: 400,
step: 10
}
}
}
}
};
//Database Logging
if (!fs.existsSync(system.pathTo(settings.LOG_PATH))) { //Create log folder if it doesn't exist
fs.mkdirSync(system.pathTo(settings.LOG_PATH));
};
var queryLog = fs.createWriteStream(system.pathTo(settings.LOG_PATH+'queries.txt'), {
flags: 'w'
});
global.settings.db.options.logging = function(toLog){
var date = new Date();
queryLog.write(date.getTime() + 'ms : ' + date.toUTCString() + ' ' + toLog + '\n');
};
//Express configuration
global.app = express();
app.set('port', process.env.PORT || 8800);
app.set('views', system.pathTo('core/views/'));
app.set('view engine', 'jade');
app.use(express.favicon());
// Request Logging
express.logger.token('user', function(req, res){
return (req.session && req.session.login) ? req.session.login.id : 'anonymous';
});
express.logger.token('session', function(req, res){
return req.sessionID || 'null';
});
app.use(express.logger({
format: ':date [:remote-addr] [:session] [:user] [:response-time ms] [req::req[Content-Length] res::res[Content-Length]] :method :status :url ',
immediate: false,
stream: fs.createWriteStream(system.pathTo(settings.LOG_PATH+'requests.txt'), {
flags: 'w'
})
}));
app.use(express.json({limit: '100mb'}));
app.use(express.urlencoded({limit: '100mb'}));
app.use(express.multipart());
app.use(express.methodOverride());
// Session Management
app.use(express.cookieParser());
app.use(express.session({secret: 'spawncampingsupersecuresession'}));
//Configure flash messages
app.use(flash());
//Helper functions for user login in Jade templates
app.use(function(req,res,next){
/**
* Indicates if the user is logged in
* @returns {boolean}
*/
res.locals.userLoggedIn = function () {
return req.session.login;
}
//Direct access to logged in user object
res.locals.user = req.session.login;
next();
});
app.use(app.router);
app.use(express.static(system.pathTo('public/')));
app.use(settings.UPLOADS_URL_PATH, express.static(system.pathTo(settings.UPLOADS_PATH))); //Direct photo requests to uploads folder
// Load mode-specific configurations
switch (settings.NODE_ENV) {
case 'development':
require('./development.js');
break;
case 'production':
require('./production.js');
break;
case 'test':
require('./test.js');
break;
}
require('./my_config'); //Load computer-specific configurations
global.helpers = requireAll(system.pathTo('/core/helpers/'));
global.classes = require(system.pathTo('/core/classes/'));
global.db = require(system.pathTo('core/models/'));
//Load routes configurations
require(system.pathTo('routes/config'));
//Create image upload directories, if they don't exist already
helpers.system.createImageUploadDirectories();
//Allow access to globals in Jade files
app.locals.db = db;
|
(function(n){typeof define=="function"&&define.amd?define(["jquery","hammerjs"],n):typeof exports=="object"?n(require("jquery"),require("hammerjs")):n(jQuery,Hammer)})(function(n,t){function i(i,r){var u=n(i);u.data("hammer")||u.data("hammer",new t(u[0],r))}n.fn.hammer=function(n){return this.each(function(){i(this,n)})};t.Manager.prototype.emit=function(t){return function(i,r){t.call(this,i,r);n(this.element).trigger({type:i,gesture:r})}}(t.Manager.prototype.emit)});
//# sourceMappingURL=jquery.hammer.min.js.map
|
/*jslint node: true */
module.exports = function (Gearman) {
'use strict';
exports.setUpGearman = function (hostname, port) {
var gearman = new Gearman(hostname, port);
console.info('Listening to gearman on %s:%d', hostname, port);
gearman.on('connect', function () {
console.info('Connected to Gearman!\n');
});
gearman.on('idle', function () {
console.info('No jobs, resting!\n');
});
gearman.on('close', function () {
console.error('Gearman connection closed!\n');
});
gearman.on('error', function () {
console.error('Gearman error, disconnected!\n');
});
return gearman;
};
return exports;
};
|
import media from '../media'
import css from 'styled-components'
describe('Testing the media utility', () => {
it('should return the correct media query for the phone size', () => {
const result = media.phone(`background-color: red`)
expect(result[0]).toBe('\n @media (max-width: ')
expect(result[1]).toBe('36')
});
it('should return the correct media query for the desktop size', () => {
const result = media.desktop(`background-color: red`)
expect(result[0]).toBe('\n @media (max-width: ')
expect(result[1]).toBe('62')
});
it('should return the correct media query for the tablet size', () => {
const result = media.tablet(`background-color: red`)
expect(result[0]).toBe('\n @media (max-width: ')
expect(result[1]).toBe('48')
});
})
|
'use strict';
var eventsApp = angular.module('eventsApp', ['ngSanitize','ngResource','ngCookies','ngRoute'])
.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when('/reg',
{
templateUrl:'templates/reg.html',
controller:'EditEventCtrl'
})
.when('/event',
{
//routeDemo:'hella manaken',
templateUrl:'templates/eventList.html',
controller:'AllEventCtrl'
})
.when('/event/:eventId',
{
templateUrl:'templates/eventDetails.html',
controller:'EventCtrl'
})
.otherwise({redirectTo:'/event'})
;
$locationProvider.html5Mode(true);
});
//.factory('cacheService', function ($cacheFactory) {
// return $cacheFactory('cacheService',{capacity:3});
//}); |
(function(define) {
'use strict';
define(function(require) {
return function(loader) {
var utils, Variable, List;
utils = require('../utils');
Variable = loader.getClass('Variable');
List = loader.getClass('List');
/**
* Return the sum of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'sum', function sum(skipMissing) {
return this.asScalar().reduce(utils.op.add, 0, skipMissing);
});
/**
* Return the product of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'prod', function prod(skipMissing) {
return this.asScalar().reduce(utils.op.mult, 1, skipMissing);
});
/**
* Return the mean of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'mean', function mean(skipMissing) {
var v; // the variable whose mean we will return
v = filterMissing(this.asScalar(), skipMissing);
return utils.singleMissing(v.sum() / v.length());
});
/**
* Return the variance of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'var', function variance(skipMissing) {
var res, K;
res = this.reduce(function(acc, val) {
if (K == null) { K = val; } // Center around first value for stability
val -= K;
acc.sum += val;
acc.sumSquares += val * val;
acc.length += 1;
return acc;
}, { sum: 0, sumSquares: 0, length: 0 }, skipMissing);
return utils.singleMissing(
(res.sumSquares - res.sum * res.sum / res.length) / (res.length - 1)
);
});
/**
* Return the standard deviation of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'sd', function sd(skipMissing) {
return utils.singleMissing(Math.sqrt(this.var(skipMissing)));
});
/**
* Return the minimum of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'min', function min(skipMissing) {
return this.asScalar().reduce(utils.op.min2, Infinity, skipMissing);
});
/**
* Return the maximum of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'max', function max(skipMissing) {
return this.asScalar().reduce(utils.op.max2, -Infinity, skipMissing);
});
/**
* Return a `Variable` representing the permutation that sorts the values of the
* original variable according to the order specified by `desc`.
* - If `desc` is a boolean value, then `false` indicates ascending order, `true`
* indicates descending order.
* - If `desc` is a function `f(a, b)`, then it is interpreted as the comparator
* for sorting, and must return `-1` if `a` precedes `b`, `0` if `a` and `b` are "equal"
* in order, and `1` if `b` precedes `a`.
* - If `desc` is omitted, it defaults to `false` (ascending order).
*/
loader.addInstanceMethod('Variable', 'order', function order(desc) {
return Variable.scalar(this.toVector().order(desc));
});
/**
* Return a new `Variable` with the values sorted in the order specified by `desc`.
* See `Variable#order`.
*/
loader.addInstanceMethod('Variable', 'sort', function sort(desc) {
return this.select(this.toVector().order(desc).toArray());
});
/**
* Return a 'named' scalar variable of the requested quantiles for the values
* of the variable.
*
* `probs` can be a single number or a one-dimensional object (`Array`,
* `Vector` or `Variable`) and is used to specify the desired quantiles.
* Each value in `probs` should be in the range [0, 1]. If a value in `probs`
* is 'utils.isMissing' then the corresponding quantile will be recorded as
* `utils.missing`.
*
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and the variable
* has missing values, an error is thrown.
*/
loader.addInstanceMethod('Variable', 'quantile',
function quantile(probs, skipMissing) {
var getQuant, quantiles, names;
if (skipMissing === true) {
return this.nonMissing().quantile(probs);
} else if (this.hasMissing()) {
throw new Error(
'missing values in variable and skipMissing not set to true'
);
}
probs = Variable.ensureArray(probs);
probs.forEach(function(p) {
if (p < 0 || p > 1) { throw new Error('"probs" outside [0, 1]'); }
});
getQuant = function(p) {
var g, k;
p = p * (this.length() - 1) + 1;
k = Math.floor(p);
g = p - k; // fractional part of scaled prob
// interpolate: (1-g)*x[k] + g*x[k+1]
return (1 - g) * this.get(k) + g * this.get(k + 1);
}.bind(this.asScalar().sort());
quantiles = probs.map(utils.makePreserveMissing(getQuant));
names = probs.map(function(prob) {
return utils.optionMap(prob, function(p) { return p * 100 + '%'; });
});
return Variable.scalar(quantiles).names(names);
});
/**
* Return the median of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'median', function median(skipMissing) {
return this.hasMissing() && skipMissing !== true ? utils.missing
: this.quantile(0.5, true).get(1);
});
/**
* Return a 'named' scalar variable of the five-number of the values of the variable.
* `skipMissing` defaults to `false`. If `skipMissing` is `false` and
* the variable has missing values, return `utils.missing`.
*/
loader.addInstanceMethod('Variable', 'fiveNum', function fiveNum(skipMissing) {
return this.quantile([0, 0.25, 0.5, 0.75, 1], skipMissing)
.names(['Min', 'Q1', 'Median', 'Q3', 'Max']);
});
/**
* Return a frequency table for the variable, in the form of a 'named' scalar
* variable. The variable is treated as a factor variable in order to
* accumulate the frequencies.
*/
loader.addInstanceMethod('Variable', 'table', function table() {
var factor, freqs, missing, names;
factor = Variable.factor(this.toArray()).sort();
freqs = [];
missing = 0;
factor.each(function(val) {
if (utils.isMissing(val)) {
missing += 1;
} else {
freqs[val - 1] = freqs[val - 1] ? freqs[val - 1] + 1 : 1;
}
});
names = factor.levels();
if (missing > 0) { freqs.push(missing); names.push(utils.missing); }
return Variable.scalar(freqs).names(names);
});
/**
* Rescale the variable based on the provided `center` and `scale`.
* Return a `List` holding three items:
* - `center`
* - `scale`
* - `values` (a `Variable` holding the rescaled values).
*
* Must be called with two arguments.
*/
loader.addInstanceMethod('Variable', 'scale', function(center, scale) {
return new List({
center: center,
scale: scale,
values: this.map(function(x) { return (x - center) / scale; })
});
});
/**
* Return the standardized values using `Variable#rescale` where `center` is the
* mean of the variable and `scale` is the standard deviation.
*
* Missing values are preserved, but are ignored in the computation.
*/
loader.addInstanceMethod('Variable', 'zscore', function zscore() {
return this.scale(this.mean(true), this.sd(true));
});
/**
* Return the Pearson correlation coefficient between two variables, `xs` and `ys`.
* By default, uses all the values of both variables. If `skipMissing` is not set
* to `true` and missing values exist, return `utils.missing`.
*
* The two variables must have the same length.
*/
loader.addModuleMethod('stats', 'correlate', function correlate(xs, ys, skipMissing) {
var M, MTM, V, validIndices; // V is vector [sumX, sumY]
// calculate M, the cleaned-up 2-col matrix of xs & ys
if (!xs.sameLength(ys)) {
throw new Error('correlate requires same-length variables');
}
validIndices = Variable.seq(xs.length())
.filter(function(i) {
return utils.isNotMissing(xs.get(i)) && utils.isNotMissing(ys.get(i));
});
if (validIndices.length() !== xs.length()) {
if (skipMissing !== true) { return utils.missing; }
xs = xs.get(validIndices);
ys = ys.get(validIndices);
}
M = new Variable.Matrix([Variable.ensureArray(xs), Variable.ensureArray(ys)]);
MTM = M.transpose().mult(M);
V = M.mapCol(function(col) { return col.reduce(utils.op.add, 0); });
M = MTM.pAdd(V.outer(V).sMult(-1 / M.nrow)); // really, -VVT / n
return M.get(1, 2) / Math.sqrt(M.get(1, 1) * M.get(2, 2));
});
// helper methods
// Takes a variable `v` and a boolean `skipMissing`.
// If `skipMissing` is true, filters out those missing values.
// skipMissing defaults to false.
function filterMissing(v, skipMissing) {
return skipMissing === true ? v.nonMissing() : v;
}
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) {
'use strict';
module.exports = factory(require);
}));
|
var SteamPriceManager = require('./index.js');
SteamPriceManager.prototype._checkCache = function(itemName, callback) {
if(this.cache) {
if(this.getCache(itemName) === null || ((this.getCache(itemName).updated_at + this.cache) < (new Date().getTime() / 1000))) {
callback(false);
} else {
callback(true, this.getCache(itemName));
}
} else {
callback(false);
}
}
SteamPriceManager.prototype._addBackpackToCache = function(data) {
var items = data.response.items;
for(var index in items) {
// BackpackTF returns values in cents... and in USD currency
this.setCache(index, { "lowest_price": items[index].value / 100, "updated_at": new Date().getTime() / 1000 });
}
this.saveCache();
}
SteamPriceManager.prototype._initCacheData = function() {
var fsCacheFileExists = this._fs.existsSync(this._cacheFile);
if(fsCacheFileExists && Object.getOwnPropertyNames(this._cacheData).length == 0) {
this._cacheData = JSON.parse(this._fs.readFileSync(this._cacheFile));
}
}
SteamPriceManager.prototype.setCache = function(itemName, data) {
data.updated_at = new Date().getTime() / 1000;
this._cacheData[itemName] = data;
}
SteamPriceManager.prototype.getCache = function(itemName) {
return this._cacheData[itemName] || null;
}
SteamPriceManager.prototype.saveCache = function() {
this._fs.writeFile(this._cacheFile, JSON.stringify(this._cacheData));
}
|
var checkPassIsValid;
function checkPass()
{
//Store the password field objects into variables ...
var pass1 = document.getElementById('pass1');
var pass2 = document.getElementById('pass2');
//Store the Confimation Message Object ...
var message = document.getElementById('confirmMessage');
//Set the colors we will be using ...
var goodColor = "#66cc66";
var badColor = "#ff6666";
//Compare the values in the password field
//and the confirmation field
if (pass1.value == pass2.value) {
//The passwords match.
//Set the color to the good color and inform
//the user that they have entered the correct password
pass2.style.backgroundColor = goodColor;
message.style.color = goodColor;
message.innerHTML = "Passwords Match";
checkPassIsValid = true;
console.log(checkPassIsValid);
} else {
//The passwords do not match.
//Set the color to the bad color and
//notify the user.
pass2.style.backgroundColor = badColor;
message.style.color = badColor;
// message.innerHTML = "Passwords Do Not Match!"
document.getElementById("confirmMessage").innerHTML = "<span class='warning'>Passwords Do Not Match!</span>";
checkPassIsValid = false;
console.log(checkPassIsValid);
}
}
function validatephone(phone)
{
var maintainplus = '';
var numval = phone.value
if ( numval.charAt(0)=='+' )
{
var maintainplus = '';
}
curphonevar = numval.replace(/[\\A-Za-z!"£$%^&\,*+_={};:'@#~,.Š\/<>?|`¬\]\[]/g,'');
phone.value = maintainplus + curphonevar;
var maintainplus = '';
phone.focus;
}
// validates text only
function Validate(txt) {
txt.value = txt.value.replace(/[^a-zA-Z-'\n\r.]+/g, '');
}
// validates text only
function Validate2(txt) {
txt.value = txt.value.replace(/[^a-zA-Z-'\n\r.]+/g, '');
}
function username_validate(txt)
{
if(txt.length < 3)
{
document.getElementById("usernameStatus").innerHTML = "<span class='warning'>user name is not valid yet.</span>";
return false;
}
else
{
document.getElementById("usernameStatus").innerHTML =null;
return true;
}
}
// validate email
function email_validate(email)
{
var regMail = /^([_a-zA-Z0-9-]+)(\.[_a-zA-Z0-9-]+)*@([a-zA-Z0-9-]+\.)+([a-zA-Z]{2,3})$/;
if(regMail.test(email) == false)
{
document.getElementById("status").innerHTML = "<span class='warning'>Email address is not valid yet.</span>";
return false;
}
else
{
document.getElementById("status").innerHTML = "<span class='valid'>Thanks, you have entered a valid Email address!</span>";
return true;
}
}
// validate password
function pass_validate(pas)
{
var input=pas;
var reo = /[0-9]/;
var re = /[a-zA-Z]/;
var letters=re.test(input);
var numbers=reo.test(input);
if (letters& numbers& pas.length>5)
{
document.getElementById("passwordStatus").innerHTML=null;
}
else
{
document.getElementById("passwordStatus").innerHTML = "<span class='warning'>Password is not valid yet.</span>";
}
}
// validate date of birth
function dob_validate(dob)
{
var regDOB = /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{4})$/;
if(regDOB.test(dob) == false)
{
document.getElementById("statusDOB").innerHTML = "<span class='warning'>DOB is only used to verify your age.</span>";
}
else
{
document.getElementById("statusDOB").innerHTML = "<span class='valid'>Thanks, you have entered a valid DOB!</span>";
}
}
// validate address
function add_validate(address)
{
var regAdd = /^(?=.*\d)[a-zA-Z\s\d\/]+$/;
if(regAdd.test(address) == false)
{
document.getElementById("statusAdd").innerHTML = "<span class='warning'>Address is not valid yet.</span>";
}
else
{
document.getElementById("statusAdd").innerHTML = "<span class='valid'>Thanks, Address looks valid!</span>";
}
}
|
import { moduleForComponent, test } from 'ember-qunit';
moduleForComponent('cart-item', 'Unit | Component | cart item', {
// Specify the other units that are required for this test
// needs: ['component:foo', 'helper:bar'],
unit: true
});
test('it renders', function(assert) {
assert.expect(2);
// Creates the component instance
var component = this.subject();
assert.equal(component._state, 'preRender');
// Renders the component to the page
this.render();
assert.equal(component._state, 'inDOM');
});
|
var incan_client = require('./index.js').client;
var YOUR_UID = 0;
var YOUR_API_KEY = "";
var client = new incan_client(YOUR_UID, YOUR_API_KEY);
client.addImageUrl('http://incandescent.xyz/wp-content/themes/twentyfifteen/logo.png');
client.assemble();
client.sendRequest(function(projectId) {
console.log(projectId);
client.getResults(projectId, function(data) {
console.log(data);
})
});
|
define( {
//var currentLine = 0;
removeCodeCompletor: function() {
var div = $('#file-drag')[0];
var cNodes = div.childNodes;
for(var n =0; n<=cNodes.length-1; n++) {
if(cNodes[n].className == 'dropdownmenu') {
div.removeChild(cNodes[n]);
}
}
},
isCompletorRunning: function() {
if($('.dropdownmenu')[0] != undefined) {
return true;
}
return false;
}
}); |
'use strict';
var util = require('util');
var path = require('path');
var yeoman = require('yeoman-generator');
var BaboonTopLevelAppGenerator = module.exports = function () {
yeoman.generators.Base.apply(this, arguments);
this.argument('TopLevelName', { type: String, required: true });
this.argument('TopLevelPageName', { type: String, required: false });
this.TopLevelName = this.TopLevelName || undefined;
};
util.inherits(BaboonTopLevelAppGenerator, yeoman.generators.Base);
BaboonTopLevelAppGenerator.prototype.ask = function () {
if (!this.TopLevelName) {
// If no AppName defined ask for it
}
this.TopLevelName = this._.camelize(this._.slugify(this._.humanize(this.TopLevelName)));
this.TopLevelPageName = (this.TopLevelPageName || 'index').toLowerCase();
};
BaboonTopLevelAppGenerator.prototype.build = function () {
// this.sourceRoot(path.join(__dirname, 'client'));
this.destinationRoot(path.join('client', 'app', this.TopLevelName));
// Basic
this.template('index.html');
this.template('navigation.json');
this.template('routes.js');
// Appname
this.template('toplevel.js', this.TopLevelName + '.js');
this.template('toplevel.less', this.TopLevelName + '.less');
// Localization
this.template(path.join('__locale', 'locale-de-de.json'));
this.template(path.join('__locale', 'locale-en-us.json'));
// Page
this.template('index/index.html', path.join(this.TopLevelPageName, this.TopLevelPageName + '.html'));
this.template('index/index.js', path.join(this.TopLevelPageName, this.TopLevelPageName + '.js'));
this.template('index/index.spec.js', path.join(this.TopLevelPageName, this.TopLevelPageName + '.spec.js'));
}; |
Package.describe({
name: 'baysao:restivus',
summary: 'Create authenticated REST APIs in Meteor 0.9+ via HTTP/HTTPS. Setup CRUD endpoints for Collections.',
version: '0.8.4',
git: 'https://github.com/baysao/meteor-restivus.git'
});
Package.onUse(function (api) {
// Minimum Meteor version
api.versionsFrom('METEOR@0.9.0');
// Meteor dependencies
api.use('check');
api.use('coffeescript');
api.use('underscore');
api.use('accounts-base@1.2.0');
api.use('simple:json-routes@1.0.4');
api.addFiles('lib/auth.coffee', 'server');
api.addFiles('lib/iron-router-error-to-response.js', 'server');
api.addFiles('lib/route.coffee', 'server');
api.addFiles('lib/restivus.coffee', 'server');
// Exports
api.export('Restivus', 'server');
});
Package.onTest(function (api) {
// Meteor dependencies
api.use('practicalmeteor:munit');
api.use('test-helpers');
api.use('nimble:restivus');
api.use('http');
api.use('coffeescript');
api.use('underscore');
api.use('accounts-base');
api.use('accounts-password');
api.use('mongo')
api.addFiles('test/api_tests.coffee', 'server');
api.addFiles('test/route_unit_tests.coffee', 'server');
api.addFiles('test/authentication_tests.coffee', 'server');
});
|
app.controller('mail_template_form_ctrl', function ($scope, $modal, $sce) {
$scope.show_info = function($event, info) {
$scope.open_info('mb', 'infoContent', info);
$event.preventDefault();
$event.stopPropagation();
};
$scope.open_info = function (size, el, info) {
var info_el= '#'+info;
var info_html = $(info_el).html();
$scope.info = $sce.trustAsHtml(info_html);
var elem = '#'+el;
var temp = $(elem).html();
var modalInstance = $modal.open({
template: temp,
controller: 'ModalInfoInstanceCtrl',
size: size,
resolve: {
info: function () {
return $scope.info;
}
}
});
modalInstance.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
});
};
});
|
import { prime } from './nth-prime';
describe('nth-prime', () => {
test('first prime', () => {
expect(prime(1)).toEqual(2);
});
xtest('second prime', () => {
expect(prime(2)).toEqual(3);
});
xtest('sixth prime', () => {
expect(prime(6)).toEqual(13);
});
xtest('big prime', () => {
expect(prime(10001)).toEqual(104743);
});
xtest('there is no zeroth prime', () => {
expect(() => prime(0)).toThrow(new Error('there is no zeroth prime'));
});
});
|
var mfoPjax = {};
(function () {
mfoPjax.init = init;
mfoPjax.onError = onError;
mfoPjax.load = load;
mfoPjax.reload = reload;
mfoPjax.onBeforeNonPjaxPushState = onBeforeNonPjaxPushState;
mfoPjax.stripBody = stripBody;
var lastButton = null;
function init() {
$(document).on('click', '[data-pjax] a', onNavigate);
$(document).on('submit', '[data-pjax] form', onSubmitForm);
$(window).on('popstate', onPopState);
$(document).on('click', 'input[type=submit], button', onSubmitClicked);
}
function onSubmitClicked(e) {
if (lastButton) {
lastButton.removeAttr('clicked');
}
lastButton = $(e.currentTarget);
lastButton.attr('clicked', 'true');
}
function onNavigate(e) {
var anchor = $(e.currentTarget);
if (anchor.attr('data-nopjax')) {
return;
}
var container = findContainer(anchor);
var url = anchor.attr('href');
if (!url || url.substr(0, 1) === '#') {
return;
}
if (url.toLowerCase().substr(0, 7) === 'http://' || url.toLowerCase().substr(0, 8) === 'https://') {
return; // we don't pjax external links
}
var context = {
anchor: anchor,
url: url,
verb: 'GET',
container: container
};
container.trigger("pjax:navigate", context);
if (context.cancel === true) {
return;
}
markFromPjax(container);
mfoPjax.load(context, navigateSuccess);
e.preventDefault();
}
function onSubmitForm(e) {
var form = $(e.currentTarget);
var clickedButton = form.find('*[clicked=true]');
if (clickedButton.attr('data-nopjax')) {
return;
}
var container = findContainer(form);
var data = form.serialize();
if (clickedButton.length > 0) {
var name = clickedButton.attr('name');
if (name) {
data += '&' + name + '=' + (clickedButton.attr('value') || "");
}
}
var context = {
form: form,
url: form.attr('action') || location.pathname + location.search + location.hash,
data: data,
verb: form.attr('method') || 'GET',
container: container
};
container.trigger("pjax:submitform", context);
if (context.cancel === true) {
return;
}
markFromPjax(container);
mfoPjax.load(context, navigateSuccess);
e.preventDefault();
}
function findContainer(child) {
var container = child.closest('[data-pjax]');
if (!container.attr('id')) {
container.attr('id', 'pjax_' + new Date().valueOf());
}
return container;
}
function markFromPjax(container) {
if (history.state === null || history.state.containerId !== container.attr('id') || !history.state.navigatedFromPjax) {
var state = history.state || {};
state.url = location.pathname + location.search + location.hash;
state.containerId = container.attr('id');
state.navigatedFromPjax = true;
history.replaceState(state, null, '');
}
}
function onBeforeNonPjaxPushState() {
var state = history.state;
if (state && state.navigatedFromPjax) {
delete state.navigatedFromPjax;
history.replaceState(state, '', null);
}
}
function onPopState(e) {
var popState = e.originalEvent.state;
if (popState === null || !popState.containerId || !popState.navigatedFromPjax) {
return;
}
var container = $('#' + popState.containerId);
if (container.length === 0) {
// no container - just refresh the page
location.reload();
return;
}
var context = {
verb: 'GET',
url: popState.url,
container: container
};
mfoPjax.load(context, function (context, data) {
render(context, data);
});
}
function onError(jqXHR, textStatus, errorThrown) {
// default is to display the error in an alert
// clients can change pjax.onError to their requirements
alert('Error: textStatus="' + textStatus + '"\nerrorThrown="' + errorThrown + '"');
}
function navigateSuccess(context, data, textStatus, jqXHR) {
render(context, data);
if (context.noPushState === true) {
return;
}
var url = stripInternalParams(jqXHR.getResponseHeader('X-PJAX-URL') || context.url);
if (url !== location.href) {
history.pushState({ url: url, containerId: context.container.attr('id'), navigatedFromPjax: true }, null, url);
}
}
function stripInternalParams(url) {
return url.replace(/([?&])(_pjax|_)=[^&]*/g, '');
}
function stripBody(data, includeErrorTitle) {
var first100 = data.substr(0, 100);
if (first100.indexOf('<html') >= 0 || first100.indexOf('<HTML') >= 0) {
// loading a full HTML page into the PJAX body is an error, so
// attempt to scrape out the <body> part of the page and
// disable the scripts
var bodyStart = Math.max(data.indexOf('<body'), data.indexOf('<BODY'));
if (bodyStart >= 0) {
data = data.substr(bodyStart + 5);
var bodyStartClose = data.indexOf('>');
if (bodyStartClose >= 0) {
data = data.substr(bodyStartClose + 1);
}
}
var bodyEnd = Math.max(data.indexOf('body>'), data.indexOf('BODY>'));
if (bodyEnd >= 0) {
data = data.substr(0, bodyEnd);
var bodyEndOpen = data.lastIndexOf('</');
if (bodyEndOpen >= 0) {
data = data.substr(0, bodyEndOpen);
}
}
data = data.replace(/<script/g, 'script_tag_disabled_pjax_error: ');
data = data.replace(/<SCRIPT/g, 'SCRIPT_TAG_DISABLED_PJAX_ERROR: ');
if (includeErrorTitle) {
data = '<div data-title="Error - Attempt to load non-PJAX page into container">'
+ '<h1 style="background:white; color: red">Error - Attempt to load non-PJAX page into container</h1>'
+ '<div>' + data + '</div></div>';
}
}
return data;
}
function render(context, data) {
data = stripBody(data, true);
var container = context.container;
container.html(data);
if (context.noPushState !== true) {
var pjaxContent = container.children(':first');
var title = pjaxContent.attr('data-title');
document.title = title;
}
}
function load(context, callback) {
callback = callback || navigateSuccess;
var overlay = mfoOverlay.add()
.css('cursor', 'wait');
var headers = {
'X-PJAX': 'true',
'X-PJAX-URL': context.url
};
$.extend(headers, context.headers);
$.ajax({
headers: headers,
cache: false,
type: context.verb,
url: context.url,
data: context.data,
timeout: 29000,
dataType: 'html',
success: function (data, textStatus, jqXHR) {
mfoOverlay.remove(overlay);
callback(context, data, textStatus, jqXHR);
if (context.container) {
context.container.trigger('pjax:loaded', context);
} else {
console.warn('context.container not set in pjax:load (cannot raise pjax:loaded event)');
}
},
error: function (jqXHR, textStatus, errorThrown) {
mfoOverlay.remove(overlay);
if (jqXHR.status === 401) {
var location = jqXHR.getResponseHeader('location');
if (location) {
context.url = location;
load(context, callback);
return;
}
}
mfoPjax.onError(jqXHR, textStatus, errorThrown, context, callback);
}
});
}
function reload(context) {
var url = context.container.attr('data-pjax');
if (url === 'true') {
url = location.pathname + location.search + location.hash;
}
context.url = url;
context.verb = 'GET';
context.noPushState = true;
load(context);
}
}());
|
"use strict";
var assert = require("assert");
var path = require("path");
var Q = require("q");
var util = require("./util");
var spawn = require("child_process").spawn;
var ReadFileCache = require("./cache").ReadFileCache;
var grepP = require("./grep");
var glob = require("glob");
var env = process.env;
function BuildContext(options, readFileCache) {
var self = this;
assert.ok(self instanceof BuildContext);
assert.ok(readFileCache instanceof ReadFileCache);
if (options) {
assert.strictEqual(typeof options, "object");
} else {
options = {};
}
Object.freeze(options);
Object.defineProperties(self, {
readFileCache: { value: readFileCache },
config: { value: options.config },
options: { value: options },
optionsHash: { value: util.deepHash(options) }
});
}
var BCp = BuildContext.prototype;
BCp.makePromise = function (callback, context) {
return util.makePromise(callback, context);
};
BCp.spawnP = function (command, args, kwargs) {
args = args || [];
kwargs = kwargs || {};
var deferred = Q.defer();
var outs = [];
var errs = [];
var options = {
stdio: "pipe",
env: env
};
if (kwargs.cwd) {
options.cwd = kwargs.cwd;
}
var child = spawn(command, args, options);
child.stdout.on("data", function (data) {
outs.push(data);
});
child.stderr.on("data", function (data) {
errs.push(data);
});
child.on("close", function (code) {
if (errs.length > 0 || code !== 0) {
var err = {
code: code,
text: errs.join("")
};
}
deferred.resolve([err, outs.join("")]);
});
var stdin = kwargs && kwargs.stdin;
if (stdin) {
child.stdin.end(stdin);
}
return deferred.promise;
};
BCp.setIgnoreDependencies = function (value) {
Object.defineProperty(this, "ignoreDependencies", {
value: !!value
});
};
// This default can be overridden by individual BuildContext instances.
BCp.setIgnoreDependencies(false);
BCp.setRelativize = function (value) {
Object.defineProperty(this, "relativize", {
value: !!value
});
};
// This default can be overridden by individual BuildContext instances.
BCp.setRelativize(false);
BCp.setUseProvidesModule = function (value) {
Object.defineProperty(this, "useProvidesModule", {
value: !!value
});
};
// This default can be overridden by individual BuildContext instances.
BCp.setUseProvidesModule(false);
BCp.setCacheDirectory = function (dir) {
if (!dir) {
// Disable the cache directory.
} else {
assert.strictEqual(typeof dir, "string");
}
Object.defineProperty(this, "cacheDir", {
value: dir || null
});
};
// This default can be overridden by individual BuildContext instances.
BCp.setCacheDirectory(null);
function PreferredFileExtension(ext) {
assert.strictEqual(typeof ext, "string");
assert.ok(this instanceof PreferredFileExtension);
Object.defineProperty(this, "extension", {
value: ext.toLowerCase()
});
}
var PFEp = PreferredFileExtension.prototype;
PFEp.check = function (file) {
return file.split(".").pop().toLowerCase() === this.extension;
};
PFEp.trim = function (file) {
if (this.check(file)) {
var len = file.length;
var extLen = 1 + this.extension.length;
file = file.slice(0, len - extLen);
}
return file;
};
PFEp.glob = function () {
return "**/*." + this.extension;
};
exports.PreferredFileExtension = PreferredFileExtension;
BCp.setPreferredFileExtension = function (pfe) {
assert.ok(pfe instanceof PreferredFileExtension);
Object.defineProperty(this, "preferredFileExtension", { value: pfe });
};
BCp.setPreferredFileExtension(new PreferredFileExtension("js"));
BCp.expandIdsOrGlobsP = function (idsOrGlobs) {
var context = this;
return Q.all(idsOrGlobs.map(this.expandSingleIdOrGlobP, this)).then(function (listOfListsOfIDs) {
var result = [];
var seen = {};
util.flatten(listOfListsOfIDs).forEach(function (id) {
if (!seen.hasOwnProperty(id)) {
seen[id] = true;
if (util.isValidModuleId(id)) result.push(id);
}
});
return result;
});
};
BCp.expandSingleIdOrGlobP = function (idOrGlob) {
var context = this;
return util.makePromise(function (callback) {
// If idOrGlob already looks like an acceptable identifier, don't
// try to expand it.
if (util.isValidModuleId(idOrGlob)) {
callback(null, [idOrGlob]);
return;
}
glob(idOrGlob, {
cwd: context.readFileCache.sourceDir
}, function (err, files) {
if (err) {
callback(err);
} else {
callback(null, files.filter(function (file) {
return !context.isHiddenFile(file);
}).map(function (file) {
return context.preferredFileExtension.trim(file);
}));
}
});
});
};
BCp.readModuleP = function (id) {
return this.readFileCache.readFileP(id + "." + this.preferredFileExtension.extension);
};
BCp.readFileP = function (file) {
return this.readFileCache.readFileP(file);
};
// Text editors such as VIM and Emacs often create temporary swap files
// that should be ignored.
var hiddenExp = /^\.|~$/;
BCp.isHiddenFile = function (file) {
return hiddenExp.test(path.basename(file));
};
BCp.getProvidedP = util.cachedMethod(function () {
var context = this;
var pattern = "@providesModule\\s+\\S+";
return grepP(pattern, context.readFileCache.sourceDir).then(function (pathToMatch) {
var idToPath = {};
Object.keys(pathToMatch).sort().forEach(function (path) {
if (context.isHiddenFile(path)) return;
var id = pathToMatch[path].split(/\s+/).pop();
// If we're about to overwrite an existing module identifier,
// make sure the corresponding path ends with the preferred
// file extension. This allows @providesModule directives in
// .coffee files, for example, but prevents .js~ temporary
// files from taking precedence over actual .js files.
if (!idToPath.hasOwnProperty(id) || context.preferredFileExtension.check(path)) idToPath[id] = path;
});
return idToPath;
});
});
var providesExp = /@providesModule[ ]+(\S+)/;
BCp.getProvidedId = function (source) {
var match = providesExp.exec(source);
return match && match[1];
};
exports.BuildContext = BuildContext;
//# sourceMappingURL=context-compiled.js.map |
(function () {
var ceclient = new CEClient();
var username, password;
$(document).ready(function () {
ceclient.init(true, true);
$('#container').html('<div id="form_login">'+
'<input id="username" class="loginFields" placeholder="username" type="text" class="inline">'+
'<input id="password" class="loginFields" placeholder="password" type="password" class="inline">'+
'<input id="submit" type="button" class="inline" value="Login" ></div>');
$('#container').on( 'click', '#submit', function () {execLogin($('#username').val(), $('#password').val());});
$('.loginFields').keypress(function (e) {
if (e.which==13){
execLogin($('#username').val(), $('#password').val());
}
});
var execLogin = function (username, password) {
ceclient.login(username, password,
function (res) {
if(res==true){
$('#form_login').slideUp('slow', function(){
$('#container').html(
'<div id="form_graph" style="display: inline">'+
'<input id="responseId" placeholder="response ID" type="text" class="inline" value="3658">'+
'<input id="checkHappy" type="checkbox" class="inline, metricCheck" value="3" checked="checked"> Happy'+
'<input id="checkSurprise" type="checkbox" class="inline, metricCheck" value="4" checked="checked"> Surprise'+
'<input id="checkAngry" type="checkbox" class="inline, metricCheck" value="5" checked="checked"> Angry'+
'<input id="checkDisgust" type="checkbox" class="inline, metricCheck" value="6" checked="checked"> Disgust'+
'<input id="checkFear" type="checkbox" class="inline, metricCheck" value="7" checked="checked"> Fear'+
'<input id="checkSadness" type="checkbox" class="inline, metricCheck" value="8" checked="checked"> Sadness'+
'<input id="checkPositiveMood" type="checkbox" class="inline, metricCheck" value="9" checked="checked"> Positive mood'+
'<input id="checkNegativeMood" type="checkbox" class="inline, metricCheck" value="10" checked="checked"> Negative mood'+
'<input id="checkEngagement" type="checkbox" class="inline, metricCheck" value="11" checked="checked"> Engagement '+
'<input id="submitRequestId" type="button" class="inline" value="Send Request" >'+
'<div id="graph"></div></div>');
$('#responseId').keypress(function (e) {
if (e.which==13){
$('#submitRequestId').click();
}
})
$('#form_graph').slideDown('slow');
});
$('#container').on( 'click', '#submitRequestId', function () {
//plot the graph
ceclient.readTimeseries($('#responseId').val(),[1,3,4,5,6,7,8],drawGraph,true);
});
$('#container').on( 'click', '#submitLogout', function () {
execLogout();
})
}
else{
alert('Login fail');
}
});
}
var execLogout = function (res) {
ceclient.logout(function (){location.reload(true);});
};
var drawGraph = function (apiData) {
$('#form_graph').slideUp('slow');
var metricIds = $('input:checkbox:checked.metricCheck').map(function () {
return this.value;
}).get();
showGraph(apiData,"line",metricIds,"graph");
$('#form_graph').slideDown('slow');
window.addEventListener('resize', function () {
d3.select("#graph").html("");
console.log(parseInt(d3.select("#graph").style("width").substring(0,d3.select("#graph").style("width").length-2)));
showGraph(apiData,"line",metricIds,"graph");
// console.log(parseInt(d3.select("#graph").style("width").substring(0,d3.select("#graph").style("width").length-2)));
});
};
});
})(); |
import createField from './createField';
import plain from './structure/plain';
export default createField(plain); |
/**
* @fileOverview Sisältää {@link Item}-luokan toteutuksen.
*/
"use strict";
/**#nocode+*/
var log = require('./Utils').log
, NET = require('./Constants').NET;
/**#nocode-*/
/**
* Luo uuden tavaran ja etsii sille paikan. Lisää tavaran Server.items listaan
* @class Tavaroiden toteutus
*
* @param {Server} server Käynnissä oleva NetMatch-palvelin
* @param {Map} map Kartta johon uusi tavara luodaan
* @param {Byte} itemId Tavaran tunnus
* @param {Byte} itemType Tavaran tyyppi, kts. {@link ITM}
*
* @property {Byte} id Tavaran tunnus
* @property {Byte} type Tavaran tyyppi, kts. {@link ITM}
* @property {Number} x Tavaran sijainti
* @property {Number} y Tavaran sijainti
*/
function Item(server, map, itemId, itemType) {
var randX, randY;
this.server = server;
this.id = itemId;
this.type = itemType;
var randomPlace = map.findSpot();
this.x = randomPlace.x;
this.y = randomPlace.y;
}
/**
* Siirtää tavaran toiseen paikkaan ja palauttaa siirretyn tavaran tyypin.
* Lähettää kaikille clienteille tiedon uudesta sijainnista.
* @see ITM
*
* @returns {Byte} Siirretyn tavaran tyyppi
*/
Item.prototype.pick = function () {
var randomPlace = this.server.gameState.map.findSpot();
this.x = randomPlace.x;
this.y = randomPlace.y;
this.server.messages.addToAll({
msgType: NET.ITEM,
itemId: this.id,
itemType: this.type,
x: this.x,
y: this.y
});
return this.type;
};
module.exports = Item;
|
import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';
const SprkTextarea = ({
additionalClasses,
analyticsString,
forwardedRef,
idString,
isDisabled,
id,
value,
formatter,
onChange,
ariaDescribedBy,
isValid,
...rest
}) => {
return (
<textarea
className={classNames('sprk-b-TextArea', additionalClasses, {
'sprk-b-TextArea--error': !isValid,
})}
id={id}
disabled={isDisabled}
ref={forwardedRef}
data-id={idString}
value={isValid && formatter ? formatter(value) : value}
onChange={onChange}
data-analytics={analyticsString}
aria-invalid={!isValid}
aria-describedby={ariaDescribedBy}
{...rest}
/>
);
};
SprkTextarea.propTypes = {
/**
* A space-separated string of classes to add
* to the outermost container of the component.
*/
additionalClasses: PropTypes.string,
/**
* Assigned to the `data-analytics` attribute serving as a
* unique selector for outside libraries to capture data.
*/
analyticsString: PropTypes.string,
/**
* A ref passed in will be attached to the textarea
* element of the rendered component.
*/
forwardedRef: PropTypes.oneOfType([PropTypes.shape(), PropTypes.func]),
/**
* Assigned to the `data-id` attribute serving as a
* unique selector for automated tools.
*/
idString: PropTypes.string,
/**
* Determines whether to render the
* component in the valid or the error state.
*/
isValid: PropTypes.bool,
/**
* Assigned to the `id` attribute
* of the rendered textarea element.
* A custom ID will
* be added if this is not supplied.
*/
id: PropTypes.string.isRequired,
/**
* Assigned to the `aria-describedby`
* attribute. Used to create
* relationships between the
* component and text that describes it,
* such as helper text or an error field.
*/
ariaDescribedBy: PropTypes.string,
/**
* Will render the component in it's disabled state.
*/
isDisabled: PropTypes.bool,
/**
* A function supplied will be passed the value of the
* textarea and then executed, if the valid prop is true. The value
* returned will be assigned to the value of the textarea.
*/
formatter: PropTypes.func,
/**
* Assigned to the `value` attribute
* of the rendered input element.
*/
value: PropTypes.string,
/**
* A function that handles the
* onChange of the textarea.
*/
onChange: PropTypes.func,
};
SprkTextarea.defaultProps = {
forwardedRef: React.createRef(),
isValid: true,
};
export default SprkTextarea;
|
/*!
* Module dependencies.
*/
var utils = require('../utils');
var SchemaType = require('../schematype');
/**
* Boolean SchemaType constructor.
*
* @param {String} path
* @param {Object} options
* @inherits SchemaType
* @api public
*/
function SchemaBoolean(path, options) {
SchemaType.call(this, path, options, 'Boolean');
}
/**
* This schema type's name, to defend against minifiers that mangle
* function names.
*
* @api public
*/
SchemaBoolean.schemaName = 'Boolean';
/*!
* Inherits from SchemaType.
*/
SchemaBoolean.prototype = Object.create(SchemaType.prototype);
SchemaBoolean.prototype.constructor = SchemaBoolean;
/**
* Check if the given value satisfies a required validator. For a boolean
* to satisfy a required validator, it must be strictly equal to true or to
* false.
*
* @param {Any} value
* @return {Boolean}
* @api public
*/
SchemaBoolean.prototype.checkRequired = function(value) {
return value === true || value === false;
};
/**
* Casts to boolean
*
* @param {Object} value
* @api private
*/
SchemaBoolean.prototype.cast = function(value) {
if (value === null) {
return value;
}
if (value === '0') {
return false;
}
if (value === 'true') {
return true;
}
if (value === 'false') {
return false;
}
return !!value;
};
SchemaBoolean.$conditionalHandlers =
utils.options(SchemaType.prototype.$conditionalHandlers, {});
/**
* Casts contents for queries.
*
* @param {String} $conditional
* @param {any} val
* @api private
*/
SchemaBoolean.prototype.castForQuery = function($conditional, val) {
var handler;
if (arguments.length === 2) {
handler = SchemaBoolean.$conditionalHandlers[$conditional];
if (handler) {
return handler.call(this, val);
}
return this.cast(val);
}
return this.cast($conditional);
};
/*!
* Module exports.
*/
module.exports = SchemaBoolean;
|
/*
Floor (and ceiling)
Used by Room, converted to 3D rect for simulation
Structure: {
properties: {
scattering: [NormNum],
transmission: [NormNum],
absorbtion: [NormNum]
}
};
Functions:
floor.serialize: Converts wall into javascript object for serialization
floor.toThree(scene): Converts wall to 3D Rect for three.js and returns mesh.
*/
var Floor = function(params){
var floor = {
bottom: (params.top || params.ceiling) ? false : (params.bottom || true)
};
floor.serialize = function(){
return {
bottom: floor.bottom,
properties: floor.properties
};
};
floor.toThree = function(scene, roomProps){
// create three.js object
var geometry = new THREE.BoxGeometry(1000, 10000, roomProps.wallWidth);
var material = new THREE.MeshBasicMaterial( { color: 0xff00ff } );
var mesh = new THREE.Mesh( geometry, material );
mesh.visible = false;
mesh.position.set(0,0, floor.bottom ? 0 : roomProps.wallHeight);
return mesh;
};
return floor;
};
|
version https://git-lfs.github.com/spec/v1
oid sha256:28b62e60259062a9375d374b582af5fecabf6c00d2a2a34e50afa583d0a47daa
size 155966
|
/**
* Created on 4/27/17.
*
* @author Andrei Petushok (apetushok@gmail.com)
*/
var questions = {
"1" : "question_1",
"2" : "question_2",
"3" : "question_3",
"4" : "question_4",
"5" : "question_5",
"6" : "question_6",
"7" : "question_7",
"8" : "question_8"
};
var answers = {
"1" : "answer_1",
"2" : "answer_2",
"3" : "answer_3",
"4" : "answer_4",
"5" : "answer_5",
"6" : "answer_6",
"7" : "answer_7",
"8" : "answer_8",
"9" : "answer_9",
"10" : "answer_10",
"11" : "answer_11",
"12" : "answer_12",
"13" : "answer_13",
"14" : "answer_14",
"15" : "answer_15",
"16" : "answer_16",
"17" : "answer_17",
"18" : "answer_18",
"19" : "answer_19",
"20" : "answer_20",
"21" : "answer_21",
"22" : "answer_22",
"23" : "answer_23",
"24" : "answer_24"
};
var answers_questions = [
{"1": "1"},
{"1": "2"},
{"1": "3"},
{"2": "4"},
{"2": "5"},
{"2": "6"},
{"3": "7"},
{"3": "8"},
{"3": "9"},
{"3": "10"},
{"4": "11"},
{"4": "12"},
{"4": "13"},
{"5": "14"},
{"5": "15"},
{"5": "16"},
{"5": "17"},
{"6": "18"},
{"6": "19"},
{"7": "20"},
{"7": "21"},
{"7": "22"},
{"8": "23"},
{"8": "24"},
];
var questions_with_type = [];
// save on server side
var correct_answers = {
"1": ["2","1"],
"2": ["5"],
"3": ["4"],
"4": ["3"]
}; |
// ComponentSettingsView.js (c) 2012 Loren West and other contributors
// May be freely distributed under the MIT license.
// For further details and documentation:
// http://lorenwest.github.com/node_monitor
(function(root){
// Module loading
var Monitor = root.Monitor || require('monitor'),
UI = Monitor.UI,
Template = UI.Template,
Backbone = Monitor.Backbone,
_ = Monitor._,
customSettings = null,
template = null;
/**
* Component settings dialog view
*
* @class ComponentSettingsView
* @extends SettingsView
* @constructor
*/
var ComponentSettingsView = UI.ComponentSettingsView = UI.SettingsView.extend({
// Constructor
initialize: function(options) {
var t = this;
t.modelBinder = new Backbone.ModelBinder();
t.viewOptionBinder = new Backbone.ModelBinder();
t.monitorParamBinder = new Backbone.ModelBinder();
t.pageView = options.pageView;
t.componentView = options.componentView;
t.model = t.componentView.model;
if (!template) {
template = new Template({
text: $('#nm-template-ComponentSettings').html()
});
}
},
// Event declarations
events: {
"click .btn-primary" : "saveChanges",
"click .btn-cancel" : "cancelChanges",
"click .nm-cs-view-source" : "toggleViewSource",
"click .nm-cs-edit" : "toggleEditSource",
"click .nm-cs-save" : "toggleEditSource",
"click .nm-cs-copy" : "copy",
"click .nm-cs-cancel" : "cancelEditSource",
"click h4" : "toggleSection",
"keydown" : "onKeydownLocal"
},
// This is called once after construction to render the
// components onto the screen. The components change their
// value when the data model changes.
render: function() {
var t = this;
t.$el.append(template.apply({}));
t.editor = t.$('.nm-cs-source-edit');
t.sourceButton = t.$('.nm-cs-view-source');
// Get bindings to 'name=' attributes before custom views are rendered
t.componentBindings = Backbone.ModelBinder.createDefaultBindings(t.$el, 'name');
},
// Set the specified data model into the component, specifying
// any custom component settings view
setModel: function(model, componentView, customView) {
var t = this,
componentPane = t.$('.nm-cs-component');
// Remember the model state on entry
t.model = model;
t.monitor = model.get('monitor');
t.originalModel = t.model.toJSON({trim:false});
// Remove any inner views
if (t.sourceView) {
t.sourceView.remove();
}
if (t.customView) {
t.customView.remove();
}
// Clean up prior monitorParams
if (t.monitorParams) {
t.monitorParams.off('change');
}
// Create the custom settings view
if (customView) {
t.customView = new customView({
model: t.model.get('viewOptions'),
monitor: t.model.get('monitor'),
pageView: UI.pageView,
component: t.model,
componentView: componentView
});
t.$('.nm-cs-view-settings').append(t.customView.el);
t.customView.render();
}
// Normal data binding - name to model
t.modelBinder.bind(t.model, t.$el, t.componentBindings);
// Bind data-view-option elements to component.viewOptions
t.viewOptionBinder.bind(
t.model.get('viewOptions'),
componentPane,
Backbone.ModelBinder.createDefaultBindings(componentPane, 'data-view-option')
);
// Bind data-monitor-param elements to monitor.initParams.
// This is a bit more difficult because initParams isnt a Backbone model.
// Copy into a Backbone model, and bind to that.
t.monitorParams = new Backbone.Model(t.monitor.get('initParams'));
t.monitorParamBinder.bind(
t.monitorParams,
componentPane,
Backbone.ModelBinder.createDefaultBindings(componentPane, 'data-monitor-param')
);
t.monitorParams.on('change', function() {
t.monitor.set('initParams', t.monitorParams.toJSON());
});
// Instantiate the source view
t.sourceView = new UI.JsonView({
model: t.model.toJSON({trim:false})
});
t.sourceView.render();
t.$('.nm-cs-source-view').append(t.sourceView.$el);
},
refreshSubViews: function(e) {
var t = this;
},
// Detect changes on keydown - after the value has been set
onKeydownLocal: function(e) {
var t = this;
// Make view options changes immediately on keydown
// Note: Don't be so aggressive with monitor initParams, because that
// could result in backend round-trips for each keystroke.
setTimeout(function(){
t.viewOptionBinder._onElChanged(e);
},0);
// Call the parent keydown
t.onKeydown(e);
},
// Copy the component
copy: function() {
var t = this;
// Add the component to the model, then to the page view
var copy = t.model.toJSON();
delete copy.id;
var component = t.pageView.model.addComponent(copy.viewClass);
component.set(copy);
// Position the component on top left
var cv = t.pageView.getComponentView(component.get('id'))
cv.raiseToTop(true);
cv.moveToLeft();
t.pageView.leftJustify();
t.pageView.centerPage();
// Close the dialog box
t.closeDialog();
},
// Validate the raw source in the editor, setting the model if valid
// and returning true/false based on valid JSON
validateSource: function() {
var t = this,
val = t.editor.val();
if (val) {
try {
// Throw away parse errors while typing
t.model.set(JSON.parse(val));
} catch (e) {
return false;
}
} else {
// Confirm deletion if user removes everything in the JSON window
if (window.confirm('Are you sure you want to delete this component?')) {
t.pageView.model.get('components').remove(t.model);
$('#nm-cv-settings').modal('hide');
} else {
// Reset source data
t.fillSourceData();
}
}
return true;
}
});
}(this));
|
import page from 'page';
function navigationHandler(routeHandler, onNavigation) {
return function(context/*, next*/) {
routeHandler(context, (error, PageComponent = {}, data = {}) => {
// if (!error && !Ractive.components[PageComponent._name]) { // I'm not proud of this
// Ractive.components[PageComponent._name] = PageComponent;
// }
context.pageName = PageComponent._name;
context.state = data;
onNavigation(error, context);
})
};
}
export function init(routes, onNavigation) {
routes.forEach((routeHandler, path) => {
page(path, navigationHandler(routeHandler, onNavigation));
});
page({
// hashbang: true
});
}
export function navTo(url) {
page.show(url);
}
|
import debug from 'debug'
import {
getState,
LOGIN_SUCCESS,
LOGIN_FAILURE,
LOGOUT_REQUEST,
} from './auth-actions'
if (__DEBUG__) {
debug.enable('auth-reducer:*')
}
const log = debug('auth-reducer:debug')
const authReducer = (state = getState(), action) => {
let newState
switch (action.type) {
case LOGIN_SUCCESS:
newState = Object.assign({}, action.state)
break
case LOGIN_FAILURE:
newState = Object.assign({}, action.state)
break
case LOGOUT_REQUEST:
newState = Object.assign({}, action.state)
break
default:
newState = state
}
if (newState !== state) {
// only log if state has changed
log('action:', action, 'state:', state, 'newState:', newState)
}
return newState
}
export default authReducer
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.