text
stringlengths 2
6.14k
|
|---|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/STIX/General/Italic/GreekItalic.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.Hub.Insert(
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['STIXGeneral-italic'],
{
0x1D6E2: [667,0,717,35,685], // MATHEMATICAL ITALIC CAPITAL ALPHA
0x1D6E3: [653,0,696,38,686], // MATHEMATICAL ITALIC CAPITAL BETA
0x1D6E4: [653,0,616,38,721], // MATHEMATICAL ITALIC CAPITAL GAMMA
0x1D6E5: [667,0,596,30,556], // MATHEMATICAL ITALIC CAPITAL DELTA
0x1D6E6: [653,0,714,38,734], // MATHEMATICAL ITALIC CAPITAL EPSILON
0x1D6E7: [653,0,772,60,802], // MATHEMATICAL ITALIC CAPITAL ZETA
0x1D6E8: [653,0,873,38,923], // MATHEMATICAL ITALIC CAPITAL ETA
0x1D6E9: [669,11,737,50,712], // MATHEMATICAL ITALIC CAPITAL THETA
0x1D6EA: [653,0,480,38,530], // MATHEMATICAL ITALIC CAPITAL IOTA
0x1D6EB: [653,0,762,38,802], // MATHEMATICAL ITALIC CAPITAL KAPPA
0x1D6EC: [667,0,718,35,686], // MATHEMATICAL ITALIC CAPITAL LAMDA
0x1D6ED: [653,0,1005,38,1055], // MATHEMATICAL ITALIC CAPITAL MU
0x1D6EE: [653,0,851,38,901], // MATHEMATICAL ITALIC CAPITAL NU
0x1D6EF: [653,0,706,52,741], // MATHEMATICAL ITALIC CAPITAL XI
0x1D6F0: [669,11,732,50,712], // MATHEMATICAL ITALIC CAPITAL OMICRON
0x1D6F1: [653,0,873,38,923], // MATHEMATICAL ITALIC CAPITAL PI
0x1D6F2: [653,0,594,38,704], // MATHEMATICAL ITALIC CAPITAL RHO
0x1D6F3: [669,11,737,50,712], // MATHEMATICAL ITALIC CAPITAL THETA SYMBOL
0x1D6F4: [653,0,735,58,760], // MATHEMATICAL ITALIC CAPITAL SIGMA
0x1D6F5: [653,0,550,25,670], // MATHEMATICAL ITALIC CAPITAL TAU
0x1D6F6: [668,0,613,28,743], // MATHEMATICAL ITALIC CAPITAL UPSILON
0x1D6F7: [653,0,772,25,747], // MATHEMATICAL ITALIC CAPITAL PHI
0x1D6F8: [653,0,790,25,810], // MATHEMATICAL ITALIC CAPITAL CHI
0x1D6F9: [667,0,670,28,743], // MATHEMATICAL ITALIC CAPITAL PSI
0x1D6FA: [666,0,800,32,777], // MATHEMATICAL ITALIC CAPITAL OMEGA
0x1D6FB: [653,15,627,42,600], // MATHEMATICAL ITALIC NABLA
0x1D6FC: [441,10,524,40,529], // MATHEMATICAL ITALIC SMALL ALPHA
0x1D6FD: [668,183,493,25,518], // MATHEMATICAL ITALIC SMALL BETA
0x1D6FE: [441,187,428,35,458], // MATHEMATICAL ITALIC SMALL GAMMA
0x1D6FF: [668,11,463,40,451], // MATHEMATICAL ITALIC SMALL DELTA
0x1D700: [441,11,484,25,444], // MATHEMATICAL ITALIC SMALL EPSILON
0x1D701: [668,183,435,40,480], // MATHEMATICAL ITALIC SMALL ZETA
0x1D702: [441,183,460,30,455], // MATHEMATICAL ITALIC SMALL ETA
0x1D703: [668,11,484,40,474], // MATHEMATICAL ITALIC SMALL THETA
0x1D704: [441,11,267,50,227], // MATHEMATICAL ITALIC SMALL IOTA
0x1D705: [441,0,534,50,549], // MATHEMATICAL ITALIC SMALL KAPPA
0x1D706: [668,16,541,50,511], // MATHEMATICAL ITALIC SMALL LAMDA
0x1D707: [428,183,579,30,549], // MATHEMATICAL ITALIC SMALL MU
0x1D708: [446,9,452,50,462], // MATHEMATICAL ITALIC SMALL NU
0x1D709: [668,183,433,25,443], // MATHEMATICAL ITALIC SMALL XI
0x1D70A: [441,11,458,40,438], // MATHEMATICAL ITALIC SMALL OMICRON
0x1D70B: [428,13,558,35,568], // MATHEMATICAL ITALIC SMALL PI
0x1D70C: [441,183,502,30,472], // MATHEMATICAL ITALIC SMALL RHO
0x1D70D: [490,183,439,35,464], // MATHEMATICAL ITALIC SMALL FINAL SIGMA
0x1D70E: [428,11,537,40,547], // MATHEMATICAL ITALIC SMALL SIGMA
0x1D70F: [428,5,442,30,472], // MATHEMATICAL ITALIC SMALL TAU
0x1D710: [439,11,460,30,445], // MATHEMATICAL ITALIC SMALL UPSILON
0x1D711: [441,183,666,50,631], // MATHEMATICAL ITALIC SMALL PHI
0x1D712: [441,202,595,30,645], // MATHEMATICAL ITALIC SMALL CHI
0x1D713: [441,183,661,30,711], // MATHEMATICAL ITALIC SMALL PSI
0x1D714: [441,11,681,20,661], // MATHEMATICAL ITALIC SMALL OMEGA
0x1D715: [668,11,471,40,471], // MATHEMATICAL ITALIC PARTIAL DIFFERENTIAL
0x1D716: [441,11,430,40,430], // MATHEMATICAL ITALIC EPSILON SYMBOL
0x1D717: [678,10,554,20,507], // MATHEMATICAL ITALIC THETA SYMBOL
0x1D718: [441,13,561,12,587], // MATHEMATICAL ITALIC KAPPA SYMBOL
0x1D719: [668,183,645,40,620], // MATHEMATICAL ITALIC PHI SYMBOL
0x1D71A: [441,187,509,40,489], // MATHEMATICAL ITALIC RHO SYMBOL
0x1D71B: [428,11,856,30,866] // MATHEMATICAL ITALIC PI SYMBOL
}
);
MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir + "/General/Italic/GreekItalic.js");
|
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
couchTests.erlang_views = function(debug) {
var db = new CouchDB("test_suite_db", {"X-Couch-Full-Commit":"false"});
db.deleteDb();
db.createDb();
if (debug) debugger;
run_on_modified_server(
[{section: "native_query_servers",
key: "erlang",
value: "{couch_native_process, start_link, []}"}],
function() {
// Note we just do some basic 'smoke tests' here - the
// test/query_server_spec.rb tests have more comprehensive tests
var doc = {_id: "1", integer: 1, string: "str1", array: [1, 2, 3]};
T(db.save(doc).ok);
var mfun = 'fun({Doc}) -> ' +
' K = couch_util:get_value(<<"integer">>, Doc, null), ' +
' V = couch_util:get_value(<<"string">>, Doc, null), ' +
' Emit(K, V) ' +
'end.';
// emitting a key value that is undefined should result in that row not
// being included in the view results
var results = db.query(mfun, null, null, null, "erlang");
T(results.total_rows == 1);
T(results.rows[0].key == 1);
T(results.rows[0].value == "str1");
// check simple reduction - another doc with same key.
var doc = {_id: "2", integer: 1, string: "str2"};
T(db.save(doc).ok);
rfun = "fun(Keys, Values, ReReduce) -> length(Values) end.";
results = db.query(mfun, rfun, null, null, "erlang");
T(results.rows[0].value == 2);
// simple 'list' tests
var designDoc = {
_id:"_design/erlview",
language: "erlang",
shows: {
simple:
'fun(Doc, {Req}) -> ' +
' {Info} = couch_util:get_value(<<"info">>, Req, {[]}), ' +
' Purged = couch_util:get_value(<<"purge_seq">>, Info, -1), ' +
' Verb = couch_util:get_value(<<"method">>, Req, <<"not_get">>), ' +
' R = list_to_binary(io_lib:format("~b - ~s", [Purged, Verb])), ' +
' {[{<<"code">>, 200}, {<<"headers">>, {[]}}, {<<"body">>, R}]} ' +
'end.'
},
lists: {
simple_list :
'fun(Head, {Req}) -> ' +
' Send(<<"head">>), ' +
' Fun = fun({Row}, _) -> ' +
' Val = couch_util:get_value(<<"value">>, Row, -1), ' +
' Send(list_to_binary(integer_to_list(Val))), ' +
' {ok, nil} ' +
' end, ' +
' {ok, _} = FoldRows(Fun, nil), ' +
' <<"tail">> ' +
'end. '
},
views: {
simple_view : {
map: mfun,
reduce: rfun
}
}
};
T(db.save(designDoc).ok);
var url = "/test_suite_db/_design/erlview/_show/simple/1";
var xhr = CouchDB.request("GET", url);
T(xhr.status == 200, "standard get should be 200");
T(xhr.responseText == "0 - GET");
var url = "/test_suite_db/_design/erlview/_list/simple_list/simple_view";
var xhr = CouchDB.request("GET", url);
T(xhr.status == 200, "standard get should be 200");
T(xhr.responseText == "head2tail");
// Larger dataset
db.deleteDb();
db.createDb();
var words = "foo bar abc def baz xxyz".split(/\s+/);
var docs = [];
for(var i = 0; i < 250; i++) {
var body = [];
for(var j = 0; j < 100; j++) {
body.push({
word: words[j%words.length],
count: j
});
}
docs.push({
"_id": "test-" + i,
"words": body
});
}
T(db.bulkSave(docs).length, 250, "Saved big doc set.");
var mfun = 'fun({Doc}) -> ' +
'Words = couch_util:get_value(<<"words">>, Doc), ' +
'lists:foreach(fun({Word}) -> ' +
'WordString = couch_util:get_value(<<"word">>, Word), ' +
'Count = couch_util:get_value(<<"count">>, Word), ' +
'Emit(WordString , Count) ' +
'end, Words) ' +
'end.';
var rfun = 'fun(Keys, Values, RR) -> length(Values) end.';
var results = db.query(mfun, rfun, null, null, "erlang");
T(results.rows[0].key === null, "Returned a reduced value.");
T(results.rows[0].value > 0, "Reduce value exists.");
});
};
|
var DOM = require('../dom');
var utils = require('../utils');
module.exports = (function() {
var canvas = DOM.newEl('canvas');
var ctx = null;
return function(sceneGraph) {
if (ctx == null) {
ctx = canvas.getContext('2d');
}
var dpr = utils.canvasRatio();
var root = sceneGraph.root;
canvas.width = dpr * root.properties.width;
canvas.height = dpr * root.properties.height ;
ctx.textBaseline = 'middle';
var bg = root.children.holderBg;
var bgWidth = dpr * bg.width;
var bgHeight = dpr * bg.height;
//todo: parametrize outline width (e.g. in scene object)
var outlineWidth = 2;
var outlineOffsetWidth = outlineWidth / 2;
ctx.fillStyle = bg.properties.fill;
ctx.fillRect(0, 0, bgWidth, bgHeight);
if (bg.properties.outline) {
//todo: abstract this into a method
ctx.strokeStyle = bg.properties.outline.fill;
ctx.lineWidth = bg.properties.outline.width;
ctx.moveTo(outlineOffsetWidth, outlineOffsetWidth);
// TL, TR, BR, BL
ctx.lineTo(bgWidth - outlineOffsetWidth, outlineOffsetWidth);
ctx.lineTo(bgWidth - outlineOffsetWidth, bgHeight - outlineOffsetWidth);
ctx.lineTo(outlineOffsetWidth, bgHeight - outlineOffsetWidth);
ctx.lineTo(outlineOffsetWidth, outlineOffsetWidth);
// Diagonals
ctx.moveTo(0, outlineOffsetWidth);
ctx.lineTo(bgWidth, bgHeight - outlineOffsetWidth);
ctx.moveTo(0, bgHeight - outlineOffsetWidth);
ctx.lineTo(bgWidth, outlineOffsetWidth);
ctx.stroke();
}
var textGroup = root.children.holderTextGroup;
ctx.font = textGroup.properties.font.weight + ' ' + (dpr * textGroup.properties.font.size) + textGroup.properties.font.units + ' ' + textGroup.properties.font.family + ', monospace';
ctx.fillStyle = textGroup.properties.fill;
for (var lineKey in textGroup.children) {
var line = textGroup.children[lineKey];
for (var wordKey in line.children) {
var word = line.children[wordKey];
var x = dpr * (textGroup.x + line.x + word.x);
var y = dpr * (textGroup.y + line.y + word.y + (textGroup.properties.leading / 2));
ctx.fillText(word.properties.text, x, y);
}
}
return canvas.toDataURL('image/png');
};
})();
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'pastetext', 'gu', {
button: 'પેસ્ટ (ટેક્સ્ટ)',
title: 'પેસ્ટ (ટેક્સ્ટ)'
} );
|
var Immutable = require("immutable");
module.exports.init = function (ui) {
var optPath = ["network-throttle"];
var serverOptPath = optPath.concat(["servers"]);
ui.servers = {};
ui.setOptionIn(optPath, Immutable.fromJS({
name: "network-throttle",
title: "Network Throttle",
active: false,
targets: require("./targets")
}));
ui.setOptionIn(serverOptPath, Immutable.Map({}));
/**
* @param input
* @returns {number}
*/
function getPortArg(input) {
input = input.trim();
if (input.length && input.match(/\d{3,5}/)) {
input = parseInt(input, 10);
} else {
input = ui.bs.options.get("port") + 1;
}
return input;
}
/**
* @returns {string}
*/
function getTargetUrl() {
return require("url").parse(ui.bs.options.getIn(["urls", "local"]));
}
var methods = {
/**
* @param data
*/
"server:create": function (data) {
data.port = getPortArg(data.port);
data.cb = data.cb || function () { /* noop */};
/**
* @param opts
*/
function saveThrottleInfo (opts) {
var urls = getUrls(ui.bs.options.set("port", opts.port).toJS());
ui.setOptionIn(serverOptPath.concat([opts.port]), Immutable.fromJS({
urls: urls,
speed: opts.speed
}));
setTimeout(function () {
ui.socket.emit("ui:network-throttle:update", {
servers: ui.getOptionIn(serverOptPath).toJS(),
event: "server:create"
});
ui.servers[opts.port] = opts.server;
data.cb(null, opts);
}, 300);
}
/**
* @param err
* @param port
*/
function createThrottle (err, port) {
var target = getTargetUrl();
var args = {
port: port,
target: target,
speed: data.speed
};
if (ui.bs.getOption("scheme") === "https") {
var httpsOpts = require("browser-sync/lib/server/utils").getHttpsOptions(ui.bs.options);
args.key = httpsOpts.key;
args.cert = httpsOpts.cert;
}
args.server = require("./throttle-server")(args);
require('server-destroy')(args.server);
args.server.listen(port);
saveThrottleInfo(args);
}
/**
* Try for a free port
*/
ui.bs.utils.portscanner.findAPortNotInUse(data.port, data.port + 100, "127.0.0.1", function (err, port) {
if (err) {
return createThrottle(err);
} else {
createThrottle(null, port);
}
});
},
/**
* @param data
*/
"server:destroy": function (data) {
if (ui.servers[data.port]) {
ui.servers[data.port].destroy();
ui.setMany(function (item) {
item.deleteIn(serverOptPath.concat([parseInt(data.port, 10)]));
});
delete ui.servers[data.port];
}
ui.socket.emit("ui:network-throttle:update", {
servers: ui.getOptionIn(serverOptPath).toJS(),
event: "server:destroy"
});
},
/**
* @param event
*/
event: function (event) {
methods[event.event](event.data);
}
};
return methods;
};
/**
* Get local + external urls with a different port
* @param opts
* @returns {List<T>|List<any>}
*/
function getUrls (opts) {
var list = [];
var bsLocal = require("url").parse(opts.urls.local);
list.push([bsLocal.protocol + "//", bsLocal.hostname, ":", opts.port].join(""));
if (opts.urls.external) {
var external = require("url").parse(opts.urls.external);
list.push([bsLocal.protocol + "//", external.hostname, ":", opts.port].join(""));
}
return Immutable.List(list);
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var error;
function testGetDescriptor() {
if (error !== undefined) {
chrome.test.sendMessage('fail');
chrome.test.fail(error);
}
chrome.test.assertTrue(descriptor != null, '\'descriptor\' is null');
chrome.test.assertEq('desc_id0', descriptor.instanceId);
chrome.test.assertEq('00001221-0000-1000-8000-00805f9b34fb', descriptor.uuid);
chrome.test.assertEq(false, descriptor.isLocal);
chrome.test.assertEq(charId, descriptor.characteristic.instanceId);
var valueBytes = new Uint8Array(descriptor.value);
chrome.test.assertEq(3, descriptor.value.byteLength);
chrome.test.assertEq(0x01, valueBytes[0]);
chrome.test.assertEq(0x02, valueBytes[1]);
chrome.test.assertEq(0x03, valueBytes[2]);
chrome.test.succeed();
}
var getDescriptor = chrome.bluetoothLowEnergy.getDescriptor;
var charId = 'char_id0';
var descId = 'desc_id0';
var badDescId = 'desc_id1';
var descriptor = null;
function earlyError(message) {
error = message;
chrome.test.runTests([testGetDescriptor]);
}
function expectError(result) {
if (result || !chrome.runtime.lastError) {
earlyError('getDescriptor should have failed');
}
return error !== undefined;
}
// 1. Unknown descriptor instanceId.
getDescriptor(badDescId, function (result) {
if (result || !chrome.runtime.lastError) {
earlyError('getDescriptor should have failed for \'badDescId\'');
return;
}
// 2. Known descriptor instanceId, but the mapped device is unknown.
getDescriptor(descId, function (result) {
if (expectError(result))
return;
// 3. Known descriptor instanceId, but the mapped service is unknown.
getDescriptor(descId, function (result) {
if (expectError(result))
return;
// 4. Known descriptor instanceId, but the mapped characteristic is
// unknown.
getDescriptor(descId, function (result) {
if (expectError(result))
return;
// 5. Known descriptor instanceId, but the mapped the characteristic
// does not know about the descriptor.
getDescriptor(descId, function (result) {
if (expectError(result))
return;
// 6. Success.
getDescriptor(descId, function (result) {
if (chrome.runtime.lastError) {
earlyError(chrome.runtime.lastError.message);
return;
}
descriptor = result;
chrome.test.sendMessage('ready', function (message) {
chrome.test.runTests([testGetDescriptor]);
});
});
});
});
});
});
});
|
// ---------------------------------------
// Test Environment Setup
// ---------------------------------------
import sinon from 'sinon'
import chai from 'chai'
import sinonChai from 'sinon-chai'
import chaiAsPromised from 'chai-as-promised'
import chaiEnzyme from 'chai-enzyme'
chai.use(sinonChai)
chai.use(chaiAsPromised)
chai.use(chaiEnzyme())
global.chai = chai
global.sinon = sinon
global.expect = chai.expect
global.should = chai.should()
// ---------------------------------------
// Require Tests
// ---------------------------------------
// for use with karma-webpack-with-fast-source-maps
const __karmaWebpackManifest__ = [] // eslint-disable-line
const inManifest = (path) => ~__karmaWebpackManifest__.indexOf(path)
// require all `tests/**/*.spec.js`
const testsContext = require.context('./', true, /\.spec\.js$/)
// only run tests that have changed after the first pass.
const testsToRun = testsContext.keys().filter(inManifest)
;(testsToRun.length ? testsToRun : testsContext.keys()).forEach(testsContext)
// require all `src/**/*.js` except for `main.js` (for isparta coverage reporting)
const componentsContext = require.context('../src/', true, /^((?!main).)*\.js$/)
componentsContext.keys().forEach(componentsContext)
|
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v5.0.2
* @link http://www.ag-grid.com/
* @license MIT
*/
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 context_1 = require("../../context/context");
var gridOptionsWrapper_1 = require("../../gridOptionsWrapper");
var sortController_1 = require("../../sortController");
var valueService_1 = require("../../valueService");
var utils_1 = require("../../utils");
var SortStage = (function () {
function SortStage() {
}
SortStage.prototype.execute = function (rowNode) {
var sortOptions;
// if the sorting is already done by the server, then we should not do it here
if (!this.gridOptionsWrapper.isEnableServerSideSorting()) {
sortOptions = this.sortController.getSortForRowController();
}
this.sortRowNode(rowNode, sortOptions);
};
SortStage.prototype.sortRowNode = function (rowNode, sortOptions) {
var _this = this;
// sort any groups recursively
rowNode.childrenAfterFilter.forEach(function (child) {
if (child.group) {
_this.sortRowNode(child, sortOptions);
}
});
rowNode.childrenAfterSort = rowNode.childrenAfterFilter.slice(0);
var sortActive = utils_1.Utils.exists(sortOptions) && sortOptions.length > 0;
if (sortActive) {
rowNode.childrenAfterSort.sort(this.compareRowNodes.bind(this, sortOptions));
}
this.updateChildIndexes(rowNode);
};
SortStage.prototype.compareRowNodes = function (sortOptions, nodeA, nodeB) {
// Iterate columns, return the first that doesn't match
for (var i = 0, len = sortOptions.length; i < len; i++) {
var sortOption = sortOptions[i];
// var compared = compare(nodeA, nodeB, sortOption.column, sortOption.inverter === -1);
var isInverted = sortOption.inverter === -1;
var valueA = this.valueService.getValue(sortOption.column, nodeA);
var valueB = this.valueService.getValue(sortOption.column, nodeB);
var comparatorResult;
if (sortOption.column.getColDef().comparator) {
//if comparator provided, use it
comparatorResult = sortOption.column.getColDef().comparator(valueA, valueB, nodeA, nodeB, isInverted);
}
else {
//otherwise do our own comparison
comparatorResult = utils_1.Utils.defaultComparator(valueA, valueB);
}
if (comparatorResult !== 0) {
return comparatorResult * sortOption.inverter;
}
}
// All matched, these are identical as far as the sort is concerned:
return 0;
};
SortStage.prototype.updateChildIndexes = function (rowNode) {
if (utils_1.Utils.missing(rowNode.childrenAfterSort)) {
return;
}
rowNode.childrenAfterSort.forEach(function (child, index) {
child.firstChild = index === 0;
child.lastChild = index === rowNode.childrenAfterSort.length - 1;
child.childIndex = index;
});
};
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata('design:type', gridOptionsWrapper_1.GridOptionsWrapper)
], SortStage.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('sortController'),
__metadata('design:type', sortController_1.SortController)
], SortStage.prototype, "sortController", void 0);
__decorate([
context_1.Autowired('valueService'),
__metadata('design:type', valueService_1.ValueService)
], SortStage.prototype, "valueService", void 0);
SortStage = __decorate([
context_1.Bean('sortStage'),
__metadata('design:paramtypes', [])
], SortStage);
return SortStage;
})();
exports.SortStage = SortStage;
|
/*!
* FileInput Estonian Translations
*
* This file must be loaded after 'fileinput.js'. Patterns in braces '{}', or
* any HTML markup tags in the messages must not be converted or translated.
*
* @see http://github.com/kartik-v/bootstrap-fileinput
*
* NOTE: this file must be saved in UTF-8 encoding.
*/
(function ($) {
"use strict";
$.fn.fileinputLocales['et'] = {
fileSingle: 'fail',
filePlural: 'failid',
browseLabel: 'Sirvi …',
removeLabel: 'Eemalda',
removeTitle: 'Clear selected files',
cancelLabel: 'Tühista',
cancelTitle: 'Abort ongoing upload',
uploadLabel: 'Salvesta',
uploadTitle: 'Salvesta valitud failid',
msgNo: 'No',
msgNoFilesSelected: 'No files selected',
msgCancelled: 'Cancelled',
msgZoomModalHeading: 'Detailed Preview',
msgFileRequired: 'You must select a file to upload.',
msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
msgSizeTooLarge: 'Fail "{name}" (<b>{size} KB</b>) ületab lubatu suuruse <b>{maxSize} KB</b>.',
msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
msgFileNotFound: 'File "{name}" not found!',
msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
msgFileNotReadable: 'File "{name}" is not readable.',
msgFilePreviewAborted: 'File preview aborted for "{name}".',
msgFilePreviewError: 'An error occurred while reading the file "{name}".',
msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
msgInvalidFileType: '"{name}" on vale tüüpi. Ainult "{types}" on lubatud.',
msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
msgFileTypes: {
'image': 'image',
'html': 'HTML',
'text': 'text',
'video': 'video',
'audio': 'audio',
'flash': 'flash',
'pdf': 'PDF',
'object': 'object'
},
msgUploadAborted: 'The file upload was aborted',
msgUploadThreshold: 'Processing...',
msgUploadBegin: 'Initializing...',
msgUploadEnd: 'Done',
msgUploadEmpty: 'No valid data available for upload.',
msgUploadError: 'Error',
msgValidationError: 'Validation Error',
msgLoading: 'Loading file {index} of {files} …',
msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
msgSelected: '{n} {files} selected',
msgFoldersNotAllowed: 'Drag & drop files only! Skipped {n} dropped folder(s).',
msgImageWidthSmall: 'Pildi laius peab olema vähemalt {size} px.',
msgImageHeightSmall: 'Pildi kõrgus peab olema vähemalt {size} px.',
msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
msgImageResizeError: 'Could not get the image dimensions to resize.',
msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
msgAjaxProgressError: '{operation} failed',
ajaxOperations: {
deleteThumb: 'file delete',
uploadThumb: 'file upload',
uploadBatch: 'batch file upload',
uploadExtra: 'form data upload'
},
dropZoneTitle: 'Lohista failid siia …',
dropZoneClickTitle: '<br>(or click to select {files})',
fileActionSettings: {
removeTitle: 'Eemalda fail',
uploadTitle: 'Salvesta fail',
uploadRetryTitle: 'Retry upload',
zoomTitle: 'Vaata detaile',
dragTitle: 'Liiguta / Korralda',
indicatorNewTitle: 'Pole veel salvestatud',
indicatorSuccessTitle: 'Uploaded',
indicatorErrorTitle: 'Salvestamise viga',
indicatorLoadingTitle: 'Salvestan ...'
},
previewZoomButtonTitles: {
prev: 'View previous file',
next: 'View next file',
toggleheader: 'Toggle header',
fullscreen: 'Toggle full screen',
borderless: 'Toggle borderless mode',
close: 'Close detailed preview'
}
};
})(window.jQuery);
|
Clazz.declarePackage("java.text");
c$=Clazz.decorateAsClass(function(){
this.pattern=null;
Clazz.instantialize(this,arguments);
},java.text,"MessageFormat");
Clazz.makeConstructor(c$,
function(pattern){
this.pattern=pattern;
},"~S");
Clazz.makeConstructor(c$,
function(pattern,locale){
this.pattern=pattern;
},"~S,java.util.Locale");
c$.format=Clazz.defineMethod(c$,"format",
function(pattern,args){
return pattern.replace(/\{(\d+)\}/g,function($0,$1){
var i=parseInt($1);
if(args==null)return null;
return args[i];
});
},"~S,~A");
Clazz.defineMethod(c$,"format",
function(obj){
return java.text.MessageFormat.format(this.pattern,[obj]);
},"~O");
|
require('../lib/node_loader');
var AWS = require('../lib/core');
var Service = require('../lib/service');
var apiLoader = require('../lib/api_loader');
apiLoader.services['discovery'] = {};
AWS.Discovery = Service.defineService('discovery', ['2015-11-01']);
Object.defineProperty(apiLoader.services['discovery'], '2015-11-01', {
get: function get() {
var model = require('../apis/discovery-2015-11-01.min.json');
return model;
},
enumerable: true,
configurable: true
});
module.exports = AWS.Discovery;
|
/*!
* isobject <https://github.com/jonschlinkert/isobject>
*
* Copyright (c) 2014-2015, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var isArray = require('isarray');
module.exports = function isObject(o) {
return o != null && typeof o === 'object' && !isArray(o);
};
|
/**
* Tabby v7.4.6
* Simple, mobile-first toggle tabs., by Chris Ferdinandi.
* http://github.com/cferdinandi/tabby
*
* Free to use under the MIT License.
* http://gomakethings.com/mit/
*/
/*
* classList.js: Cross-browser full element.classList implementation.
* 2014-01-31
*
* By Eli Grey, http://eligrey.com
* Public Domain.
* NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
*/
/*global self, document, DOMException */
/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/
if ("document" in self && !("classList" in document.createElement("_"))) {
(function (view) {
"use strict";
if (!('Element' in view)) return;
var
classListProp = "classList",
protoProp = "prototype",
elemCtrProto = view.Element[protoProp],
objCtr = Object,
strTrim = String[protoProp].trim || function () {
return this.replace(/^\s+|\s+$/g, "");
},
arrIndexOf = Array[protoProp].indexOf || function (item) {
var
i = 0,
len = this.length;
for (; i < len; i++) {
if (i in this && this[i] === item) {
return i;
}
}
return -1;
},
// Vendors: please allow content code to instantiate DOMExceptions
DOMEx = function (type, message) {
this.name = type;
this.code = DOMException[type];
this.message = message;
},
checkTokenAndGetIndex = function (classList, token) {
if (token === "") {
throw new DOMEx(
"SYNTAX_ERR",
"An invalid or illegal string was specified"
);
}
if (/\s/.test(token)) {
throw new DOMEx(
"INVALID_CHARACTER_ERR",
"String contains an invalid character"
);
}
return arrIndexOf.call(classList, token);
},
ClassList = function (elem) {
var
trimmedClasses = strTrim.call(elem.getAttribute("class") || ""),
classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [],
i = 0,
len = classes.length;
for (; i < len; i++) {
this.push(classes[i]);
}
this._updateClassName = function () {
elem.setAttribute("class", this.toString());
};
},
classListProto = ClassList[protoProp] = [],
classListGetter = function () {
return new ClassList(this);
};
// Most DOMException implementations don't allow calling DOMException's toString()
// on non-DOMExceptions. Error's toString() is sufficient here.
DOMEx[protoProp] = Error[protoProp];
classListProto.item = function (i) {
return this[i] || null;
};
classListProto.contains = function (token) {
token += "";
return checkTokenAndGetIndex(this, token) !== -1;
};
classListProto.add = function () {
var
tokens = arguments,
i = 0,
l = tokens.length,
token,
updated = false;
do {
token = tokens[i] + "";
if (checkTokenAndGetIndex(this, token) === -1) {
this.push(token);
updated = true;
}
}
while (++i < l);
if (updated) {
this._updateClassName();
}
};
classListProto.remove = function () {
var
tokens = arguments,
i = 0,
l = tokens.length,
token,
updated = false;
do {
token = tokens[i] + "";
var index = checkTokenAndGetIndex(this, token);
if (index !== -1) {
this.splice(index, 1);
updated = true;
}
}
while (++i < l);
if (updated) {
this._updateClassName();
}
};
classListProto.toggle = function (token, force) {
token += "";
var
result = this.contains(token),
method = result ? force !== true && "remove" : force !== false && "add";
if (method) {
this[method](token);
}
return !result;
};
classListProto.toString = function () {
return this.join(" ");
};
if (objCtr.defineProperty) {
var classListPropDesc = {
get: classListGetter,
enumerable: true,
configurable: true
};
try {
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
} catch (ex) { // IE 8 doesn't support enumerable:true
if (ex.number === -0x7FF5EC54) {
classListPropDesc.enumerable = false;
objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
}
}
} else if (objCtr[protoProp].__defineGetter__) {
elemCtrProto.__defineGetter__(classListProp, classListGetter);
}
}(self));
}
|
var sliced = require('../')
var assert = require('assert')
describe('sliced', function(){
it('exports a function', function(){
assert.equal('function', typeof sliced);
})
describe('with 1 arg', function(){
it('returns an array of the arg', function(){
var o = [3, "4", {}];
var r = sliced(o);
assert.equal(3, r.length);
assert.equal(o[0], r[0]);
assert.equal(o[1], r[1]);
assert.equal(o[1], r[1]);
})
})
describe('with 2 args', function(){
it('returns an array of the arg starting at the 2nd arg', function(){
var o = [3, "4", 5, null];
var r = sliced(o, 2);
assert.equal(2, r.length);
assert.equal(o[2], r[0]);
assert.equal(o[3], r[1]);
})
})
describe('with 3 args', function(){
it('returns an array of the arg from the 2nd to the 3rd arg', function(){
var o = [3, "4", 5, null];
var r = sliced(o, 1, 2);
assert.equal(1, r.length);
assert.equal(o[1], r[0]);
})
})
describe('with negative start and no end', function(){
it('begins at an offset from the end and includes all following elements', function(){
var o = [3, "4", 5, null];
var r = sliced(o, -2);
assert.equal(2, r.length);
assert.equal(o[2], r[0]);
assert.equal(o[3], r[1]);
var r = sliced(o, -12);
assert.equal(4, r.length);
assert.equal(o[0], r[0]);
assert.equal(o[1], r[1]);
})
})
describe('with negative start and positive end', function(){
it('begins at an offset from the end and includes `end` elements', function(){
var o = [3, "4", {x:1}, null];
var r = sliced(o, -2, 1);
assert.equal(0, r.length);
var r = sliced(o, -2, 2);
assert.equal(0, r.length);
var r = sliced(o, -2, 3);
assert.equal(1, r.length);
assert.equal(o[2], r[0]);
})
})
describe('with negative start and negative end', function(){
it('begins at `start` offset from the end and includes all elements up to `end` offset from the end', function(){
var o = [3, "4", {x:1}, null];
var r = sliced(o, -3, -1);
assert.equal(2, r.length);
assert.equal(o[1], r[0]);
assert.equal(o[2], r[1]);
var r = sliced(o, -3, -3);
assert.equal(0, r.length);
var r = sliced(o, -3, -4);
assert.equal(0, r.length);
})
})
})
|
/*
* /MathJax/jax/output/HTML-CSS/fonts/STIX/IntegralsUpSm/Bold/All.js
*
* Copyright (c) 2009-2018 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.Hub.Insert(MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS["STIXIntegralsUpSm-bold"],{32:[0,0,250,0,0],160:[0,0,250,0,0],8747:[732,193,396,52,414],8748:[732,193,666,52,684],8749:[732,193,936,52,954],8750:[732,193,466,52,426],8751:[732,193,736,52,696],8752:[732,193,998,52,965],8753:[732,193,501,52,468],8754:[732,193,501,52,469],8755:[732,193,496,52,486],10764:[732,193,1206,52,1224],10765:[732,193,450,52,420],10766:[732,193,450,52,420],10767:[732,193,550,40,518],10768:[732,193,479,52,447],10769:[732,193,511,52,478],10770:[732,193,489,52,449],10771:[732,193,487,52,447],10772:[732,193,572,52,534],10773:[732,193,520,52,480],10774:[732,193,523,52,483],10775:[732,193,600,8,646],10776:[733,192,505,31,467],10777:[732,193,516,52,476],10778:[732,193,516,52,476],10779:[802,193,403,40,428],10780:[732,268,411,52,440]});MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].fontDir+"/IntegralsUpSm/Bold/All.js");
|
function Gdn_Queue() {
this.Queue = [];
this.ActiveItem = false;
Gdn_Queue.prototype.Add = function(QueueObject) {
this.Queue.push(QueueObject);
}
Gdn_Queue.prototype.Length = function() {
return this.Queue.length;
}
Gdn_Queue.prototype.Get = function() {
if (!this.Length()) return false;
return this.Queue.shift();
}
}
gdn.loaded('queue');
|
process.env.NODE_ENV = process.env.NODE_ENV || 'development'
const { environment } = require('@rails/webpacker')
module.exports = environment.toWebpackConfig()
|
'use strict';
var util = require('util');
function AbortError (obj) {
Error.captureStackTrace(this, this.constructor);
Object.defineProperty(this, 'message', {
value: obj.message || '',
configurable: true,
writable: true
});
for (var keys = Object.keys(obj), key = keys.pop(); key; key = keys.pop()) {
this[key] = obj[key];
}
}
function AggregateError (obj) {
Error.captureStackTrace(this, this.constructor);
Object.defineProperty(this, 'message', {
value: obj.message || '',
configurable: true,
writable: true
});
for (var keys = Object.keys(obj), key = keys.pop(); key; key = keys.pop()) {
this[key] = obj[key];
}
}
util.inherits(AbortError, Error);
util.inherits(AggregateError, AbortError);
Object.defineProperty(AbortError.prototype, 'name', {
value: 'AbortError',
// configurable: true,
writable: true
});
Object.defineProperty(AggregateError.prototype, 'name', {
value: 'AggregateError',
// configurable: true,
writable: true
});
module.exports = {
AbortError: AbortError,
AggregateError: AggregateError
};
|
/**
* API Bound Models for AngularJS
* @version v0.18.0 - 2014-08-26
* @link https://github.com/angular-platanus/restmod
* @author Ignacio Baixas <ignacio@platan.us>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
!function(a,b){"use strict";a.module("restmod").factory("PagedModel",["restmod",function(a){return a.mixin({"@$pageHeader":"X-Page","@$pageCountHeader":"X-Page-Total","~afterFetchMany":function(a){var c=a.headers(this.$pageHeader),d=a.headers(this.$pageCountHeader);this.$page=c!==b?parseInt(c,10):1,this.$pageCount=d!==b?parseInt(d,10):1}})}])}(angular);
|
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": {
"0": "a.m.",
"1": "p.m."
},
"DAY": {
"0": "domingo",
"1": "lunes",
"2": "martes",
"3": "mi\u00e9rcoles",
"4": "jueves",
"5": "viernes",
"6": "s\u00e1bado"
},
"MONTH": {
"0": "enero",
"1": "febrero",
"2": "marzo",
"3": "abril",
"4": "mayo",
"5": "junio",
"6": "julio",
"7": "agosto",
"8": "septiembre",
"9": "octubre",
"10": "noviembre",
"11": "diciembre"
},
"SHORTDAY": {
"0": "dom",
"1": "lun",
"2": "mar",
"3": "mi\u00e9",
"4": "jue",
"5": "vie",
"6": "s\u00e1b"
},
"SHORTMONTH": {
"0": "ene",
"1": "feb",
"2": "mar",
"3": "abr",
"4": "may",
"5": "jun",
"6": "jul",
"7": "ago",
"8": "sep",
"9": "oct",
"10": "nov",
"11": "dic"
},
"fullDate": "EEEE, d 'de' MMMM 'de' y",
"longDate": "d 'de' MMMM 'de' y",
"medium": "dd/MM/yyyy HH:mm:ss",
"mediumDate": "dd/MM/yyyy",
"mediumTime": "HH:mm:ss",
"short": "dd/MM/yy HH:mm",
"shortDate": "dd/MM/yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20ac",
"DECIMAL_SEP": ",",
"GROUP_SEP": ".",
"PATTERNS": {
"0": {
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
"1": {
"gSize": 3,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-",
"negSuf": "\u00a0\u00a4",
"posPre": "",
"posSuf": "\u00a0\u00a4"
}
}
},
"id": "es-sv",
"pluralCat": function (n) { if (n == 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.shave = factory());
}(this, (function () { 'use strict';
function shave(target, maxHeight, opts) {
if (!maxHeight) throw Error('maxHeight is required');
var els = typeof target === 'string' ? document.querySelectorAll(target) : target;
if (!('length' in els)) els = [els];
var defaults = {
character: '…',
classname: 'js-shave',
spaces: true
};
var character = opts && opts.character || defaults.character;
var classname = opts && opts.classname || defaults.classname;
var spaces = opts && opts.spaces === false ? false : defaults.spaces;
var charHtml = '<span class="js-shave-char">' + character + '</span>';
for (var i = 0; i < els.length; i++) {
var el = els[i];
var span = el.querySelector('.' + classname);
// If element text has already been shaved
if (span) {
// Remove the ellipsis to recapture the original text
el.removeChild(el.querySelector('.js-shave-char'));
el.textContent = el.textContent; // nuke span, recombine text
}
// If already short enough, we're done
if (el.offsetHeight < maxHeight) continue;
var fullText = el.textContent;
var words = spaces ? fullText.split(' ') : fullText;
// If 0 or 1 words, we're done
if (words.length < 2) continue;
// Binary search for number of words which can fit in allotted height
var max = words.length - 1;
var min = 0;
var pivot = void 0;
while (min < max) {
pivot = min + max + 1 >> 1;
el.textContent = spaces ? words.slice(0, pivot).join(' ') : words.slice(0, pivot);
el.insertAdjacentHTML('beforeend', charHtml);
if (el.offsetHeight > maxHeight) max = spaces ? pivot - 1 : pivot - 2;else min = pivot;
}
el.textContent = spaces ? words.slice(0, max).join(' ') : words.slice(0, max);
el.insertAdjacentHTML('beforeend', charHtml);
var diff = spaces ? words.slice(max + 1).join(' ') : words.slice(max);
el.insertAdjacentHTML('beforeend', '<span class="' + classname + '" style="display:none;">' + diff + '</span>');
}
}
var plugin = window.$ || window.jQuery || window.Zepto;
if (plugin) {
plugin.fn.extend({
shave: function shaveFunc(maxHeight, opts) {
return shave(this, maxHeight, opts);
}
});
}
return shave;
})));
|
// Generated by CoffeeScript 1.8.0
var ConnectApp, connect, es, fs, http, https, liveReload, lr, opt, path, server, tiny_lr, util;
path = require("path");
es = require("event-stream");
util = require("gulp-util");
http = require("http");
https = require("https");
fs = require("fs");
connect = require("connect");
liveReload = require("connect-livereload");
tiny_lr = require("tiny-lr");
opt = {};
server = void 0;
lr = void 0;
ConnectApp = (function() {
function ConnectApp(options) {
opt = options;
opt.port = opt.port || "8080";
opt.root = opt.root || path.dirname(module.parent.id);
opt.host = opt.host || "localhost";
if (opt.open) {
this.oldMethod("open");
}
this.server();
}
ConnectApp.prototype.server = function() {
var app;
app = connect();
this.middleware().forEach(function(middleware) {
return app.use(middleware);
});
if (opt.https != null) {
server = https.createServer({
key: opt.https.key || fs.readFileSync(__dirname + '/certs/server.key'),
cert: opt.https.cert || fs.readFileSync(__dirname + '/certs/server.crt'),
ca: opt.https.ca || fs.readFileSync(__dirname + '/certs/ca.crt'),
passphrase: opt.https.passphrase || 'gulp'
}, app);
} else {
server = http.createServer(app);
}
app.use(connect.directory(typeof opt.root === "object" ? opt.root[0] : opt.root));
return server.listen(opt.port, (function(_this) {
return function(err) {
var sockets, stopServer, stoped;
if (err) {
return _this.log("Error on starting server: " + err);
} else {
_this.log("Server started http://" + opt.host + ":" + opt.port);
stoped = false;
sockets = [];
server.on('close', function() {
if (!stoped) {
stoped = true;
return _this.log("Server stopped");
}
});
server.on("connection", function(socket) {
sockets.push(socket);
return socket.on("close", function() {
return sockets.splice(sockets.indexOf(socket), 1);
});
});
stopServer = function() {
if (!stoped) {
sockets.forEach(function(socket) {
return socket.destroy();
});
server.close();
return process.nextTick(function() {
return process.exit(0);
});
}
};
process.on("SIGINT", stopServer);
process.on("exit", stopServer);
if (opt.livereload) {
tiny_lr.Server.prototype.error = function() {};
if (opt.https != null) {
lr = tiny_lr({
key: opt.https.key || fs.readFileSync(__dirname + '/certs/server.key'),
cert: opt.https.cert || fs.readFileSync(__dirname + '/certs/server.crt')
});
} else {
lr = tiny_lr();
}
lr.listen(opt.livereload.port);
return _this.log("LiveReload started on port " + opt.livereload.port);
}
}
};
})(this));
};
ConnectApp.prototype.middleware = function() {
var middleware;
middleware = opt.middleware ? opt.middleware.call(this, connect, opt) : [];
if (opt.livereload) {
if (typeof opt.livereload === "boolean") {
opt.livereload = {};
}
if (!opt.livereload.port) {
opt.livereload.port = 35729;
}
middleware.push(liveReload({
port: opt.livereload.port
}));
}
if (typeof opt.root === "object") {
opt.root.forEach(function(path) {
return middleware.push(connect["static"](path));
});
} else {
middleware.push(connect["static"](opt.root));
}
if (opt.fallback) {
middleware.push(function(req, res) {
return require('fs').createReadStream(opt.fallback).pipe(res);
});
}
return middleware;
};
ConnectApp.prototype.log = function(text) {
this.text = text;
if (!opt.silent) {
return util.log(util.colors.green(this.text));
}
};
ConnectApp.prototype.logWarning = function(text) {
this.text = text;
if (!opt.silent) {
return util.log(util.colors.yellow(this.text));
}
};
ConnectApp.prototype.oldMethod = function(type) {
var text;
text = 'does not work in gulp-connect v 2.*. Please read "readme" https://github.com/AveVlad/gulp-connect';
switch (type) {
case "open":
return this.logWarning("Option open " + text);
}
};
return ConnectApp;
})();
module.exports = {
server: function(options) {
if (options == null) {
options = {};
}
return new ConnectApp(options);
},
reload: function() {
return es.map(function(file, callback) {
if (opt.livereload && typeof lr === "object") {
lr.changed({
body: {
files: file.path
}
});
}
return callback(null, file);
});
},
serverClose: function() {
return server.close();
}
};
|
module.exports = require('../package.json').version;
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
chrome.test.runTests([
function content_test() {
window.addEventListener('message', function(event) {
var msg = event.data;
if (msg == 'original') {
console.log('VICTIM: No content changed.');
chrome.test.succeed();
} else {
console.log('VICTIM: Detected injected content - ' + msg);
chrome.test.fail('Content changed: ' + msg);
}
},
false);
chrome.test.getConfig(function(config) {
chrome.test.log("Creating tab...");
var test_url = ("http://a.com:PORT/extensions/api_test" +
"/content_scripts/other_extensions/iframe_content.html#" +
escape(chrome.extension.getURL("test.html")))
.replace(/PORT/, config.testServer.port);
console.log('Opening frame: ' + test_url);
document.getElementById('content_frame').src = test_url;
});
}
]);
|
/*global describe, it, before, beforeEach, after, afterEach, browser: true, chai, selectnav*/
var assert = chai.assert;
var sandbox = document.createElement('div');
sandbox.setAttribute('id', 'sandbox');
document.body.appendChild(sandbox);
describe('selectnav', function () {
var result;
beforeEach(function () {
sandbox.innerHTML = '<ul id="foo"><li><a href="bar.html">Bar</a></li><li><a href="baz.html" class="active">Baz</a></ul>';
});
it('is attached to window', function () {
assert.isFunction(window.selectnav);
});
it('is accessible from global namespace', function () {
assert.isFunction(selectnav);
});
describe('when invoked with ID of a one-level <ul> list', function () {
beforeEach(function () {
result = selectnav('foo');
});
it('returns a "select" element', function () {
assert.equal(result.tagName, 'SELECT');
});
it('inserts "select" element after "ul" element', function () {
assert.equal(document.getElementById('foo').nextSibling, result);
});
});
describe('with simple one level navigation and no options', function () {
beforeEach(function () {
result = selectnav('foo');
});
it('has +1 children than original "ul" (because of first label element)', function () {
assert.equal(document.getElementById('foo').children.length+1, result.children.length);
});
it('has first child that is a label', function () {
assert.equal(result.children[0].value, '');
assert.equal(result.children[0].innerText, '- Navigation -');
});
it('has children that are all <option> element', function () {
assert.equal(result.children[0].tagName, 'OPTION');
assert.equal(result.children[1].tagName, 'OPTION');
assert.equal(result.children[2].tagName, 'OPTION');
});
it('has children that have all "value" property equal to "href" attribute of the original <a> element', function () {
assert.include(result.children[1].value, 'bar.html');
assert.include(result.children[2].value, 'baz.html');
});
it('has children that have text equal to the text of the original <a> element', function () {
assert.include(result.children[1].innerText, 'Bar');
assert.include(result.children[2].innerText, 'Baz');
});
it('mark element with "active" class as selected', function () {
assert.ok(result.children[2].selected);
});
});
describe('when "label" option is set to a string', function () {
beforeEach(function () {
result = selectnav('foo', {label: 'foobar'});
});
it('set text of first element accordingly', function () {
assert.equal(result.children[0].innerText, 'foobar');
});
});
describe.skip('when "label" option is set to false', function () {
beforeEach(function () {
result = selectnav('foo', {label: false});
});
it('do not include label', function () {
assert.lengthOf(result.children, 2);
});
});
describe('when "activeclass" option is set', function () {
beforeEach(function () {
sandbox.innerHTML = '<ul id="foo"><li><a href="bar.html" class="activeClass">Bar</a></li><li><a href="baz.html" class="active">Baz</a></ul>';
});
beforeEach(function () {
result = selectnav('foo', {activeclass: 'activeClass'});
});
it('mark corresponding element as selected', function () {
assert.ok(result.children[1].selected);
assert.notOk(result.children[2].selected);
});
});
});
|
export default function() {
var callback = arguments[0];
arguments[0] = this;
callback.apply(null, arguments);
return this;
}
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"AM",
"PM"
],
"DAY": [
"\u0627\u062a\u0648\u0627\u0631",
"\u067e\u06cc\u0631",
"\u0645\u0646\u06af\u0644",
"\u0628\u064f\u062f\u06be",
"\u062c\u0645\u0639\u0631\u0627\u062a",
"\u062c\u0645\u0639\u06c1",
"\u06c1\u0641\u062a\u06c1"
],
"MONTH": [
"\u062c\u0646\u0648\u0631\u06cc",
"\u0641\u0631\u0648\u0631\u06cc",
"\u0645\u0627\u0631\u0686",
"\u0627\u067e\u0631\u06cc\u0644",
"\u0645\u0626",
"\u062c\u0648\u0646",
"\u062c\u0648\u0644\u0627\u0626\u06cc",
"\u0627\u06af\u0633\u062a",
"\u0633\u062a\u0645\u0628\u0631",
"\u0627\u06a9\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0645\u0628\u0631",
"\u062f\u0633\u0645\u0628\u0631"
],
"SHORTDAY": [
"\u0a10\u0a24.",
"\u0a38\u0a4b\u0a2e.",
"\u0a2e\u0a70\u0a17\u0a32.",
"\u0a2c\u0a41\u0a27.",
"\u0a35\u0a40\u0a30.",
"\u0a38\u0a3c\u0a41\u0a71\u0a15\u0a30.",
"\u0a38\u0a3c\u0a28\u0a40."
],
"SHORTMONTH": [
"\u0a1c\u0a28\u0a35\u0a30\u0a40",
"\u0a2b\u0a3c\u0a30\u0a35\u0a30\u0a40",
"\u0a2e\u0a3e\u0a30\u0a1a",
"\u0a05\u0a2a\u0a4d\u0a30\u0a48\u0a32",
"\u0a2e\u0a08",
"\u0a1c\u0a42\u0a28",
"\u0a1c\u0a41\u0a32\u0a3e\u0a08",
"\u0a05\u0a17\u0a38\u0a24",
"\u0a38\u0a24\u0a70\u0a2c\u0a30",
"\u0a05\u0a15\u0a24\u0a42\u0a2c\u0a30",
"\u0a28\u0a35\u0a70\u0a2c\u0a30",
"\u0a26\u0a38\u0a70\u0a2c\u0a30"
],
"fullDate": "EEEE, dd MMMM y",
"longDate": "d MMMM y",
"medium": "d MMM y h:mm:ss a",
"mediumDate": "d MMM y",
"mediumTime": "h:mm:ss a",
"short": "dd/MM/y h:mm a",
"shortDate": "dd/MM/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "\u20b9",
"DECIMAL_SEP": ".",
"GROUP_SEP": ",",
"PATTERNS": [
{
"gSize": 2,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 2,
"lgSize": 3,
"macFrac": 0,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4-",
"negSuf": "",
"posPre": "\u00a4",
"posSuf": ""
}
]
},
"id": "pa-arab",
"pluralCat": function (n, opt_precision) { if (n >= 0 && n <= 1) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
var _filter = require('./_filter');
/**
* @private
* @param {Function} fn The strategy for extracting function names from an object
* @return {Function} A function that takes an object and returns an array of function names.
*/
module.exports = function _functionsWith(fn) {
return function(obj) {
return _filter(function(key) { return typeof obj[key] === 'function'; }, fn(obj));
};
};
|
const SemVer = require('../classes/semver')
const parse = require('./parse')
const {re, t} = require('../internal/re')
const coerce = (version, options) => {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
let match = null
if (!options.rtl) {
match = version.match(re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
let next
while ((next = re[t.COERCERTL].exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
re[t.COERCERTL].lastIndex = -1
}
if (match === null)
return null
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
}
module.exports = coerce
|
// SpryUtils.js - version 0.2 - Spry Pre-Release 1.6
//
// Copyright (c) 2007. Adobe Systems Incorporated.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Adobe Systems Incorporated nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
var Spry; if (!Spry) Spry = {}; if (!Spry.Utils) Spry.Utils = {};
Spry.Utils.submitForm = function(form, callback, opts)
{
if (!form)
return true;
if ( typeof form == 'string' )
form = document.getElementById(form) || document.forms[form];
var frmOpts = {};
frmOpts.method = form.method;
frmOpts.url = form.action || document.location.href;
frmOpts.enctype = form.enctype;
Spry.Utils.setOptions(frmOpts, opts);
var submitData = Spry.Utils.extractParamsFromForm(form, frmOpts.elements);
if (frmOpts.additionalData)
submitData += "&" + frmOpts.additionalData;
if (frmOpts.enctype.toLowerCase() != 'multipart/form-data')
{
// Ajax submission of a form doesn't work for multipart/form-data!
frmOpts.method = (frmOpts.method.toLowerCase() == "post") ? 'POST' : 'GET';
if (frmOpts.method == "GET")
{
// Data will be submitted in the url.
if (frmOpts.url.indexOf('?') == -1)
frmOpts.url += '?';
else
frmOpts.url += '&';
frmOpts.url += submitData;
}
else
{
// Send Content-Type header.
if (!frmOpts.headers) frmOpts.headers = {};
if (!frmOpts.headers['Content-Type'] || frmOpts.headers['Content-Type'].indexOf("application/x-www-form-urlencoded") ==-1 )
frmOpts.headers['Content-Type'] = 'application/x-www-form-urlencoded';
// Set the postData
frmOpts.postData = submitData;
}
Spry.Utils.loadURL(frmOpts.method, frmOpts.url, true, callback, frmOpts);
return false;
}
// Native submission when 'multipart/form-data' is used.
return true;
};
Spry.Utils.extractParamsFromForm = function (form, elements)
{
if (!form)
return '';
if ( typeof form == 'string' )
form = document.getElementById(form) || document.forms[form];
var formElements;
if (elements)
formElements = ',' + elements.join(',') + ',';
var compStack = new Array(); // key=value pairs
var el;
for (var i = 0; i < form.elements.length; i++ )
{
el = form.elements[i];
if (el.disabled || !el.name)
{
// Don't submit disabled elements.
// Don't submit elements without name.
continue;
}
if (!el.type)
{
// It seems that this element doesn't have a type set,
// so skip it.
continue;
}
if (formElements && formElements.indexOf(',' + el.name + ',')==-1)
continue;
switch(el.type.toLowerCase())
{
case 'text':
case 'password':
case 'textarea':
case 'hidden':
case 'submit':
compStack.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
break;
case 'select-one':
var value = '';
var opt;
if (el.selectedIndex >= 0) {
opt = el.options[el.selectedIndex];
value = opt.value || opt.text;
}
compStack.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(value));
break;
case 'select-multiple':
for (var j = 0; j < el.length; j++)
{
if (el.options[j].selected)
{
value = el.options[j].value || el.options[j].text;
compStack.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(value));
}
}
break;
case 'checkbox':
case 'radio':
if (el.checked)
compStack.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(el.value));
break;
default:
// file, button, reset
break;
}
}
return compStack.join('&');
};
|
export{default}from"./FormHelperText";
|
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Grade dialogue.
*
* @package tool_lp
* @copyright 2016 Frédéric Massart - FMCorz.net
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
define(['jquery',
'core/notification',
'core/templates',
'tool_lp/dialogue',
'tool_lp/event_base',
'core/str'],
function($, Notification, Templates, Dialogue, EventBase, Str) {
/**
* Grade dialogue class.
* @param {Array} ratingOptions
*/
var Grade = function(ratingOptions) {
EventBase.prototype.constructor.apply(this, []);
this._ratingOptions = ratingOptions;
};
Grade.prototype = Object.create(EventBase.prototype);
/** @type {Dialogue} The dialogue. */
Grade.prototype._popup = null;
/** @type {Array} Array of objects containing, 'value', 'name' and optionally 'selected'. */
Grade.prototype._ratingOptions = null;
/**
* After render hook.
*
* @method _afterRender
* @protected
*/
Grade.prototype._afterRender = function() {
var btnRate = this._find('[data-action="rate"]'),
lstRating = this._find('[name="rating"]'),
txtComment = this._find('[name="comment"]');
this._find('[data-action="cancel"]').click(function(e) {
e.preventDefault();
this._trigger('cancelled');
this.close();
}.bind(this));
lstRating.change(function() {
var node = $(this);
if (!node.val()) {
btnRate.prop('disabled', true);
} else {
btnRate.prop('disabled', false);
}
}).change();
btnRate.click(function(e) {
e.preventDefault();
var val = lstRating.val();
if (!val) {
return;
}
this._trigger('rated', {
'rating': val,
'note': txtComment.val()
});
this.close();
}.bind(this));
};
/**
* Close the dialogue.
*
* @method close
*/
Grade.prototype.close = function() {
this._popup.close();
this._popup = null;
};
/**
* Opens the picker.
*
* @param {Number} competencyId The competency ID of the competency to work on.
* @method display
* @return {Promise}
*/
Grade.prototype.display = function() {
return this._render().then(function(html) {
return Str.get_string('rate', 'tool_lp').then(function(title) {
this._popup = new Dialogue(
title,
html,
this._afterRender.bind(this)
);
}.bind(this));
}.bind(this)).fail(Notification.exception);
};
/**
* Find a node in the dialogue.
*
* @param {String} selector
* @method _find
* @returns {node} The node
* @protected
*/
Grade.prototype._find = function(selector) {
return $(this._popup.getContent()).find(selector);
};
/**
* Render the dialogue.
*
* @method _render
* @protected
* @return {Promise}
*/
Grade.prototype._render = function() {
var context = {
cangrade: this._canGrade,
ratings: this._ratingOptions
};
return Templates.render('tool_lp/competency_grader', context);
};
return /** @alias module:tool_lp/grade_dialogue */ Grade;
});
|
"use strict";
exports.__esModule = true;
// istanbul ignore next
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } }
// istanbul ignore next
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _helpersBuildComprehension = require("../../helpers/build-comprehension");
var _helpersBuildComprehension2 = _interopRequireDefault(_helpersBuildComprehension);
var _traversal = require("../../../traversal");
var _traversal2 = _interopRequireDefault(_traversal);
var _util = require("../../../util");
var util = _interopRequireWildcard(_util);
var _types = require("../../../types");
var t = _interopRequireWildcard(_types);
var metadata = {
stage: 0
};
exports.metadata = metadata;
/**
* [Please add a description.]
*/
var visitor = {
/**
* [Please add a description.]
*/
ComprehensionExpression: function ComprehensionExpression(node, parent, scope) {
var callback = array;
if (node.generator) callback = generator;
return callback(node, parent, scope);
}
};
exports.visitor = visitor;
/**
* [Please add a description.]
*/
function generator(node) {
var body = [];
var container = t.functionExpression(null, [], t.blockStatement(body), true);
container.shadow = true;
body.push(_helpersBuildComprehension2["default"](node, function () {
return t.expressionStatement(t.yieldExpression(node.body));
}));
return t.callExpression(container, []);
}
/**
* [Please add a description.]
*/
function array(node, parent, scope) {
var uid = scope.generateUidIdentifierBasedOnNode(parent);
var container = util.template("array-comprehension-container", {
KEY: uid
});
container.callee.shadow = true;
var block = container.callee.body;
var body = block.body;
if (_traversal2["default"].hasType(node, scope, "YieldExpression", t.FUNCTION_TYPES)) {
container.callee.generator = true;
container = t.yieldExpression(container, true);
}
var returnStatement = body.pop();
body.push(_helpersBuildComprehension2["default"](node, function () {
return util.template("array-push", {
STATEMENT: node.body,
KEY: uid
}, true);
}));
body.push(returnStatement);
return container;
}
|
/*!
* content-type
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1
*
* parameter = token "=" ( token / quoted-string )
* token = 1*tchar
* tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
* / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
* / DIGIT / ALPHA
* ; any VCHAR, except delimiters
* quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE
* qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text
* obs-text = %x80-FF
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
*/
var paramRegExp = /; *([!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+) */g
var textRegExp = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/
var tokenRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* RegExp to match quoted-pair in RFC 7230 sec 3.2.6
*
* quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text )
* obs-text = %x80-FF
*/
var qescRegExp = /\\([\u000b\u0020-\u00ff])/g
/**
* RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6
*/
var quoteRegExp = /([\\"])/g
/**
* RegExp to match type in RFC 6838
*
* media-type = type "/" subtype
* type = token
* subtype = token
*/
var typeRegExp = /^[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+\/[!#$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+$/
/**
* Module exports.
* @public
*/
exports.format = format
exports.parse = parse
/**
* Format object to media type.
*
* @param {object} obj
* @return {string}
* @public
*/
function format(obj) {
if (!obj || typeof obj !== 'object') {
throw new TypeError('argument obj is required')
}
var parameters = obj.parameters
var type = obj.type
if (!type || !typeRegExp.test(type)) {
throw new TypeError('invalid type')
}
var string = type
// append parameters
if (parameters && typeof parameters === 'object') {
var param
var params = Object.keys(parameters).sort()
for (var i = 0; i < params.length; i++) {
param = params[i]
if (!tokenRegExp.test(param)) {
throw new TypeError('invalid parameter name')
}
string += '; ' + param + '=' + qstring(parameters[param])
}
}
return string
}
/**
* Parse media type to object.
*
* @param {string|object} string
* @return {Object}
* @public
*/
function parse(string) {
if (!string) {
throw new TypeError('argument string is required')
}
if (typeof string === 'object') {
// support req/res-like objects as argument
string = getcontenttype(string)
if (typeof string !== 'string') {
throw new TypeError('content-type header is missing from object');
}
}
if (typeof string !== 'string') {
throw new TypeError('argument string is required to be a string')
}
var index = string.indexOf(';')
var type = index !== -1
? string.substr(0, index).trim()
: string.trim()
if (!typeRegExp.test(type)) {
throw new TypeError('invalid media type')
}
var key
var match
var obj = new ContentType(type.toLowerCase())
var value
paramRegExp.lastIndex = index
while (match = paramRegExp.exec(string)) {
if (match.index !== index) {
throw new TypeError('invalid parameter format')
}
index += match[0].length
key = match[1].toLowerCase()
value = match[2]
if (value[0] === '"') {
// remove quotes and escapes
value = value
.substr(1, value.length - 2)
.replace(qescRegExp, '$1')
}
obj.parameters[key] = value
}
if (index !== -1 && index !== string.length) {
throw new TypeError('invalid parameter format')
}
return obj
}
/**
* Get content-type from req/res objects.
*
* @param {object}
* @return {Object}
* @private
*/
function getcontenttype(obj) {
if (typeof obj.getHeader === 'function') {
// res-like
return obj.getHeader('content-type')
}
if (typeof obj.headers === 'object') {
// req-like
return obj.headers && obj.headers['content-type']
}
}
/**
* Quote a string if necessary.
*
* @param {string} val
* @return {string}
* @private
*/
function qstring(val) {
var str = String(val)
// no need to quote tokens
if (tokenRegExp.test(str)) {
return str
}
if (str.length > 0 && !textRegExp.test(str)) {
throw new TypeError('invalid parameter value')
}
return '"' + str.replace(quoteRegExp, '\\$1') + '"'
}
/**
* Class to represent a content type.
* @private
*/
function ContentType(type) {
this.parameters = Object.create(null)
this.type = type
}
|
export{default}from"./Snackbar";
|
/*************************************************************
*
* MathJax/jax/output/HTML-CSS/fonts/TeX/Size4/Regular/Main.js
*
* Copyright (c) 2009-2015 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
MathJax.OutputJax['HTML-CSS'].FONTDATA.FONTS['MathJax_Size4'] = {
directory: 'Size4/Regular',
family: 'MathJax_Size4',
testString: "() [] {}",
0x20: [0,0,250,0,0], // SPACE
0x28: [1750,1249,792,237,758], // LEFT PARENTHESIS
0x29: [1750,1249,792,33,554], // RIGHT PARENTHESIS
0x2F: [1750,1249,1278,56,1221], // SOLIDUS
0x5B: [1750,1249,583,269,577], // LEFT SQUARE BRACKET
0x5C: [1750,1249,1278,56,1221], // REVERSE SOLIDUS
0x5D: [1750,1249,583,5,313], // RIGHT SQUARE BRACKET
0x7B: [1750,1249,806,144,661], // LEFT CURLY BRACKET
0x7D: [1750,1249,806,144,661], // RIGHT CURLY BRACKET
0xA0: [0,0,250,0,0], // NO-BREAK SPACE
0x2C6: [845,-561,1889,-14,1902], // MODIFIER LETTER CIRCUMFLEX ACCENT
0x2DC: [823,-583,1889,1,1885], // SMALL TILDE
0x302: [845,-561,0,-1903,13], // COMBINING CIRCUMFLEX ACCENT
0x303: [823,-583,0,-1888,-4], // COMBINING TILDE
0x221A: [1750,1250,1000,111,1020], // SQUARE ROOT
0x2308: [1750,1249,639,269,633], // LEFT CEILING
0x2309: [1750,1249,639,5,369], // RIGHT CEILING
0x230A: [1750,1249,639,269,633], // LEFT FLOOR
0x230B: [1750,1249,639,5,369], // RIGHT FLOOR
0x239B: [1154,655,875,291,843], // LEFT PARENTHESIS UPPER HOOK
0x239C: [610,10,875,291,417], // LEFT PARENTHESIS EXTENSION
0x239D: [1165,644,875,291,843], // LEFT PARENTHESIS LOWER HOOK
0x239E: [1154,655,875,31,583], // RIGHT PARENTHESIS UPPER HOOK
0x239F: [610,10,875,457,583], // RIGHT PARENTHESIS EXTENSION
0x23A0: [1165,644,875,31,583], // RIGHT PARENTHESIS LOWER HOOK
0x23A1: [1154,645,667,319,666], // LEFT SQUARE BRACKET UPPER CORNER
0x23A2: [602,0,667,319,403], // LEFT SQUARE BRACKET EXTENSION
0x23A3: [1155,644,667,319,666], // LEFT SQUARE BRACKET LOWER CORNER
0x23A4: [1154,645,667,0,347], // RIGHT SQUARE BRACKET UPPER CORNER
0x23A5: [602,0,667,263,347], // RIGHT SQUARE BRACKET EXTENSION
0x23A6: [1155,644,667,0,347], // RIGHT SQUARE BRACKET LOWER CORNER
0x23A7: [899,10,889,384,718], // LEFT CURLY BRACKET UPPER HOOK
0x23A8: [1160,660,889,170,504], // LEFT CURLY BRACKET MIDDLE PIECE
0x23A9: [10,899,889,384,718], // LEFT CURLY BRACKET LOWER HOOK
0x23AA: [310,10,889,384,504], // CURLY BRACKET EXTENSION
0x23AB: [899,10,889,170,504], // RIGHT CURLY BRACKET UPPER HOOK
0x23AC: [1160,660,889,384,718], // RIGHT CURLY BRACKET MIDDLE PIECE
0x23AD: [10,899,889,170,504], // RIGHT CURLY BRACKET LOWER HOOK
0x23B7: [935,885,1056,111,742], // RADICAL SYMBOL BOTTOM
0x27E8: [1750,1248,806,140,703], // MATHEMATICAL LEFT ANGLE BRACKET
0x27E9: [1750,1248,806,103,665], // MATHEMATICAL RIGHT ANGLE BRACKET
0xE000: [625,14,1056,702,742], // stix-radical symbol vertical extender
0xE001: [605,14,1056,702,1076], // stix-radical symbol top corner piece
0xE150: [120,213,450,-24,460], // stix-horizontal brace, down left piece
0xE151: [120,213,450,-10,474], // stix-horizontal brace, down right piece
0xE152: [333,0,450,-24,460], // stix-horizontal brace, upper left piece
0xE153: [333,0,450,-10,474], // stix-horizontal brace, upper right piece
0xE154: [120,0,400,-10,410] // stix-oblique open face capital letter A
};
MathJax.Callback.Queue(
["initFont",MathJax.OutputJax["HTML-CSS"],"MathJax_Size4"],
["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Size4/Regular/Main.js"]
);
|
//// Copyright (c) Microsoft Corporation. All rights reserved
(function () {
"use strict";
})();
|
var B = require('../').Buffer
var test = require('tape')
if (process.env.OBJECT_IMPL) B.TYPED_ARRAY_SUPPORT = false
test('modifying buffer created by .slice() modifies original memory', function (t) {
if (!B._useTypedArrays) return t.end()
var buf1 = new B(26)
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97 // 97 is ASCII a
}
var buf2 = buf1.slice(0, 3)
t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
buf2[0] = '!'.charCodeAt(0)
t.equal(buf1.toString('ascii', 0, buf2.length), '!bc')
t.end()
})
test('modifying parent buffer modifies .slice() buffer\'s memory', function (t) {
if (!B._useTypedArrays) return t.end()
var buf1 = new B(26)
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97 // 97 is ASCII a
}
var buf2 = buf1.slice(0, 3)
t.equal(buf2.toString('ascii', 0, buf2.length), 'abc')
buf1[0] = '!'.charCodeAt(0)
t.equal(buf2.toString('ascii', 0, buf2.length), '!bc')
t.end()
})
|
'use strict';
module.exports.definition = {
set: function (v) {
this.setProperty('border-image-repeat', v);
},
get: function () {
return this.getPropertyValue('border-image-repeat');
},
enumerable: true,
configurable: true
};
|
import "interpolate";
d3.interpolateObject = d3_interpolateObject;
function d3_interpolateObject(a, b) {
var i = {},
c = {},
k;
for (k in a) {
if (k in b) {
i[k] = d3_interpolate(a[k], b[k]);
} else {
c[k] = a[k];
}
}
for (k in b) {
if (!(k in a)) {
c[k] = b[k];
}
}
return function(t) {
for (k in i) c[k] = i[k](t);
return c;
};
}
|
var convert = require('./convert');
module.exports = convert('overEvery', require('../overEvery'));
|
'use strict';
var _ = require('lodash');
function init (ctx) {
var allPlugins = []
, enabledPlugins = [];
function plugins(name) {
if (name) {
return _.find(allPlugins, {name: name});
} else {
return plugins;
}
}
plugins.base = require('./pluginbase');
var clientDefaultPlugins = [
require('./bgnow')(ctx)
, require('./rawbg')(ctx)
, require('./direction')(ctx)
, require('./timeago')(ctx)
, require('./upbat')(ctx)
, require('./ar2')(ctx)
, require('./errorcodes')(ctx)
, require('./iob')(ctx)
, require('./cob')(ctx)
, require('./careportal')(ctx)
, require('./pump')(ctx)
, require('./openaps')(ctx)
, require('./loop')(ctx)
, require('./boluswizardpreview')(ctx)
, require('./cannulaage')(ctx)
, require('./sensorage')(ctx)
, require('./insulinage')(ctx)
, require('./basalprofile')(ctx)
, require('./boluscalc')(ctx) // fake plugin to show/hide
, require('./profile')(ctx) // fake plugin to hold extended settings
];
var serverDefaultPlugins = [
require('./bgnow')(ctx)
, require('./rawbg')(ctx)
, require('./direction')(ctx)
, require('./upbat')(ctx)
, require('./ar2')(ctx)
, require('./simplealarms')(ctx)
, require('./errorcodes')(ctx)
, require('./iob')(ctx)
, require('./cob')(ctx)
, require('./pump')(ctx)
, require('./openaps')(ctx)
, require('./loop')(ctx)
, require('./boluswizardpreview')(ctx)
, require('./cannulaage')(ctx)
, require('./sensorage')(ctx)
, require('./insulinage')(ctx)
, require('./treatmentnotify')(ctx)
, require('./timeago')(ctx)
, require('./basalprofile')(ctx)
];
plugins.registerServerDefaults = function registerServerDefaults() {
plugins.register(serverDefaultPlugins);
return plugins;
};
plugins.registerClientDefaults = function registerClientDefaults() {
plugins.register(clientDefaultPlugins);
return plugins;
};
plugins.register = function register(all) {
_.each(all, function eachPlugin(plugin) {
allPlugins.push(plugin);
});
enabledPlugins = [];
var enable = _.get(ctx, 'settings.enable');
function isEnabled(plugin) {
//TODO: unify client/server env/app
return enable && enable.indexOf(plugin.name) > -1;
}
_.each(allPlugins, function eachPlugin(plugin) {
plugin.enabled = isEnabled(plugin);
if (plugin.enabled) {
enabledPlugins.push(plugin);
}
});
};
plugins.eachPlugin = function eachPlugin(f) {
_.each(allPlugins, f);
};
plugins.eachEnabledPlugin = function eachEnabledPlugin(f) {
_.each(enabledPlugins, f);
};
//these plugins are either always on or have custom settings
plugins.specialPlugins = 'ar2 bgnow delta direction timeago upbat rawbg errorcodes profile';
plugins.shownPlugins = function(sbx) {
return _.filter(enabledPlugins, function filterPlugins(plugin) {
return plugins.specialPlugins.indexOf(plugin.name) > -1 || (sbx && sbx.showPlugins && sbx.showPlugins.indexOf(plugin.name) > -1);
});
};
plugins.eachShownPlugins = function eachShownPlugins(sbx, f) {
_.each(plugins.shownPlugins(sbx), f);
};
plugins.hasShownType = function hasShownType(pluginType, sbx) {
return _.find(plugins.shownPlugins(sbx), function findWithType(plugin) {
return plugin.pluginType === pluginType;
}) !== undefined;
};
plugins.setProperties = function setProperties(sbx) {
plugins.eachEnabledPlugin(function eachPlugin (plugin) {
if (plugin.setProperties) {
plugin.setProperties(sbx.withExtendedSettings(plugin));
}
});
};
plugins.checkNotifications = function checkNotifications(sbx) {
plugins.eachEnabledPlugin(function eachPlugin (plugin) {
if (plugin.checkNotifications) {
plugin.checkNotifications(sbx.withExtendedSettings(plugin));
}
});
};
plugins.updateVisualisations = function updateVisualisations(sbx) {
plugins.eachShownPlugins(sbx, function eachPlugin(plugin) {
if (plugin.updateVisualisation) {
plugin.updateVisualisation(sbx.withExtendedSettings(plugin));
}
});
};
plugins.getAllEventTypes = function getAllEventTypes(sbx) {
var all = [];
plugins.eachEnabledPlugin(function eachPlugin(plugin) {
if (plugin.getEventTypes) {
var eventTypes = plugin.getEventTypes(sbx.withExtendedSettings(plugin));
if (_.isArray(eventTypes)) {
all = all.concat(eventTypes);
}
}
});
return all;
};
plugins.enabledPluginNames = function enabledPluginNames() {
return _.map(enabledPlugins, function mapped(plugin) {
return plugin.name;
}).join(' ');
};
plugins.extendedClientSettings = function extendedClientSettings (allExtendedSettings) {
var clientSettings = {};
_.each(clientDefaultPlugins, function eachClientPlugin (plugin) {
clientSettings[plugin.name] = allExtendedSettings[plugin.name];
});
//HACK: include devicestatus
clientSettings.devicestatus = allExtendedSettings.devicestatus;
return clientSettings;
};
return plugins();
}
module.exports = init;
|
/*!
* http-errors
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2016 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var deprecate = require('depd')('http-errors')
var setPrototypeOf = require('setprototypeof')
var statuses = require('statuses')
var inherits = require('inherits')
/**
* Module exports.
* @public
*/
module.exports = createError
module.exports.HttpError = createHttpErrorConstructor()
// Populate exports for all constructors
populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError)
/**
* Get the code class of a status code.
* @private
*/
function codeClass (status) {
return Number(String(status).charAt(0) + '00')
}
/**
* Create a new HTTP Error.
*
* @returns {Error}
* @public
*/
function createError () {
// so much arity going on ~_~
var err
var msg
var status = 500
var props = {}
for (var i = 0; i < arguments.length; i++) {
var arg = arguments[i]
if (arg instanceof Error) {
err = arg
status = err.status || err.statusCode || status
continue
}
switch (typeof arg) {
case 'string':
msg = arg
break
case 'number':
status = arg
if (i !== 0) {
deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)')
}
break
case 'object':
props = arg
break
}
}
if (typeof status === 'number' && (status < 400 || status >= 600)) {
deprecate('non-error status code; use only 4xx or 5xx status codes')
}
if (typeof status !== 'number' ||
(!statuses[status] && (status < 400 || status >= 600))) {
status = 500
}
// constructor
var HttpError = createError[status] || createError[codeClass(status)]
if (!err) {
// create error
err = HttpError
? new HttpError(msg)
: new Error(msg || statuses[status])
Error.captureStackTrace(err, createError)
}
if (!HttpError || !(err instanceof HttpError) || err.status !== status) {
// add properties to generic error
err.expose = status < 500
err.status = err.statusCode = status
}
for (var key in props) {
if (key !== 'status' && key !== 'statusCode') {
err[key] = props[key]
}
}
return err
}
/**
* Create HTTP error abstract base class.
* @private
*/
function createHttpErrorConstructor () {
function HttpError () {
throw new TypeError('cannot construct abstract class')
}
inherits(HttpError, Error)
return HttpError
}
/**
* Create a constructor for a client error.
* @private
*/
function createClientErrorConstructor (HttpError, name, code) {
var className = name.match(/Error$/) ? name : name + 'Error'
function ClientError (message) {
// create the error object
var msg = message != null ? message : statuses[code]
var err = new Error(msg)
// capture a stack trace to the construction point
Error.captureStackTrace(err, ClientError)
// adjust the [[Prototype]]
setPrototypeOf(err, ClientError.prototype)
// redefine the error message
Object.defineProperty(err, 'message', {
enumerable: true,
configurable: true,
value: msg,
writable: true
})
// redefine the error name
Object.defineProperty(err, 'name', {
enumerable: false,
configurable: true,
value: className,
writable: true
})
return err
}
inherits(ClientError, HttpError)
ClientError.prototype.status = code
ClientError.prototype.statusCode = code
ClientError.prototype.expose = true
return ClientError
}
/**
* Create a constructor for a server error.
* @private
*/
function createServerErrorConstructor (HttpError, name, code) {
var className = name.match(/Error$/) ? name : name + 'Error'
function ServerError (message) {
// create the error object
var msg = message != null ? message : statuses[code]
var err = new Error(msg)
// capture a stack trace to the construction point
Error.captureStackTrace(err, ServerError)
// adjust the [[Prototype]]
setPrototypeOf(err, ServerError.prototype)
// redefine the error message
Object.defineProperty(err, 'message', {
enumerable: true,
configurable: true,
value: msg,
writable: true
})
// redefine the error name
Object.defineProperty(err, 'name', {
enumerable: false,
configurable: true,
value: className,
writable: true
})
return err
}
inherits(ServerError, HttpError)
ServerError.prototype.status = code
ServerError.prototype.statusCode = code
ServerError.prototype.expose = false
return ServerError
}
/**
* Populate the exports object with constructors for every error class.
* @private
*/
function populateConstructorExports (exports, codes, HttpError) {
codes.forEach(function forEachCode (code) {
var CodeError
var name = toIdentifier(statuses[code])
switch (codeClass(code)) {
case 400:
CodeError = createClientErrorConstructor(HttpError, name, code)
break
case 500:
CodeError = createServerErrorConstructor(HttpError, name, code)
break
}
if (CodeError) {
// export the constructor
exports[code] = CodeError
exports[name] = CodeError
}
})
// backwards-compatibility
exports["I'mateapot"] = deprecate.function(exports.ImATeapot,
'"I\'mateapot"; use "ImATeapot" instead')
}
/**
* Convert a string of words to a JavaScript identifier.
* @private
*/
function toIdentifier (str) {
return str.split(' ').map(function (token) {
return token.slice(0, 1).toUpperCase() + token.slice(1)
}).join('').replace(/[^ _0-9a-z]/gi, '')
}
|
var exec = require('child_process').exec
, path = require('path')
;
/**
* open a file or uri using the default application for the file type.
*
* @return {ChildProcess} - the child process object.
* @param {string} target - the file/uri to open.
* @param {string} appName - (optional) the application to be used to open the
* file (for example, "chrome", "firefox")
* @param {function(Error)} callback - called with null on success, or
* an error object that contains a property 'code' with the exit
* code of the process.
*/
module.exports = open;
function open(target, appName, callback) {
var opener;
if (typeof(appName) === 'function') {
callback = appName;
appName = null;
}
switch (process.platform) {
case 'darwin':
if (appName) {
opener = 'open -a "' + escape(appName) + '"';
} else {
opener = 'open';
}
break;
case 'win32':
// if the first parameter to start is quoted, it uses that as the title
// so we pass a blank title so we can quote the file we are opening
if (appName) {
opener = 'start "" "' + escape(appName) + '"';
} else {
opener = 'start ""';
}
break;
default:
if (appName) {
opener = escape(appName);
} else {
// use Portlands xdg-open everywhere else
opener = path.join(__dirname, '../vendor/xdg-open');
}
break;
}
return exec(opener + ' "' + escape(target) + '"', callback);
}
function escape(s) {
return s.replace(/"/g, '\\\"');
}
|
define(
"dojo/cldr/nls/ja/buddhist", //begin v1.x content
{
"dateFormatItem-yM": "y/M",
"dateFormatItem-yyyyMMMEd": "Gy年M月d日(EEE)",
"dateFormatItem-yQ": "y/Q",
"dayPeriods-format-wide-pm": "午後",
"dateFormatItem-GGGGyMd": "GGGGy年M月d日",
"dateFormatItem-MMMEd": "M月d日(E)",
"dateTimeFormat-full": "{1}{0}",
"dateFormatItem-hms": "ah:mm:ss",
"dateFormatItem-yQQQ": "yQQQ",
"dateFormatItem-MMdd": "MM/dd",
"dateFormatItem-MMM": "LLL",
"dayPeriods-format-wide-am": "午前",
"dateFormatItem-y": "Gy年",
"timeFormat-full": "H時mm分ss秒 zzzz",
"dateFormatItem-yyyy": "Gy年",
"dateFormatItem-Ed": "d日(EEE)",
"dateFormatItem-yMMM": "y年M月",
"days-standAlone-narrow": [
"日",
"月",
"火",
"水",
"木",
"金",
"土"
],
"dateFormatItem-yyyyMM": "Gyy/MM",
"dateFormat-long": "Gy年M月d日",
"timeFormat-medium": "H:mm:ss",
"dateFormatItem-Hm": "H:mm",
"dateFormat-medium": "Gy/MM/dd",
"dateFormatItem-Hms": "H:mm:ss",
"dateFormatItem-ms": "mm:ss",
"dateTimeFormat-long": "{1}{0}",
"dateFormatItem-yyyyMd": "Gyy/M/d",
"dateFormatItem-yyyyMMMd": "Gy年M月d日",
"dateFormatItem-yyyyMEd": "Gyy/M/d(E)",
"dateFormatItem-MMMd": "M月d日",
"timeFormat-long": "H:mm:ss z",
"timeFormat-short": "H:mm",
"dateFormatItem-H": "H時",
"days-format-abbr": [
"日",
"月",
"火",
"水",
"木",
"金",
"土"
],
"dateFormatItem-M": "M月",
"dateFormatItem-MEd": "M/d(E)",
"dateFormatItem-hm": "ah:mm",
"dateFormat-short": "Gy/MM/dd",
"dateFormatItem-yMMMEd": "y年M月d日(EEE)",
"dateFormat-full": "Gy年M月d日EEEE",
"dateFormatItem-Md": "M/d",
"dateFormatItem-yyyyQ": "Gyy/Q",
"dateFormatItem-yMEd": "y/M/d(EEE)",
"months-format-wide": [
"1月",
"2月",
"3月",
"4月",
"5月",
"6月",
"7月",
"8月",
"9月",
"10月",
"11月",
"12月"
],
"dateFormatItem-yyyyMMM": "Gy年M月",
"dateFormatItem-d": "d日",
"quarters-format-wide": [
"第1四半期",
"第2四半期",
"第3四半期",
"第4四半期"
],
"days-format-wide": [
"日曜日",
"月曜日",
"火曜日",
"水曜日",
"木曜日",
"金曜日",
"土曜日"
],
"dateFormatItem-h": "ah時"
}
//end v1.x content
);
|
/// <reference path='m1.ts'/>
var a1 = 10;
var c1 = /** @class */ (function () {
function c1() {
}
return c1;
}());
var instance1 = new c1();
function f1() {
return instance1;
}
//# sourceMappingURL=test.js.map
|
var path = require('path');
var srcPath = path.join(__dirname, '../../src/');
module.exports = {
devtool: 'eval',
module: {
loaders: [
{
test: /\.(png|jpg|gif|woff|woff2|md|css|sass|scss|less|styl)$/,
loader: 'null-loader'
},
{
test: /\.(js|jsx)$/,
loader: 'babel',
exclude: [/node_modules/]
}
]
},
node : { fs: 'empty' },
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
helpers: path.join(__dirname, '../../test/helpers'),
actions: srcPath + '/common' + '/actions/',
components: srcPath + '/common' + '/components/',
containers: srcPath + '/common' + '/containers/',
content: srcPath + '/common' + '/content/',
icons: srcPath + '/common' + '/components/icons/',
images: srcPath + '/common' + '/images/',
lib: srcPath + '/common' + '/lib/',
reducers: srcPath + '/common' + '/reducers/',
styles: srcPath + '/common' + '/styles/',
validators: srcPath + '/common' + '/validators/',
types: srcPath + '/common' + '/types/',
schemas: srcPath + '/common' + '/schemas/',
}
}
};
|
var methodAliases = require('./method-map');
module.exports = function getMethodName(categoryName, methodAlias) {
return methodAliases[categoryName] && methodAliases[categoryName][methodAlias];
};
|
define([
"utils/range"
],function(Range) {
"use strict";
function BoundingBox(position, width, height) {
this.position = position;
this.width = width;
this.height = height;
this.rangeX = new Range(position.x, position.x + width);
this.rangeY = new Range(position.y, position.y + width);
}
BoundingBox.prototype.setPosition = function(position) {
this.position = position;
return updateRanges(this);
};
BoundingBox.prototype.move = function(velocity) {
this.position.move(velocity);
return updateRanges(this);
};
BoundingBox.prototype.setWidth = function(width) {
this.width = width;
return updateRanges(this);
};
BoundingBox.prototype.setHeight = function(height) {
this.height = height;
return updateRanges(this);
};
/**
* Is this bounding box colliding with another?
*
* @param {BoundingBox} other
* @return bool
*/
BoundingBox.prototype.isColliding = function(other) {
var isCollidingX = this.rangeX.intersects(other.rangeX),
isCollidingY = this.rangeY.intersects(other.rangeY);
return isCollidingX && isCollidingY;
};
BoundingBox.prototype.toString = function() {
return "BoundingBox(rangeX = " + this.rangeX + ", rangeY = " + this.rangeY + ")";
};
function updateRanges(boundingBox) {
var pos = boundingBox.position;
boundingBox.rangeX.update(pos.x, pos.x + boundingBox.width);
boundingBox.rangeY.update(pos.y, pos.y + boundingBox.height);
return boundingBox;
}
return BoundingBox;
});
|
google.load("gdata", "1");
google.setOnLoadCallback(loadFeed);
var feedURL = "http://www.google.com/calendar/feeds/calendar%40ourladymotherchurch.com/public/full";
var calendarDiv = null;
var service = null;
function loadFeed() {
service = new google.gdata.calendar.CalendarService('OLMC');
var query = new google.gdata.calendar.CalendarEventQuery(feedURL);
query.setFutureEvents(true);
query.setOrderBy('starttime');
query.setSortOrder('ascending');
query.setMaxResults(5);
service.getEventsFeed(query, loadedFeed, handleError);
}
function handleError (error) {
console.log("Couldn't fetch events: " + error);
}
function loadedFeed (result) {
var entries = result.feed.getEntries();
if (!entries.length) {
var calendarDiv = getCalendar();
calendarDiv.innerHTML = "<p id=\"noEvents\">No upcoming events found</p>";
return;
}
var lastMonth = -1;
for (var n = 0; n < entries.length; n++) {
var entry = entries[n];
var title = entry.getTitle().getText();
var desc = entry.getContent().getText();
var times = entry.getTimes();
var firstTime = null;
if (times.length > 0) {
firstTime = times[0].getStartTime();
}
var date = firstTime.getDate();
var day = date.getDate();
var month = date.getMonth();
if (month != lastMonth) {
insertHeader(nameForMonth(month));
lastMonth = month;
}
var time = null;
if (!firstTime.isDateOnly()) {
time = formatShortTime(date);
}
addEvent(title, day, desc, time);
}
}
function insertHeader (month) {
var header = document.createElement("div");
header.className = "header";
header.innerHTML = '<p>' + month + '</p>';
getCalendar().appendChild(header);
}
function addEvent (title, day, desc, time) {
var event = document.createElement("div");
event.className = "event";
var month = document.createElement("div");
month.className = "month";
month.innerHTML = '<p>' + day + '</p>';
var info = document.createElement("div");
info.className = "info";
var clearFix = document.createElement("div");
clearFix.className = "clearFix";
var titleP = document.createElement("p");
titleP.className = "title";
titleP.innerHTML = title;
var subtitle = null;
if (desc) {
subtitle = desc;
if (time) {
subtitle += (" - " + time);
}
}
else if (time) {
subtitle = time;
}
var subtitleP = document.createElement("p");
subtitleP.className = "subtitle";
subtitleP.innerHTML = subtitle ? subtitle : "";
info.appendChild(titleP);
info.appendChild(subtitleP);
event.appendChild(month);
event.appendChild(info);
event.appendChild(clearFix);
getCalendar().appendChild(event);
}
/* Utility */
function getCalendar() {
if (!calendarDiv) {
calendarDiv = document.getElementById("calendar");
var throbber = document.getElementById("throbber");
calendarDiv.removeChild(throbber);
}
return calendarDiv;
}
function nameForMonth (month) {
if (month == 0) {
return "January";
}
else if (month == 1) {
return "February";
}
else if (month == 2) {
return "March";
}
else if (month == 3) {
return "April";
}
else if (month == 4) {
return "May";
}
else if (month == 5) {
return "June";
}
else if (month == 6) {
return "July";
}
else if (month == 7) {
return "August";
}
else if (month == 8) {
return "September";
}
else if (month == 9) {
return "October";
}
else if (month == 10) {
return "November";
}
return "December";
}
function formatShortTime (date) {
var rawHours = date.getHours();
var rawMinutes = date.getMinutes();
var hours = rawHours > 12 ? rawHours - 12 : rawHours;
var minutes = padNumber(rawMinutes);
var suffix = rawHours > 11 ? "PM" : "AM";
return hours + ":" + minutes + " " + suffix;
}
function padNumber (num) {
if (num <= 9)
return "0" + num;
return num;
}
|
'use strict';
var test = require('prova'),
path = require('path'),
exec = require('child_process').exec;
function documentation(args, options, callback) {
if (!callback) {
callback = options;
options = {};
}
if (!options.cwd) {
options.cwd = __dirname;
}
args.unshift(path.join(__dirname, '../bin/documentation.js'));
exec(args.join(' '), options, function (err, stdout, stderr) {
if (err) return callback(err, stdout, stderr);
callback(err, JSON.parse(stdout), stderr);
});
}
test('documentation binary', function (t) {
documentation(['fixture/simple.input.js'], function (err, data) {
t.error(err);
t.equal(data.length, 1, 'simple has no dependencies');
t.end();
});
});
test('defaults to parsing package.json main', function (t) {
documentation([], { cwd: path.join(__dirname, '..') }, function (err, data) {
t.error(err);
t.ok(data.length, 'we document ourself');
t.end();
});
});
|
import { dispatch as d3_dispatch } from 'd3-dispatch';
import {
event as d3_event,
select as d3_select
} from 'd3-selection';
import { d3keybinding as d3_keybinding } from '../lib/d3.keybinding.js';
import { osmEntity } from '../osm/index';
import { utilRebind } from '../util/rebind';
/*
The hover behavior adds the `.hover` class on mouseover to all elements to which
the identical datum is bound, and removes it on mouseout.
The :hover pseudo-class is insufficient for iD's purposes because a datum's visual
representation may consist of several elements scattered throughout the DOM hierarchy.
Only one of these elements can have the :hover pseudo-class, but all of them will
have the .hover class.
*/
export function behaviorHover(context) {
var dispatch = d3_dispatch('hover'),
_selection = d3_select(null),
newId = null,
buttonDown,
altDisables,
target;
function keydown() {
if (altDisables && d3_event.keyCode === d3_keybinding.modifierCodes.alt) {
_selection.selectAll('.hover')
.classed('hover-suppressed', true)
.classed('hover', false);
_selection
.classed('hover-disabled', true);
dispatch.call('hover', this, null);
}
}
function keyup() {
if (altDisables && d3_event.keyCode === d3_keybinding.modifierCodes.alt) {
_selection.selectAll('.hover-suppressed')
.classed('hover-suppressed', false)
.classed('hover', true);
_selection
.classed('hover-disabled', false);
dispatch.call('hover', this, target ? target.id : null);
}
}
var hover = function(selection) {
_selection = selection;
newId = null;
_selection
.on('mouseover.hover', mouseover)
.on('mouseout.hover', mouseout)
.on('mousedown.hover', mousedown);
d3_select(window)
.on('keydown.hover', keydown)
.on('keyup.hover', keyup);
function mouseover() {
if (buttonDown) return;
var target = d3_event.target;
enter(target ? target.__data__ : null);
}
function mouseout() {
if (buttonDown) return;
var target = d3_event.relatedTarget;
enter(target ? target.__data__ : null);
}
function mousedown() {
buttonDown = true;
d3_select(window)
.on('mouseup.hover', mouseup, true);
}
function mouseup() {
buttonDown = false;
d3_select(window)
.on('mouseup.hover', null, true);
}
function enter(d) {
if (d === target) return;
target = d;
_selection.selectAll('.hover')
.classed('hover', false);
_selection.selectAll('.hover-suppressed')
.classed('hover-suppressed', false);
if (target instanceof osmEntity && target.id !== newId) {
// If drawing a way, don't hover on a node that was just placed. #3974
var mode = context.mode() && context.mode().id;
if ((mode === 'draw-line' || mode === 'draw-area') && !newId && target.type === 'node') {
newId = target.id;
return;
}
var selector = '.' + target.id;
if (target.type === 'relation') {
target.members.forEach(function(member) {
selector += ', .' + member.id;
});
}
var suppressed = altDisables && d3_event && d3_event.altKey;
_selection.selectAll(selector)
.classed(suppressed ? 'hover-suppressed' : 'hover', true);
dispatch.call('hover', this, !suppressed && target.id);
} else {
dispatch.call('hover', this, null);
}
}
};
hover.off = function(selection) {
selection.selectAll('.hover')
.classed('hover', false);
selection.selectAll('.hover-suppressed')
.classed('hover-suppressed', false);
selection
.classed('hover-disabled', false);
selection
.on('mouseover.hover', null)
.on('mouseout.hover', null)
.on('mousedown.hover', null);
d3_select(window)
.on('keydown.hover', null)
.on('keyup.hover', null);
};
hover.altDisables = function(_) {
if (!arguments.length) return altDisables;
altDisables = _;
return hover;
};
return utilRebind(hover, dispatch, 'on');
}
|
angular.module('square', [])
.factory('square', function() {
return function (num) {
return num * num;
};
});
|
function getEvents (cloudformation, argv, utils) {
const stackName = argv._[1]
if (!stackName) {
console.error('cirrus events <stackname>')
process.exit(1)
}
utils.fetchEvents(stackName, function (err, events) {
if (err) {
utils.checkExists(stackName, err)
throw new Error(err)
}
utils.logEvents(events)
})
}
export default {
name: 'events',
description: 'Returns events for a stack',
fn: getEvents
}
|
'use strict';
var program = require('commander');
program
.version('0.0.1')
.option('-p, --peppers', 'Add peppers')
.option('-P, --pineapple', 'Add pineapple')
.option('-b, --bbq', 'Add bbq sauce')
.option('-c, --cheese [type]', 'Add the specified type of cheese [marble]', 'marble')
.parse(process.argv);
console.log('you ordered a pizza with:');
if (program.peppers) console.log(' - peppers');
if (program.pineapple) console.log(' - pineapple');
if (program.bbq) console.log(' - bbq');
console.log(' - %s cheese', program.cheese);
|
// jshint node: true, esversion: 6
'use strict';
const mailgun = require('mailgun-js')({ apiKey: process.env.MAILGUN_KEY, domain: 'lcssl.org' });
const mail = {
send: (recipient, subject, message, done) => {
var data = {
from: 'Civil Service Softball League <results@lcssl.org>',
cc: 'nick@mantonbradbury.com',
to: recipient,
subject: subject,
text: message
};
mailgun.messages().send(data).then(response => {
console.log('email sent', response); // move to winston
done(response);
}, err => {
console.error('not sent', err); // move to winston
done(err);
});
}
};
module.exports = mail;
|
'use strict';
// ------------------------------------------------------
// TABLE OF CONTENTS
// ------------------------------------------------------
// 1 - GENERAL NOTES
// 2 - STEP BY STEP
// 3 - GENERAL GUIDE
// 4 - COMMON PROBLEMS
// ------------------------------------------------------
// ------------------------------------------------------
// GENERAL NOTES
// ------------------------------------------------------
// VALUES
// - Numbers
// - Strings
// - Boolean (true / false)
// - null
// - undefined
//
// VARIABLES
// - Declaration
// - Scope
// - Hoisting
//
// CONSTANTS
// ------------------------------------------------------
// STEP BY STEP
// ------------------------------------------------------
// VARIABLES
// ------------------------------------------------------
// DECLARATION
var surname;
var name;
var age;
// INITIALIZATION
var surname = 'Silva';
var name = 'Fabrício';
var age = 28;
// ASSIGNMENT
surname = 'Mendes';
name = 'Francisco';
age = 29;
// CONSTANTS
// ------------------------------------------------------
const dev = 'Fabrício Silva';
// VALUES
// ------------------------------------------------------
// NUMBERS
var number = 1;
var integer = 1;
var floatPointer = 1.0;
var notANumber = NaN;
// STRINGS
var string = "This is a String";
var name = "Fabrício Silva";
// BOOLEAN
var truthy = true;
var falsy = false;
// NULL
var notValue = null;
// UNDEFINED
var notDefinied;
// ------------------------------------------------------
// GENERAL GUIDE
// ------------------------------------------------------
// ------------------------------------------------------
// COMMON PROBLEMS
// ------------------------------------------------------
|
import EndOfGameEvent from "../events/EndOfGameEvent";
import ExitLevelEvent from "../events/ExitLevelEvent";
class CollisionDetector {
constructor(scoreMgr) {
this.scoreManager = scoreMgr;
}
detectAll(hero, level) {
var that = this;
var collided = false;
// Detects collisions with enemies
level.enemies.getChildren().forEach(function(enemy){
// There are two types of collisions with enemies:
// 1. If player is falling (hero.ySpeed > 0 [1.a]
// AND hero.getY() < enemy.getY() [1.b]),
// then the player kills the enemy
// 2. Else, the enemy kills the player
if(that.detectCollision(enemy, hero)
&& hero.ySpeed > 2 // 1.a
&& hero.getY() < enemy.getY()) { // 1.b
that.scoreManager.scoreEnemy();
enemy.remove();
} else if(that.detectCollision(enemy, hero)) { // 2
throw new EndOfGameEvent('Game Over!');
}
});
// Detects collisions with platforms
level.platforms.getChildren().forEach(function(platform){
// We're interested in collisions that:
// 1. Actually occurs (detectCollision(a, b) is true)
// 2. Player is over the platform (hero.getY() < platform.getY())
// 3. Player is falling over (hero.ySpeed > 0)
if(that.detectCollision(platform, hero) // 1
&& hero.getY() < platform.getY() // 2
&& hero.ySpeed >= 0) { // 3
hero.ySpeed *= hero.bounce;
hero.counter = 0;
hero.setY(platform.getY() - hero.getHeight());
}
});
// Detects collisions with coins
level.coins.getChildren().forEach(function(coin){
// Collisions with coins are straightforward:
// it they occur, score is rewarded and coin
// dissapears from stage.
if(that.detectCollision(coin, hero)) {
that.scoreManager.scoreCoin();
coin.remove();
}
});
// Detects collision with the exit door
// In order to advance to the next level,
// player MUST have collected the key.
if(that.detectCollision(level.door, hero) && level.key) {
throw new ExitLevelEvent();
}
}
detectCollision(a, b) {
var hit = false;
// Horizontal collisions
if(b.getX() + b.getWidth() >= a.getX() && b.getX() < a.getX() + a.getWidth()) {
// Vertical collisions
if(b.getY() + b.getHeight() >= a.getY() && b.getY() < a.getY() + a.getHeight()) {
hit = true;
}
}
// A gets inside B horizontally
if(b.getX() <= a.getX() && b.getX() + b.getWidth() >= a.getX() + a.getWidth()) {
// A is completely inside B
if(b.getY() <= a.getY() && b.getY() + b.getHeight() >= a.getY() + a.getHeight()) {
hit = true;
}
}
// B collides with A
if(a.getX() <= b.getX() && a.getX() + a.getWidth() >= b.getX() + b.getWidth()) {
if(a.getY() <= b.getY() && a.getY() + a.getHeight() >= b.getY() + b.getHeight()) {
hit = true;
}
}
return hit;
}
}
export default CollisionDetector;
|
version https://git-lfs.github.com/spec/v1
oid sha256:01d70387a0bf27d86a3b8d1aeefd71878327cc4827313de91b68e746a587783a
size 104603
|
import * as actionTypes from "./action-types";
import { fromJS } from "immutable"; // 将 JS 对象转换成 immutable 对象
import {
getBannerRequest,
getRecommendListRequest,
} from "../../../api/request";
export const changeBannerList = (data) => ({
type: actionTypes.CHANGE_BANNER,
data: fromJS(data),
});
export const changeRecommendList = (data) => ({
type: actionTypes.CHANGE_RECOMMEND_LIST,
data: fromJS(data),
});
export const changeEnterLoading = (data) => ({
type: actionTypes.CHANGE_ENTER_LOADING,
data,
});
export const getBannerList = () => {
return (dispatch) => {
getBannerRequest()
.then((data) => {
dispatch(changeBannerList(data.banners));
})
.catch(() => {
console.log("轮播图数据传输错误");
});
};
};
export const getRecommendList = () => {
return (dispatch) => {
getRecommendListRequest()
.then((data) => {
dispatch(changeRecommendList(data.result));
// 在获取推荐歌单后,应把 loading 状态改为 false
dispatch (changeEnterLoading (false));
})
.catch(() => {
console.log("推荐歌单数据传输错误");
});
};
};
|
var getNative = require('lodash/internal/getNative');
/** Native method references. */
var WeakMap = getNative(global, 'WeakMap');
/** Used to store function metadata. */
var metaMap = WeakMap && new WeakMap;
module.exports = metaMap;
|
/*
* lib/iterator.js
*
*/
var _ = require("lodash");
var fs = require("fs-extra");
var zlib = require("zlib");
var readline = require("readline");
var readChunk = require("read-chunk");
var fileType = require("file-type");
//==============================================================================
module.exports = function(fpath, handler, done) {
try {
var input = fs.createReadStream(fpath);
if (isGzip(fpath)) {
input = input.pipe(zlib.createGunzip());
}
var lineReader = readline.createInterface({ input: input });
} catch (e) {
//-- something went wrong!
return done(e);
}
//-- initialize
var lineNo = 0;
var processedLines = 0;
var doneReading = false;
var doneProcessing = false;
var paused = false;
var minDiff = 5;
var maxDiff = 10;
//-- trottling
function trottle() {
var diff = lineNo - processedLines;
if (paused) {
if (diff < minDiff) {
paused = false;
lineReader.resume();
}
} else {
if (diff > maxDiff) {
paused = true;
lineReader.pause();
}
}
}
//-- callback
function next() {
if (!doneProcessing && doneReading && processedLines >= lineNo) {
//-- done processing
doneProcessing = true;
done();
} else {
trottle();
}
}
//-- process line
lineReader.on("line", function(line) {
++lineNo;
handler(fpath, lineNo, _.trim(line), function(err) {
++processedLines;
next();
});
trottle();
});
//-- done reading file
lineReader.on("close", function() {
doneReading = true;
//-- this is important !!! :)
next();
});
};
//==============================================================================
function isGzip(fpath) {
var buffer = readChunk.sync(fpath, 0, 4100);
var ftype = fileType(buffer);
return (_.get(ftype, "mime") === "application/gzip");
}
//------------------------------------------------------------------------------
//==============================================================================
|
require('./lib/plato-repo-report')(
'your repo url here'
);
|
define([
"app/config"
], function (config) {
var obj = deepExtend({
baseUrl: './',
paths: {
app: './app',
nls: "./nls",
core: "./core",
service: "./core/loader/service",
controller: "./core/loader/controller",
directive: "./core/loader/directive",
//libs
text: "./lib/require/text",
i18n: "./lib/require/i18n",
angular: "./lib/angular/angular",
angularRoute: './lib/angular/angular-route',
angularSegment: './lib/angular/angular-route-segment',
angularView: './lib/angular/angular-view-segment',
angularMocks: './lib/angular/angular-mocks',
async: "./lib/async/async",
less: "./lib/require-less/less",
lessc: "./lib/require-less/lessc",
"less-builder": "./lib/require-less/less-builder",
normalize: "./lib/require-less/normalize",
jasmine: "./lib/jasmine-2.0.3/jasmine",
"jasmine-html": "./lib/jasmine-2.0.3/jasmine-html",
"jasmine-boot": "./lib/jasmine-2.0.3/boot"
},
shim: {
'angular': {
exports: 'angular'
},
'angularRoute': ['angular'],
'angularSegment': ['angular'],
'angularView': ['angular'],
'angularMocks':{
deps: ['angular'],
exports:'angular.mock'
},
'jasmine': {
exports: 'window.jasmineRequire'
},
'jasmine-html': {
deps: ['jasmine'],
exports: 'window.jasmineRequire'
},
'jasmine-boot': {
deps: ['jasmine', 'jasmine-html'],
exports: 'window.jasmineRequire'
}
},
less: {
env: "development"
}
}, config);
requirejs.config(obj);
return obj;
//we do not want load any frameworks with extend() function here (jquery, angular, ...). So we are providing
// some basic extend here, based on http://andrewdupont.net/2009/08/28/deep-extending-objects-in-javascript/
function deepExtend(destination, source) {
for (var property in source) {
if (source[property] && source[property].constructor &&
source[property].constructor === Object) {
destination[property] = destination[property] || {};
arguments.callee(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
};
});
|
'use strict'
var express = require('express')
var expect = require('chai').expect
var request = require('supertest')
var bodyParser = require('body-parser')
var routes = require('../route/poiRoute')
var MongoClient = require('mongodb').MongoClient
var Types = require('../Types')
var db
MongoClient.connect(process.env.DB_URL, function(err, conn) {
db = conn
})
var app = express()
.set('types', new Types())
.use(bodyParser.json())
.use(bodyParser.urlencoded({extended: true}))
.use(routes)
function cleanAllDB(item) {
db.dropDatabase()
}
function insertData(poi) {
db.collection('poi').insertOne(poi)
}
describe('API controller tests', function () {
beforeEach(function() {
cleanAllDB()
})
describe('POIs operations', function() {
describe('GET ALL', function() {
beforeEach(function() {
insertData({x: 1, y: 2, name: 'TestData'})
})
it('Should return 200 and get the all POIs on data base', function (done) {
setTimeout(function() {
request(app)
.get('/poi')
.expect(200)
.expect(function(req) {
expect(req.body.length).to.equal(1)
expect(req.body[0].x).to.equal(1)
expect(req.body[0].y).to.equal(2)
expect(req.body[0].name).to.equal('TestData')
})
.end(done)
}, 500);
})
})
describe('GET BY PROXIMITY', function() {
beforeEach(function() {
insertData({x: 15, y: 15, name: 'TestData1'})
insertData({x: 30, y: 30, name: 'TestData2'})
insertData({x: 40, y: 40, name: 'TestData3'})
})
it('Should return 200 with two POI on range', function (done) {
setTimeout(function() {
request(app)
.get('/poi/proximity?x=35&y=35&range=10')
.expect(function(req) {
expect(req.body.length).to.equal(2)
expect(req.body[0].x).to.equal(30)
expect(req.body[0].name).to.equal('TestData2')
expect(req.body[1].x).to.equal(40)
expect(req.body[1].name).to.equal('TestData3')
})
.expect(200)
.end(done)
}, 500);
})
it('Should return 200 with empty array', function (done) {
request(app)
.get('/poi/proximity?x=1&y=4&range=10')
.expect(function(req) {
expect(req.body.length).to.equal(0)
})
.expect(200)
.end(done)
})
it('Should return 500 error if no querystring was informed', function (done) {
request(app)
.get('/poi/proximity')
.expect(/Coodinates parameter not informed or invalid on queryString/)
.expect(500)
.end(done)
})
it('Should return 500 error if the querystring is invalid', function (done) {
request(app)
.get('/poi/proximity?x=abc&y=1')
.expect(/Coodinates parameter not informed or invalid on queryString/)
.expect(500)
.end(done)
})
})
describe('POST', function() {
it('Should return error 400 when call post opperation with invalid body', function (done) {
request(app)
.post('/poi')
.send({z: 1, w: 2})
.expect(/Data validation failed/)
.expect(400)
.end(done)
})
it('Should return error 400 when call post opperation with negative coordinates', function (done) {
request(app)
.post('/poi')
.send({x: -100, y: -2, name: 'invalid'})
.expect(/Data validation failed/)
.expect(400)
.end(done)
})
it('Should return error 400 when call post opperation with non integer coordinates', function (done) {
request(app)
.post('/poi')
.send({x: 10.3, y: 2, name: 'invalid'})
.expect(/Data validation failed/)
.expect(400)
.end(done)
})
it('Should return error 200 and insert on data base', function (done) {
setTimeout(function() {
request(app)
.post('/poi')
.send({x: 5, y: 5, name: 'test'})
.expect(function(req) {
expect(req.body.x).to.equal(5)
expect(req.body.y).to.equal(5)
expect(req.body.name).to.equal('test')
})
.expect(201)
.end(done)
}, 500);
})
})
})
})
|
var app = angular.module('JukeTubeApp', []);
// Run
app.run(function () {
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
});
// Config
app.config( function ($httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
// Service
app.service('VideosService', ['$window', '$rootScope', '$log', function ($window, $rootScope, $log) {
var service = this;
var youtube = {
ready: false,
player: null,
playerId: null,
videoId: null,
videoTitle: null,
playerHeight: '480',
playerWidth: '640',
state: 'stopped'
};
var results = [];
var upcoming = [
{id: 'G6KuhTsiLVI', title: 'Alicia Keys - In Common (Black Coffee Remix) (Audio)'},
{id: 'lfEVLXu3NXs', title: 'David Zowie - House Every Weekend'},
{id: 'QNsPI6V4Iec', title: 'Tough Love - So Freakin Tight'},
{id: 'KDxJlW6cxRk', title: 'Duke Dumont - Ocean Drive'}
];
var history = [
{id: 'NYhxaZXXwsg', title: 'Imany – Dont be so shy (Filatov & Karas Remix)'}
];
$window.onYouTubeIframeAPIReady = function () {
$log.info('Youtube API is ready');
youtube.ready = true;
service.bindPlayer('placeholder');
service.loadPlayer();
$rootScope.$apply();
};
function onYoutubeReady (event) {
$log.info('YouTube Player is ready');
youtube.player.cueVideoById(history[0].id);
youtube.videoId = history[0].id;
youtube.videoTitle = history[0].title;
}
function onYoutubeStateChange (event) {
if (event.data == YT.PlayerState.PLAYING) {
youtube.state = 'playing';
} else if (event.data == YT.PlayerState.PAUSED) {
youtube.state = 'paused';
} else if (event.data == YT.PlayerState.ENDED) {
youtube.state = 'ended';
service.launchPlayer(upcoming[0].id, upcoming[0].title);
service.archiveVideo(upcoming[0].id, upcoming[0].title);
service.deleteVideo(upcoming, upcoming[0].id);
}
$rootScope.$apply();
}
this.bindPlayer = function (elementId) {
$log.info('Binding to ' + elementId);
youtube.playerId = elementId;
};
this.createPlayer = function () {
$log.info('Creating a new Youtube player for DOM id ' + youtube.playerId + ' and video ' + youtube.videoId);
return new YT.Player(youtube.playerId, {
height: youtube.playerHeight,
width: youtube.playerWidth,
playerVars: {
rel: 0,
showinfo: 0
},
events: {
'onReady': onYoutubeReady,
'onStateChange': onYoutubeStateChange
}
});
};
this.loadPlayer = function () {
if (youtube.ready && youtube.playerId) {
if (youtube.player) {
youtube.player.destroy();
}
youtube.player = service.createPlayer();
}
};
this.launchPlayer = function (id, title) {
youtube.player.loadVideoById(id);
youtube.videoId = id;
youtube.videoTitle = title;
return youtube;
}
this.listResults = function (data) {
results.length = 0;
for (var i = data.items.length - 1; i >= 0; i--) {
results.push({
id: data.items[i].id.videoId,
title: data.items[i].snippet.title,
description: data.items[i].snippet.description,
thumbnail: data.items[i].snippet.thumbnails.default.url,
author: data.items[i].snippet.channelTitle
});
}
return results;
}
this.queueVideo = function (id, title) {
upcoming.push({
id: id,
title: title
});
return upcoming;
};
this.archiveVideo = function (id, title) {
history.unshift({
id: id,
title: title
});
return history;
};
this.deleteVideo = function (list, id) {
for (var i = list.length - 1; i >= 0; i--) {
if (list[i].id === id) {
list.splice(i, 1);
break;
}
}
};
this.getYoutube = function () {
return youtube;
};
this.getResults = function () {
return results;
};
this.getUpcoming = function () {
return upcoming;
};
this.getHistory = function () {
return history;
};
}]);
// Controller
app.controller('VideosController', function ($scope, $http, $log, VideosService) {
init();
function init() {
$scope.youtube = VideosService.getYoutube();
$scope.results = VideosService.getResults();
$scope.upcoming = VideosService.getUpcoming();
$scope.history = VideosService.getHistory();
$scope.playlist = true;
}
$scope.launch = function (id, title) {
VideosService.launchPlayer(id, title);
VideosService.archiveVideo(id, title);
VideosService.deleteVideo($scope.upcoming, id);
$log.info('Launched id:' + id + ' and title:' + title);
};
$scope.queue = function (id, title) {
VideosService.queueVideo(id, title);
VideosService.deleteVideo($scope.history, id);
$log.info('Queued id:' + id + ' and title:' + title);
};
$scope.delete = function (list, id) {
VideosService.deleteVideo(list, id);
};
$scope.search = function () {
$http.get('https://www.googleapis.com/youtube/v3/search', {
params: {
key: 'AIzaSyBNdACA8nV5eYsAzD-fms8Z5Ld7WNEq6Gk',
type: 'video',
maxResults: '8',
part: 'id,snippet',
fields: 'items/id,items/snippet/title,items/snippet/description,items/snippet/thumbnails/default,items/snippet/channelTitle',
q: this.query
}
})
.success( function (data) {
VideosService.listResults(data);
$log.info(data);
})
.error( function () {
$log.info('Search error');
});
}
$scope.tabulate = function (state) {
$scope.playlist = state;
}
});
|
/*******************************************************************************
NAME MILLER CYLINDRICAL
PURPOSE: Transforms input longitude and latitude to Easting and
Northing for the Miller Cylindrical projection. The
longitude and latitude must be in radians. The Easting
and Northing values will be returned in meters.
PROGRAMMER DATE
---------- ----
T. Mittan March, 1993
This function was adapted from the Lambert Azimuthal Equal Area projection
code (FORTRAN) in the General Cartographic Transformation Package software
which is available from the U.S. Geological Survey National Mapping Division.
ALGORITHM REFERENCES
1. "New Equal-Area Map Projections for Noncircular Regions", John P. Snyder,
The American Cartographer, Vol 15, No. 4, October 1988, pp. 341-355.
2. Snyder, John P., "Map Projections--A Working Manual", U.S. Geological
Survey Professional Paper 1395 (Supersedes USGS Bulletin 1532), United
State Government Printing Office, Washington D.C., 1987.
3. "Software Documentation for GCTP General Cartographic Transformation
Package", U.S. Geological Survey National Mapping Division, May 1982.
*******************************************************************************/
Proj4js.Proj.mill = {
/* Initialize the Miller Cylindrical projection
-------------------------------------------*/
init: function() {
//no-op
},
/* Miller Cylindrical forward equations--mapping lat,long to x,y
------------------------------------------------------------*/
forward: function(p) {
var lon=p.x;
var lat=p.y;
/* Forward equations
-----------------*/
dlon = Proj4js.common.adjust_lon(lon -this.long0);
var x = this.x0 +this.R * dlon;
var y = this.y0 + this.R *Math.log(Math.tan((Proj4js.common.PI / 4.0) + (lat / 2.5))) * 1.25;
p.x=x;
p.y=y;
return p;
},//millFwd()
/* Miller Cylindrical inverse equations--mapping x,y to lat/long
------------------------------------------------------------*/
inverse: function(p) {
p. x -= this.x0;
p. y -= this.y0;
var lon = Proj4js.common.adjust_lon(this.long0 + p.x /this.R);
var lat = 2.5 * (Math.atan(Math.exp(p.y/ this.R / 1.25)) - Proj4js.common.PI / 4.0);
p.x=lon;
p.y=lat;
return p;
}//millInv()
};
|
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['test/**/spec.js']
};
|
'use strict';
var React = require('react/addons'),
TestUtils = React.addons.TestUtils,
_ = require('lodash'),
WordCloud = require('../wordcloud.js'),
WordCloudTable = require('../wordcloudtable.js'),
propsBase = require('./fixtures/propsBase.js'),
topics = require('./fixtures/topics.json.js');
describe('WordCloudTable rendering', function (){
var props = propsBase,
wordCloud = TestUtils.renderIntoDocument(<WordCloud {...props} />),
wordCloudTable,
node;
it('loads without error', function (){
should.exist(wordCloud);
wordCloudTable = TestUtils.findRenderedComponentWithType(wordCloud, WordCloudTable);
should.exist(wordCloudTable);
});
it('renders div', function (){
node = React.findDOMNode(wordCloudTable);
node.tagName.toLowerCase().should.be.equal('div');
node.getAttribute('class').should.be.equal('word-cloud-table');
});
it('renders table', function (){
var table = node.firstChild;
table.tagName.toLowerCase().should.be.equal('table');
});
it('renders table body', function (){
var tbody = node.firstChild.firstChild;
tbody.tagName.toLowerCase().should.be.equal('tbody');
});
it('renders rows and table divs', function (){
var rows = node.firstChild.firstChild.childNodes;
should.exist(rows);
rows.length.should.be.equal(5);
_.map(rows, function (row){
row.tagName.toLowerCase().should.be.equal('tr');
should.exist(row.childNodes);
row.childNodes.length.should.be.equal(2);
row.childNodes[0].tagName.toLowerCase().should.be.equal('td');
row.childNodes[1].tagName.toLowerCase().should.be.equal('td');
});
});
});
|
'use strict';
module.exports = function(app) {
var getRouterFor = require('../fake-backend.js').getRouterFor;
var contactsRouter = getRouterFor('contact', 'contacts');
app.use('/api/contacts', contactsRouter);
};
|
var login = new Object();
jQuery.extend(login, {
init: function(formulario) {
login.peticion(formulario);
},
peticion: function(formulario) {
jQuery.ajax({
url : "{{ RUTA_APP|e }}/Index/Index/autenticacion",
async : false,
data : jQuery(formulario).serialize(),
dataType : "json",
type : "POST",
cache : false,
error : function(error_mensaje) {
swal("Error!", "Se ha presentado un error, validar con el administrador del sistema", "error");
},
success : function(resultado) {
login.success(resultado);
}
});
},
success : function(info) {
if(info.status == true) {
location.href = info.data;
}
else {
swal("Error!", info.data, "error");
}
}
});
|
/**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import Location from './lib/Location';
import Layout from './components/Layout';
import WordStore from './lib/WordStore'
const routes = {}; // Auto-generated on build. See tools/lib/routes-loader.js
const route = async (path, callback) => {
const handler = routes[path] || routes['/404'];
const component = await handler();
await callback(<Layout>{React.createElement(component)}</Layout>);
};
function run() {
const container = document.getElementById('app');
Location.listen(location => {
route(location.pathname, async (component) => ReactDOM.render(component, container, () => {
// Track the page view event via Google Analytics
window.ga('send', 'pageview');
}));
});
}
if (canUseDOM) {
// Run the application when both DOM is ready
// and page content is loaded
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', run);
} else {
window.attachEvent('onload', run);
}
}
export default { route, routes };
|
import expect from 'expect'
import _ from 'lodash';
describe('multi', function() {
it('add new multi method', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
expect(typeof area).toBe('function');
});
it('throw if no method and no default', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
expect(() => area({shape: 'circle'})).toThrow();
});
it('use default no matter what value is passed', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
area.defaultMethod(() => 42);
expect(area('stuff')).toBe(42);
expect(area({shape:'circle'})).toBe(42);
expect(area(undefined)).toBe(42);
expect(area(null)).toBe(42);
});
it('falls back to default', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
area.method('circle', () => 43);
area.defaultMethod(() => 42);
expect(area('stuff')).toBe(42);
expect(area({shape:'circle'})).toBe(43);
});
it('differentiates between methods', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
area.method('circle', () => 43);
area.method('square', () => 44);
area.defaultMethod(() => 42);
expect(area('stuff')).toBe(42);
expect(area({shape:'circle'})).toBe(43);
expect(area({shape:'square'})).toBe(44);
});
it('pass along the right variable', function() {
var multi = require('src/').default;
var area = multi(_.property('shape'));
area.method('circle', (s) => Math.PI * Math.pow(s.radius,2));
area.method('square', (s) => Math.pow(s.side, 2));
area.defaultMethod(() => 42);
expect(area('stuff')).toBe(42);
expect(area({shape:'circle', radius: 1})).toBe(Math.PI);
expect(area({shape:'square', side: 3})).toBe(9);
});
});
|
/**
* Internal helper functions for parsing DICOM elements
*/
var dicomParser = (function (dicomParser)
{
"use strict";
if(dicomParser === undefined)
{
dicomParser = {};
}
function readDicomDataSetImplicitUndefinedLength(byteStream)
{
var elements = {};
while(byteStream.position < byteStream.byteArray.length)
{
var element = dicomParser.readDicomElementImplicit(byteStream);
elements[element.tag] = element;
// we hit an item delimiter tag, return the current offset to mark
// the end of this sequence item
if(element.tag === 'xfffee00d')
{
return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
}
}
// eof encountered - log a warning and return what we have for the element
byteStream.warnings.push('eof encountered before finding sequence item delimiter in sequence item of undefined length');
return new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, elements);
}
function readSequenceItemImplicit(byteStream)
{
var item = dicomParser.readSequenceItem(byteStream);
if(item.length === 4294967295)
{
item.hadUndefinedLength = true;
item.dataSet = readDicomDataSetImplicitUndefinedLength(byteStream);
item.length = byteStream.position - item.dataOffset;
}
else
{
item.dataSet = new dicomParser.DataSet(byteStream.byteArrayParser, byteStream.byteArray, {});
dicomParser.parseDicomDataSetImplicit(item.dataSet, byteStream, byteStream.position + item.length);
}
return item;
}
function readSQElementUndefinedLengthImplicit(byteStream, element)
{
while(byteStream.position < byteStream.byteArray.length)
{
// end reading this sequence if the next tag is the sequence delimitation item
var nextTag = dicomParser.readTag(byteStream);
byteStream.seek(-4);
if (nextTag === 'xfffee0dd') {
// set the correct length
element.length = byteStream.position - element.dataOffset;
byteStream.seek(8);
return element;
}
var item = readSequenceItemImplicit(byteStream);
element.items.push(item);
}
element.length = byteStream.byteArray.length - element.dataOffset;
}
function readSQElementKnownLengthImplicit(byteStream, element)
{
var maxPosition = element.dataOffset + element.length;
while(byteStream.position < maxPosition)
{
var item = readSequenceItemImplicit(byteStream);
element.items.push(item);
}
}
/**
* Reads sequence items for an element in an implicit little endian byte stream
* @param byteStream the implicit little endian byte stream
* @param element the element to read the sequence items for
*/
dicomParser.readSequenceItemsImplicit = function(byteStream, element)
{
if(byteStream === undefined)
{
throw "dicomParser.readSequenceItemsImplicit: missing required parameter 'byteStream'";
}
if(element === undefined)
{
throw "dicomParser.readSequenceItemsImplicit: missing required parameter 'element'";
}
element.items = [];
if(element.length === 4294967295)
{
readSQElementUndefinedLengthImplicit(byteStream, element);
}
else
{
readSQElementKnownLengthImplicit(byteStream, element);
}
};
return dicomParser;
}(dicomParser));
|
import ScrollController from "properjs-scrollcontroller";
import * as core from "../../core";
import Controller from "properjs-controller";
/**
*
* @public
* @global
* @class AnimateController
* @param {Element} element The dom element to work with.
* @classdesc Handle scroll events for a DOMElement.
*
*/
class AnimateController {
constructor ( container, elements, delay ) {
this.container = container;
this.elements = elements;
this.delay = delay || 100;
}
noop () {
this.animate( this.elements );
}
/**
*
* @instance
* @description Initialize the animation frame
* @memberof AnimateController
* @method start
*
*/
start () {
this.scroller = new ScrollController();
this.scroller.on( "scroll", () => {
this.handle();
});
this.handle();
}
handle () {
this.elements = this.container.find( core.config.lazyAnimSelector ).not( "[data-animate='true']" );
if ( !this.elements.length ) {
this.scroller.stop();
this.scroller = null;
core.log( "[AnimateController] Done!" );
} else {
const visible = core.util.getElementsInView( this.elements );
if ( visible.length ) {
this.animate( visible );
}
}
}
animate ( elems ) {
elems.attr( "data-animate", "true" );
// Sequence the animation of the elements
const animator = new Controller();
let lastTime = Date.now();
let currElem = 0;
animator.go(() => {
const currTime = Date.now();
if ( currElem === elems.length ) {
animator.stop();
core.log( "[AnimateController] Animation Complete!" );
} else if ( (currTime - lastTime) >= this.delay ) {
lastTime = currTime;
elems[ currElem ].className += " is-animated";
currElem++;
}
});
}
/**
*
* @instance
* @description Stop the animation frame
* @memberof AnimateController
* @method destroy
*
*/
destroy () {
if ( this.scroller ) {
this.scroller.destroy();
this.scroller = null;
}
}
}
/******************************************************************************
* Export
*******************************************************************************/
export default AnimateController;
|
var Reflux = require('reflux');
var socket = require('../socket');
var channelActions = Reflux.createActions([
'join',
'part',
'invite',
'kick',
'addUser',
'removeUser',
'removeUserAll',
'renameUser',
'setUsers',
'setTopic',
'setMode',
'load'
]);
channelActions.join.preEmit = (channels, server) => {
socket.send('join', { server, channels });
};
channelActions.part.preEmit = (channels, server) => {
socket.send('part', { server, channels });
};
channelActions.invite.preEmit = (user, channel, server) => {
socket.send('invite', { server, channel, user });
};
channelActions.kick.preEmit = (user, channel, server) => {
socket.send('kick', { server, channel, user });
};
module.exports = channelActions;
|
'use strict';
angular.module('app.channels')
.directive('scrollToBottom', [
function() {
return {
restrict: "A",
link: function(scope, element, attrs) {
// We dont want to abuse on watch but here it is critical to determine if the parameter has changed.
scope.$watch(function() {
return element[0].scrollHeight;
}, function(newValue, oldValue) {
element[0].scrollTop = newValue;
});
}
};
}
]);
|
module.exports = (sequelize, DataTypes) => {
const Songs = sequelize.define('Songs', {
title: DataTypes.STRING,
artist: DataTypes.STRING,
genre: DataTypes.STRING,
album: DataTypes.STRING,
albumImage: DataTypes.STRING,
youtubId: DataTypes.STRING,
lyrics: DataTypes.STRING,
tab: DataTypes.STRING
})
return Songs
}
|
var express = require('express'),
app = express(),
router = express.Router(),
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
morest = require('../src/morest').Morest;
//Connect to your mongoDB database
mongoose.connect('mongodb://127.0.0.1:27017/bears');
//Use bodyparser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
var port = 8000;
//Load all the controllers
var BearController = require('./app/controllers/bear'),
HoneypotController = require('./app/controllers/honeypot'),
CaveController = require('./app/controllers/cave');
//Let Morest generate the routes for the /api endpoint
app.use('/api', morest(router, mongoose, {
controllers: [
BearController,
HoneypotController,
CaveController
]
}));
//Remove all old data
mongoose.model('Bear').remove()
.then(function () {
return mongoose.model('Honeypot').remove();
})
.then(function () {
return mongoose.model('Cave').remove();
})
//Prepare some new data to use
.then(function () {
return HoneypotController.prepData();
})
.then(function () {
return CaveController.prepData()
})
.then(function () {
return BearController.prepData()
})
.then(function () {
app.listen(port);
});
|
var mongodb = require('./mongodb');
var Schema = mongodb.Schema;
var ColumnMetaSchema = new Schema({
columnName : String,
order : Number,
locked : Boolean,
visible : Boolean
});
var ColumnMeta = mongodb.model("ColumnMeta", ColumnMetaSchema);
var ColumnMetaDAO = function(){};
//±£´æÐÅÏ¢
ColumnMetaDAO.prototype.save = function(obj, callback) {
var instance = new ColumnMeta(obj);
instance.save(function(err){
callback(err);
});
};
//»ñÈ¡ÁбíÐÅÏ¢
ColumnMetaDAO.prototype.getColumnMetaList = function(query, callback) {
ColumnMeta.find(query, '-_id -__v', {}, callback);
};
//»ñÈ¡µ¥ÌõÐÅÏ¢
ColumnMetaDAO.prototype.getColumnMeta = function(query, callback) {
ColumnMeta.findOne(query, '-_id -__v', {}, callback);
};
module.exports = new ColumnMetaDAO();
|
(function () {
var cache = {};
window.Storage = {
Set: function (key, value) {
//chrome.storage.sync.set({[key]: value});
chrome.storage.local.set({[key]: value});
},
SetLocal: function (key, value) {
chrome.storage.local.set({[key]: value});
},
GetSync: function (key, sendResponse) {
chrome.storage.sync.get(key, function (response) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
sendResponse(response);
}
});
},
Get: function (key, sendResponse) {
chrome.storage.local.get(key, function (response) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
if (Object.keys(response).length === 0 && response.constructor === Object) {
Storage.GetSync(key, sendResponse);
}
else {
sendResponse(response);
}
}
});
},
GetMultipleSync: function (key, sendResponse) {
chrome.storage.sync.get(key, function (response) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
for (var i = 0; i < key.length; i++) {
cache[key[i]] = response[key[i]];
Storage.Set(key[i], response[key[i]]);
}
sendResponse(response);
}
});
},
GetMultiple: function (key, sendResponse) {
chrome.storage.local.get(key, function (response) {
if (chrome.runtime.lastError) {
console.log(chrome.runtime.lastError);
} else {
for (var i = 0; i < key.length; i++) {
cache[key[i]] = response[key[i]];
}
if (Object.keys(response).length === 0 && response.constructor === Object) {
Storage.GetMultipleSync(key, sendResponse);
} else {
sendResponse(response);
}
}
});
}
}
})();
|
function save_options(){
var openInNewTab = document.getElementById('open-in-new-tab').checked;
chrome.storage.sync.set({
openInNewTab: openInNewTab
})
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
chrome.storage.sync.get({
openInNewTab: false
}, function(items) {
document.getElementById('open-in-new-tab').checked = items.openInNewTab;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click', function(){
save_options();
})
|
describe('Wheel.Utils.ObjectPath', function() {
describe('#write', function() {
it('builds the full path with object literals, if none are found in window', function() {
if (window.Foo) { window.Foo = undefined; }
Wheel.Utils.ObjectPath.write('Foo.Bar.Zardoz', 3);
expect(window.Foo).toEqual({Bar: {Zardoz: 3}});
});
it('does not overwrite existing objects', function() {
var func = function () {};
window.Bar = func;
Wheel.Utils.ObjectPath.write('Bar.Foo.Zardoz', 42);
expect(window.Bar).toBe(func);
expect(window.Bar.Foo).toEqual({Zardoz: 42});
});
it('works when the path is not an object path', function() {
Wheel.Utils.ObjectPath.write('Wazup', 42);
expect(window.Wazup).toBe(42);
});
it('return the full path', function() {
expect(Wheel.Utils.ObjectPath.write('Kiss.My.App', 13)).toBe(Kiss.My.App);
});
});
describe('#read', function() {
it('will get the value at a path', function() {
Wheel.Utils.ObjectPath.write('Kiss.My.App', 13);
expect(Wheel.Utils.ObjectPath.read('Kiss.My.App')).toBe(13);
});
it('will return null if the path does not exist', function() {
expect(Wheel.Utils.ObjectPath.read('Funk.The.Dunk')).toBe(null);
});
});
});
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2016
*/
/* eslint-disable max-len */
import LocalizedStrings from 'react-native-localization';
export const buttonStrings = new LocalizedStrings({
gb: {
add_batch: 'Add Batch',
add_master_list_items: 'Add Master List Items',
all_items_selected: 'All Items Selected',
create_automatic_order: 'Create Automatic Order',
current: 'Current',
done: 'Done',
hide_stockouts: 'Hide Stockouts',
manage_stocktake: 'Manage Stocktake',
new_invoice: 'New Invoice',
new_item: 'New Item',
new_line: 'New Line',
new_requisition: 'New Requisition',
new_stocktake: 'New Stocktake',
new_supplier_invoice: 'New Supplier Invoice',
past: 'Past',
use_suggested_quantities: 'Use Suggested Quantities',
use_requested_quantities: 'Use Requested Quantities',
},
fr: {
add_batch: 'Ajouter un lot',
add_master_list_items: "Ajouter une liste-Maître d'articles ?",
all_items_selected: 'Tout les articles sélectionnés',
create_automatic_order: 'Créer une commande automatiquement',
current: 'Actuel',
done: 'Terminé',
hide_stockouts: 'Cacher les ruptures de stocks',
manage_stocktake: "Gérer l'inventaire",
new_invoice: 'Nouvelle facture',
new_item: 'Nouvel Article',
new_line: 'Nouvelle ligne',
new_requisition: 'Nouvelle réquisition',
new_stocktake: 'Nouvel inventaire',
new_supplier_invoice: 'Nouvelle facture fournisseur',
past: 'Archives',
use_suggested_quantities: 'Utiliser les quantités suggérées',
use_requested_quantities: 'Utiliser les quantités demandées',
},
gil: { // TODO: add_batch
add_master_list_items: 'Rinea am list',
all_items_selected: 'Aikai nikabane',
create_automatic_order: 'Create Automatic Order',
current: 'Ai tibwa ngkai',
done: 'E a tia',
hide_stockouts: 'Tai kaoti ake a bane',
manage_stocktake: 'Manage Stocktake',
new_invoice: 'Am karao-oota\nae boou',
new_item: 'Karina am bwai\nn aoraki ae boou',
new_line: 'Te bwain aoraki\nae kainnanoaki',
new_requisition: 'Am oota\nae karina',
new_stocktake: 'Warebwai ae boou',
new_supplier_invoice: 'Bebwan am oota\nman pharmacy',
past: 'Are I mwaina',
use_requested_quantities: 'Kabongana maitina\nae kainnanoaki',
use_suggested_quantities: 'Kabongana te\nmwaiti are e katauaki',
},
tl: { // TODO: add_batch
add_master_list_items: 'Utiliza Lista Master',
all_items_selected: 'Hili Item Hotu',
create_automatic_order: 'Kria Orden Automátiku',
current: 'Atuál',
done: 'Hotu',
hide_stockouts: 'Hili item ho Qtd ejiste',
manage_stocktake: 'Maneja Ajustamentu',
new_invoice: 'Invoice Foun',
new_item: 'Item Foun',
new_line: 'Linha Foun',
new_requisition: 'Rekuizisaun Foun',
new_stocktake: 'Ajustamentu Foun',
new_supplier_invoice: 'Distribuidor nia Invoice Foun',
past: 'Pasadu',
use_suggested_quantities: 'Kuantidade Sujere',
use_requested_quantities: 'Kuantidade Ezije',
},
la: {
add_batch: 'ໃສ່ເລກຊຸດຜະລິດ',
add_master_list_items: 'ເພີ່ມລາຍການສິນຄ້າທັງໝົດທີ່ມີຢູ່',
all_items_selected: 'ລາຍການທັງໝົດຖືກເລືອກແລ້ວ',
create_automatic_order: 'ຄຳສັງແບບອັດຕະໂນມັດ',
current: 'ປັດຈຸບັນ',
done: 'ສໍາເລັດແລ້ວ',
hide_stockouts: 'ເຊື່ອງ ການຂາດສິນຄ້າໃສສາງ',
manage_stocktake: 'ເຮັດການຈັດການ ກວດກາສິນຄ້າໃນສາງ',
new_invoice: 'ເຮັດໃບເກັບເງິນໃໝ່',
new_item: 'ເຮັດລາຍການສິນຄ້າມາໃໝ່',
new_line: 'ເພີ່ມລາຍການໃໝ່',
new_requisition: 'ເຮັດການສະເໜີຂໍໃຫມ່',
new_stocktake: 'ເຮັດການກວດສາສາງໃໝ່',
new_supplier_invoice: 'ໃບຮັບສິນຄ້າໃໝ່',
past: 'ໃນທີ່ຜ່ານມາ',
use_suggested_quantities: 'ນຳໃຊ້ຈຳນວນທີ່ຖືກແນະນຳ',
use_requested_quantities: 'ນຳໃຊ້ຈຳນວນທີ່ສະເໜີຂໍ',
},
});
|
import React, { Component, PropTypes } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as ViewActions from '../actions';
import Marker from '../components/Marker';
import Card from '../components/Card';
import SelectedWrapper from '../containers/SelectedWrapper';
import PictureWithFrame from '../components/PictureWithFrame';
import { MAINPAGE_STYLE, MAINPAGE_WRAPPER_STYLE } from '../constants/styles/Mainpage-Styles';
import { CARD_STYLE } from '../constants/styles/Card-Styles';
import { MARKER_STYLES } from '../constants/styles/Marker-Styles';
import Radium, { StyleRoot } from 'radium';
import { iconMappings } from '../constants/iconMappings';
import { fetchData } from '../actions/index';
import { getData } from '../data/dataFetcher';
@Radium
class MainpageContainer extends Component {
static fetchData() {
return getData('cards');
}
_renderCards() {
const selectedCardId = this._extractSelectedCard(this.props.views.items);
if (this._extractCardIds(this.props.views.items).indexOf(selectedCardId) > -1) {
return (<SelectedWrapper
actions={this.props.actions}
selectedTab={this.props.tab}
component={this.props.views.items[selectedCardId - 1]} />);
}
else {
return (<PictureWithFrame />);
}
}
_renderMarkers() {
return (this.props.views.items.map(item => <Marker key={item.id} markerId={item.id}
actions={this.props.actions}
selected={item.selected}
style={MARKER_STYLES[item.id]}
hoverIcon={this._generateHoverIcon(item.icon)} />));
}
_generateHoverIcon(iconKey) {
return iconMappings[iconKey];
}
_extractSelectedCard(cards) {
const selectedCard = cards.find(card => {
return card.selected === true;
});
return selectedCard ? selectedCard.id : 0;
}
_extractCardIds(cards) {
return cards.map(card => {
return card.id;
});
}
render() {
const markers = this._renderMarkers();
const cards = this._renderCards();
return (<StyleRoot><div style={MAINPAGE_STYLE}>
<div style={MAINPAGE_WRAPPER_STYLE}>
{markers}
{cards}
</div>
</div>
</StyleRoot>
);
}
}
MainpageContainer
.propTypes = {
views: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired
}
function
mapStateToProps(state) {
return {
views: state.views,
tab: state.tab.selectedTab
}
}
function
mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(ViewActions, dispatch)
}
}
export default connect(mapStateToProps,
mapDispatchToProps)(MainpageContainer)
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
errorHandler = require('./errors.server.controller'),
Project = mongoose.model('Project'),
Task = mongoose.model('Task'),
User = mongoose.model('User'),
_ = require('lodash');
/**
* Create a Project
*/
exports.createProject = function(req, res) {
var project = new Project(req.body);
project.user = req.user;
User.findById(req.user._id).exec(function(err, userTimeline){
project.timeline = userTimeline.timeline;
project.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(project);
}
});
});
};
/**
* Show the current Project
*/
exports.readProject = function(req, res) {
res.jsonp(req.project);
};
/**
* Update a Project
*/
exports.updateProject = function(req, res) {
var project = req.project;
project = _.extend(project, req.body);
project.save(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
Task.findOne({projectId: project._id}).exec(function(err, task){
if(task){
task.projectName = project.name;
task.save();
}
});
res.jsonp(project);
}
});
};
/**
* Delete an Project
*/
exports.deleteProject = function(req, res) {
var project = req.project;
if(project.user._id !== req.user._id)
return res.status(403).send('User is not authorized');
project.remove(function(err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(project);
}
});
};
/**
* List of Projects
*/
exports.listProjects = function(req, res) {
Project.find({'timeline':req.user.timeline}).where(req.query).sort('-created').populate('user', 'username').populate('tasks', 'projectName personName group cohort startDate endDate').exec(function(err, projects) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.jsonp(projects);
}
});
};
/**
* Project middleware
*/
exports.projectByID = function(req, res, next, id) {
Project.findById(id).populate('user', 'displayName').exec(function(err, project) {
if (err) return next(err);
if (!project) return next(new Error('Failed to load Project ' + id));
req.project = project;
next();
});
};
/**
* Project authorization middleware
*/
exports.hasAuthorization = function(req, res, next) {
if (req.project.timeline._id !== req.user.timeline._id) {
return res.status(403).send('User is not authorized');
}
next();
};
|
'use strict';
/**
* An Animation.
* @param frameRate {Number} The ideal number of frame changes per second for this animation.
* @constructor
*/
var Animation = function (frameRate) {
this.frameDeltaSum = 0;
this.targetFrameDelta = 1000 / (frameRate || 20);
this.frame = 0;
this.frames = [];
};
/**
* Manually add a draw function for a single frame.
* @param draw {Function} A draw function.
* @returns {Object} The Animation.
*/
Animation.prototype.addFrame = function (draw) {
if ('function' === typeof(draw)) {
this.frames.push(draw);
}
return this;
};
/**
* Add an image to an animation.
* @param image {String} The image key from the the ResourceLoader.
* @param width (optional) {Number} The width of each cell in a multi-cell image.
* @param height (optional) {Number} The height of each cell in a multi-cell image.
* @param rows (optional) {Number} The number of rows in a multi-cell image.
* @param columns (optional) {Number} The number of columns in a multi-cell image.
* @param x {Number} (optional) The x offset of the first cell in a multi-cell image.
* @param y {Number} (optional) The x offset of the first cell in a multi-cell image.
* @returns {Object} The Animation.
*/
Animation.prototype.addFrames = function (image, width, height, rows, columns, x, y) {
if (!image) {
throw new Error('Animation.addFrames requires an image argument.');
}
width = width || image.naturalWidth || 0;
height = height || image.naturalHeight || 0;
rows = rows || 1;
columns = columns || 1;
x = x || 0;
y = y || 0;
function getDrawFn(image, x, y, width, height) {
return function (context) {
context.drawImage(image, x, y, width, height, 0, 0, width, height);
}
}
for (var row = 0; row < rows; row++) {
for (var col = 0; col < columns; col++) {
var fn = getDrawFn(image, (col * width) + x, (row * height) + y, width, height);
this.addFrame(fn);
}
}
return this;
};
Animation.prototype.update = function (game) {
if (this.frameDeltaSum < this.targetFrameDelta) {
this.frameDeltaSum += game.frameDelta;
return;
}
this.frameDeltaSum = 0;
if (this.frame === this.frames.length - 1) {
this.frame = -1;
}
this.frame += 1;
};
Animation.prototype.draw = function () {
this.frames[this.frame].apply(this, arguments);
};
Animation.prototype.reset = function () {
this.frame = 0;
};
module.exports = Animation;
|
import Ember from 'ember';
export default Ember.Controller.extend({
actions: {
/**
Hide Sidebar by clicking submenu item.
@method actions.subMenuEl
*/
hideSidebar() {
Ember.$('.ui.sidebar').sidebar('hide');
},
/**
Expand menu items by click.
@method actions.subMenuEl
*/
subMenuEl(event) {
let $this = Ember.$(event.currentTarget).parent().find('.subMenu:first');
if ($this.hasClass('hidden')) {
$this.removeClass('hidden');
Ember.$(event.target).parent().find('.item-minus:first').removeClass('hidden');
Ember.$(event.target).parent().find('.item-plus:first').addClass('hidden');
} else {
$this.addClass('hidden');
Ember.$(event.target).parent().find('.item-minus:first').addClass('hidden');
Ember.$(event.target).parent().find('.item-plus:first').removeClass('hidden');
}
}
}
});
|
(function () {
'use strict';
angular
.module('app.layout')
.controller('Header', Header);
function Header($scope, authenticatedUser, $state, $timeout, $mdDialog, usersApi) {
$scope.logout = function () {
authenticatedUser.logout();
$timeout(function () {
$state.go('login');
}, 2000);
};
}
})();
|
import axios from 'axios';
import {
FETCH_USER,
FETCH_ITEMS,
FETCH_BACKPACK,
ADD_ITEM_TO_BACKPACK,
DEL_ITEM_FROM_BACKPACK,
REMOVE_ITEM_FROM_BACKPACK,
RECALCULATE_TOTAL_PRICE,
DISCARD_BACKPACK,
SAVE_BACKPACK,
CHECKOUT_BACKPACK,
BACKPACK_IS_LOADING,
BACKPACK_HAS_ERRORED,
FETCH_BACKPACK_SUCCESS
} from './types';
export const fetchItems = () => async dispatch => {
//console.log('_action_fetchItems_Getting Items');
//const res = await axios.get('/api/items');
//console.log('_action_fetchItems_Got Items', res.data);
//dispatch({ type: FETCH_ITEMS, payload: res.data });
//console.log('_action_fetchItems_state', getState());
dispatch(BackpackIsLoading(true));
const res = await axios.get('/api/items');
dispatch(BackpackIsLoading(false));
if (!res.data) {
dispatch(BackpackHasErrored(true));
}
//console.log('_action_fetchItems_Got items ', res.data);
dispatch(FetchBackpackSuccess(res.data));
};
export const fetchUser = () => async dispatch => {
//console.log('_action_fetchUser_Getting user');
const res = await axios.get('/api/current_user');
//console.log('_action_fetchUser_Got user', res.data);
dispatch({ type: FETCH_USER, payload: res.data });
};
export const fetchBackpack = () => async (dispatch, getState) => {
//console.log('_action_fetchBackpack_state', getState());
const state = getState();
const id = state.user._id;
dispatch(IsLoading(true));
const res = await axios.get(`/api/backpacks/user/${id}`);
dispatch(IsLoading(false));
if (!res.data.backpack) {
dispatch(HasErrored(true));
}
//console.log('_action_fetchBackpack_Got user backpack', res.data.backpack);
dispatch(FetchDataSuccess(res.data.backpack));
//dispatch({ type: FETCH_BACKPACK, payload: res.data.backpack });
};
// };
export const addItemToBackpack = id => dispatch => {
//console.log('_action_addItemToBackpack ', id);
dispatch({ type: ADD_ITEM_TO_BACKPACK, payload: id });
};
export const delItemFromBackpack = id => dispatch => {
//console.log('_action_delItemFromBackpack ', id);
dispatch({ type: DEL_ITEM_FROM_BACKPACK, payload: id });
};
export const removeItemFromBackpack = id => dispatch => {
//console.log('_action_removeItemFromBackpack ', id);
dispatch({ type: REMOVE_ITEM_FROM_BACKPACK, payload: id });
};
export const recalcutateTotalPrice = () => (dispatch, getState) => {
//console.log('_action_recalculateTotalPrice');
const state = getState();
const items = state.items;
dispatch({
type: RECALCULATE_TOTAL_PRICE,
items: items
});
};
export const discardBackpack = id => async dispatch => {
//console.log('_action_discardBackpack');
const res = await axios.get(`/api/backpacks/${id}/del`);
dispatch({ type: DISCARD_BACKPACK, payload: res });
};
export const saveBackpack = backpack => async dispatch => {
//console.log('_action_saveBackpack');
const res = await axios.post(
`/api/backpacks/${backpack._id}/update`,
backpack
);
dispatch({ type: SAVE_BACKPACK, payload: res });
};
export const checkoutBackpack = id => dispatch => {
//console.log('_action_checkoutBackpack');
const res = 'checked out';
dispatch({ type: CHECKOUT_BACKPACK, payload: res });
};
export function BackpackHasErrored(bool) {
return {
type: HAS_ERRORED,
hasErrored: bool
};
}
export function BackpackIsLoading(bool) {
return {
type: IS_LOADING,
isLoading: bool
};
}
export function FetchBackpackSuccess(backpack) {
return {
type: FETCH_BACKPACK_SUCCESS,
backpack
};
}
export function ItemsHasErrored(bool) {
return {
type: HAS_ERRORED,
hasErrored: bool
};
}
export function ItemsIsLoading(bool) {
return {
type: IS_LOADING,
isLoading: bool
};
}
export function FetchItemsSuccess(items) {
return {
type: FETCH_ITEMS_SUCCESS,
items
};
}
|
/**
* array-some
* Array#some ponyfill for older browsers
* (Ponyfill: A polyfill that doesn't overwrite the native method)
*
* https://github.com/twada/array-some
*
* Copyright (c) 2015-2016 Takuto Wada
* Licensed under the MIT license.
* https://github.com/twada/array-some/blob/master/MIT-LICENSE
*/
'use strict';
module.exports = function some (ary, callback, thisArg) {
if (ary.some) {
return ary.some(callback, thisArg);
}
for (var i = 0; i < ary.length; i+=1) {
if (callback.call(thisArg, ary[i], i, ary)) {
return true;
}
}
return false;
};
|
// DOM Manipulation Challenge
// I worked on this challenge with: Austin Dorff.
// Add your JavaScript calls to this page:
// Release 0:
// Set up
// Release 1:
var div_r_1 = document.getElementById("release-0");
div_r_1.className = "done";
// Release 2:
var div_r_2 = document.getElementById('release-1');
div_r_2.style.display = "none";
// Release 3:
var div_r_3 = document.getElementsByTagName('h1')[0];
div_r_3.innerHTML = "I completed release 2.";
// Release 4:
var div_r_4 = document.getElementById('release-3');
div_r_4.style.backgroundColor = "#955251";
// Release 5:
var div_r_5 = document.getElementsByClassName("release-4");
for (var i = 0; i < div_r_5.length; i++) {
div_r_5[i].style.fontSize = "2em";
}
// Release 6:
var template = document.getElementById('hidden');
document.body.appendChild(template.content.cloneNode(true));
|
$(document).ready(function() {
$("#calculator-body").draggable();
var total = "";
var currentNumber = "";
var operator;
var operatorChosen = false;
var decimalAlready = false;
$("#ac").on("click", function() {
total = "";
currentNumber = "";
operatorChosen = false;
operator = "";
$("#output").text(0);
});
$("#ce").on("click", function() {
currentNumber = "";
operatorChosen = false;
$("#output").text(0);
});
function resetOperator() {
if (operatorChosen) {
currentNumber = "";
}
};
$("#percent").on("click", function() {
resetOperator();
operator = "%";
operatorChosen = true;
$("#output").text("%");
});
$("#add").on("click", function() {
resetOperator();
operator = "+";
operatorChosen = true;
$("#output").text("+");
});
$("#subtract").on("click", function() {
resetOperator();
operator = "-";
operatorChosen = true;
$("#output").text("-");
});
$("#divide").on("click", function() {
resetOperator();
operator = "/";
operatorChosen = true;
$("#output").text("/");
});
$("#multiply").on("click", function() {
resetOperator();
operator = "*";
operatorChosen = true;
$("#output").text("*");
});
$("#decimal").on("click", function() {
if (operatorChosen && !decimalAlready) {
currentNumber += ".";
$("#output").text(currentNumber);
} else if (!decimalAlready) {
total += ".";
$("#output").text(total);
}
decimalAlready = true;
});
$("#equals").on("click", function() {
var truncatedTotal;
total = eval(total + operator + currentNumber);
var totalDigits = total.toString().length;
if (totalDigits > 12) {
truncatedTotal = total.toString().slice(0, 12);
} else {
truncatedTotal = total;
}
decimalAlready = false;
$("#output").text(truncatedTotal);
});
for (var i = 0; i < 10; i++) {
$("#" + i).on("click", function() {
if (total === "" && !operator) {
total = this.id;
$("#output").text(total);
} else if (total !== "" && !operator) {
total += this.id;
$("#output").text(total);
} else if (operator) {
currentNumber += this.id;
$("#output").text(currentNumber);
}
});
}
});
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2z" />
, 'LensSharp');
|
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
'use strict';
var assert = require('chai').assert;
var Client = require('./client.js');
var ConnectionString = require('azure-iot-common').ConnectionString;
var Message = require('azure-iot-common').Message;
var Amqp = require('./amqp.js');
var AmqpWS = require('./amqp_ws.js');
var host = ConnectionString.parse(process.env.IOTHUB_CONNECTION_STRING).HostName;
var deviceId = process.env.IOTHUB_DEVICE_ID;
var key = process.env.IOTHUB_DEVICE_KEY;
var connectionString = 'HostName=' + host + ';DeviceId=' + deviceId + ';SharedAccessKey=' + key;
var badConnStrings = [
'HostName=bad;DeviceId=' + deviceId + ';SharedAccessKey=' + key,
'HostName=' + host + ';DeviceId=bad;SharedAccessKey=' + key,
'HostName=' + host + ';DeviceId=' + deviceId + ';SharedAccessKey=bad;'
];
function badConfigTests(opName, badConnStrings, Transport, requestFn) {
function makeRequestWith(connectionString, test, done) {
var client = Client.fromConnectionString(connectionString, Transport);
requestFn(client, function (err, res) {
test(err, res);
done();
});
}
function expectNotFoundError(err) {
assert.include(err.message, 'getaddrinfo ENOTFOUND bad');
}
function expectTimeout(err) {
assert.isNotNull(err);
assert.include(err.message, "ETIMEDOUT");
}
var tests = [
{ name: 'hostname is malformed', expect: expectNotFoundError },
{ name: 'device is not registered', expect: expectTimeout },
{ name: 'password is wrong', expect: expectTimeout }
];
/*Tests_SRS_NODE_DEVICE_CLIENT_05_016: [When a Client method encounters an error in the transport, the callback function (indicated by the done argument) shall be invoked with the following arguments:
err - the standard JavaScript Error object, with a response property that points to a transport-specific response object, and a responseBody property that contains the body of the transport response.]*/
badConnStrings.forEach(function (test, index) {
it.skip('fails to ' + opName + ' when the ' + tests[index].name, function (done) {
this.timeout(30000);
makeRequestWith(test, tests[index].expect, done);
});
});
}
function runAmqpTests(Transport, goodConnectionString, badConnectionStrings) {
describe('Client', function () {
describe('#sendEvent', function () {
/*Tests_SRS_NODE_DEVICE_CLIENT_05_007: [The sendEvent method shall send the event indicated by the message argument via the transport associated with the Client instance.]*/
/*Tests_SRS_NODE_DEVICE_CLIENT_05_017: [With the exception of receive, when a Client method completes successfully, the callback function (indicated by the done argument) shall be invoked with the following arguments:
err - null
response - a transport-specific response object]*/
/*Tests_SRS_NODE_DEVICE_AMQP_16_002: [The sendEvent method shall construct an AMQP request using the message passed in argument as the body of the message.] */
/*Tests_SRS_NODE_DEVICE_AMQP_16_003: [The sendEvent method shall call the done() callback with no arguments when the message has been successfully sent.] */
/*Tests_SRS_NODE_DEVICE_AMQP_16_004: [If sendEvent encounters an error before it can send the request, it shall invoke the done callback function and pass the standard JavaScript Error object with a text description of the error (err.message). ] */
it('sends the event', function (done) {
this.timeout(15000);
var client = Client.fromConnectionString(goodConnectionString, Transport);
var message = new Message('hello');
client.sendEvent(message, function (err, res) {
assert.isNull(err);
assert.isNotNull(res);
done();
});
});
badConfigTests('send an event', badConnectionStrings, Transport, function (client, done) {
client.sendEvent(new Message(''), done);
});
});
/*Tests_SRS_NODE_DEVICE_AMQP_16_006: [If a receiver for this endpoint has already been created, the getReceiver method should call the done() method with the existing instance as an argument.]*/
/*Tests_SRS_NODE_DEVICE_AMQP_16_007: [If a receiver for this endpoint doesn’t exist, the getReceiver method should create a new AmqpReceiver object and then call the done() method with the object that was just created as an argument.]*/
describe('#getReceiver', function() {
it('returns the same receiver instance if called multiple times', function(done) {
this.timeout(15000);
var client = Client.fromConnectionString(goodConnectionString, Transport);
client.getReceiver(function(err1, receiver1) {
client.getReceiver(function(err2, receiver2) {
assert.isNotNull(receiver1);
assert.isNotNull(receiver2);
assert.equal(receiver1, receiver2);
done();
});
});
});
});
});
}
function makeConnectionString(host, device, key) {
return 'HostName='+host+';DeviceId='+device+';SharedAccessKey='+key;
}
var badConnStrings = [
makeConnectionString('bad', 'device', 'key'),
makeConnectionString('host', 'bad', 'key'),
makeConnectionString('host', 'device', 'bad')
];
describe('Over AMQPS', function () {
runAmqpTests(Amqp, connectionString, badConnStrings);
});
describe('Over AMQP/WS', function () {
runAmqpTests(AmqpWS, connectionString, badConnStrings);
});
module.exports = runAmqpTests;
|
/*
* Author: Eddy Huang
* Date: 2015-07-29
* File: api
*/
|
var toEncoding = require("./toEncoding")
module.exports = toValueEncoding
function toValueEncoding(data, options) {
return toEncoding(data && data.value
, options.valueEncoding || options.encoding)
}
|
import React from 'react';
import PropTypes from 'prop-types';
import { Provider } from 'react-redux';
import IntlProvider from './IntlProvider';
function Provide({ store, children }) {
return (
<Provider store={store}>
<IntlProvider>{children}</IntlProvider>
</Provider>
);
}
Provide.propTypes = {
store: PropTypes.shape({
subscribe: PropTypes.func.isRequired,
dispatch: PropTypes.func.isRequired,
getState: PropTypes.func.isRequired,
}).isRequired,
children: PropTypes.element.isRequired,
};
export default Provide;
|
/**
* CustomEmailSettings Schema
*/
Core.Schemas.CustomEmailSettings = new SimpleSchema({
username: {
type: String,
optional: true
},
password: {
type: String,
optional: true
},
host: {
type: String,
optional: true
},
port: {
type: Number,
allowedValues: [25, 587, 465, 475, 2525],
optional: true
}
});
/**
* Metafield Schema
*/
Core.Schemas.Metafield = new SimpleSchema({
_id: {
type: String,
autoValue: Core.schemaIdAutoValue,
optional: true
},
key: {
type: String,
max: 30,
optional: true
},
namespace: {
type: String,
max: 20,
optional: true
},
scope: {
type: String,
optional: true
},
value: {
type: String,
optional: true
},
valueType: {
type: String,
optional: true
},
description: {
type: String,
optional: true
}
});
/**
* Locale Schema
*/
Core.Schemas.Locale = new SimpleSchema({
continents: {
type: Object,
blackbox: true
},
countries: {
type: Object,
blackbox: true
}
});
/**
* Tenants Schema
*/
Core.Schemas.Tenant = new SimpleSchema({
"_id": {
type: String,
optional: true
},
"status": {
type: String,
defaultValue: "active",
optional: true
},
"name": {
type: String,
index: 1,
unique: true
},
"description": {
type: String,
optional: true
},
"keywords": {
type: String,
optional: true
},
"addressBook": {
type: Array,
optional: true
},
"addressBook.$": {
type: Object,
optional: true
},
"addressBook.$.address1": {
type: String,
optional: true
},
"industry": {
type: String,
optional: true
},
"domains": {
type: [String],
unique: true,
index: 1,
optional: true
//autoValue: function(){return [this.field('name')]}
},
"emails": {
type: [Core.Schemas.Email],
optional: true
},
"country": {
type: String
},
"baseCurrency": {
label: "Base Currency",
optional: true,
type: Object,
autoValue: function () {
if (this.isInsert && Meteor.isServer) {
let country = this.field('country');
if (!this.isSet && country.isSet) {
let locales = EJSON.parse(Assets.getText("settings/locales.json"));
let currency = {};
if (locales.countries[country.value]) {
currency.iso = locales.countries[country.value].currency;
let currencies = EJSON.parse(Assets.getText("settings/currencies.json"));
currency.symbol = currencies[currency.iso] ? currencies[currency.iso].symbol : '';
return currency;
}
}
}
}
},
"baseCurrency.iso": {
type: String,
optional: true
},
"baseCurrency.symbol": {
type: String,
optional: true
},
"currencies": {
type: [String],
optional: true
},
"locale": {
type: String,
defaultValue: "en",
optional: true
},
"public": {
type: String,
optional: true
},
"timezone": {
type: String,
optional: true
},
"baseUOM": {
type: String,
optional: true,
defaultValue: "OZ",
label: "Base Unit of Measure"
},
"metafields": {
type: [Core.Schemas.Metafield],
optional: true
},
"defaultRoles": {
type: [String],
defaultValue: ["business/manage", "employee/view"],
optional: true
},
"layout": {
type: [Object],
optional: true
},
"layout.$.layout": {
type: String,
defaultValue: "ApplicationLayout",
optional: true
},
"layout.$.theme": {
type: String,
defaultValue: "default",
optional: true
},
"layout.$.workflow": {
type: String,
optional: true
},
"layout.$.collection": {
type: String,
optional: true
},
"layout.$.enabled": {
type: Boolean,
defaultValue: true,
optional: true
},
"settings": {
type: Object,
optional: true
},
"settings.rounding": {
type: Object,
optional: true,
blackbox: true
},
"adminEmail": {
type: String,
regEx: SimpleSchema.RegEx.Email,
optional: true
},
"createdAt": {
type: Date,
autoValue: function () {
if (this.isInsert) {
return new Date;
} else if (this.isUpsert) {
return {
$setOnInsert: new Date
};
}
},
denyUpdate: true,
optional: true
},
"updatedAt": {
type: Date,
autoValue: function () {
if (this.isUpdate) {
return new Date;
}
},
optional: true
}
});
|
'use strict';
const url = require('url');
const _ = {
map: require('lodash/map'),
trimStart: require('lodash/trimStart'),
sortBy: require('lodash/sortBy'),
isString: require('lodash/isString'),
forEach: require('lodash/forEach'),
remove: require('lodash/remove'),
has: require('lodash/has'),
groupBy: require('lodash/groupBy'),
split: require('lodash/split'),
findIndex: require('lodash/findIndex'),
join: require('lodash/join')
};
exports.treefy = treefy;
exports.domain = domain;
exports.treefyByPathname = treefyByPathname;
exports.linkDirectories = linkDirectories;
function treefy(urls){
let domains = exports.domain(urls);
return _.map(domains, function(domain){
return exports.treefyByPathname(domain);
});
};
function domain(links){
links = _.map(links, parse);
let domains = _.groupBy(links, function(link){
return _.trimStart(link.hostname, 'www.');
});
domains = _.sortBy(domains, function(node){
return -node.length;
});
return domains;
};
function parse(link){
if(_.isString(link)){
return url.parse(link);
}
return url.parse(link.url);
};
function treefyByPathname(urls){
let host = urls[0].host;
let tree = {
branch: []
};
_.forEach(urls, function(urlObj){
let pathparts = _.split(urlObj.pathname, '/');
_.remove(pathparts, function(name) {
return name === '';
});
pathparts.unshift(host);
let node = tree;
_.forEach(pathparts, function(name){
node = expandTree(node, name);
});
});
return tree.branch[0];
};
function expandTree(node, name){
if(_.has(node, 'branch') === false){
node.branch = [];
}
let index = _.findIndex(node.branch, function(o) { return o.name === name; });
if(index === -1){
index = node.branch.push({
name: name,
count: 0
}) - 1;
}
let branchNode = node.branch[index];
branchNode.count += 1;
return branchNode;
};
function linkDirectories(urls){
let treeList = treefy(urls);
_.forEach(treeList, linkDirectory);
return treeList;
};
function linkDirectory(node){
if(node.branch && node.branch.length === 1){
let child = node.branch[0];
node.name = _.join([node.name, child.name], '/');
node.branch = child.branch;
linkDirectory(node);
}
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.