code stringlengths 2 1.05M | repo_name stringlengths 5 114 | path stringlengths 4 991 | language stringclasses 1 value | license stringclasses 15 values | size int32 2 1.05M |
|---|---|---|---|---|---|
/*
* SoftVis3D Sonar plugin
* Copyright (C) 2014 Stefan Rinderle
* stefan@rinderle.info
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
goog.provide('Viewer.ObjectFactory');
Viewer.ObjectFactory = function (params) {
this.context = params.context;
};
Viewer.ObjectFactory.prototype = {
createObjects: function (platformArray) {
var result = [];
for (var i = 0; i < platformArray.length; i++) {
var platformResult = this.createPlatform(platformArray[i]);
result = result.concat(platformResult);
}
return result;
},
createPlatform: function (platform) {
var result = [];
var position = [];
position.x = platform.positionX;
position.y = platform.height3d;
position.z = platform.positionY;
var geometryLayer = new THREE.BoxGeometry(
platform.width, platform.platformHeight, platform.height);
var layerMaterial = new THREE.MeshLambertMaterial({
color: platform.color,
transparent: true,
opacity: platform.opacity
});
result.push(this.createBox(geometryLayer, layerMaterial, position, platform.platformId, "node"));
for (var i = 0; i < platform.nodes.length; i++) {
var buildingResult = this.createBuilding(platform.nodes[i]);
result = result.concat(buildingResult);
}
return result;
},
createBuilding: function (building) {
var result = [];
var nodeMaterial = new THREE.MeshLambertMaterial({
color: building.color,
transparent: true,
opacity: 1
});
var nodeGeometry = new THREE.BoxGeometry(
building.width, building.buildingHeight, building.height);
var position = [];
position.x = building.positionX;
position.y = building.height3d + building.buildingHeight / 2;
position.z = building.positionY;
result.push(this.createBox(nodeGeometry, nodeMaterial, position, building.id, "leaf"));
for (var i = 0; i < building.arrows.length; i++) {
var arrowResult = this.createArrow(building.arrows[i]);
result = result.concat(arrowResult);
}
return result;
},
createBox: function (geometry, material, position, id, type) {
var object = new THREE.Mesh(geometry, material);
object.position.x = position.x;
object.position.y = position.y;
object.position.z = position.z;
object.softVis3dId = id;
object.softVis3dType = type;
return object;
},
createArrow: function (arrow) {
var result = [];
result.push(this.createSpline(arrow));
var pointsLength = arrow.translatedPoints.length;
result.push(this.createArrowHead(arrow.translatedPoints[pointsLength - 2],
arrow.translatedPoints[pointsLength - 1],
arrow));
return result;
},
createSpline: function (arrow) {
var radius = 1 + (10 * (arrow.radius / 100));
// NURBS curve
var nurbsControlPoints = [];
var nurbsKnots = [];
var nurbsDegree = 3;
for (var i = 0; i <= nurbsDegree; i++) {
nurbsKnots.push(0);
}
for (var pointsIndex = 0; pointsIndex < arrow.translatedPoints.length; pointsIndex++) {
nurbsControlPoints.push(
new THREE.Vector4(
arrow.translatedPoints[pointsIndex].x,
arrow.translatedPoints[pointsIndex].y,
arrow.translatedPoints[pointsIndex].z,
// weight of control point: higher means stronger attraction
1
)
);
var knot = ( pointsIndex + 1 ) / ( arrow.translatedPoints.length - nurbsDegree );
nurbsKnots.push(THREE.Math.clamp(knot, 0, 1));
}
var nurbsCurve = new THREE.NURBSCurve(nurbsDegree, nurbsKnots, nurbsControlPoints);
var pipeSpline = new THREE.SplineCurve3(nurbsCurve.getPoints(200));
var tubegeometry = new THREE.TubeGeometry(
pipeSpline, //path
20, //segments
radius, //radius
8, //radiusSegments
false //closed
);
var edgeMesh = new THREE.Mesh(tubegeometry,
new THREE.MeshBasicMaterial({color: "#0000ff"}));
edgeMesh.softVis3dId = arrow.id;
edgeMesh.softVis3dType = "dependency";
return edgeMesh;
},
createArrowHead: function (startPoint, endPoint, arrow) {
var pointXVector = this.createVectorFromPoint(startPoint);
var pointYVector = this.createVectorFromPoint(endPoint);
var orientation = new THREE.Matrix4();
/* THREE.Object3D().up (=Y) default orientation for all objects */
orientation.lookAt(pointXVector, pointYVector, new THREE.Object3D().up);
/* rotation around axis X by -90 degrees
* matches the default orientation Y
* with the orientation of looking Z */
var multiplyMatrix = new THREE.Matrix4();
multiplyMatrix.set(1, 0, 0, 0,
0, 0, 1, 0,
0, -1, 0, 0,
0, 0, 0, 1);
orientation.multiply(multiplyMatrix);
/* thickness is in percent at the moment */
var radius = 1 + (10 * (arrow.radius / 100));
// add head
/* cylinder: radiusAtTop, radiusAtBottom,
height, radiusSegments, heightSegments */
var edgeHeadGeometry = new THREE.CylinderGeometry(1, radius + 3, 10, 8, 1);
var edgeHead = new THREE.Mesh(edgeHeadGeometry,
new THREE.MeshBasicMaterial({color: "#000000"}));
edgeHead.applyMatrix(orientation);
edgeHead.applyMatrix(new THREE.Matrix4().makeTranslation(
pointYVector.x, pointYVector.y, pointYVector.z));
edgeHead.softVis3dId = arrow.id;
edgeHead.softVis3dType = "dependency";
return edgeHead;
},
createVectorFromPoint: function (point) {
return new THREE.Vector3(point.x, point.y, point.z);
}
}; | stefanrinderle/sonar-softvis3d-plugin | src/main/resources/static/threeViewer/three/objectFactory.js | JavaScript | lgpl-3.0 | 6,284 |
'use strict';
let IdocPage = require('./idoc-page').IdocPage;
let TEXT_STYLE = require('./idoc-page').ListEditorMenu.TEXT_STYLE;
let TestUtils = require('../test-utils');
let ObjectDataWidget = require('./widget/object-data-widget/object-data-widget.js').ObjectDataWidget;
let ObjectDataWidgetConfig = require('./widget/object-data-widget/object-data-widget.js').ObjectDataWidgetConfig;
let DatatableWidget = require('./widget/data-table-widget/datatable-widget.js').DatatableWidget;
let DatatableWidgetConfig = require('./widget/data-table-widget/datatable-widget.js').DatatableWidgetConfigDialog;
let ObjectSelector = require('./widget/object-selector/object-selector.js').ObjectSelector;
let BusinessProcessDiagramWidget = require('./widget/business-process/buisness-process-diagram-widget').BusinessProcessDiagramWidget;
let BusinessProcessDiagramConfigDialog = require('./widget/business-process/buisness-process-diagram-widget').BusinessProcessDiagramConfigDialog;
let ChartViewWidget = require('./widget/chart-view-widget/chart-view-widget').ChartViewWidget;
let ChartViewWidgetConfigDialog = require('./widget/chart-view-widget/chart-view-widget').ChartViewWidgetConfigDialog;
let CommentsWidget = require('./widget/comments-widget/comments-widget').CommentsWidget;
let ImageWidget = require('./widget/image-widget/image-widget').ImageWidget;
let ImageWidgetConfigDialog = require('./widget/image-widget/image-widget').ImageWidgetConfigDialog;
let ObjectLinkWidget = require('./widget/object-link-widget/object-link-widget').ObjectLinkWidget;
let ObjectLinkWidgetConfigDialog = require('./widget/object-link-widget/object-link-widget').ObjectLinkWidgetConfigDialog;
let HeadingMenu = require('./idoc-page').HeadingMenu;
const IDOC_ID = 'emf:123456';
let idocPage = new IdocPage();
describe('undo/redo', () => {
const FIELDS = {
FIELD_ONE: 'field1',
FIELD_TWO: 'field2',
FIELD_THREE: 'field3'
};
let DISABLED = 'cke_button_disabled';
let ACTIVE = 'cke_button_off';
it('should undo formatting properly', () => {
idocPage.open(true, IDOC_ID);
let undoRedoToolbar = idocPage.getEditorToolbar(1).getUndoRedoToolbar();
let undoButton = undoRedoToolbar.getUndoButton();
let contentArea = idocPage.getTabEditor(1);
// inserting various ckeditor elements must be undoable
let toolbar = idocPage.getEditorToolbar(1).getTextOptionsToolbar();
contentArea.clear().click();
// bold text
contentArea.type('this text is bold');
contentArea.selectAll();
toolbar.boldText();
expect($$('strong').count()).to.eventually.equal(1);
undoButton.click();
expect($$('strong').count(), 'bold effect must be removed after undo').to.eventually.equal(0);
expect(contentArea.getAsText()).to.eventually.equal('this text is bold');
contentArea.clear().click();
// toggle back
toolbar.boldText();
// italic text
contentArea.type('this text is italic');
contentArea.selectAll();
toolbar.italicText();
expect($$('em').count()).to.eventually.equal(1);
undoButton.click();
expect($$('em').count(), 'italic effect must be removed after undo').to.eventually.equal(0);
expect(contentArea.getAsText()).to.eventually.equal('this text is italic');
contentArea.clear().click();
toolbar.italicText();
// striked text
contentArea.type('this text is striked');
contentArea.selectAll();
toolbar.strikeText(TEXT_STYLE.STRIKE);
expect($$('s').count()).to.eventually.equal(1);
undoButton.click();
expect($$('s').count(), 'striked effect must be removed after undo').to.eventually.equal(0);
expect(contentArea.getAsText()).to.eventually.equal('this text is striked')
contentArea.clear().click();
// lists
// bulleted lists
contentArea.type('this text is in a bulleted list');
contentArea.selectAll();
toolbar.insertbulletedList();
expect(contentArea.getContentElement().$$('li').count()).to.eventually.equal(1);
expect(contentArea.getAsText()).to.eventually.equal('this text is in a bulleted list');
undoButton.click();
// to remove selection
contentArea.newLine();
toolbar.insertbulletedList();
contentArea.type('this is the second bulleted item');
expect(contentArea.getContentElement().$$('li').count()).to.eventually.equal(1);
undoButton.click();
expect(contentArea.getContentElement().$$('li').count()).to.eventually.equal(1);
expect(contentArea.getAsText()).to.eventually.not.equal('this is the second bulleted item');
contentArea.clear().click();
// numbered lists
contentArea.type('this text is in a bulleted list');
contentArea.selectAll();
toolbar.insertNumberedList();
expect(contentArea.getContentElement().$$('li').count()).to.eventually.equal(1);
expect(contentArea.getAsText()).to.eventually.equal('this text is in a bulleted list');
undoButton.click();
// to remove selection
contentArea.newLine();
toolbar.insertNumberedList();
contentArea.type('this is the second bulleted item');
expect(contentArea.getContentElement().$$('li').count()).to.eventually.equal(1);
undoButton.click();
expect(contentArea.getContentElement().$$('li').count()).to.eventually.equal(1);
expect(contentArea.getAsText()).to.eventually.not.equal('this is the second bulleted item');
contentArea.clear().click();
// horizontal rule
contentArea.type('Above the horizontal rule');
toolbar.insertHorizontalRule();
contentArea.type('Below the horizontal rule');
expect(contentArea.getContentElement().$$('hr').count()).to.eventually.equal(1);
undoButton.click();
undoButton.click();
expect(contentArea.getContentElement().$$('hr').count(), 'horizontal line must be removed after undo').to.eventually.equal(0);
expect(contentArea.getAsText()).to.eventually.equal('Above the horizontal rule');
contentArea.clear().click();
// blockquote
contentArea.type('This should be blockQuoted');
contentArea.selectAll();
toolbar.insertBlockQuote();
expect(contentArea.getContentElement().$$('blockquote').count()).to.eventually.equal(1);
undoButton.click();
expect(contentArea.getContentElement().$$('blockquote', 'blockquote must be removed after undo').count()).to.eventually.equal(0);
expect(contentArea.getAsText()).to.eventually.equal('This should be blockQuoted');
contentArea.clear().click();
// page break
contentArea.type('Above the page break');
toolbar.insertPageBreak();
contentArea.type('Below the page break');
undoButton.click();
expect(contentArea.getContentElement().$$('.cke_pagebreak').count()).to.eventually.equal(1);
undoButton.click();
expect(contentArea.getContentElement().$$('.cke_pagebreak').count(), ' pagebreak must be removed after undo.').to.eventually.equal(0);
expect(contentArea.getAsText()).to.eventually.equal('Above the page break');
});
it('should enable and disable buttons properly', () => {
idocPage.open(true, IDOC_ID);
let contentArea = idocPage.getTabEditor(1);
let undoRedoToolbar = idocPage.getEditorToolbar(1).getUndoRedoToolbar();
let undoButton = undoRedoToolbar.getUndoButton();
let redoButton = undoRedoToolbar.getRedoButton();
expect(TestUtils.hasClass(undoButton, DISABLED), 'initial condition must be both buttons disabled').to.eventually.be.true;
expect(TestUtils.hasClass(redoButton, DISABLED), 'initial condition must be both buttons disabled').to.eventually.be.true;
contentArea.setContent('test content');
browser.wait(TestUtils.hasClass(undoButton, ACTIVE), DEFAULT_TIMEOUT);
expect(TestUtils.hasClass(redoButton, DISABLED), 'after content is inserted, the undo button must be active').to.eventually.be.true;
contentArea.setContent('more test content');
undoRedoToolbar.undo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(redoButton, ACTIVE), DEFAULT_TIMEOUT);
expect(TestUtils.hasClass(undoButton, ACTIVE), 'after initial undo, both buttons must be active').to.eventually.be.true;
undoRedoToolbar.undo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(TestUtils.hasClass(redoButton, ACTIVE), 'after the snapshots are exhausted, only redo must be active').to.eventually.be.true;
undoRedoToolbar.redo(contentArea.getContentElement());
undoRedoToolbar.redo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
expect(TestUtils.hasClass(undoButton, ACTIVE), 'after redo is exhausted, only undo must be active').to.eventually.be.true;
});
it('should undo to content containing widget', () => {
idocPage.open(true, IDOC_ID);
let contentArea = idocPage.getTabEditor(1);
let undoRedoToolbar = idocPage.getEditorToolbar(1).getUndoRedoToolbar();
let undoButton = undoRedoToolbar.getUndoButton();
let redoButton = undoRedoToolbar.getRedoButton();
contentArea.insertWidget(ObjectDataWidget.WIDGET_NAME);
let widgetConfig = new ObjectDataWidgetConfig();
widgetConfig.selectObjectSelectTab().selectObjectSelectionMode(ObjectSelector.CURRENT_OBJECT);
let propertiesSelector = widgetConfig.selectObjectDetailsTab();
propertiesSelector.selectProperty(FIELDS.FIELD_ONE);
widgetConfig.save();
// undo must be active after widget insert
browser.wait(TestUtils.hasClass(undoButton, ACTIVE), DEFAULT_TIMEOUT);
undoButton.click();
// after undo is exhausted, only redo must be active
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
browser.wait(TestUtils.hasClass(redoButton, ACTIVE), DEFAULT_TIMEOUT);
expect(contentArea.getAsText()).to.eventually.equal('Content tab 0');
redoButton.click();
browser.wait(EC.visibilityOf($('#field1')), DEFAULT_TIMEOUT);
contentArea.type('test-message');
// after redo, selection must remain below widget.
expect(contentArea.getAsText()).to.eventually.equal('Content tab 0\nField 1 *\nSee more\ntest-message');
expect(TestUtils.hasClass(undoButton, ACTIVE)).to.eventually.be.true;
expect(TestUtils.hasClass(redoButton, DISABLED), 'after undo and insertion of new text, redo must be inactive').to.eventually.be.true;
idocPage.insertLayout(10);
let firstColumn = $('.layout-column-one');
// select the first layout column
firstColumn.$('p').click();
firstColumn.sendKeys('test-message');
contentArea.insertWidget(DatatableWidget.WIDGET_NAME);
widgetConfig = new DatatableWidgetConfig();
let objectSelector = widgetConfig.selectObjectSelectTab();
let search = objectSelector.getSearch();
search.getCriteria().getSearchBar().search();
// And I select the first object to be visualized in the widget
search.getResults().clickResultItem(0);
widgetConfig.selectObjectDetailsTab().selectProperties(['field1', 'field2', 'field3', 'field4', 'field5']);
widgetConfig.save();
undoButton.click();
expect(contentArea.widgetsCount()).to.eventually.equal(1);
expect($('.layoutmanager').isPresent(), 'layout should not be removed on undo').to.eventually.be.true;
// this will remove selection
undoButton.click();
// should remove layout
undoButton.click();
expect(contentArea.widgetsCount()).to.eventually.equal(1);
expect($('.layoutmanager').isPresent(), 'layout should be removed on sequential undo').to.eventually.be.false;
// this should remove text
undoButton.click();
// this should remove widget and reset undo plugin
undoButton.click();
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount()).to.eventually.equal(0);
});
it('should undo after each widget insert', () => {
idocPage.open(true, IDOC_ID);
let contentArea = idocPage.getTabEditor(1);
let undoRedoToolbar = idocPage.getEditorToolbar(1).getUndoRedoToolbar();
let undoButton = undoRedoToolbar.getUndoButton();
let redoButton = undoRedoToolbar.getRedoButton();
// ODW
contentArea.insertWidget(ObjectDataWidget.WIDGET_NAME);
let widgetConfig = new ObjectDataWidgetConfig();
widgetConfig.selectObjectSelectTab().selectObjectSelectionMode(ObjectSelector.CURRENT_OBJECT);
let propertiesSelector = widgetConfig.selectObjectDetailsTab();
propertiesSelector.selectProperty(FIELDS.FIELD_ONE);
widgetConfig.save();
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
undoRedoToolbar.undo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount(), 'undo should remove ODW').to.eventually.equal(0);
// DTW
contentArea.insertWidget(DatatableWidget.WIDGET_NAME);
widgetConfig = new DatatableWidgetConfig();
let objectSelector = widgetConfig.selectObjectSelectTab();
let search = objectSelector.getSearch();
search.getCriteria().getSearchBar().search();
// And I select the first object to be visualized in the widget
search.getResults().clickResultItem(0);
widgetConfig.selectObjectDetailsTab().selectProperties(['field1', 'field2', 'field3', 'field4', 'field5']);
widgetConfig.save();
// undo button should be active, but insertion of new widget should disable redo
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
undoRedoToolbar.undo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount(), 'undo should remove DTW').to.eventually.equal(0);
// Image Widget
contentArea.insertWidget(ImageWidget.WIDGET_NAME);
widgetConfig = new ImageWidgetConfigDialog();
widgetConfig.save();
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
undoButton.click();
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount(), 'undo should remove image widget').to.eventually.equal(0);
// object-links
contentArea.executeWidgetCommand(ObjectLinkWidget.COMMAND);
widgetConfig = new ObjectLinkWidgetConfigDialog();
search = widgetConfig.getSearch();
let searchResults = search.getResults();
searchResults.waitForResults();
searchResults.clickResultItem(0);
widgetConfig.save();
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
undoRedoToolbar.undo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount()).to.eventually.equal(0);
// comments widget
contentArea.insertWidget(CommentsWidget.WIDGET_NAME);
let commentsWidget = new CommentsWidget(contentArea.getWidgetByNameAndOrder(CommentsWidget.WIDGET_NAME, 0));
widgetConfig = commentsWidget.getCommentsWidgetConfig();
widgetConfig.save();
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
undoRedoToolbar.undo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount(), 'undo should remove comments widget').to.eventually.equal(0);
//chart view widget
contentArea.insertWidget(ChartViewWidget.WIDGET_NAME);
widgetConfig = new ChartViewWidgetConfigDialog();
objectSelector = widgetConfig.selectObjectSelectTab();
search = objectSelector.getSearch();
search.getCriteria().getSearchBar().search();
search.getResults().waitForResults();
search.getResults().clickResultItem(0);
search.getResults().clickResultItem(1);
let chartConfigTab = widgetConfig.selectChartConfiguration();
chartConfigTab.selectGroupBy('Type');
widgetConfig.save();
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
undoRedoToolbar.undo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount(), 'undo should remove chart view widget').to.eventually.equal(0);
// business process
contentArea.insertWidget(BusinessProcessDiagramWidget.WIDGET_NAME);
widgetConfig = new BusinessProcessDiagramConfigDialog();
objectSelector = widgetConfig.getObjectSelector();
objectSelector.selectObjectSelectionMode(ObjectSelector.MANUALLY);
search = objectSelector.getSearch();
search.getCriteria().getSearchBar().search();
search.getResults().waitForResults();
search.getResults().clickResultItem(0);
widgetConfig.save();
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
undoRedoToolbar.undo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(undoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount(), 'undo should remove business process widget').to.eventually.equal(0);
// at least two widgets in one doc, undo should remove one widget
contentArea.insertWidget(ObjectDataWidget.WIDGET_NAME);
widgetConfig = new ObjectDataWidgetConfig();
widgetConfig.selectObjectSelectTab().selectObjectSelectionMode(ObjectSelector.CURRENT_OBJECT);
propertiesSelector = widgetConfig.selectObjectDetailsTab();
propertiesSelector.selectProperty(FIELDS.FIELD_ONE);
widgetConfig.save();
contentArea.insertWidget(DatatableWidget.WIDGET_NAME);
widgetConfig = new DatatableWidgetConfig();
objectSelector = widgetConfig.selectObjectSelectTab();
search = objectSelector.getSearch();
search.getCriteria().getSearchBar().search();
// And I select the first object to be visualized in the widget
search.getResults().clickResultItem(0);
widgetConfig.selectObjectDetailsTab().selectProperties(['field1', 'field2', 'field3', 'field4', 'field5']);
widgetConfig.save();
undoRedoToolbar.undo(contentArea.getContentElement());
expect(contentArea.widgetsCount(), 'undo operation removes 1 widget').to.eventually.equal(1);
undoRedoToolbar.redo(contentArea.getContentElement());
browser.wait(TestUtils.hasClass(redoButton, DISABLED), DEFAULT_TIMEOUT);
expect(contentArea.widgetsCount(), 'redo should return widgets to two').to.eventually.equal(2);
});
it.skip('should undo content containing widget and lists', () => {
idocPage.open(true, IDOC_ID);
let contentArea = idocPage.getTabEditor(1);
let undoRedoToolbar = idocPage.getEditorToolbar(1).getUndoRedoToolbar();
let undoButton = undoRedoToolbar.getUndoButton();
contentArea.insertWidget(DatatableWidget.WIDGET_NAME);
new DatatableWidgetConfig().save();
idocPage.getEditorToolbar(1).getTextOptionsToolbar().insertNumberedList();
contentArea.type('list item 1');
undoButton.click();
expect(contentArea.getContentElement().$$('li').count()).to.eventually.equal(0);
undoButton.click();
expect(contentArea.widgetsCount()).to.eventually.equal(0);
});
it.skip('should undo content containing widget in section', () => {
idocPage.open(true, IDOC_ID);
let contentArea = idocPage.getTabEditor(1);
let undoRedoToolbar = idocPage.getEditorToolbar(1).getUndoRedoToolbar();
let undoButton = undoRedoToolbar.getUndoButton();
contentArea.insertWidget(DatatableWidget.WIDGET_NAME);
let widgetConfig = new DatatableWidgetConfig();
let objectSelector = widgetConfig.selectObjectSelectTab();
let search = objectSelector.getSearch();
search.getCriteria().getSearchBar().search();
search.getResults().clickResultItem(0);
widgetConfig.selectObjectDetailsTab().selectProperties(['field1', 'field2', 'field3', 'field4', 'field5']);
widgetConfig.save();
contentArea.type('heading 1');
let toolbar = idocPage.getEditorToolbar(1);
let headingMenu = toolbar.getHeadingMenu();
headingMenu.select(HeadingMenu.HEADING1);
contentArea.newLine();
idocPage.getEditorToolbar(1).getTextOptionsToolbar().boldText();
contentArea.type('123');
// undo inserted bold text '123'
undoButton.click();
expect($$('strong').count()).to.eventually.equal(0);
// undo new line
undoButton.click();
// undo section creation
undoButton.click();
expect($$('h1').count(), 'heading should be removed after undo').to.eventually.equal(0);
});
});
| SirmaITT/conservation-space-1.7.0 | docker/sep-ui/test-e2e/idoc/undo-redo.spec.js | JavaScript | lgpl-3.0 | 20,371 |
/*
* WorkspaceToolbar.js
*
* Copyright (c) 2011, OSBI Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
/**
* The global toolbar
*
* With Buttons
* - Append Join
* - Append Union
* - Create Output
* - Reset
* - Vielleicht auch für den Output standardmößig einen letzten Tab einfügen
* - Oder Pro output einen Tab mit dem Entsprechenden Symbol
*/
var Toolbar = Backbone.View.extend({
tagName: "div",
events: {
'click #add_join': 'add_join',
'click #add_union': 'add_union',
'click #create_prpt_output': 'create_prpt_output',
'click #create_table_output': 'create_table_output',
'click #create_xls_output': 'create_xls_output'
},
template: function() {
return _.template("<ul>" +
"<li><a id='new_query' href='#new_query' title='New query' class='new_tab i18n sprite'></a></li>" +
"<li class='separator'> </li>" +
"<li><a id='open_query' href='#open_query' title='Open query' class='open_query i18n sprite'></a></li>" +
"<li class='separator'> </li>" +
"<li><a id='logout' href='#logout' title='Logout' class='logout i18n sprite'></a></li>" +
"<li><a id='about' href='#about' title='About' class='about i18n sprite'></a></li>" +
"<li class='separator'> </li>" +
"<li><a id='issue_tracker' href='#issue_tracker' title='Issue Tracker' class='bug i18n sprite'></a></li>" +
"</ul>" +
"<h1 id='logo'><a href='http://www.analytical-labs.com/' title='Saiku - Next Generation Open Source Analytics' class='sprite'>Saiku</a></h1>"
)(this);
},
initialize: function() {
this.render();
},
render: function() {
$(this.el).attr('id', 'toolbar')
.html(this.template());
// Trigger render event on toolbar so plugins can register buttons
Application.events.trigger('toolbar:render', { toolbar: this });
return this;
},
/**
* Add a new tab to the interface
*/
new_query: function() {
Saiku.tabs.add(new Workspace());
return false;
},
/**
* Open a query from the repository into a new tab
*/
open_query: function() {
var dialog = _.detect(Saiku.tabs._tabs, function(tab) {
return tab.content instanceof OpenQuery;
});
if (dialog) {
dialog.select();
} else {
Saiku.tabs.add(new OpenQuery());
}
return false;
},
/**
* Clear the current session and show the login window
*/
logout: function() {
Saiku.session.logout();
},
/**
* Show the credits dialog
*/
about: function() {
(new AboutModal).render().open();
return false;
},
/**
* Go to the issue tracker
*/
issue_tracker: function() {
window.open('http://projects.analytical-labs.com/projects/saiku/issues/new');
return false;
}
}); | Mgiepz/saiku-adhoc-ui | js/adhoc/views/Toolbar.js | JavaScript | lgpl-3.0 | 3,887 |
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import { connect } from 'react-redux';
import ProjectCard from './ProjectCard';
import { getComponent, getComponentMeasures } from '../../../store/rootReducer';
export default connect((state, ownProps) => ({
project: getComponent(state, ownProps.projectKey),
measures: getComponentMeasures(state, ownProps.projectKey)
}))(ProjectCard);
| lbndev/sonarqube | server/sonar-web/src/main/js/apps/projects/components/ProjectCardContainer.js | JavaScript | lgpl-3.0 | 1,184 |
/*
* This file is part of IMS Caliper Analytics™ and is licensed to
* IMS Global Learning Consortium, Inc. (http://www.imsglobal.org)
* under one or more contributor license agreements. See the NOTICE
* file distributed with this work for additional information.
*
* IMS Caliper is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* IMS Caliper is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with this program. If not, see http://www.gnu.org/licenses/.
*/
var _ = require('lodash');
var moment = require('moment');
var test = require('tape');
var config = require('../../src/config/config');
var entityFactory = require('../../src/entities/entityFactory');
var VideoObject = require('../../src/entities/resource/videoObject');
var clientUtils = require('../../src/clients/clientUtils');
var testUtils = require('../testUtils');
const path = config.testFixturesBaseDir + "caliperEntityVideoObject.json";
testUtils.readFile(path, function(err, fixture) {
if (err) throw err;
test('videoObjectTest', function (t) {
// Plan for N assertions
t.plan(1);
const BASE_IRI = "https://example.edu";
var entity = entityFactory().create(VideoObject, {
id: BASE_IRI.concat("/videos/1225"),
name: "Introduction to IMS Caliper",
mediaType: "video/ogg",
dateCreated: moment.utc("2016-08-01T06:00:00.000Z"),
dateModified: moment.utc("2016-09-02T11:30:00.000Z"),
duration: "PT1H12M27S",
version: "1.1"
});
// Compare
var diff = testUtils.compare(fixture, clientUtils.parse(entity));
var diffMsg = "Validate JSON" + (!_.isUndefined(diff) ? " diff = " + clientUtils.stringify(diff) : "");
t.equal(true, _.isUndefined(diff), diffMsg);
//t.end();
});
}); | IMSGlobal/caliper-js-public | test/entities/videoObjectTest.js | JavaScript | lgpl-3.0 | 2,161 |
var server = require('./app');
server.listen({host:'127.0.0.1', port:3002}, function(){
console.log('[SERVER] running at http://127.0.0.1:3002/');
}); | samshum/Nodejs.Web | server.js | JavaScript | lgpl-3.0 | 152 |
/*
* AAC.js - Advanced Audio Coding decoder in JavaScript
* Created by Devon Govett
* Copyright (c) 2012, Official.fm Labs
*
* AAC.js is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 3 of the
* License, or (at your option) any later version.
*
* AAC.js is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General
* Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library.
* If not, see <http://www.gnu.org/licenses/>.
*/
var ICStream = require('./ics');
var Huffman = require('./huffman');
// Channel Coupling Element
function CCEElement(config) {
this.ics = new ICStream(config);
this.channelPair = new Array(8);
this.idSelect = new Int32Array(8);
this.chSelect = new Int32Array(8);
this.gain = new Array(16);
}
CCEElement.BEFORE_TNS = 0;
CCEElement.AFTER_TNS = 1;
CCEElement.AFTER_IMDCT = 2;
const CCE_SCALE = new Float32Array([
1.09050773266525765921,
1.18920711500272106672,
1.4142135623730950488016887,
2.0
]);
CCEElement.prototype = {
decode: function(stream, config) {
var channelPair = this.channelPair,
idSelect = this.idSelect,
chSelect = this.chSelect;
this.couplingPoint = 2 * stream.read(1);
this.coupledCount = stream.read(3);
var gainCount = 0;
for (var i = 0; i <= this.coupledCount; i++) {
gainCount++;
channelPair[i] = stream.read(1);
idSelect[i] = stream.read(4);
if (channelPair[i]) {
chSelect[i] = stream.read(2);
if (chSelect[i] === 3)
gainCount++;
} else {
chSelect[i] = 2;
}
}
this.couplingPoint += stream.read(1);
this.couplingPoint |= (this.couplingPoint >>> 1);
var sign = stream.read(1),
scale = CCE_SCALE[stream.read(2)];
this.ics.decode(stream, config, false);
var groupCount = this.ics.info.groupCount,
maxSFB = this.ics.info.maxSFB,
bandTypes = this.ics.bandTypes;
for (var i = 0; i < gainCount; i++) {
var idx = 0,
cge = 1,
gain = 0,
gainCache = 1;
if (i > 0) {
cge = this.couplingPoint === CCEElement.AFTER_IMDCT ? 1 : stream.read(1);
gain = cge ? Huffman.decodeScaleFactor(stream) - 60 : 0;
gainCache = Math.pow(scale, -gain);
}
var gain_i = this.gain[i] = new Float32Array(120);
if (this.couplingPoint === CCEElement.AFTER_IMDCT) {
gain_i[0] = gainCache;
} else {
for (var g = 0; g < groupCount; g++) {
for (var sfb = 0; sfb < maxSFB; sfb++) {
if (bandTypes[idx] !== ICStream.ZERO_BT) {
if (cge === 0) {
var t = Huffman.decodeScaleFactor(stream) - 60;
if (t !== 0) {
var s = 1;
t = gain += t;
if (!sign) {
s -= 2 * (t & 0x1);
t >>>= 1;
}
gainCache = Math.pow(scale, -t) * s;
}
}
gain_i[idx++] = gainCache;
}
}
}
}
}
},
applyIndependentCoupling: function(index, data) {
var gain = this.gain[index][0],
iqData = this.ics.data;
for (var i = 0; i < data.length; i++) {
data[i] += gain * iqData[i];
}
},
applyDependentCoupling: function(index, data) {
var info = this.ics.info,
swbOffsets = info.swbOffsets,
groupCount = info.groupCount,
maxSFB = info.maxSFB,
bandTypes = this.ics.bandTypes,
iqData = this.ics.data;
var idx = 0,
offset = 0,
gains = this.gain[index];
for (var g = 0; g < groupCount; g++) {
var len = info.groupLength[g];
for (var sfb = 0; sfb < maxSFB; sfb++, idx++) {
if (bandTypes[idx] !== ICStream.ZERO_BT) {
var gain = gains[idx];
for (var group = 0; group < len; group++) {
for (var k = swbOffsets[sfb]; k < swbOffsets[swb + 1]; k++) {
data[offset + group * 128 + k] += gain * iqData[offset + group * 128 + k];
}
}
}
}
offset += len * 128;
}
}
};
module.exports = CCEElement;
| audiocogs/aac.js | src/cce.js | JavaScript | lgpl-3.0 | 5,232 |
/* eslint complexity: "off"*/
odoo.define("media_form_widget", function(require) {
"use strict";
var core = require("web.core");
var KanbanRecord = require("web.KanbanRecord");
var session = require("web.session");
var qweb = core.qweb;
var basic_fields = require("web.basic_fields");
var FieldBinaryImage = basic_fields.FieldBinaryImage;
var field_utils = require("web.field_utils");
var _t = core._t;
FieldBinaryImage.include({
init: function(parent, name, record) {
var res = this._super.apply(this, arguments);
this.media = this.attrs.media;
this.media_type = this.record.data.media_type;
this.media_video_ID = this.record.data.media_video_ID;
this.media_video_service = this.record.data.media_video_service;
return res;
},
_render: function() {
// Unique ID for popup
var model = this.record.model.split(".").join("");
this.media_id = model + this.record.res_id;
var application_mimetype = false;
if (
this.media &&
this.value &&
(!this.media_type ||
(this.media_type &&
this.media_type.split("/")[0] === "application"))
) {
application_mimetype = true;
}
if (
this.media &&
(this.media_type === "video/url" ||
application_mimetype ||
this.media_type === "application/msword")
) {
var url = "/web/static/src/img/mimetypes/document.png";
if (this.media_type === "video/url") {
url = "/web/static/src/img/mimetypes/video.png";
if (this.media_video_service === "youtube") {
url = "/web_preview/static/src/img/youtube.png";
} else if (this.media_video_service === "vimeo") {
url = "/web_preview/static/src/img/vimeo.png";
}
} else if (this.media_type === "application/pdf") {
url = "/web_preview/static/src/img/pdf.png";
this.pdf_url = this.get_media_url("/web/pdf");
} else if (this.media_type === "application/msword") {
url = "/web_preview/static/src/img/doc.png";
this.msword_url = this.get_media_url("/web/doc");
} else if (
this.media_type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
) {
url = "/web_preview/static/src/img/xlsx.png";
this.xlsx_url = this.get_media_url("/web/xlsx");
} else if (this.media_type === "application/vnd.ms-excel") {
url = "/web_preview/static/src/img/xls.png";
this.xls_url = this.get_media_url("/web/xls");
} else if (
this.media_type ===
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
) {
url = "/web_preview/static/src/img/docx.png";
this.docx_url = this.get_media_url("/web/docx");
} else {
this.do_warn(
_t("Document"),
_t("Could not display the selected document.")
);
}
var $img = $(
qweb.render("FieldBinaryImage-img", {widget: this, url: url})
);
this.$("> img").remove();
this.$("> a img").remove();
this.$el.prepend($img);
} else {
if (this.media_type && this.media_type.split("/")[0] === "image") {
this.media_type = "image";
}
this._super();
}
},
on_file_uploaded_and_valid: function(size, name, content_type, file_base64) {
this.media_type = content_type;
this._super(size, name, content_type, file_base64);
},
get_media_url: function(request) {
var url = session.url(request, {
model: this.model,
id: JSON.stringify(this.res_id),
field: this.name,
filename: this.record.data.name,
unique: field_utils.format
.datetime(this.recordData.__last_update)
.replace(/[^0-9]/g, ""),
});
return url;
},
});
KanbanRecord.include({
_getImageURL: function(model, field, id, cache, options) {
if (this.recordData.media_type === "application/pdf") {
return "/web_preview/static/src/img/pdf.png";
} else if (this.recordData.media_type === "application/msword") {
return "/web_preview/static/src/img/doc.png";
} else if (
this.recordData.media_type ===
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
) {
return "/web_preview/static/src/img/docx.png";
} else if (this.recordData.media_type === "application/vnd.ms-excel") {
return "/web_preview/static/src/img/xls.png";
} else if (
this.recordData.media_type ===
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
) {
return "/web_preview/static/src/img/xlsx.png";
} else if (this.recordData.media_video_service) {
var video = this.recordData.media_video_service;
if (video === "youtube") {
return "/web_preview/static/src/img/youtube.png";
}
if (video === "vimeo") {
return "/web_preview/static/src/img/vimeo.png";
}
}
return this._super(model, field, id, cache, options);
},
});
});
| yelizariev/addons-yelizariev | web_preview/static/src/js/media_form_widget.js | JavaScript | lgpl-3.0 | 6,190 |
// Production key
Parse.initialize("XYwe86rF27FL0zSEeNETivcLQ9nyBtniNxh6Swub", "R4C0M1hxn3FGyvRHgZBSeXO8ULwffzld77ZtFjTf");
//Safe-dev key
// Parse.initialize("FcavaMqNGXulqDITFSUd3cngJo6ttTctma1r2e3X", "jNfnNnqVxA5djYXg6iYZmWxADD6BRpoGn48ixPsz");
var Full_movie = React.createClass({
componentDidMount: function(){
// debugger;
},
componentDidUpdate: function(){
// debugger;
},
getInitialState: function() {
return {metadata: ''};
},
handleClick: function(event) {
event.preventDefault();
$('#videoplayer video source').attr('src', this.props.url);
$('#videoplayer video').load();
activate_player(this.props.src);
},
render: function() {
// Render the text of each comment as a list item
return (
<div style={{
'width': '18%',
'height': 'auto',
'margin': '1%',
'float': 'left'
}}>
<img
src={this.props.src}
title={this.props.title}
url={this.props.url}
style={{
'object-fit': 'cover',
'height': '300px'
}}>
</img>
<p style={{'font' : 'normal 1.5em/1 Ailerons', 'text-align': 'center'}}>
<a
href='play'
style={{'color': '#FF00DC'}}
onClick={this.handleClick}>
{this.props.title}
</a>
</p>
</div>
);
}
});
var Full_movie_gallery = React.createClass({
mixins: [ParseReact.Mixin], // Enable query subscriptions
observe: function() {
// Subscribe to all Comment objects, ordered by creation date
// The results will be available at this.data.comments
return {
comments: (new Parse.Query('full_movies')).limit(5)
};
},
handleClick: function(event) {
event.preventDefault();
$('#videoplayer video source').attr('src', this.props.url);
$('#videoplayer video').load();
activate_player(this.props.src);
},
render: function() {
// Render the text of each comment as a list item
return (
<ul>
{this.data.comments.map(function (c) {
return <Full_movie src={c.img} title={c.title} url={c.url} />;
})}
</ul>
);
}
});
React.render(
<Full_movie_gallery/>,
document.getElementById('parse')
);
var Video = React.createClass({
componentDidMount: function(){
// debugger;
},
componentDidUpdate: function(){
// debugger;
},
getInitialState: function() {
return {metadata: ''};
},
handleClick: function(event) {
event.preventDefault();
$('#videoplayer video source').attr('src', this.props.url);
$('#videoplayer video').load();
activate_player(this.props.src);
},
render: function() {
// Render the text of each comment as a list item
return (
<div style={{
'width': '31.3%',
'height': '180px',
'margin': '1%',
'float': 'left'
}}>
<img
src={this.props.src}
title={this.props.title}
url={this.props.url}
style={{
// 'width':'100%',
'object-fit': 'cover'
// 'max-height': '120px'
}}>
</img>
<p style={{'font' : 'normal 1.5em/1 Ailerons', 'text-align': 'center'}}>
<a href='play' style={{'color': '#FF00DC'}} onClick={this.handleClick}>
{this.props.title}
</a>
</p>
</div>
);
}
});
var Video_gallery = React.createClass({
mixins: [ParseReact.Mixin], // Enable query subscriptions
observe: function(props, state) {
// Subscribe to all videos objects, limited to gallery_size
// The results will be available at this.data.comments
return {
comments: (new Parse.Query('videos')).skip(state.skip).limit(state.limit)
};
},
getInitialState: function() {
return {skip:0, limit: 9}
},
componentDidUpdate: function(){
},
handleClick: function(event) {
event.preventDefault();
this.setState({
skip: this.state.skip + this.state.limit,
limit: this.state.limit
});
},
render: function() {
if(this.data.comments.length != 0){
// Render the text of each comment as a list item
return (
<div>
<ul>
{this.data.comments.map(function (c) {
return <Video src={c.img} title={c.title} url={c.url} />;
})}
</ul>
<div className="title clearfix">
<p
id="load"
style={{'float': 'left'}}>
<a href='' className="text" onClick={this.handleClick}>
Load more...
</a>
</p>
</div>
</div>
);
} else {
return (
<div>
<div className="title clearfix">
<p
id="load"
className="text"
onClick={this.handleClick}>
End of list
</p>
</div>
</div>
);
}
}
});
var gallery = React.render(
<Video_gallery/>,
document.getElementById('latest-theater')
); //.getElementsByClassName('container'));
//gallery.setState({skip: 0, limit: 9}) skip page number or +1. Or do limit+=9. Run this function on click load more
var Featured = React.createClass({
mixins: [ParseReact.Mixin], // Enable query subscriptions
observe: function() {
// Subscribe to all Comment objects, ordered by creation date
// The results will be available at this.data.comments
return {
comments: (new Parse.Query('videos')).equalTo('presentation', true).limit(1)
};
},
getInitialState: function() {
return {comments: ''};
},
componentDidUpdate: function(){
this.state = this.data.comments[0];
},
handleClick: function(event) {
event.preventDefault();
$('#videoplayer video source').attr('src', this.state[event.target.attributes.data.value]);
$('#videoplayer video').load();
activate_player();
},
render: function() {
var c = this.data.comments[0];
if(!c){
return null;
}else{
// Render the text of each comment as a list item
return (
<div
className='presentation'
style={{'backgroundImage':'url('+c.img+')', 'backgroundSize': 'cover', 'backgroundPosition': 'center center'}}>
<div className="play-options">
<div className="row-play-options">
<div className="row-play-options-container">
<div className="play-button play">
<a
className='video-link'
href={c.teaser}
data='teaser'
onClick={this.handleClick}>Teaser</a>
</div>
<div className="play-button play">
<a
className='video-link'
href={c.trailer}
data='trailer'
onClick={this.handleClick}>Trailer</a>
</div>
</div>
</div>
<div className="row-play-options">
<div className="row-play-options-container">
<div className="play-button play">
<a
className='video-link'
href={c.url}
data='url'
onClick={this.handleClick}>
Full Video
</a>
</div>
</div>
</div>
</div>
<div className="overlay">
</div>
</div>
);
}
}
});
React.render(
<Featured/>,
document.getElementById('featured')
);
| EroticaDevelopers/EroticaDevelopers.github.io | js/parse_data.js | JavaScript | lgpl-3.0 | 7,655 |
// Generated on 2017-05-08 using generator-jhipster 4.4.1
'use strict';
var gulp = require('gulp'),
rev = require('gulp-rev'),
templateCache = require('gulp-angular-templatecache'),
htmlmin = require('gulp-htmlmin'),
imagemin = require('gulp-imagemin'),
ngConstant = require('gulp-ng-constant'),
rename = require('gulp-rename'),
eslint = require('gulp-eslint'),
argv = require('yargs').argv,
gutil = require('gulp-util'),
protractor = require('gulp-protractor').protractor,
del = require('del'),
runSequence = require('run-sequence'),
browserSync = require('browser-sync'),
// KarmaServer = require('karma').Server,
plumber = require('gulp-plumber'),
changed = require('gulp-changed'),
gulpIf = require('gulp-if');
var handleErrors = require('./gulp/handle-errors'),
serve = require('./gulp/serve'),
util = require('./gulp/utils'),
copy = require('./gulp/copy'),
inject = require('./gulp/inject'),
build = require('./gulp/build');
var config = require('./gulp/config');
gulp.task('clean', function () {
return del([config.dist], { dot: true });
});
gulp.task('copy', ['copy:i18n', 'copy:fonts', 'copy:common']);
gulp.task('copy:i18n', copy.i18n);
gulp.task('copy:languages', copy.languages);
gulp.task('copy:fonts', copy.fonts);
gulp.task('copy:common', copy.common);
gulp.task('copy:swagger', copy.swagger);
gulp.task('copy:images', copy.images);
gulp.task('images', function () {
return gulp.src(config.app + 'content/images/**')
.pipe(plumber({ errorHandler: handleErrors }))
.pipe(changed(config.dist + 'content/images'))
.pipe(imagemin({ optimizationLevel: 5, progressive: true, interlaced: true }))
.pipe(rev())
.pipe(gulp.dest(config.dist + 'content/images'))
.pipe(rev.manifest(config.revManifest, {
base: config.dist,
merge: true
}))
.pipe(gulp.dest(config.dist))
.pipe(browserSync.reload({ stream: true }));
});
gulp.task('styles', [], function () {
return gulp.src(config.app + 'content/css')
.pipe(browserSync.reload({ stream: true }));
});
gulp.task('inject', function () {
runSequence('inject:dep', 'inject:app');
});
gulp.task('inject:dep', ['inject:test', 'inject:vendor']);
gulp.task('inject:app', inject.app);
gulp.task('inject:vendor', inject.vendor);
gulp.task('inject:test', inject.test);
gulp.task('inject:troubleshoot', inject.troubleshoot);
gulp.task('assets:prod', ['images', 'styles', 'html', 'copy:swagger', 'copy:images'], build);
gulp.task('html', function () {
return gulp.src(config.app + 'app/**/*.html')
.pipe(htmlmin({ collapseWhitespace: true }))
.pipe(templateCache({
module: 'kevoreeRegistryApp',
root: 'app/',
moduleSystem: 'IIFE'
}))
.pipe(gulp.dest(config.tmp));
});
gulp.task('ngconstant:dev', function () {
return ngConstant({
name: 'kevoreeRegistryApp',
constants: {
VERSION: util.parseVersion(),
DEBUG_INFO_ENABLED: true
},
template: config.constantTemplate,
stream: true
})
.pipe(rename('app.constants.js'))
.pipe(gulp.dest(config.app + 'app/'));
});
gulp.task('ngconstant:prod', function () {
return ngConstant({
name: 'kevoreeRegistryApp',
constants: {
VERSION: util.parseVersion(),
DEBUG_INFO_ENABLED: false
},
template: config.constantTemplate,
stream: true
}).pipe(rename('app.constants.js'))
.pipe(gulp.dest(config.app + 'app/'));
});
// check app for eslint errors
gulp.task('eslint', function () {
return gulp.src(['gulpfile.js', config.app + 'app/**/*.js'])
.pipe(plumber({ errorHandler: handleErrors }))
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError());
});
// check app for eslint errors anf fix some of them
gulp.task('eslint:fix', function () {
return gulp.src(config.app + 'app/**/*.js')
.pipe(plumber({ errorHandler: handleErrors }))
.pipe(eslint({
fix: true
}))
.pipe(eslint.format())
.pipe(gulpIf(util.isLintFixed, gulp.dest(config.app + 'app')));
});
// gulp.task('test', ['inject:test', 'ngconstant:dev'], function (done) {
// new KarmaServer({
// configFile: __dirname + '/' + config.test + 'karma.conf.js',
// singleRun: true
// }, done).start();
// });
gulp.task('test', function () {
console.log('TODO'); // eslint-disable-line
});
/* to run individual suites pass `gulp itest --suite suiteName` */
gulp.task('protractor', function () {
var configObj = {
configFile: config.test + 'protractor.conf.js'
};
if (argv.suite) {
configObj['args'] = ['--suite', argv.suite];
}
return gulp.src([])
.pipe(plumber({ errorHandler: handleErrors }))
.pipe(protractor(configObj))
.on('error', function () {
gutil.log('E2E Tests failed');
process.exit(1);
});
});
gulp.task('itest', ['protractor']);
gulp.task('watch', function () {
gulp.watch('bower.json', ['install']);
gulp.watch(['gulpfile.js', 'pom.xml'], ['ngconstant:dev']);
gulp.watch(config.app + 'content/css/**/*.css', ['styles']);
gulp.watch(config.app + 'content/images/**', ['images']);
gulp.watch(config.app + 'app/**/*.js', ['inject:app']);
gulp.watch([config.app + '*.html', config.app + 'app/**', config.app + 'i18n/**']).on('change', browserSync.reload);
});
gulp.task('install', function () {
runSequence(['inject:dep', 'ngconstant:dev'], 'copy:languages', 'inject:app', 'inject:troubleshoot');
});
gulp.task('serve', ['install'], serve);
gulp.task('build', ['clean'], function (cb) {
runSequence(['copy', 'inject:vendor', 'ngconstant:prod', 'copy:languages'], 'inject:app', 'inject:troubleshoot', 'assets:prod', cb);
});
gulp.task('default', ['serve']);
| kevoree/kevoree-registry | gulpfile.js | JavaScript | lgpl-3.0 | 5,676 |
var class_relay_command =
[
[ "RelayCommand", "class_relay_command.html#a711f0ac6148aa35a81fef72ef1a12c2e", null ],
[ "RelayCommand", "class_relay_command.html#ad7534667812f0cbdc9a07fe852daceb3", null ],
[ "RelayCommand", "class_relay_command.html#aaf0f6af75435c95b4cea61d461a62d1f", null ],
[ "CanExecute", "class_relay_command.html#a4550a344e1e9d3589eaf37cf4a1ba7a7", null ],
[ "Execute", "class_relay_command.html#a62136b7eca4542b47e874b3de97c4657", null ],
[ "CanExecuteChanged", "class_relay_command.html#a70399f94d9c09f56d569f712aca8adbb", null ]
]; | clement-chollet/Easy-Video-Edition | docs/documentation/class_relay_command.js | JavaScript | lgpl-3.0 | 579 |
var V;
var G = [[]]; // input edge weights
var dist = [[]]; // distance matrix
// for all pairs shortest paths
// O(V^3)
function floydwarshall() {
for (var i = 0; i < V; ++i) {
for (var j = 0; j < G[i].length; ++j) {
dist[i].push(G[i][j]);
}
}
// pick intermediate vertex
for (var k = 0; k < V; ++k) {
// pick src
for (var i = 0; i < V; ++i) {
// pick dest
for (var j = 0; j < V; ++j) {
if (dist[i][k] + dist[k][j] < dist[i][j])
dist[i][j] = dist[i][k] + dist[k][j];
}
}
}
}
| jan25/code_sorted | Graph/floydwarshall.js | JavaScript | unlicense | 517 |
(function() {
'use strict';
angular
.module('santafeJhApp')
.factory('AddressSearch', AddressSearch);
AddressSearch.$inject = ['$resource'];
function AddressSearch($resource) {
var resourceUrl = 'api/_search/addresses/:id';
return $resource(resourceUrl, {}, {
'query': { method: 'GET', isArray: true}
});
}
})();
| acardenasnet/santafe_jh | src/main/webapp/app/entities/address/address.search.service.js | JavaScript | unlicense | 390 |
module.exports = {
Project: require('./lib/project')
} | RaniSputnik/GM-Studio | index.js | JavaScript | unlicense | 55 |
//BG Color Change
var colors = ["red", "green", "blue", "purple", "yellow", "orange"];
var currentColor = 0;
function switchColor() {
if (currentColor >= colors.length) currentColor = 0;
$('#outer').css('background-color', colors[currentColor++]);
setTimeout(switchColor, 400);
}
switchColor();
//Rotate Drinker
var angle = 0;
setInterval(function(){
angle+=3;
$("#drinker").rotate(angle);
},50);
//Swop Drinker
var drinker = ["img/PINT.png", "img/ED_PINT.png", "img/NF_PINT.png"];
var currentDrinker = 0;
function switchDrinker(){
if (currentDrinker >= drinker.length) currentDrinker = 0;
$("#drinker").attr('src', drinker[currentDrinker++]);
setTimeout(switchDrinker, 1400);
}
switchDrinker();
//Bounce Play me
function rumble(){
$(".point span").effect( "shake", {times:3}, 2000 );
};
$(window).on('load', function() {
rumble();
});
window.setInterval(function(){
rumble();
}, 5000);
| edwarddakin/edwarddakin.github.io | pint/js/scripts.js | JavaScript | unlicense | 925 |
import toAverageProp from "../dist/toAverageProp.js";
describe("toAverageProp", function() {
var mockup = [{
city: "Rio de Janeiro",
temperature: 96,
demographics: {
population: 6.32
}
}, {
city: "São Paulo",
temperature: 82.5,
demographics: {
population: 12.04
}
}, {
city: "Curitiba",
temperature: 70,
demographics: {
population: 1.752
}
}, {
city: "Florianópolis",
temperature: 86,
demographics: {
population: 0.249
}
}];
it(`Should conclude that São Paulo has the average temperature amongst the cities in the array.`, function() {
expect(
mockup.reduce(toAverageProp("temperature"))
).toBe(mockup[1]); // São Paulo
});
it(`Should conclude that Rio de Janeiro has the average population amongst the cities in the array.`, function() {
expect(
mockup.reduce(toAverageProp("demographics.population"))
).toBe(mockup[0]); // Rio de Janeiro
});
var test = [{
n: "a",
p: 2
}, {
n: "b",
p: 4
}, {
n: "c",
p: 6
}, {
n: "d",
p: 2
}, {
n: "e",
p: 4
}];
it(`Should return the first result when two or more are found.`, function() {
expect(
test.reduce(toAverageProp("p"))
).toBe(test[1]);
});
});
| leofavre/canivete | test/toAveragePropSpecs.js | JavaScript | unlicense | 1,201 |
var async = require('async'),
request = require('request'),
fs = require('fs'),
url = require('url'),
path = require('path');
function downloadImage(imageUrl, outFilePath, imageNum, onFinished) {
request.head(imageUrl, function(err, res) {
if (err) {
console.error('Unable to download image [' + imageNum + ']: ' + imageUrl);
console.error('Error: ' + err.message);
return onFinished();
} else if (res) {
switch (res.statusCode) {
// Forbidden
case 403:
console.warn('Unable to download image [' + imageNum + '] - (403): ' + imageUrl);
return onFinished();
}
}
request(imageUrl)
.pipe(fs.createWriteStream(outFilePath))
.on('close', onFinished);
});
}
/**
* Pad leading zeroes onto a digit string.
*/
function pad(num, size) {
return ('000000000' + num).substr(-size);
}
module.exports = {
downloadImages: function(params, onFinished) {
var imageUrls = params.imageUrls;
var work = [];
var workFunc = function(imageUrl, outFilePath, imageNum) {
return function(cb) {
console.log('Downloading [' + imageNum + ']: ' + imageUrl);
downloadImage(imageUrl, outFilePath, imageNum, cb);
};
};
var digitCount = imageUrls.length.toString().length;
for (var i = 0; i < imageUrls.length; i++) {
var imageUrl = imageUrls[i];
var pathname = url.parse(imageUrl).pathname; // /x/y/z.png
// Order the images by digit with padded zeroes so that
// when we process them, they'll be processed in the desired
// alphabetical order.
var filePath = path.join(params.outputDir, pad(i + 1, digitCount) + path.extname(pathname));
work.push(workFunc(imageUrl, filePath, i + 1));
}
async.parallel(work,
function(err) {
if (err) {
console.error('Error: ' + err.message);
}
onFinished();
}
);
}
};
| doggan/recurrimg | lib/image_download.js | JavaScript | unlicense | 2,208 |
var Player = function (game, gameSize) {
this.game = game;
this.size = {
x: 20,
y: 20
};
this.center = {
x: gameSize.x / 2 - this.size.x / 2,
y: gameSize.y - this.size.y
};
this.controls = new Controls();
};
Player.prototype = {
update: function () {
if (this.controls.isDown(this.controls.KEYS.LEFT)) {
this.center.x -= 3;
}
if (this.controls.isDown(this.controls.KEYS.RIGHT)) {
this.center.x += 3;
}
if (this.controls.isDown(this.controls.KEYS.SPACE)) {
var bullet = new Bullet(this.game, {
x: this.center.x,
y: this.center.y - this.size.y
}, {
x: 0,
y: -10
});
this.game.shootSound.load();
this.game.shootSound.play();
this.game.addBody(bullet);
}
},
draw: function (screen, gameSize) {
drawRect(screen, this);
}
}; | begedin/JavaScriptGameLoop | objects/player.js | JavaScript | unlicense | 936 |
module.exports = Backbone.View.extend({
className: 'login',
initialize: function(){
var self = this
self.$el.html(ss.tmpl['login-base'].render()).appendTo('.dash')
var $logIn = self.$el.find('#log-in');
var $loggingIn = self.$el.find('#logging-in');
var $authenticationFailed = self.$el.find('#authentication-failed');
var $authenticationPaused = self.$el.find('#authentication-paused');
self.$el.find('input').each(function(index, element){
var $e = $(element)
var value = $e.val()
$e.keyup(function (e) {
// Only try logging in when Enter is pressed.
if (e.keyCode !== 13) {
return;
}
var username = self.$el.find('#login_username').val();
var password = self.$el.find('#login_password').val();
$logIn.hide();
$authenticationFailed.hide();
$authenticationPaused.hide();
$loggingIn.show();
self.user.login(username, password, function (err, authenticated) {
if (err && err.name === 'RateLimitError') {
$loggingIn.hide();
$authenticationPaused.show();
return;
}
if (!authenticated) {
$loggingIn.hide();
$authenticationFailed.show();
}
});
})
$e.focus(function(){
if ($e.val() === value ){
if (value === 'password')
$e.prop('type', 'password')
$e.val('')
}
})
$e.blur(function(){
if ($e.val() === ''){
if (value === 'password')
$e.prop('type', 'text')
$e.val(value)
}
})
})
},
clear: function(){
var self = this
self.$el.children().children().removeClass('animated flipInX')
self.$el.children().children().addClass('animatedQuick fadeOutUp')
setTimeout(function(){
self.$el.remove()
}, 1000)
}
})
| lamassu/lamassu-admin | client/code/app/Views/Login/index.js | JavaScript | unlicense | 1,928 |
/**
* Solution for problem from here:
* https://www.reddit.com/r/dailyprogrammer/comments/6jr76h/20170627_challenge_321_easy_talking_clock/
*/
const numbers = {
0: 'twelve',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
30: 'thirty',
40: 'fourty',
50: 'fifty',
};
const handleMins = mm => {
}
const getSuffix = hh => hh >= 12 ? 'pm' : 'am';
const getHour = hh => numbers[hh % 12];
const getMinutes = mm => {
if (mm === 0) {
return null;
} else if (mm < 10) {
return `oh ${numbers[mm]}`;
} else if (mm < 20) {
return `${numbers[mm]}`;
} else {
return `${numbers[Math.floor(mm / 10) * 10]}${mm % 10 !== 0 ? ` ${numbers[mm % 10]}` : ''}`;
}
}
/**
* @param {array} string
* @returns {string}
*/
exports.default = function(time) {
const [hours, minutes] = time.split(':').map(str => parseInt(str));
const formattedHours = getHour(hours);
const formattedMinutes = getMinutes(minutes);
const formattedSuffix = getSuffix(hours);
return `${formattedHours} ${formattedMinutes ? `${formattedMinutes} ` : '' }${formattedSuffix}`;
}
| jimalgo/funalgos | TimeToSpeech/index.js | JavaScript | unlicense | 1,334 |
/*!
* SAP UI development toolkit for HTML5 (SAPUI5/OpenUI5)
* (c) Copyright 2009-2015 SAP SE or an SAP affiliate company.
* Licensed under the Apache License, Version 2.0 - see LICENSE.txt.
*/
// Provides control sap.ui.unified.DateTypeRange.
sap.ui.define(['jquery.sap.global', './DateRange', './library'],
function(jQuery, DateRange, library) {
"use strict";
/**
* Constructor for a new DateTypeRange.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* Date range with calendar day type information. Used to visualize special days in the Calendar.
* @extends sap.ui.unified.DateRange
* @version 1.28.10
*
* @constructor
* @public
* @since 1.24.0
* @alias sap.ui.unified.DateTypeRange
* @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
*/
var DateTypeRange = DateRange.extend("sap.ui.unified.DateTypeRange", /** @lends sap.ui.unified.DateTypeRange.prototype */ { metadata : {
library : "sap.ui.unified",
properties : {
/**
* Type of the date range.
*/
type : {type : "sap.ui.unified.CalendarDayType", group : "Appearance", defaultValue : sap.ui.unified.CalendarDayType.Type01}
}
}});
///**
// * This file defines behavior for the control,
// */
//sap.ui.unified.DateTypeRange.prototype.init = function(){
// // do something for initialization...
//};
return DateTypeRange;
}, /* bExport= */ true);
| ghostxwheel/utorrent-webui | resources/sap/ui/unified/DateTypeRange-dbg.js | JavaScript | unlicense | 1,552 |
mycallback( {"_record_type": "fec.version.v7_0.TEXT", "FILER COMMITTEE ID NUMBER": "C00441410", "REC TYPE": "TEXT", "TEXT4000": "Complete Campaigns", "TRANSACTION ID NUMBER": "TINCA504", "_src_file": "2011/20110504/727399.fec_1.yml", "BACK REFERENCE TRAN ID NUMBER": "INCA504", "BACK REFERENCE SCHED / FORM NAME": "SA11AI"});
| h4ck3rm1k3/federal-election-commission-aggregation-json-2011 | objects/e9/925c4637bcc14a1887bdf564f3199c5b5d7e99.js | JavaScript | unlicense | 326 |
import '../src/styles/variables.css';
| pascalduez/react-module-boilerplate | .storybook/preview.js | JavaScript | unlicense | 38 |
/**
* AngularJS Tutorial 1
* @author Nick Kaye <nick.c.kaye@gmail.com>
*/
/**
* Main AngularJS Web Application
*/
var app = angular.module('tutorialWebApp', [
'ngRoute'
]);
/**
* Configure the Routes
*/
app.config(['$routeProvider', function ($routeProvider) {
$routeProvider
// Home
.when("/", {templateUrl: "partials/home.html", controller: "PageCtrl"})
// Pages
.when("/about", {templateUrl: "partials/about.html", controller: "PageCtrl"})
.when("/faq", {templateUrl: "partials/faq.html", controller: "PageCtrl"})
.when("/properties", {templateUrl: "partials/properties.html", controller: "PageCtrl"})
.when("/services", {templateUrl: "partials/services.html", controller: "PageCtrl"})
.when("/contact", {templateUrl: "partials/contact.html", controller: "PageCtrl"})
// Blog
.when("/blog", {templateUrl: "partials/blog.html", controller: "BlogCtrl"})
.when("/blog/post", {templateUrl: "partials/blog_item.html", controller: "BlogCtrl"})
.when("/sub", {templateUrl: "partials/search.html", controller: "PageCtrl"})
// else 404
.otherwise("/404", {templateUrl: "partials/404.html", controller: "PageCtrl"});
}]);
/**
* Controls the Blog
*/
app.controller('BlogCtrl', function ($scope, $location, $http ) {
console.log("Blog Controller reporting for duty.");
});
/**
* Controls all other Pages
*/
app.controller('myCtrl', function($scope,$http) {
console.log($scope.this.this);
$scope.sub= function(){
var data = $.param({
search: JSON.stringify({
zipcode: $scope.zipcode,
})
});
$http.post("/api/search", data).success(function(data, status) {
console.log('Data posted successfully');
})
}
});
app.controller('PageCtrl', function ( $scope, $location, $http ) {
console.log("Page Controller reporting for duty.");
// Activates the Carousel
$('.carousel').carousel({
interval: 5000
});
// Activates Tooltips for Social Links
$('.tooltip-social').tooltip({
selector: "a[data-toggle=tooltip]"
})
}); | Apeksha14/AngularAppExample | .history/public/js/main_20170501192448.js | JavaScript | unlicense | 2,084 |
import {_map, deepAccess, isArray, logWarn} from '../src/utils.js';
import {registerBidder} from '../src/adapters/bidderFactory.js';
import {auctionManager} from '../src/auctionManager.js';
import {BANNER, VIDEO} from '../src/mediaTypes.js';
import {Renderer} from '../src/Renderer.js';
import {find} from '../src/polyfill.js';
const BIDDER_CODE = 'hybrid';
const DSP_ENDPOINT = 'https://hbe198.hybrid.ai/prebidhb';
const TRAFFIC_TYPE_WEB = 1;
const PLACEMENT_TYPE_BANNER = 1;
const PLACEMENT_TYPE_VIDEO = 2;
const PLACEMENT_TYPE_IN_IMAGE = 3;
const TTL = 60;
const RENDERER_URL = 'https://acdn.adnxs.com/video/outstream/ANOutstreamVideo.js';
const placementTypes = {
'banner': PLACEMENT_TYPE_BANNER,
'video': PLACEMENT_TYPE_VIDEO,
'inImage': PLACEMENT_TYPE_IN_IMAGE
};
function buildBidRequests(validBidRequests) {
return _map(validBidRequests, function(validBidRequest) {
const params = validBidRequest.params;
const bidRequest = {
bidId: validBidRequest.bidId,
transactionId: validBidRequest.transactionId,
sizes: validBidRequest.sizes,
placement: placementTypes[params.placement],
placeId: params.placeId,
imageUrl: params.imageUrl || ''
};
return bidRequest;
})
}
const outstreamRender = bid => {
bid.renderer.push(() => {
window.ANOutstreamVideo.renderAd({
sizes: [bid.width, bid.height],
targetId: bid.adUnitCode,
rendererOptions: {
showBigPlayButton: false,
showProgressBar: 'bar',
showVolume: false,
allowFullscreen: true,
skippable: false,
content: bid.vastXml
}
});
});
}
const createRenderer = (bid) => {
const renderer = Renderer.install({
targetId: bid.adUnitCode,
url: RENDERER_URL,
loaded: false
});
try {
renderer.setRender(outstreamRender);
} catch (err) {
logWarn('Prebid Error calling setRender on renderer', err);
}
return renderer;
}
function buildBid(bidData) {
const bid = {
requestId: bidData.bidId,
cpm: bidData.price,
width: bidData.width,
height: bidData.height,
creativeId: bidData.bidId,
currency: bidData.currency,
netRevenue: true,
ttl: TTL,
meta: {
advertiserDomains: bidData.advertiserDomains || [],
}
};
if (bidData.placement === PLACEMENT_TYPE_VIDEO) {
bid.vastXml = bidData.content;
bid.mediaType = VIDEO;
let adUnit = find(auctionManager.getAdUnits(), function (unit) {
return unit.transactionId === bidData.transactionId;
});
if (adUnit) {
bid.width = adUnit.mediaTypes.video.playerSize[0][0];
bid.height = adUnit.mediaTypes.video.playerSize[0][1];
if (adUnit.mediaTypes.video.context === 'outstream') {
bid.renderer = createRenderer(bid);
}
}
} else if (bidData.placement === PLACEMENT_TYPE_IN_IMAGE) {
bid.mediaType = BANNER;
bid.inImageContent = {
content: {
content: bidData.content,
actionUrls: {}
}
};
let actionUrls = bid.inImageContent.content.actionUrls;
actionUrls.loadUrls = bidData.inImage.loadtrackers || [];
actionUrls.impressionUrls = bidData.inImage.imptrackers || [];
actionUrls.scrollActUrls = bidData.inImage.startvisibilitytrackers || [];
actionUrls.viewUrls = bidData.inImage.viewtrackers || [];
actionUrls.stopAnimationUrls = bidData.inImage.stopanimationtrackers || [];
actionUrls.closeBannerUrls = bidData.inImage.closebannertrackers || [];
if (bidData.inImage.but) {
let inImageOptions = bid.inImageContent.content.inImageOptions = {};
inImageOptions.hasButton = true;
inImageOptions.buttonLogoUrl = bidData.inImage.but_logo;
inImageOptions.buttonProductUrl = bidData.inImage.but_prod;
inImageOptions.buttonHead = bidData.inImage.but_head;
inImageOptions.buttonHeadColor = bidData.inImage.but_head_colour;
inImageOptions.dynparams = bidData.inImage.dynparams || {};
}
bid.ad = wrapAd(bid, bidData);
} else {
bid.ad = bidData.content;
bid.mediaType = BANNER;
}
return bid;
}
function getMediaTypeFromBid(bid) {
return bid.mediaTypes && Object.keys(bid.mediaTypes)[0]
}
function hasVideoMandatoryParams(mediaTypes) {
const isHasVideoContext = !!mediaTypes.video && (mediaTypes.video.context === 'instream' || mediaTypes.video.context === 'outstream');
const isPlayerSize =
!!deepAccess(mediaTypes, 'video.playerSize') &&
isArray(deepAccess(mediaTypes, 'video.playerSize'));
return isHasVideoContext && isPlayerSize;
}
function wrapAd(bid, bidData) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="https://st.hybrid.ai/prebidrenderer.js"></script>
<style>html, body {width: 100%; height: 100%; margin: 0;}</style>
</head>
<body>
<div data-hyb-ssp-in-image-overlay="${bidData.placeId}" style="width: 100%; height: 100%;"></div>
<script>
if (parent.window.frames[window.name]) {
var parentDocument = window.parent.document.getElementById(parent.window.frames[window.name].name);
parentDocument.style.height = "100%";
parentDocument.style.width = "100%";
}
var _content = "${encodeURIComponent(JSON.stringify(bid.inImageContent))}";
window._hyb_prebid_ssp.registerInImage(JSON.parse(decodeURIComponent(_content)));
</script>
</body>
</html>`;
}
export const spec = {
code: BIDDER_CODE,
supportedMediaTypes: [BANNER, VIDEO],
placementTypes: placementTypes,
/**
* Determines whether or not the given bid request is valid.
*
* @param {BidRequest} bid The bid params to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid(bid) {
return (
!!bid.params.placeId &&
!!bid.params.placement &&
(
(getMediaTypeFromBid(bid) === BANNER && bid.params.placement === 'banner') ||
(getMediaTypeFromBid(bid) === BANNER && bid.params.placement === 'inImage' && !!bid.params.imageUrl) ||
(getMediaTypeFromBid(bid) === VIDEO && bid.params.placement === 'video' && hasVideoMandatoryParams(bid.mediaTypes))
)
);
},
/**
* Make a server request from the list of BidRequests.
*
* @param {validBidRequests[]} - an array of bids
* @return ServerRequest Info describing the request to the server.
*/
buildRequests(validBidRequests, bidderRequest) {
const payload = {
url: bidderRequest.refererInfo.referer,
cmp: !!bidderRequest.gdprConsent,
trafficType: TRAFFIC_TYPE_WEB,
bidRequests: buildBidRequests(validBidRequests)
};
if (payload.cmp) {
const gdprApplies = bidderRequest.gdprConsent.gdprApplies;
if (gdprApplies !== undefined) payload['ga'] = gdprApplies;
payload['cs'] = bidderRequest.gdprConsent.consentString;
}
const payloadString = JSON.stringify(payload);
return {
method: 'POST',
url: DSP_ENDPOINT,
data: payloadString,
options: {
contentType: 'application/json'
}
}
},
/**
* Unpack the response from the server into a list of bids.
*
* @param {ServerResponse} serverResponse A successful response from the server.
* @return {Bid[]} An array of bids which were nested inside the server.
*/
interpretResponse: function(serverResponse, bidRequest) {
let bidRequests = JSON.parse(bidRequest.data).bidRequests;
const serverBody = serverResponse.body;
if (serverBody && serverBody.bids && isArray(serverBody.bids)) {
return _map(serverBody.bids, function(bid) {
let rawBid = find(bidRequests, function (item) {
return item.bidId === bid.bidId;
});
bid.placement = rawBid.placement;
bid.transactionId = rawBid.transactionId;
bid.placeId = rawBid.placeId;
return buildBid(bid);
});
} else {
return [];
}
}
}
registerBidder(spec);
| prebid/Prebid.js | modules/hybridBidAdapter.js | JavaScript | apache-2.0 | 8,044 |
/*
Copyright 2017 Kurt Wagner. All rights reserved
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.
*/
'use strict';
/* eslint-disable max-len */
/* eslint-env node */
module.exports = {
getLocalBrowsers: getLocalBrowsers,
};
function getLocalBrowsers() {
const seleniumAssistant = require('selenium-assistant');
return seleniumAssistant.getLocalBrowsers().filter((browserInfo) => {
return browserInfo.getId() === 'chrome' ||
(browserInfo.getId() === 'firefox' && browserInfo.getVersionNumber() >= 50);
});
}
| KurtWagner/sw-navigation-prefetch | test/helpers/get-local-browsers.js | JavaScript | apache-2.0 | 1,003 |
angular
.module('sbAdminApp.protocol', [
'oc.lazyLoad',
'ui.router',
'ui.bootstrap',
'angular-loading-bar',
'ngFileUpload'
])
.config(['$stateProvider', '$urlRouterProvider', '$ocLazyLoadProvider', function ($stateProvider, $urlRouterProvider, $ocLazyLoadProvider) {
$ocLazyLoadProvider.config({
debug: false,
events: true,
});
$stateProvider
.state('dashboard.protocol-list',{
templateUrl:'views/protocol/search-protocol.html',
url:'/protocol/search',
controller:'protocolController'
})
.state('dashboard.add-protocol',{
templateUrl:'views/protocol/create-protocol.html',
url:'/protocol/add',
controller:'protocolController'
})
}])
.controller('protocolController',['$scope','$http', 'Upload', '$timeout', function($scope,$http, Upload, $timeout) {
$scope.upload = function(file) {
alert(file);
file.upload = Upload.upload({
url: 'http://10.32.34.38:8083/uploadPrikey',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
fields: {tenantCode: 1111},
file: file,
fileFormDataName: 'file'
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
});
file.upload.progress(function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
}]);
| BrianMa2014/payment-admin-ui | app/scripts/controllers/protocol.js | JavaScript | apache-2.0 | 2,032 |
/*
* Copyright 2021 Google LLC
*
* 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
*
* https://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.
*/
/**
* External dependencies
*/
import { waitFor } from '@testing-library/react';
import { DATA_VERSION } from '@googleforcreators/migration';
/**
* Internal dependencies
*/
import { Fixture } from '../../../karma';
import { useInsertElement } from '../../canvas';
import { ACCESSIBILITY_COPY, DESIGN_COPY, PRIORITY_COPY } from '../constants';
describe('Checklist integration', () => {
let fixture;
beforeEach(async () => {
fixture = new Fixture();
await fixture.render();
await fixture.collapseHelpCenter();
});
afterEach(() => {
fixture.restore();
});
const emptyContent = () => {
return fixture.screen.queryByText(
/You are all set for now. Return to this checklist as you build your Web Story for tips on how to improve it./
);
};
const addPages = async (count) => {
let clickCount = 1;
while (clickCount <= count) {
// eslint-disable-next-line no-await-in-loop
await fixture.events.click(fixture.editor.canvas.pageActions.addPage);
// eslint-disable-next-line no-await-in-loop, no-loop-func
await waitFor(() => {
if (!fixture.editor.footer.carousel.pages.length) {
throw new Error('page not yet added');
}
expect(fixture.editor.footer.carousel.pages.length).toBe(
clickCount + 1
);
});
clickCount++;
}
};
const openChecklist = async () => {
const { toggleButton } = fixture.editor.checklist;
await fixture.events.click(toggleButton);
// wait for animation
await fixture.events.sleep(500);
};
/**
* Inserts an image without assistive text. This will trigger
* an a11y issue in the checklist.
*/
const addAccessibilityIssue = async () => {
const insertElement = await fixture.renderHook(() => useInsertElement());
await fixture.act(() =>
insertElement('image', {
x: 0,
y: 0,
width: 640 / 2,
height: 529 / 2,
resource: {
type: 'image',
mimeType: 'image/jpg',
src: 'http://localhost:9876/__static__/earth.jpg',
alt: '',
width: 640,
height: 529,
baseColor: '#734727',
},
})
);
};
const openChecklistWithKeyboard = async () => {
const { toggleButton } = fixture.editor.checklist;
await fixture.events.focus(toggleButton);
await fixture.events.keyboard.press('Enter');
// wait for animation
await fixture.events.sleep(500);
};
describe('initial state', () => {
it('should begin with empty message on a new story', async () => {
await openChecklist();
const emptyMessage = fixture.screen.getByText(
'You are all set for now. Return to this checklist as you build your Web Story for tips on how to improve it.'
);
expect(emptyMessage).toBeTruthy();
});
});
describe('open and close', () => {
it('should toggle the checklist', async () => {
const { toggleButton } = fixture.editor.checklist;
await fixture.events.click(toggleButton);
// wait for animation
await fixture.events.sleep(500);
expect(
fixture.editor.checklist.issues.getAttribute('data-isexpanded')
).toBe('true');
await fixture.events.click(toggleButton);
// wait for animation
await fixture.events.sleep(500);
});
it('should close the checklist when the "close" button is clicked', async () => {
await openChecklist();
await fixture.events.click(fixture.editor.checklist.closeButton);
await fixture.events.sleep(500);
});
});
describe('Checklist aXe tests', () => {
it('should have no aXe violations with empty message on a new story', async () => {
await openChecklist();
await expectAsync(fixture.editor.checklist.node).toHaveNoViolations();
});
it('should have no aXe violations with checks present', async () => {
await addPages(4);
await addAccessibilityIssue();
await openChecklist();
await expectAsync(fixture.editor.checklist.node).toHaveNoViolations();
});
});
describe('Checklist cursor interaction', () => {
it('should open the high priority section by default when 4 pages are added to the story', async () => {
// need to add some pages, the add page button is under the checklist so do this before expanding
await addPages(4);
await openChecklist();
expect(fixture.editor.checklist.priorityPanel).toBeDefined();
});
it('should open the design section when clicked', async () => {
// need to add some pages, the add page button is under the checklist so do this before expanding
await addPages(4);
await openChecklist();
await fixture.events.click(fixture.editor.checklist.designTab);
expect(fixture.editor.checklist.designPanel).toBeDefined();
});
it('should open the design section by default when 2 pages are added to the story', async () => {
// need to add some pages, the add page button is under the checklist so do this before expanding
await addPages(2);
await openChecklist();
expect(fixture.editor.checklist.designPanel).toBeDefined();
});
it('should open the accessibility section', async () => {
// need to add some pages, the add page button is under the checklist so do this before expanding
await addPages(2);
await addAccessibilityIssue();
await openChecklist();
await fixture.events.click(fixture.editor.checklist.accessibilityTab);
expect(fixture.editor.checklist.accessibilityPanel).toBeDefined();
});
});
describe('Checklist keyboard interaction', () => {
it('should toggle the Checklist with keyboard', async () => {
await fixture.events.focus(fixture.editor.checklist.toggleButton);
await fixture.events.keyboard.press('Enter');
// wait for animation
await fixture.events.sleep(500);
expect(
fixture.editor.checklist.issues.getAttribute('data-isexpanded')
).toBe('true');
await fixture.events.keyboard.press('Enter');
// wait for animation
await fixture.events.sleep(500);
});
it('should close the Checklist when pressing enter on the "close" button', async () => {
await openChecklistWithKeyboard();
// will already be focused on the close button
expect(
fixture.editor.checklist.issues.getAttribute('data-isexpanded')
).toBe('true');
expect(fixture.editor.checklist.closeButton).toEqual(
document.activeElement
);
await fixture.events.keyboard.press('Enter');
await fixture.events.sleep(500);
});
it('should open the tab panels with tab and enter', async () => {
// need to add some pages, the add page button is under the checklist so do this before expanding
await addPages(4);
await openChecklistWithKeyboard();
// tab to priority section
await fixture.events.keyboard.press('tab');
await fixture.events.keyboard.press('Enter');
expect(fixture.editor.checklist.priorityPanel).toBeDefined();
expect(fixture.editor.checklist.designPanel).toBeNull();
expect(fixture.editor.checklist.accessibilityPanel).toBeNull();
// tab to design section
await fixture.events.keyboard.press('tab');
await fixture.events.keyboard.press('Enter');
expect(fixture.editor.checklist.priorityPanel).toBeNull();
expect(fixture.editor.checklist.designPanel).toBeDefined();
expect(fixture.editor.checklist.accessibilityPanel).toBeNull();
// add accessibility section
await addAccessibilityIssue();
// tab to accessibility section
let tabCount = 1;
while (
tabCount < 4 &&
fixture.editor.checklist.accessibilityTab !== document.activeElement
) {
// eslint-disable-next-line no-await-in-loop
await fixture.events.keyboard.press('tab');
tabCount++;
}
await fixture.events.keyboard.press('Enter');
expect(fixture.editor.checklist.priorityPanel).toBeNull();
expect(fixture.editor.checklist.designPanel).toBeNull();
expect(fixture.editor.checklist.accessibilityPanel).toBeDefined();
});
});
describe('Checkpoints', () => {
it('empty story should begin in the empty state', async () => {
await openChecklist();
const { priorityPanel, designPanel, accessibilityPanel } =
fixture.editor.checklist;
expect(await emptyContent()).toBeDefined();
expect(priorityPanel).toBeNull();
expect(designPanel).toBeNull();
expect(accessibilityPanel).toBeNull();
});
it('should expand the design panel after adding 2 pages', async () => {
await addPages(1);
await openChecklist();
const {
expandedDesignTab,
priorityPanel,
designPanel,
accessibilityPanel,
} = fixture.editor.checklist;
expect(await emptyContent()).toBeNull();
expect(priorityPanel).toBeNull();
expect(designPanel).toBeDefined();
expect(accessibilityPanel).toBeNull();
expect(expandedDesignTab).toBeDefined();
});
it('should add the accessibility panel after adding 2 pages if there is an a11y problem. This will not open the panel.', async () => {
await addPages(1);
await openChecklist();
await addAccessibilityIssue();
const {
priorityPanel,
designPanel,
accessibilityPanel,
expandedDesignTab,
} = fixture.editor.checklist;
expect(await emptyContent()).toBeNull();
expect(priorityPanel).toBeNull();
expect(designPanel).toBeDefined();
expect(accessibilityPanel).toBeDefined();
expect(expandedDesignTab).toBeDefined();
});
it('should expand the priority panel after adding 5 pages', async () => {
await addPages(4);
await openChecklist();
const {
expandedPriorityTab,
priorityPanel,
designPanel,
accessibilityPanel,
} = fixture.editor.checklist;
expect(await emptyContent()).toBeNull();
expect(priorityPanel).toBeDefined();
expect(designPanel).toBeDefined();
expect(accessibilityPanel).toBeNull();
expect(expandedPriorityTab).toBeDefined();
});
});
describe('checklist should have no aXe accessibility violations', () => {
it('should have no aXe violations with with a closed checklist', async () => {
await expectAsync(fixture.editor.checklist.node).toHaveNoViolations();
});
it('should have no aXe violations with an open empty checklist', async () => {
await openChecklist();
await expectAsync(fixture.editor.checklist.node).toHaveNoViolations();
});
it('should have no aXe violations with a open non-empty checklist', async () => {
await addPages(4);
await openChecklist();
await expectAsync(fixture.editor.checklist.node).toHaveNoViolations();
});
});
it('should open the checklist after following "review checklist" button in dialog on publishing story', async () => {
fixture.events.click(fixture.editor.titleBar.publish);
// Ensure the debounced callback has taken effect.
await fixture.events.sleep(800);
const reviewButton = await fixture.screen.getByRole('button', {
name: /^Review Checklist$/,
});
await fixture.events.click(reviewButton);
// This is the initial load of the checklist tab so we need to wait for it to load
// before we can see tabs.
await fixture.events.sleep(300);
expect(
fixture.editor.checklist.issues.getAttribute('data-isexpanded')
).toBe('true');
expect(fixture.editor.checklist.priorityPanel).toBeDefined();
});
});
describe('Checklist integration - Card visibility', () => {
let fixture;
const priorityIssuesRequiringMediaUploadPermissions = [
PRIORITY_COPY.storyMissingPoster.title,
PRIORITY_COPY.videoMissingPoster.title,
];
// issues that show if there is a poster image
const posterIssuesRequiringMediaUploadPermissions = [
PRIORITY_COPY.storyPosterSize.title,
];
const designIssuesRequiringMediaUploadPermissions = [
DESIGN_COPY.videoResolutionTooLow.title,
DESIGN_COPY.imageResolutionTooLow.title,
];
const accessibilityIssuesRequiringMediaUploadPermissions = [
ACCESSIBILITY_COPY.videoMissingCaptions.title,
];
beforeEach(() => {
// mock the wordpress media explorer
const media = () => ({
state: () => ({
get: () => ({
first: () => ({
toJSON: () => ({
id: 10,
type: 'image',
mimeType: 'image/jpg',
src: 'http://localhost:9876/__static__/earth.jpg',
alt: 'earth',
width: 640,
height: 529,
baseColor: '#734727',
}),
}),
}),
}),
on: (_type, callback) => callback(),
once: (_type, callback) =>
callback({
id: 10,
type: 'image',
mimeType: 'image/jpg',
src: 'http://localhost:9876/__static__/earth.jpg',
alt: 'earth',
width: 640,
height: 529,
baseColor: '#734727',
}),
open: () => {},
close: () => {},
setState: () => {},
});
class Library {}
class Cropper {
extend() {
return class ExtendedCropper {};
}
}
media.controller = {
Cropper,
Library,
};
media.query = () => {};
// Create fake media browser
window.wp = {
...window.wp,
media,
};
});
const addPages = async (count) => {
let clickCount = 1;
while (clickCount <= count) {
// eslint-disable-next-line no-await-in-loop
await fixture.events.click(fixture.editor.canvas.pageActions.addPage);
// eslint-disable-next-line no-await-in-loop, no-loop-func
await waitFor(() => {
if (!fixture.editor.footer.carousel.pages.length) {
throw new Error('page not yet added');
}
expect(fixture.editor.footer.carousel.pages.length).toBe(
clickCount + 1
);
});
clickCount++;
}
};
const openChecklist = async () => {
const { toggleButton } = fixture.editor.checklist;
await fixture.events.click(toggleButton);
// wait for animation
await fixture.events.sleep(500);
};
/**
* Inserts an image that has
* - width less than the minimum allowed image width (2 times element width)
* - height less than the minimum allowed image height (2 times element height)
*
* This will trigger an a11y issue in the checklist.
*/
const addImageWithIssues = async () => {
const insertElement = await fixture.renderHook(() => useInsertElement());
await fixture.act(() =>
insertElement('image', {
x: 0,
y: 0,
width: 640 / 2,
height: 529 / 2,
resource: {
id: 10,
type: 'image',
mimeType: 'image/jpg',
src: 'http://localhost:9876/__static__/earth.jpg',
alt: 'earth',
width: 640,
height: 529,
baseColor: '#734727',
},
})
);
};
/**
* Inserts a video that has
* - no poster image
* - width less than the minimum allowed video width
* - height less than the minimum allowed video height
*
* This will trigger an a11y issue in the checklist.
*/
const addVideoWithIssues = async () => {
const insertElement = await fixture.renderHook(() => useInsertElement());
await fixture.act(() =>
insertElement('video', {
resource: {
type: 'video',
mimeType: 'video/webm',
creationDate: '2021-05-21T00:09:18',
src: 'http://localhost:8899/wp-content/uploads/2021/05/small-video-10.webm',
// resolution too low
height: 220,
width: 320,
// no poster image
poster: null,
posterId: null,
id: 10,
length: 6,
lengthFormatted: '0:06',
title: 'small-video',
alt: 'small-video',
isOptimized: false,
baseColor: '#734727',
},
controls: false,
loop: false,
autoPlay: true,
tracks: [],
type: 'video',
x: 66,
y: 229,
width: 280,
height: 160,
id: '6e7f5de8-7793-4aef-8835-c1d32477b4e0',
})
);
};
describe('hasUploadMediaAction=false', () => {
beforeEach(async () => {
fixture = new Fixture({
mocks: {
getStoryById: () =>
Promise.resolve({
title: { raw: '' },
status: 'draft',
author: 1,
slug: '',
date: '2020-05-06T22:32:37',
dateGmt: '2020-05-06T22:32:37',
modified: '2020-05-06T22:32:37',
excerpt: { raw: '' },
link: 'http://stories.local/?post_type=web-story&p=1',
previewLink: 'http://stories.local/?post_type=web-story&p=1',
storyData: {
version: DATA_VERSION,
pages: [],
},
featuredMedia: 2,
permalinkTemplate: 'http://stories3.local/stories/%pagename%/',
stylePresets: { textStyles: [], colors: [] },
password: '',
}),
},
});
fixture.setFlags({ enableChecklistCompanion: true });
fixture.setConfig({ capabilities: { hasUploadMediaAction: false } });
await fixture.render();
});
afterEach(() => {
fixture.restore();
});
/**
* Check if a card is not visible in the application.
*
* @param {string} title Title of the card
*/
const checkIfCardDoesNotExist = async (title) => {
const card = await fixture.screen.queryByText(title);
expect(card).toBeNull();
};
it(`should not show cards that require the \`hasUploadMediaAction\` permission`, async () => {
// add issues to checklist that need to be resolved by uploading media
await addImageWithIssues();
await addVideoWithIssues();
// show all checkpoints
await addPages(4);
await openChecklist();
priorityIssuesRequiringMediaUploadPermissions.forEach(
checkIfCardDoesNotExist
);
posterIssuesRequiringMediaUploadPermissions.forEach(
checkIfCardDoesNotExist
);
// open design tab
await fixture.events.click(fixture.editor.checklist.designTab);
designIssuesRequiringMediaUploadPermissions.forEach(
checkIfCardDoesNotExist
);
accessibilityIssuesRequiringMediaUploadPermissions.forEach(
checkIfCardDoesNotExist
);
});
});
});
| GoogleForCreators/web-stories-wp | packages/story-editor/src/components/checklist/karma/checklist.karma.js | JavaScript | apache-2.0 | 19,426 |
/* Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. */
/******************************************************************************
*
* You may not use the identified files except in compliance with the Apache
* License, Version 2.0 (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.
*
* NAME
* 191. currentSchema.js
*
* DESCRIPTION
* Test the "connection.currentSchema" property.
*
*****************************************************************************/
'use strict';
const oracledb = require('oracledb');
const should = require('should');
const dbconfig = require('./dbconfig.js');
const testsUtil = require('./testsUtil.js');
describe('191. currentSchema.js', function() {
let isRunnable = false;
before(async function() {
isRunnable = await testsUtil.checkPrerequisites();
if (!isRunnable) {
this.skip();
return;
}
});
it('191.1 the value will be empty until it has been explicitly set', async () => {
try {
const conn = await oracledb.getConnection(dbconfig);
should.strictEqual(conn.currentSchema, '');
let schema = dbconfig.user;
conn.currentSchema = schema;
should.strictEqual(conn.currentSchema, schema);
await conn.close();
} catch(err) {
should.not.exist(err);
}
}); // 191.1
it('191.2 SQL alternative', async () => {
try {
const conn = await oracledb.getConnection(dbconfig);
let schema = dbconfig.user.toUpperCase();
let query = "ALTER SESSION SET CURRENT_SCHEMA = " + schema;
await conn.execute(query);
should.strictEqual(conn.currentSchema, schema);
await conn.close();
} catch(err) {
should.not.exist(err);
}
}); // 191.2
it('191.3 Negative - can not set inexistent schema', async () => {
async function setInvalidSchema() {
const conn = await oracledb.getConnection(dbconfig);
let schema = "foo";
conn.currentSchema = schema;
await conn.close();
}
await testsUtil.assertThrowsAsync(
async () => await setInvalidSchema(),
/ORA-01435/
);
// ORA-01435: user does not exist
}); // 191.3
});
| oracle/Node-oracledb | test/currentSchema.js | JavaScript | apache-2.0 | 2,571 |
var maxSDHAnzahl;
var maxTWAnzahl;
var maxTPAnzahl;
function showClassInfo(elem, number, event) {
setClassInfoText(number + ' elements on unit');
showClassInfoDiv();
positionClassInfoDiv(event);
}
function setClassInfoText(text) {
var classInfoDiv = document.getElementById('classInfoDiv');
while (classInfoDiv.lastChild != null) {
classInfoDiv.removeChild(classInfoDiv.lastChild);
}
classInfoDiv.appendChild(document.createTextNode(text));
var w = Math.ceil(text.length * 0.6);
classInfoDiv.style.width = w + "em";
}
function showClassInfoDiv() {
var classInfoDiv = document.getElementById('classInfoDiv');
classInfoDiv.style.display = 'block';
}
function hideClassInfoDiv() {
var classInfoDiv = document.getElementById('classInfoDiv');
classInfoDiv.style.display = 'none';
}
function positionClassInfoDiv(event) {
var classInfoDiv = document.getElementById('classInfoDiv');
var values = getPositionForMouseObject(event);
classInfoDiv.style.top = values[1];
classInfoDiv.style.left = values[0];
}
// JS code for the mouse over information of the mapped input vectors
function showInputInfo(elem, qe, mqe, dist, unit, event) {
setInputInfoText(qe, mqe, dist, unit);
showInputInfoDiv();
positionInputInfoDiv(event);
}
function setInputInfoText(qe, mqe, dist, unit) {
var inputInfoDiv = document.getElementById('inputInfoDiv');
var inputfield;
inputfield = document.getElementById('inputInfoDiv_qe');
while (inputfield.lastChild != null) {
inputfield.removeChild(inputfield.lastChild);
}
inputfield.appendChild(document.createTextNode(qe));
inputfield = document.getElementById('inputInfoDiv_mqe');
while (inputfield.lastChild != null) {
inputfield.removeChild(inputfield.lastChild);
}
inputfield.appendChild(document.createTextNode(mqe));
inputfield = document.getElementById('inputInfoDiv_dist');
while (inputfield.lastChild != null) {
inputfield.removeChild(inputfield.lastChild);
}
inputfield.appendChild(document.createTextNode(dist));
inputfield = document.getElementById('inputInfoDiv_unit');
while (inputfield.lastChild != null) {
inputfield.removeChild(inputfield.lastChild);
}
inputfield.appendChild(document.createTextNode(unit));
}
function showInputInfoDiv() {
var inputInfoDiv = document.getElementById('inputInfoDiv');
inputInfoDiv.style.display = 'block';
}
function hideInputInfoDiv() {
var inputInfoDiv = document.getElementById('inputInfoDiv');
inputInfoDiv.style.display = 'none';
}
function positionInputInfoDiv(event) {
var inputInfoDiv = document.getElementById('inputInfoDiv');
var values = getPositionForMouseObject(event);
inputInfoDiv.style.top = values[1];
inputInfoDiv.style.left = values[0];
}
// helper function
function getPositionForMouseObject(event) {
if (!event) {
event = window.event;
}
var yoffset = 0;
if (window.pageYOffset > 0) {
yoffset = window.pageYOffset;
} else {
yoffset = document.documentElement.scrollTop;
}
var xoffset = 0;
if (window.pageXOffset > 0) {
xoffset = window.pageXOffset;
} else {
xoffset = document.documentElement.scrollLeft;
}
var x = event.clientX + 20 + xoffset + 'px';
if (this.status == 2) {
x = event.clientX - 20 - 550 - xoffset + 'px';
}
return new Array(x, event.clientY + yoffset + 'px');
}
// JS function for expanding and collapsing the cluster tree
function swapClusterDisp(level) {
var content = document.getElementById("clusterNode_" + level);
if (content.style.display == "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
}
// JS function for expanding the classlist within a cluster
function showClassesInCluster(level, runId) {
var content = document.getElementById("classes_" + level + "_" + runId);
if (content.style.display == "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
}
// JS function for showing the descriptions from the individual Visualizations
function showVisualisationDescriptions(text) {
desc_win = window.open("", "", "width=600,height=300,scrollbars=yes,resizable=yes");
desc_win.document.write(text);
desc_win.document.close();
}
// JS helper function for initializing the SDH, TP and TW array
function initSDH() {
for (i = 0; i < sdhArray.length; i++) {
sdhArray[i] = 1;
}
}
function initTP() {
for (i = 0; i < tpArray.length; i++) {
tpArray[i] = 1;
}
}
function initTW() {
for (i = 0; i < twArray.length; i++) {
twArray[i] = 1;
}
}
function setMaxAnzahlSDH(max) {
maxSDHAnzahl = max
}
function setMaxAnzahlTW(max) {
maxTWAnzahl = max
}
function setMaxAnzahlTP(max) {
maxTPAnzahl = max
}
// JSfunction for showing the SDH,TP & TW Images
function nextSDH(runId, step) {
if (sdhArray[runId] >= maxSDHAnzahl) {
document.getElementById("sdh_" + runId + "_" + sdhArray[runId]).style.display = 'none';
document.getElementById("sdh_" + runId + "_" + 1).style.display = 'block';
sdhArray[runId] = 1;
} else {
document.getElementById("sdh_" + runId + "_" + sdhArray[runId]).style.display = 'none';
document.getElementById("sdh_" + runId + "_" + (sdhArray[runId] + step)).style.display = 'block';
sdhArray[runId] += step;
}
}
function prevSDH(runId, step) {
if (sdhArray[runId] <= 1) {
document.getElementById("sdh_" + runId + "_" + 1).style.display = 'none';
document.getElementById("sdh_" + runId + "_" + maxSDHAnzahl).style.display = 'block';
sdhArray[runId] = maxSDHAnzahl;
} else {
document.getElementById("sdh_" + runId + "_" + sdhArray[runId]).style.display = 'none';
document.getElementById("sdh_" + runId + "_" + (sdhArray[runId] - step)).style.display = 'block';
sdhArray[runId] -= step;
}
}
function nextTP(runId, step) {
if (tpArray[runId] >= maxTPAnzahl) {
document.getElementById("tp_" + runId + "_" + tpArray[runId]).style.display = 'none';
document.getElementById("tp_" + runId + "_" + 1).style.display = 'block';
tpArray[runId] = 1;
} else {
document.getElementById("tp_" + runId + "_" + tpArray[runId]).style.display = 'none';
document.getElementById("tp_" + runId + "_" + (tpArray[runId] + step)).style.display = 'block';
tpArray[runId] += step;
}
}
function prevTP(runId, step) {
if (tpArray[runId] <= 1) {
document.getElementById("tp_" + runId + "_" + 1).style.display = 'none';
document.getElementById("tp_" + runId + "_" + maxTPAnzahl).style.display = 'block';
tpArray[runId] = maxTPAnzahl;
} else {
document.getElementById("tp_" + runId + "_" + tpArray[runId]).style.display = 'none';
document.getElementById("tp_" + runId + "_" + (tpArray[runId] - step)).style.display = 'block';
tpArray[runId] -= step;
}
}
function nextTW(runId, step) {
if (twArray[runId] >= maxTWAnzahl) {
document.getElementById("tw_" + runId + "_" + twArray[runId]).style.display = 'none';
document.getElementById("tw_" + runId + "_" + 1).style.display = 'block';
twArray[runId] = 1;
} else {
document.getElementById("tw_" + runId + "_" + twArray[runId]).style.display = 'none';
document.getElementById("tw_" + runId + "_" + (twArray[runId] + step)).style.display = 'block';
twArray[runId] += step;
}
}
function prevTW(runId, step) {
if (twArray[runId] <= 1) {
document.getElementById("tw_" + runId + "_" + 1).style.display = 'none';
document.getElementById("tw_" + runId + "_" + maxTWAnzahl).style.display = 'block';
twArray[runId] = maxTWAnzahl;
} else {
document.getElementById("tw_" + runId + "_" + twArray[runId]).style.display = 'none';
document.getElementById("tw_" + runId + "_" + (twArray[runId] - step)).style.display = 'block';
twArray[runId] -= step;
}
}
// Functions to display Semantic Classes
function showSemanticClassesinRegion(text, index, runId) {
var content = document.getElementById("classes_" + text + "_" + index + "_" + runId);
if (content.style.display == "none") {
content.style.display = "block";
} else {
content.style.display = "none";
}
}
function showSemanticDescription(text) {
top.consoleRef = window.open('', 'myconsole', 'width=450', 'height=550', 'menubar=0', 'toolbar=1', 'status=0',
'scrollbars=1', 'resizable=1');
top.consoleRef.document.writeln('<html><head><title>Console</title></head>'
+ '<script LANGUAGE="JavaScript" TYPE="text/javascript" src="reporter.js"></script>'
+ '<body bgcolor=white onLoad="self.focus()">' + text + '</body></html>');
top.consoleRef.document.close();
}
| vbuendia/lfsom | lfsom/contents/libraries/G4P/library/rsc/reportGenerator/reporter.js | JavaScript | apache-2.0 | 9,022 |
module.exports = {
up(queryInterface, Sequelize) {
return queryInterface.createTable('Upvotes', {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.INTEGER
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
userId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Users',
key: 'id',
as: 'userId',
}
},
recipeId: {
type: Sequelize.INTEGER,
onDelete: 'CASCADE',
references: {
model: 'Recipes',
key: 'id',
as: 'recipeId',
}
}
});
},
down(queryInterface /* , Sequelize */) {
return queryInterface.dropTable('Upvotes');
}
};
| larrystone/BC-26-More-Recipes | server/migrations/20170903211231-create-upvote.js | JavaScript | apache-2.0 | 900 |
/*
* Copyright (c) 2016 highstreet technologies GmbH and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
define(['app/mwtnSpectrum/mwtnSpectrum.module','app/mwtnSpectrum/mwtnSpectrum.services','app/mwtnCommons/mwtnCommons.services'], function(mwtnSpectrumApp) {
mwtnSpectrumApp.register.controller('mwtnSpectrumCtrl', ['$scope', '$rootScope', '$mwtnSpectrum', '$mwtnCommons', '$mwtnLog', function($scope, $rootScope, $mwtnSpectrum, $mwtnCommons, $mwtnLog) {
$rootScope['section_logo'] = 'src/app/mwtnSpectrum/images/mwtnSpectrum.png'; // Add your topbar logo location here such as 'assets/images/logo_topology.gif'
$scope.mwtnSpectrumInfo = {};
$mwtnCommons.getData(function(data){
$scope.data = data;
});
}]);
});
| demx8as6/CENTENNIAL | 03-WTP-PoC/code/ux/mwtnSpectrum/mwtnSpectrum-module/src/main/resources/mwtnSpectrum/mwtnSpectrum.controller.js | JavaScript | apache-2.0 | 967 |
'use strict';
describe('Controller: AddstationCtrl', function () {
// load the controller's module
beforeEach(module('clientApp'));
var AddstationCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
AddstationCtrl = $controller('AddstationCtrl', {
$scope: scope
});
}));
it('should attach a list of awesomeThings to the scope', function () {
expect(scope.awesomeThings.length).toBe(3);
});
});
| bonds0097/eliteauthority | client/test/spec/controllers/addstation.js | JavaScript | apache-2.0 | 529 |
'use strict';
angular.module('jhipsterApp')
.config(function ($stateProvider) {
$stateProvider
.state('sessions', {
parent: 'account',
url: '/sessions',
data: {
roles: ['ROLE_USER'],
pageTitle: 'Sessions'
},
views: {
'content@': {
templateUrl: 'scripts/app/account/sessions/sessions.html',
controller: 'SessionsController'
}
},
resolve: {
}
});
});
| gmarziou/jhipster-ionic | server/src/main/webapp/scripts/app/account/sessions/sessions.js | JavaScript | apache-2.0 | 667 |
var eslint = require('gulp-eslint');
module.exports = function (gulp) {
/**
* Lints the javascript
* @name eslint
* @memberof build.tasks
*/
gulp.task('eslint', function () {
return gulp.src(['./src/js/**/*.js'])
.pipe(eslint())
});
};
| jewetnitg/edia-frontend-build-proposal | tasks/eslint.js | JavaScript | apache-2.0 | 265 |
import React, { PureComponent } from 'react';
import Modal from 'react-native-modal';
import {
Container,
Content,
Body,
Button,
Footer,
FooterTab,
Header,
Text,
Title
} from 'native-base';
import style from './styles/content_group_editor';
class ContentGroupEditor extends PureComponent {
render() {
const { visible, onClose } = this.props;
return (
<Modal
isVisible={visible}
onBackButtonPress={onClose}
onBackdropPress={onClose} >
<Container>
<Header>
<Body>
<Title>HAHAHAHA</Title>
</Body>
</Header>
<Content>
<Text>ABCDEFG</Text>
</Content>
<Footer style={style.footer}>
<Button block light onPress={onClose}>
<Text>Cancel</Text>
</Button>
<Button
block
info
style={style.confirmButton}
onPress={onClose}>
<Text>Create</Text>
</Button>
</Footer>
</Container>
</Modal>
);
}
}
export default ContentGroupEditor;
| Vosie/QianLiYan | src/components/ContentGroupEditor.js | JavaScript | apache-2.0 | 1,474 |
_exportHelpers = {
/**
*
* Returns the export templates that are defined on this table.
* NOTE If this returns `null`, then the exportTemplates is not defined on the table or schema
* NOTE The returned array should not be directly used as it might be using fragments
* @param {ERMrest.Table} table
* @param {string} context
* @private
* @ignore
*/
getExportAnnotTemplates: function (table, context) {
var exp = module._annotations.EXPORT,
expCtx = module._annotations.EXPORT_CONTEXTED,
annotDefinition = {}, hasAnnot = false,
chosenAnnot, templates = [];
// start from table, then try schema, and then catalog
[table, table.schema, table.schema.catalog].forEach(function (el) {
if (hasAnnot) return;
// get from table annotation
if (el.annotations.contains(exp)) {
annotDefinition = {"*": el.annotations.get(exp).content};
hasAnnot = true;
}
// get from table contextualized annotation
if (el.annotations.contains(expCtx)) {
annotDefinition = Object.assign({}, annotDefinition, el.annotations.get(expCtx).content);
hasAnnot = true;
}
if (hasAnnot) {
// find the annotation defined for the context
chosenAnnot = module._getAnnotationValueByContext(context, annotDefinition);
// not defined for the context
if (chosenAnnot === -1) {
hasAnnot = false;
}
// make sure it's the correct format
else if (isObjectAndNotNull(chosenAnnot) && ("templates" in chosenAnnot) && Array.isArray(chosenAnnot.templates)) {
templates = chosenAnnot.templates;
}
}
});
if (hasAnnot) {
return templates;
}
return null;
},
/**
* Return the export fragments that should be used with export annotation.
* @param {ERMrest.Table} table
* @param {Object} defaultExportTemplate
* @returns An object that can be used in combination with export annotation
* @private
* @ignore
*/
getExportFragmentObject: function (table, defaultExportTemplate) {
var exportFragments = {
"$chaise_default_bdbag_template": {
"type": "BAG",
"displayname": {"fragment_key": "$chaise_default_bdbag_displayname"},
"outputs": [{"fragment_key": "$chaise_default_bdbag_outputs"}]
},
"$chaise_default_bdbag_displayname": "BDBag",
"$chaise_default_bdbag_outputs": defaultExportTemplate ? defaultExportTemplate.outputs : null
};
var annotKey = module._annotations.EXPORT_FRAGMENT_DEFINITIONS, annot;
[table.schema.catalog, table.schema, table].forEach(function (el) {
if (!el.annotations.contains(annotKey)) return;
annot = el.annotations.get(annotKey).content;
if (isObjectAndNotNull(annot)) {
// remove the keys that start with $
Object.keys(annot).filter(function (k) {
return k.startsWith("$");
}).forEach(function (k) {
module._log.warn("Export: ignoring `" + k + "` fragment as it cannot start with $.");
delete annot[k];
});
Object.assign(exportFragments, annot);
}
});
return exportFragments;
},
/**
* Replace the fragments used in templates with actual definition
* @param {Array} templates the template definitions
* @param {*} exportFragments the fragment object
* @returns An array of templates that should be validated and used
* @private
* @ignore
*/
replaceFragments: function (templates, exportFragments) {
var hasError;
// traverse through the object and replace fragment with the actual definition
var _replaceFragments = function (obj, usedFragments) {
if (hasError) return null;
if (!usedFragments) {
usedFragments = {};
}
var res, intRes;
// if it's an array, then we have to process each individual value
if (Array.isArray(obj)) {
res = [];
obj.forEach(function (item) {
// flatten the values and just concat with each other
intRes = _replaceFragments(item, usedFragments);
if (intRes == null || hasError) {
res = null;
return;
}
res = res.concat(intRes);
});
return res;
}
// if it's an object, we have to see whether it's fragment or not
if (isObjectAndNotNull(obj)) {
if ("fragment_key" in obj) {
var fragmentKey = obj.fragment_key;
// there was a cycle, so just set the variables and abort
if (fragmentKey in usedFragments) {
module._log.warn("Export: circular dependency detected in the defined templates and therefore ignored and template will be ignored (caused by `" + fragmentKey +"` key)");
hasError = true;
return null;
}
// fragment_key is invalid
if (!(fragmentKey in exportFragments)) {
hasError = true;
module._log.warn("Export: the given fragment_key `" + fragmentKey + "` is not valid and template will be ignored.");
return null;
}
// replace with actual definition
var modified = module._simpleDeepCopy(usedFragments);
modified[fragmentKey] = true;
return _replaceFragments(exportFragments[fragmentKey], modified);
}
// run the function for each value
res = {};
for (var k in obj) {
intRes = _replaceFragments(obj[k], usedFragments);
if (intRes == null || hasError) {
res = null;
return;
}
res[k] = intRes;
}
return res;
}
// for other data types, just return the input without any change
return obj;
};
var finalRes = [];
templates.forEach(function (t) {
hasError = false;
var tempRes = _replaceFragments(t, {});
// if there was an issue, the whole thing should return null
if (tempRes != null) {
finalRes = finalRes.concat(tempRes);
}
});
return finalRes;
}
};
/**
* Given an object, returns a boolean that indicates whether it is a valid template or not
* NOTE This will only validate the structure and not the values
* @param {Object} template
* @return {boolean}
*/
module.validateExportTemplate = function (template) {
var errMessage = function (reason) {
module._log.info("export template ignored with displayname=`" + template.displayname + "`. Reason: " + reason);
};
// template is not an object
if (template !== Object(template) || Array.isArray(template) || !template) {
module._log.info("export template ignored. Reason: it's not an object.");
return false;
}
// doesn't have the expected attributes
if (!module.ObjectHasAllKeys(template, ['displayname', 'type'])) {
module._log.info("export template ignored. Reason: first level required attributes are missing.");
return false;
}
//type must be either FILE or BAG
if (["BAG", "FILE"].indexOf(template.type) === -1) {
module._log.info("export template ignored. Reason: template.type must be either `BAG` or `FILE`.");
return false;
}
// in FILE, outputs must be properly defined
if (!Array.isArray(template.outputs) || template.outputs.length === 0) {
errMessage("outputs must be a non-empty array.");
return false;
}
var output;
for (var i = 0; i < template.outputs.length; i++) {
output = template.outputs[i];
//output must be an object
if (output !== Object(output) || Array.isArray(output) || !output) {
errMessage("output index=" + i + " is not an object.");
return false;
}
// output must have source and destination
if (!module.ObjectHasAllKeys(output, ['source', 'destination'])) {
errMessage("output index=" + i + " has missing required attributes.");
return false;
}
// output.source must have api
if (!module.ObjectHasAllKeys(output.source, ['api'])) {
errMessage("output.source index=" + i + " has missing required attributes.");
return false;
}
// output.destination must have at least a type
if (!module.ObjectHasAllKeys(output.destination, ['type'])) {
errMessage("output.destination index=" + i + " has missing required attributes.");
return false;
}
}
return true;
};
/**
* @desc Export Object
*
* @memberof ERMrest
* @class
* @param {ERMrest.Reference} reference
* @param {String} bagName the name that will be used for the bag
* @param {Object} template the tempalte must be in the valid format.
* @param {String} servicePath the path to the service, i.e. "/deriva/export/"
*
*
* @returns {Export}
* @constructor
*/
var exporter = function (reference, bagName, template, servicePath) {
if (!module.validateExportTemplate(template)) {
throw new module.InvalidInputError("Given Template is not valid.");
}
if (typeof servicePath !== "string" || servicePath.length === 0) {
throw new module.InvalidInputError("Given service path is not valid.");
}
this.reference = reference;
this.template = template;
this.servicePath = module.trimSlashes(servicePath);
this.formatOptions = {
"BAG": {
name: bagName,
algs: ["md5"],
archiver: "zip",
metadata: {},
table_format: "csv"
}
};
};
exporter.prototype = {
constructor: exporter,
/**
* TODO: add description
*/
get exportParameters () {
if (this._exportParameters === undefined) {
var exportParameters = {};
var bagOptions = this.formatOptions.BAG;
var template = this.template;
var bagParameters = {
bag_name: bagOptions.name,
bag_algorithms: bagOptions.algs,
bag_archiver: bagOptions.archiver,
bag_metadata: bagOptions.metadata
};
exportParameters.bag = bagParameters;
var base_url = this.reference.location.service;
var queries = [];
var catalogParameters = {
host: base_url.substring(0, base_url.lastIndexOf("/")),
catalog_id: this.reference.location.catalog,
query_processors: queries
};
exportParameters.catalog = catalogParameters;
if (!template) {
// this is basically the same as a single file CSV or JSON export but packaged as a bag
var query = {
processor: bagOptions.table_format,
processor_params: {
output_path: bagOptions.name,
query_path: "/" + this.reference.location.api + "/" +
this.reference.location.ermrestCompactPath + "?limit=none"
}
};
queries.push(query);
} else {
var outputs = template.outputs;
var predicate = this.reference.location.ermrestCompactPath;
var table = this.reference.table.name;
var output_path = module._sanitizeFilename(this.reference.displayname.unformatted);
outputs.forEach(function (output, index) {
var source = output.source, dest = output.destination;
var query = {}, queryParams = {};
// <api>/<current reference path>/<path>
var queryFrags = [
source.api,
predicate
];
if (typeof source.path === "string") {
// remove the first and last slash if it has one
queryFrags.push(module.trimSlashes(source.path));
}
query.processor = dest.type || bagOptions.table_format;
queryParams.output_path = dest.name || output_path;
var queryStr = queryFrags.join("/");
if (queryStr.length > module.URL_PATH_LENGTH_LIMIT) {
module._log.warn("Cannot send the output index `" + index + "` for table `" + table + "` to ermrest (URL LENGTH ERROR). Generated query:", queryStr);
return;
}
queryParams.query_path = "/" + queryStr + "?limit=none";
if (dest.impl != null) {
query.processor_type = dest.impl;
}
if (dest.params != null) {
Object.assign(queryParams, dest.params);
}
query.processor_params = queryParams;
queries.push(query);
});
}
if (template.transforms != null) {
exportParameters.transform_processors = template.transforms;
}
if (template.postprocessors != null) {
exportParameters.post_processors = template.postprocessors;
}
if (template.public != null) {
exportParameters.public = template.public;
}
if (template.bag_archiver != null) {
exportParameters.bag.bag_archiver = template.bag_archiver;
}
this._exportParameters = exportParameters;
}
return this._exportParameters;
},
/**
* sends the export request to ioboxd
* @param {Object} contextHeaderParams the object that will be logged
* @returns {Promise}
*/
run: function (contextHeaderParams) {
try {
var defer = module._q.defer(), self = this;
var serviceUrl = [
self.exportParameters.catalog.host,
self.servicePath,
(self.template.type == "BAG" ? "bdbag" : "file")
].join("/");
// log parameters
var headers = {};
if (!contextHeaderParams || typeof contextHeaderParams !== "object") {
contextHeaderParams = {"action": "export"};
}
// add the reference information
for (var key in self.reference.defaultLogInfo) {
if (key in contextHeaderParams) continue;
contextHeaderParams[key] = self.reference.defaultLogInfo[key];
}
headers[module.contextHeaderName] = contextHeaderParams;
self.canceled = false;
if (self.exportParameters.public != null) {
serviceUrl += "?public=" + self.exportParameters.public;
}
self.reference._server.http.post(serviceUrl, self.exportParameters, {headers: headers}).then(function success(response) {
return defer.resolve({data: response.data.split("\n"), canceled: self.canceled});
}).catch(function (err) {
var error = module.responseToError(err);
return defer.reject(error);
});
return defer.promise;
} catch (e) {
return module._q.reject(e);
}
},
/**
* Will set the canceled flag so when the datat comes back, we can tell the client
* to ignore the value. If it is already canceled it won't do anything.
* @return {boolean} returns false if the export is already canceled
*/
cancel: function () {
if (this.canceled) return false;
this.canceled = true;
return true;
}
};
module.Exporter = exporter;
/**
* Try export/<context> then export then 'detailed'
* @param {ERMrest.reference} ref
* @param {Boolean} useCompact - whether the current context is compact or not
*/
module._getExportReference = function (ref, useCompact) {
var detCtx = module._contexts.DETAILED,
expCompCtx = module._contexts.EXPORT_COMPACT,
expDetCtx = module._contexts.EXPORT_DETAILED;
var isContext = function (context) {
return context == ref._context;
};
var hasColumns = function (ctx) {
var res = module._getRecursiveAnnotationValue(ctx, ref.table.annotations.get(module._annotations.VISIBLE_COLUMNS).content, true);
return res !== -1 && Array.isArray(res);
};
var useMainContext = function () {
return isContext(detCtx) ? ref : ref.contextualize.detailed;
};
if (ref.table.annotations.contains(module._annotations.VISIBLE_COLUMNS)) {
// export/<context>
// NOTE even if only export context is defined, the visible-columns logic will handle it
if (useCompact) {
if (hasColumns(expCompCtx)) {
return isContext(expCompCtx) ? ref : ref.contextualize.exportCompact;
}
} else {
if (hasColumns(expDetCtx)) {
return isContext(expDetCtx) ? ref : ref.contextualize.exportDetailed;
}
}
}
// <context> or no annot
return useMainContext();
};
/**
* Given a reference object, will return the appropriate output object.
* It might use attributegroup or entity apis based on the situation.
*
* given a reference and the path from main table to it (it might be empty),
* will generate the appropriate output.
* - If addMainKey is true,
* it will add the shortestkey of main table to the projection list.
* - will go based on visible columns defined for `export` (if not `detailed`):
* - Normal Columns: add to the projection list.
* - ForeignKey pseudo-column: Add the constituent columns alongside extra "candidate" columns (if needed).
* - Key pseudo-column: add the constituent columns.
* - Asset pseudo-column: add all the metadata columns alongside the url value.
* - Inline table: not applicable. Because of the one-to-many nature of the relationship this is not feasible.
* - other pseudo-columns (aggregate): not applicable.
* If the genarated attributegroup path is long, will fall back to the entity api
*
* In case of attributegroup, we will change the projection list.
* Assume that this is the model:
* main_table <- t1 <- t2
* the key list will be based on:
* - shortestkey of main_table and t2 (with alias name in `<tablename>.<shortestkey_column_name>` format)
* the projection list will be based on:
* - visible columns of t2
* - "candidate" columns of the foreignkeys (with alias name in `<tablename>.<candidate_column_name>` format)
*
* by "candidate" we mean columns that might make more sense to user instead of the typical "RID" or "ID".
* These are the same column names that we are using for row-name generation.
*
* @private
* @param {ERMrest.reference} ref the reference that we want the output for
* @param {String} tableAlias the alias that is used for projecting table (last table in path)
* @param {String=} path the string that will be prepended to the path
* @param {String=} addMainKey whether we want to add the key of the main table.
* if this is true, the next parameter is required.
* @param {ERMrest.Reference=} mainRef The main reference
* @return {Object} the output object
*/
module._referenceExportOutput = function(ref, tableAlias, path, addMainKey, mainRef, useCompact) {
var projectionList = [],
keyList = [],
name, i = 0,
consideredFks = {},
addedCols = {},
usedNames = {},
shortestKeyCols = {},
fkeys = [],
fk, fkAlias, candidate,
addedColPrefix, names = {};
var encode = module._fixedEncodeURIComponent;
// find the candidate column of the table
var getCandidateColumn = function(table) {
return module._getCandidateRowNameColumn(table.columns.all().map(function(col) {
return col.name;
}));
};
// check whether the given column is a candidate column
var isCandidateColumn = function (column) {
return module._getCandidateRowNameColumn([column.name]) !== false;
};
var addColumn = function (c) {
var columns = Array.isArray(c) ? c : [c];
columns.forEach(function (col) {
if (col == null || typeof col !== 'object' || addedCols[col.name]) return;
addedCols[col.name] = true;
projectionList.push(encode(col.name));
});
};
// don't use any of the table column names
ref.table.columns.all().forEach(function(col) {
usedNames[col.name] = true;
});
// shortestkey of the current reference
ref.table.shortestKey.forEach(function(col) {
keyList.push(encode(col.name));
addedCols[col.name] = true;
});
// if it's a related entity and we need to key of the main table
if (addMainKey) {
// we have to add the shortestkey of main table
addedColPrefix = encode(mainRef.table.name) + ".";
mainRef.table.shortestKey.forEach(function(col) {
shortestKeyCols[col.name] = true;
name = addedColPrefix + encode(col.name);
// make sure the alias doesn't exist in the table
while (name in usedNames) {
name = addedColPrefix + encode(col.name) + "_" + (++i);
}
usedNames[name] = true;
keyList.push(name + ":=" + mainRef.location.mainTableAlias + ":" + encode(col.name));
});
//add the candidate column of main table too
candidate = getCandidateColumn(mainRef.table);
if (candidate && !(candidate in shortestKeyCols)) {
name = addedColPrefix + encode(candidate);
// make sure the alias doesn't exist in the table
while (name in usedNames) {
name = addedColPrefix + encode(candidate) + "_" + (++i);
}
usedNames[name] = true;
}
}
var exportRef = module._getExportReference(ref, useCompact);
if (exportRef.columns.length === 0) {
return null;
}
exportRef.columns.forEach(function (col) {
if (!col.isPseudo) {
addColumn(col);
return;
}
if (col.isForeignKey || (col.isPathColumn && col.isUnique && col.isEntityMode)) {
if (consideredFks[col.name]) return;
consideredFks[col.name] = true;
// add the constituent columns
var hasCandidate = false;
var firstFk = col.firstForeignKeyNode.nodeObject;
firstFk.colset.columns.forEach(function (fkeyCol) {
addColumn(fkeyCol);
if (!hasCandidate && col.foreignKeyPathLength === 1 && isCandidateColumn(firstFk.mapping.get(fkeyCol))) {
hasCandidate = true;
}
});
// if any of the constituent columns is candidate, don't add fk projection
if (hasCandidate) return;
// find the candidate column in the referred table;
candidate = getCandidateColumn(col.lastForeignKeyNode.nodeObject.key.table);
// we couldn't find any candidate columns
if (!candidate) return;
// add the fkey
fkAlias = "F" + (fkeys.length + 1);
var fkeyPath = [];
col.sourceObjectNodes.forEach(function (f, index, arr) {
if (f.isFilter) {
fkeyPath.push(f.toString());
} else {
fkeyPath.push(((f === col.lastForeignKeyNode) ? fkAlias + ":=" : "") + f.toString(false,true));
}
});
// path to the foreignkey + reset the path to the main table
fkeys.push(fkeyPath.join("/") + "/$" + tableAlias);
// add to projectionList
addedColPrefix = encode(col.table.name) + ".";
name = addedColPrefix + encode(candidate);
i = 0;
while (name in usedNames) {
name = addedColPrefix + encode(candidate) + "_" + (++i);
}
usedNames[name] = true;
name = name + ":=" + fkAlias + ":" + candidate;
projectionList.push(name);
return;
}
if (col.isKey) {
// add constituent columns
col.key.colset.columns.forEach(addColumn);
return;
}
if (col.isAsset) {
// add the column alongside the metadata columns
addColumn([col, col.filenameColumn, col.byteCountColumn, col.md5, col.sha256]);
return;
}
// other pseudo-columns won't be added
});
// generate the path, based on given values.
var exportPath = (typeof path === "string") ? (path + "/") : "";
if (fkeys.length > 0) {
exportPath += fkeys.join("/") + "/";
}
exportPath += keyList.join(",") + ";" + projectionList.join(",");
if (exportPath.length > module.URL_PATH_LENGTH_LIMIT) {
module._log.warn("Cannot use attributegroup api for exporting `" + ref.table.name + "` because of url limitation.");
return module._referenceExportEntityOutput(ref, path);
}
return {
destination: {
name: module._sanitizeFilename(ref.displayname.unformatted),
type: "csv"
},
source: {
api: "attributegroup",
path: exportPath
}
};
};
/**
* Given a reference object, will return the appropriate output object using entity api
* @private
* @param {ERMrest.Reference} ref the reference object
* @param {String} path the string that will be prepended to the path
* @return {Object} the output object
*/
module._referenceExportEntityOutput = function(ref, path) {
var source = {
api: "entity"
};
if (path) {
source.path = path;
}
return {
destination: {
name: module._sanitizeFilename(ref.displayname.unformatted),
type: "csv"
},
source: source
};
};
/**
* Given a column will return the appropriate output object for asset.
* It will return null if column is not an asset.
* @private
* @param {ERMrest.Column} col the column object
* @param {String} destinationPath the string that will be prepended to destination path
* @param {String} sourcePath the string that will be prepended to source path
* @return {Object}
*/
module._getAssetExportOutput = function(col, destinationPath, sourcePath) {
if (!col.isAsset) return null;
var path = [], key;
var sanitize = module._sanitizeFilename,
encode = module._fixedEncodeURIComponent;
// attributes
var attributes = {
byteCountColumn: "length",
filenameColumn: "filename",
md5: "md5",
sha256: "sha256"
};
// add the url
path.push("url:=" + encode(col.name));
// add the attributes (ignore the ones that are not defined)
for (key in attributes) {
if (col[key] == null) continue;
path.push(attributes[key] + ":=" + encode(col[key].name));
}
return {
destination: {
name: "assets/" + (destinationPath ? sanitize(destinationPath) + "/" : "") + sanitize(col.name),
type: "fetch"
},
source: {
api: "attribute",
// exporter will throw an error if the url is null, so we are adding the check for not-null.
path: (sourcePath ? sourcePath + "/" : "") + "!(" + encode(col.name) + "::null::)/" + path.join(",")
}
};
};
| informatics-isi-edu/ermrestjs | js/export.js | JavaScript | apache-2.0 | 31,427 |
// Autogenerated by hob
window.cls || (window.cls = {});
cls.ResourceManager || (cls.ResourceManager = {});
cls.ResourceManager["1.3"] || (cls.ResourceManager["1.3"] = {});
cls.ResourceManager["1.3"].ResourceID = function(arr)
{
this.resourceID = arr[0];
};
| operasoftware/dragonfly | src/resource-manager/resourcemanager.1.3.responses.createrequest.js | JavaScript | apache-2.0 | 265 |
// This file is part of mapchat released under Apache License, Version 2.0.
// See the NOTICE for more information.
function(event, text) {
var that = $(this);
$.pathbinder.go('/');
if (/^@/.test(text)) {
// Search by username
that.trigger('startload');
$$(window).app.db.view('mapchat/messages_by_author', {
descending: true,
startkey: [text.substr(1), 'z'],
limit: 1,
success: function(response) {
if (response.rows[0]) {
var loc = response.rows[0].value.loc;
$.pathbinder.go('/point/' + loc[0] + '/' + loc[1]);
}
that.trigger('endload');
},
error: function(status, error, reason) {
$.error('Search', 'Failed to load user messages! Reason:' + reason);
that.trigger('endload');
}
});
return;
}
// Otherwise search by location
var query = {address: text, language: "en"};
$$(window).geo.geocode(query, function (response, status) {
if (status === google.maps.GeocoderStatus.OK &&
response && response.length !== 0) {
$$(window).map.fitBounds(response[0].geometry.bounds);
}
});
}
| mapchat/mapchat | evently/content/_init/selectors/#overlay/search-query.js | JavaScript | apache-2.0 | 1,151 |
//-----------------------------------------------------------------
// fpago_mysql
// implementa el acceso a la basde de datos mysql
//-----------------------------------------------------------------
var mysql = require('mysql');
var conector = require('../comun/conector_mysql');
// getFPago
// devuelve las formas de pago cuyo nombre coincide con el
// parcial pasado
module.exports.getFPago = function (parnom, callback) {
var clientes = null
var sql = "SELECT * from sforpa";
sql += " WHERE true";
sql += " AND tipforpa IN (0,2,3)"
if (parnom) {
sql += " AND nomforpa LIKE ?";
sql = mysql.format(sql, ['%' + parnom + '%']);
}
sql += " order by nomforpa";
var connection = conector.getConnectionConta();
connection.query(sql, function (err, result) {
if (err) {
callback(err, null);
conector.closeConnection(connection);
return;
}
if (result && (result.length > 0)) {
clientes = result;
}
callback(null, clientes);
conector.closeConnection(connection);
});
};
| icedrum/ariconta6 | api/AntiguosLIB/fpago/fpago_mysql.js | JavaScript | apache-2.0 | 1,123 |
var search = require('search');
function getDepartments(path) {
search.doDepartmentSearch({
success: function(data){
var rows = [];
_.each(data, function(item) {
rows.push(Alloy.createController("departmentListRow", {
item: item
}).getView());
});
$.departmentListTable.setData(rows);
}
}, path);
}
if(Ti.Network.online) {
var path = "http://m.uwosh.edu/api/beta/2.0/directory/deptList";
// Perform the search
getDepartments(path);
} else {
alert('No network connection detected.');
}
| uwoshkosh/uwo-mobile-alloy | app/controllers/departmentList.js | JavaScript | apache-2.0 | 627 |
const {waitUntilReady, cleanup, PouchDB} = require('./utils');
describe('signatures', () => {
before(waitUntilReady);
afterEach(cleanup);
it('seamless auth', () => {
const promise = PouchDB.seamlessSession(() => {});
promise.then.should.be.ok;
promise.catch.should.be.ok;
return promise;
});
});
| pouchdb/pouchdb-server | tests/pouchdb-seamless-auth/signatures.js | JavaScript | apache-2.0 | 322 |
treeDirectives.directive(
'sidebarDirective', function () {
return {
restrict: 'E',
replace: true,
scope: true,
controller: [
'$scope',
'$modal',
'TreeService',
function ($scope, $modal, TreeService) {
var sidebarData = {
modalInstance: {},
element: {},
treeService: TreeService,
showAddModal: function (parentElement) {
this.modalInstance = $modal.open({
templateUrl: '/templates/modal/element/form.html',
controller: 'ModalElementAddController',
size: 'small',
resolve: {
parentElement: function () {
return parentElement;
}
}
});
}
};
$scope.sidebarData = sidebarData;
}],
templateUrl: '/templates/directives/sidebar.html'
};
}
); | kitolog/Tree | app/js/directives/sidebar.js | JavaScript | apache-2.0 | 1,306 |
function goDiary(e) {
//alert($.label.text);
var diary = Alloy.createController("diary").getView();
diary.open();
}
$.index.open();
| ruchango/Test06 | app/controllers/index.js | JavaScript | apache-2.0 | 145 |
/**
* Created by Emil Atanasov
*/
//##############################################################################
// TweenMaxJS.js
//##############################################################################
// TODO: possibly add a END actionsMode (only runs actions that == position)?
// TODO: evaluate a way to decouple paused from tick registration.
this.createjs = this.createjs||{};
(function() {
"use strict";
// constructor
/**
* A Tween instance tweens properties for a single target. Instance methods can be chained for easy construction and sequencing:
*
* <h4>Example</h4>
*
* target.alpha = 1;
* createjs.Tween.get(target)
* .wait(500)
* .to({alpha:0, visible:false}, 1000)
* .call(handleComplete);
* function handleComplete() {
* //Tween complete
* }
*
* Multiple tweens can point to the same instance, however if they affect the same properties there could be unexpected
* behaviour. To stop all tweens on an object, use {{#crossLink "Tween/removeTweens"}}{{/crossLink}} or pass `override:true`
* in the props argument.
*
* createjs.Tween.get(target, {override:true}).to({x:100});
*
* Subscribe to the {{#crossLink "Tween/change:event"}}{{/crossLink}} event to get notified when a property of the
* target is changed.
*
* createjs.Tween.get(target, {override:true}).to({x:100}).addEventListener("change", handleChange);
* function handleChange(event) {
* // The tween changed.
* }
*
* See the Tween {{#crossLink "Tween/get"}}{{/crossLink}} method for additional param documentation.
* @class Tween
* @param {Object} target The target object that will have its properties tweened.
* @param {Object} [props] The configuration properties to apply to this tween instance (ex. `{loop:true, paused:true}`.
* All properties default to false. Supported props are:<UL>
* <LI> loop: sets the loop property on this tween.</LI>
* <LI> useTicks: uses ticks for all durations instead of milliseconds.</LI>
* <LI> ignoreGlobalPause: sets the {{#crossLink "Tween/ignoreGlobalPause:property"}}{{/crossLink}} property on this tween.</LI>
* <LI> override: if true, `Tween.removeTweens(target)` will be called to remove any other tweens with the same target.
* <LI> paused: indicates whether to start the tween paused.</LI>
* <LI> position: indicates the initial position for this tween.</LI>
* <LI> onChange: specifies a listener for the "change" event.</LI>
* </UL>
* @param {Object} [pluginData] An object containing data for use by installed plugins. See individual
* plugins' documentation for details.
* @extends EventDispatcher
* @constructor
*/
function TweenMaxJS(target, props, pluginData) {
// public properties:
/**
* Causes this tween to continue playing when a global pause is active. For example, if TweenJS is using {{#crossLink "Ticker"}}{{/crossLink}},
* then setting this to true (the default) will cause this tween to be paused when <code>Ticker.setPaused(true)</code>
* is called. See the Tween {{#crossLink "Tween/tick"}}{{/crossLink}} method for more info. Can be set via the props
* parameter.
* @property ignoreGlobalPause
* @type Boolean
* @default false
*/
this.ignoreGlobalPause = false;
/**
* If true, the tween will loop when it reaches the end. Can be set via the props param.
* @property loop
* @type {Boolean}
* @default false
*/
this.loop = false;
/**
* Specifies the total duration of this tween in milliseconds (or ticks if useTicks is true).
* This value is automatically updated as you modify the tween. Changing it directly could result in unexpected
* behaviour.
* @property duration
* @type {Number}
* @default 0
* @readonly
*/
this.duration = 0;
/**
* Allows you to specify data that will be used by installed plugins. Each plugin uses this differently, but in general
* you specify data by setting it to a property of pluginData with the same name as the plugin class.
* @example
* myTween.pluginData.PluginClassName = data;
* <br/>
* Also, most plugins support a property to enable or disable them. This is typically the plugin class name followed by "_enabled".<br/>
* @example
* myTween.pluginData.PluginClassName_enabled = false;<br/>
* <br/>
* Some plugins also store instance data in this object, usually in a property named _PluginClassName.
* See the documentation for individual plugins for more details.
* @property pluginData
* @type {Object}
*/
this.pluginData = pluginData || {};
/**
* The target of this tween. This is the object on which the tweened properties will be changed. Changing
* this property after the tween is created will not have any effect.
* @property target
* @type {Object}
* @readonly
*/
this.target = target;
/**
* The current normalized position of the tween. This will always be a value between 0 and duration.
* Changing this property directly will have no effect.
* @property position
* @type {Object}
* @readonly
*/
this.position = null;
/**
* Indicates the tween's current position is within a passive wait.
* @property passive
* @type {Boolean}
* @default false
* @readonly
**/
this.passive = false;
// private properties:
/**
* @property _paused
* @type {Boolean}
* @default false
* @protected
*/
this._paused = false;
/**
* @property _curQueueProps
* @type {Object}
* @protected
*/
this._curQueueProps = {};
/**
* @property _initQueueProps
* @type {Object}
* @protected
*/
this._initQueueProps = {};
/**
* @property _steps
* @type {Array}
* @protected
*/
this._steps = [];
/**
* @property _actions
* @type {Array}
* @protected
*/
this._actions = [];
/**
* Raw position.
* @property _prevPosition
* @type {Number}
* @default 0
* @protected
*/
this._prevPosition = 0;
/**
* The position within the current step.
* @property _stepPosition
* @type {Number}
* @default 0
* @protected
*/
this._stepPosition = 0; // this is needed by MovieClip.
/**
* Normalized position.
* @property _prevPos
* @type {Number}
* @default -1
* @protected
*/
this._prevPos = -1;
/**
* @property _target
* @type {Object}
* @protected
*/
this._target = target;
/**
* @property _useTicks
* @type {Boolean}
* @default false
* @protected
*/
this._useTicks = false;
/**
* @property _inited
* @type {boolean}
* @default false
* @protected
*/
this._inited = false;
/**
* Indicates whether the tween is currently registered with Tween.
* @property _registered
* @type {boolean}
* @default false
* @protected
*/
this._registered = false;
var timelineOptions = {};
if(props) {
if (props.loop) {
timelineOptions["repeat"] = -1;
}
if (props.useTicks) {
timelineOptions["useFrames"] = !!props.useTicks;
}
if(props.pause) {
timelineOptions["paused"] = true;
}
}
//timeline
this._timelineMax = new TimelineMax(timelineOptions);
if (props) {
this._useTicks = props.useTicks;
this.ignoreGlobalPause = props.ignoreGlobalPause;
this.loop = props.loop;
props.onChange && this.addEventListener("change", props.onChange);
if (props.override) { TweenMaxJS.removeTweens(target); }
}
if (props&&props.paused) { this._paused=true; }
else {
//object has a _timelineMax and all tweens will be attach to it
//createjs.TweenMaxJS._register(this,true);
}
if (props&&props.position!=null) { this.setPosition(props.position, TweenMaxJS.NONE); }
};
var p = createjs.extend(TweenMaxJS, createjs.EventDispatcher);
// TODO: deprecated
// p.initialize = function() {}; // searchable for devs wondering where it is. REMOVED. See docs for details.
// static properties
/**
* Constant defining the none actionsMode for use with setPosition.
* @property NONE
* @type Number
* @default 0
* @static
*/
TweenMaxJS.NONE = 0;
/**
* Constant defining the loop actionsMode for use with setPosition.
* @property LOOP
* @type Number
* @default 1
* @static
*/
TweenMaxJS.LOOP = 1;
/**
* Constant defining the reverse actionsMode for use with setPosition.
* @property REVERSE
* @type Number
* @default 2
* @static
*/
TweenMaxJS.REVERSE = 2;
/**
* Constant returned by plugins to tell the TweenMaxJS not to use default assignment.
* @property IGNORE
* @type Object
* @static
*/
TweenMaxJS.IGNORE = {};
/**
* @property _listeners
* @type Array[TweenMaxJS]
* @static
* @protected
*/
TweenMaxJS._TweenMaxJSs = [];
/**
* @property _plugins
* @type Object
* @static
* @protected
*/
TweenMaxJS._plugins = {};
// static methods
/**
* Returns a new tween instance. This is functionally identical to using "new Tween(...)", but looks cleaner
* with the chained syntax of TweenJS.
* <h4>Example</h4>
*
* var tween = createjs.Tween.get(target);
*
* @method get
* @param {Object} target The target object that will have its properties tweened.
* @param {Object} [props] The configuration properties to apply to this tween instance (ex. `{loop:true, paused:true}`).
* All properties default to `false`. Supported props are:
* <UL>
* <LI> loop: sets the loop property on this tween.</LI>
* <LI> useTicks: uses ticks for all durations instead of milliseconds.</LI>
* <LI> ignoreGlobalPause: sets the {{#crossLink "Tween/ignoreGlobalPause:property"}}{{/crossLink}} property on
* this tween.</LI>
* <LI> override: if true, `createjs.Tween.removeTweens(target)` will be called to remove any other tweens with
* the same target.
* <LI> paused: indicates whether to start the tween paused.</LI>
* <LI> position: indicates the initial position for this tween.</LI>
* <LI> onChange: specifies a listener for the {{#crossLink "Tween/change:event"}}{{/crossLink}} event.</LI>
* </UL>
* @param {Object} [pluginData] An object containing data for use by installed plugins. See individual plugins'
* documentation for details.
* @param {Boolean} [override=false] If true, any previous tweens on the same target will be removed. This is the
* same as calling `Tween.removeTweens(target)`.
* @return {Tween} A reference to the created tween. Additional chained tweens, method calls, or callbacks can be
* applied to the returned tween instance.
* @static
*/
TweenMaxJS.get = function(target, props, pluginData, override) {
if (override) { TweenMaxJS.removeTweens(target); }
return new TweenMaxJS(target, props, pluginData);
};
/**
* Advances all tweens. This typically uses the {{#crossLink "Ticker"}}{{/crossLink}} class, but you can call it
* manually if you prefer to use your own "heartbeat" implementation.
* @method tick
* @param {Number} delta The change in time in milliseconds since the last tick. Required unless all tweens have
* `useTicks` set to true.
* @param {Boolean} paused Indicates whether a global pause is in effect. Tweens with {{#crossLink "Tween/ignoreGlobalPause:property"}}{{/crossLink}}
* will ignore this, but all others will pause if this is `true`.
* @static
*/
TweenMaxJS.tick = function(delta, paused) {
var tweens = TweenMaxJS._tweens.slice(); // to avoid race conditions.
for (var i=tweens.length-1; i>=0; i--) {
var tween = tweens[i];
if ((paused && !tween.ignoreGlobalPause) || tween._paused) { continue; }
tween.tick(tween._useTicks?1:delta);
}
};
/**
* Handle events that result from Tween being used as an event handler. This is included to allow Tween to handle
* {{#crossLink "Ticker/tick:event"}}{{/crossLink}} events from the createjs {{#crossLink "Ticker"}}{{/crossLink}}.
* No other events are handled in Tween.
* @method handleEvent
* @param {Object} event An event object passed in by the {{#crossLink "EventDispatcher"}}{{/crossLink}}. Will
* usually be of type "tick".
* @private
* @static
* @since 0.4.2
*/
TweenMaxJS.handleEvent = function(event) {
console.log("handle event");
if (event.type == "tick") {
this.tick(event.delta, event.paused);
}
};
/**
* Removes all existing tweens for a target. This is called automatically by new tweens if the `override`
* property is `true`.
* @method removeTweens
* @param {Object} target The target object to remove existing tweens from.
* @static
*/
TweenMaxJS.removeTweens = function(target) {
if (!target.tweenjs_count) { return; }
var tweens = TweenMaxJS._tweens;
for (var i=tweens.length-1; i>=0; i--) {
var tween = tweens[i];
if (tween._target == target) {
tween._paused = true;
tweens.splice(i, 1);
}
}
target.tweenjs_count = 0;
};
/**
* Stop and remove all existing tweens.
* @method removeAllTweens
* @static
* @since 0.4.1
*/
TweenMaxJS.removeAllTweens = function() {
var tweens = TweenMaxJS._tweens;
for (var i= 0, l=tweens.length; i<l; i++) {
var tween = tweens[i];
tween._paused = true;
tween.target&&(tween.target.tweenjs_count = 0);
}
tweens.length = 0;
};
/**
* Indicates whether there are any active tweens (and how many) on the target object (if specified) or in general.
* @method hasActiveTweens
* @param {Object} [target] The target to check for active tweens. If not specified, the return value will indicate
* if there are any active tweens on any target.
* @return {Boolean} If there are active tweens.
* @static
*/
TweenMaxJS.hasActiveTweens = function(target) {
if (target) { return target.tweenjs_count != null && !!target.tweenjs_count; }
return TweenMaxJS._tweens && !!TweenMaxJS._tweens.length;
};
/**
* Installs a plugin, which can modify how certain properties are handled when tweened. See the {{#crossLink "CSSPlugin"}}{{/crossLink}}
* for an example of how to write TweenJS plugins.
* @method installPlugin
* @static
* @param {Object} plugin The plugin class to install
* @param {Array} properties An array of properties that the plugin will handle.
*/
TweenMaxJS.installPlugin = function(plugin, properties) {
var priority = plugin.priority;
if (priority == null) { plugin.priority = priority = 0; }
for (var i=0,l=properties.length,p=TweenMaxJS._plugins;i<l;i++) {
var n = properties[i];
if (!p[n]) { p[n] = [plugin]; }
else {
var arr = p[n];
for (var j=0,jl=arr.length;j<jl;j++) {
if (priority < arr[j].priority) { break; }
}
p[n].splice(j,0,plugin);
}
}
};
/**
* Registers or unregisters a tween with the ticking system.
* @method _register
* @param {Tween} tween The tween instance to register or unregister.
* @param {Boolean} value If `true`, the tween is registered. If `false` the tween is unregistered.
* @static
* @protected
*/
TweenMaxJS._register = function(tween, value) {
var target = tween._target;
var tweens = TweenMaxJS._tweens;
if (value && !tween._registered) {
// TODO: this approach might fail if a dev is using sealed objects in ES5
if (target) { target.tweenjs_count = target.tweenjs_count ? target.tweenjs_count+1 : 1; }
tweens.push(tween);
if (!TweenMaxJS._inited && createjs.Ticker) { createjs.Ticker.addEventListener("tick", TweenMaxJS); TweenMaxJS._inited = true; }
} else if (!value && tween._registered) {
if (target) { target.tweenjs_count--; }
var i = tweens.length;
while (i--) {
if (tweens[i] == tween) {
tweens.splice(i, 1);
break;
}
}
}
tween._registered = value;
};
// events:
/**
* Called whenever the tween's position changes.
* @event change
* @since 0.4.0
**/
// public methods:
/**
* Queues a wait (essentially an empty tween).
* <h4>Example</h4>
*
* //This tween will wait 1s before alpha is faded to 0.
* createjs.Tween.get(target).wait(1000).to({alpha:0}, 1000);
*
* @method wait
* @param {Number} duration The duration of the wait in milliseconds (or in ticks if `useTicks` is true).
* @param {Boolean} [passive] Tween properties will not be updated during a passive wait. This
* is mostly useful for use with {{#crossLink "Timeline"}}{{/crossLink}} instances that contain multiple tweens
* affecting the same target at different times.
* @return {Tween} This tween instance (for chaining calls).
**/
p.wait = function(duration, passive) {
if (duration == null || duration <= 0) { return this; }
var o = this._cloneProps(this._curQueueProps);
//handle the tween and add it to the timeline
//timeline
this._timelineMax.add(TweenMax.to(this.target, duration, o));
return this._addStep({d:duration, p0:o, e:this._linearEase, p1:o, v:passive});
};
/**
* Queues a tween from the current values to the target properties. Set duration to 0 to jump to these value.
* Numeric properties will be tweened from their current value in the tween to the target value. Non-numeric
* properties will be set at the end of the specified duration.
* <h4>Example</h4>
*
* createjs.Tween.get(target).to({alpha:0}, 1000);
*
* @method to
* @param {Object} props An object specifying property target values for this tween (Ex. `{x:300}` would tween the x
* property of the target to 300).
* @param {Number} [duration=0] The duration of the wait in milliseconds (or in ticks if `useTicks` is true).
* @param {Function} [ease="linear"] The easing function to use for this tween. See the {{#crossLink "Ease"}}{{/crossLink}}
* class for a list of built-in ease functions.
* @return {Tween} This tween instance (for chaining calls).
*/
p.to = function(props, duration, ease) {
if (isNaN(duration) || duration < 0) { duration = 0; }
if(ease) {
props.ease = ease;
}
//timeline
this._timelineMax.to(this.target, duration, props)
return this._addStep({d:duration||0, p0:this._cloneProps(this._curQueueProps), e:ease, p1:this._cloneProps(this._appendQueueProps(props))});
};
/**
* Queues an action to call the specified function.
* <h4>Example</h4>
*
* //would call myFunction() after 1 second.
* myTween.wait(1000).call(myFunction);
*
* @method call
* @param {Function} callback The function to call.
* @param {Array} [params]. The parameters to call the function with. If this is omitted, then the function
* will be called with a single param pointing to this tween.
* @param {Object} [scope]. The scope to call the function in. If omitted, it will be called in the target's
* scope.
* @return {Tween} This tween instance (for chaining calls).
*/
p.call = function(callback, params, scope) {
//timeline
this._timelineMax.call(callback, params, scope);
return this._addAction({f:callback, p:params ? params : [this], o:scope ? scope : this._target});
};
// TODO: add clarification between this and a 0 duration .to:
/**
* Queues an action to set the specified props on the specified target. If target is null, it will use this tween's
* target.
* <h4>Example</h4>
*
* myTween.wait(1000).set({visible:false},foo);
*
* @method set
* @param {Object} props The properties to set (ex. `{visible:false}`).
* @param {Object} [target] The target to set the properties on. If omitted, they will be set on the tween's target.
* @return {Tween} This tween instance (for chaining calls).
*/
p.set = function(props, target) {
//timeline
this._timelineMax.set(target ? target : this._target, props);
return this._addAction({f:this._set, o:this, p:[props, target ? target : this._target]});
};
/**
* Queues an action to play (unpause) the specified tween. This enables you to sequence multiple tweens.
* <h4>Example</h4>
*
* myTween.to({x:100},500).play(otherTween);
*
* @method play
* @param {Tween} tween The tween to play.
* @return {Tween} This tween instance (for chaining calls).
*/
p.play = function(tween) {
if (!tween) { tween = this; }
return this.call(tween.setPaused, [false], tween);
};
/**
* Queues an action to pause the specified tween.
* @method pause
* @param {Tween} tween The tween to pause. If null, it pauses this tween.
* @return {Tween} This tween instance (for chaining calls)
*/
p.pause = function(tween) {
if (!tween) { tween = this; }
return this.call(tween.setPaused, [true], tween);
};
/**
* Advances the tween to a specified position.
* @method setPosition
* @param {Number} value The position to seek to in milliseconds (or ticks if useTicks is true).
* @param {Number} [actionsMode=1] Specifies how actions are handled (ie. call, set, play, pause):
* <ul>
* <li>{{#crossLink "Tween/NONE:property"}}{{/crossLink}} (0) - run no actions.</li>
* <li>{{#crossLink "Tween/LOOP:property"}}{{/crossLink}} (1) - if new position is less than old, then run all
* actions between old and duration, then all actions between 0 and new.</li>
* <li>{{#crossLink "Tween/REVERSE:property"}}{{/crossLink}} (2) - if new position is less than old, run all
* actions between them in reverse.</li>
* </ul>
* @return {Boolean} Returns `true` if the tween is complete (ie. the full tween has run & {{#crossLink "Tween/loop:property"}}{{/crossLink}}
* is `false`).
*/
p.setPosition = function(value, actionsMode) {
if (value < 0) { value = 0; }
if (actionsMode == null) { actionsMode = 1; }
// normalize position:
var t = value;
var end = false;
if (t >= this.duration) {
if (this.loop) { t = t%this.duration; }
else {
t = this.duration;
end = true;
}
}
if (t == this._prevPos) { return end; }
var prevPos = this._prevPos;
this.position = this._prevPos = t; // set this in advance in case an action modifies position.
this._prevPosition = value;
//todo: should this be fired ?!@?
this.dispatchEvent("change");
//timeline
return this._timelineMax.seek(this._prevPosition).progress() === 1.0;
//TODO: check what are ACTIONS?
// handle tweens:
if (this._target) {
if (end) {
// addresses problems with an ending zero length step.
this._updateTargetProps(null,1);
} else if (this._steps.length > 0) {
// find our new tween index:
for (var i=0, l=this._steps.length; i<l; i++) {
if (this._steps[i].t > t) { break; }
}
var step = this._steps[i-1];
this._updateTargetProps(step,(this._stepPosition = t-step.t)/step.d);
}
}
// run actions:
if (actionsMode != 0 && this._actions.length > 0) {
if (this._useTicks) {
// only run the actions we landed on.
this._runActions(t,t);
} else if (actionsMode == 1 && t<prevPos) {
if (prevPos != this.duration) { this._runActions(prevPos, this.duration); }
this._runActions(0, t, true);
} else {
this._runActions(prevPos, t);
}
}
if (end) { this.setPaused(true); }
this.dispatchEvent("change");
return end;
};
/**
* Advances this tween by the specified amount of time in milliseconds (or ticks if`useTicks` is `true`).
* This is normally called automatically by the Tween engine (via {{#crossLink "Tween/tick"}}{{/crossLink}}), but is
* exposed for advanced uses.
* @method tick
* @param {Number} delta The time to advance in milliseconds (or ticks if `useTicks` is `true`).
*/
p.tick = function(delta) {
if (this._paused) { return; }
this.setPosition(this._prevPosition+delta);
};
/**
* Pauses or plays this tween.
* @method setPaused
* @param {Boolean} [value=true] Indicates whether the tween should be paused (`true`) or played (`false`).
* @return {Tween} This tween instance (for chaining calls)
*/
p.setPaused = function(value) {
if (this._paused === !!value) { return this; }
this._paused = !!value;
if(this._paused) {
//timeline
this._timelineMax.pause();
} else {
//timeline
this._timelineMax.play();
}
//TweenMaxJS._register(this, !value);
return this;
};
// tiny api (primarily for tool output):
p.w = p.wait;
p.t = p.to;
p.c = p.call;
p.s = p.set;
/**
* Returns a string representation of this object.
* @method toString
* @return {String} a string representation of the instance.
*/
p.toString = function() {
return "[TweenMaxJS]";
};
/**
* @method clone
* @protected
*/
p.clone = function() {
throw("TweenMaxJS can not be cloned.")
};
// private methods:
/**
* @method _updateTargetProps
* @param {Object} step
* @param {Number} ratio
* @protected
*/
p._updateTargetProps = function(step, ratio) {
var p0,p1,v,v0,v1,arr;
if (!step && ratio == 1) {
// GDS: when does this run? Just at the very end? Shouldn't.
this.passive = false;
p0 = p1 = this._curQueueProps;
} else {
this.passive = !!step.v;
if (this.passive) { return; } // don't update props.
// apply ease to ratio.
if (step.e) { ratio = step.e(ratio,0,1,1); }
p0 = step.p0;
p1 = step.p1;
}
for (var n in this._initQueueProps) {
if ((v0 = p0[n]) == null) { p0[n] = v0 = this._initQueueProps[n]; }
if ((v1 = p1[n]) == null) { p1[n] = v1 = v0; }
if (v0 == v1 || ratio == 0 || ratio == 1 || (typeof(v0) != "number")) {
// no interpolation - either at start, end, values don't change, or the value is non-numeric.
v = ratio == 1 ? v1 : v0;
} else {
v = v0+(v1-v0)*ratio;
}
var ignore = false;
if (arr = TweenMaxJS._plugins[n]) {
for (var i=0,l=arr.length;i<l;i++) {
var v2 = arr[i].tween(this, n, v, p0, p1, ratio, !!step&&p0==p1, !step);
if (v2 == TweenMaxJS.IGNORE) { ignore = true; }
else { v = v2; }
}
}
if (!ignore) { this._target[n] = v; }
}
};
/**
* @method _runActions
* @param {Number} startPos
* @param {Number} endPos
* @param {Boolean} includeStart
* @protected
*/
p._runActions = function(startPos, endPos, includeStart) {
var sPos = startPos;
var ePos = endPos;
var i = -1;
var j = this._actions.length;
var k = 1;
if (startPos > endPos) {
// running backwards, flip everything:
sPos = endPos;
ePos = startPos;
i = j;
j = k = -1;
}
while ((i+=k) != j) {
var action = this._actions[i];
var pos = action.t;
if (pos == ePos || (pos > sPos && pos < ePos) || (includeStart && pos == startPos) ) {
action.f.apply(action.o, action.p);
}
}
};
/**
* @method _appendQueueProps
* @param {Object} o
* @protected
*/
p._appendQueueProps = function(o) {
var arr,oldValue,i, l, injectProps;
for (var n in o) {
if (this._initQueueProps[n] === undefined) {
oldValue = this._target[n];
// init plugins:
if (arr = TweenMaxJS._plugins[n]) {
for (i=0,l=arr.length;i<l;i++) {
oldValue = arr[i].init(this, n, oldValue);
}
}
this._initQueueProps[n] = this._curQueueProps[n] = (oldValue===undefined) ? null : oldValue;
} else {
oldValue = this._curQueueProps[n];
}
}
for (var n in o) {
oldValue = this._curQueueProps[n];
if (arr = TweenMaxJS._plugins[n]) {
injectProps = injectProps||{};
for (i=0, l=arr.length;i<l;i++) {
// TODO: remove the check for .step in the next version. It's here for backwards compatibility.
if (arr[i].step) { arr[i].step(this, n, oldValue, o[n], injectProps); }
}
}
this._curQueueProps[n] = o[n];
}
if (injectProps) { this._appendQueueProps(injectProps); }
return this._curQueueProps;
};
/**
* @method _cloneProps
* @param {Object} props
* @protected
*/
p._cloneProps = function(props) {
var o = {};
for (var n in props) {
o[n] = props[n];
}
return o;
};
/**
* @method _addStep
* @param {Object} o
* @protected
*/
p._addStep = function(o) {
if (o.d > 0) {
this._steps.push(o);
o.t = this.duration;
this.duration += o.d;
}
return this;
};
/**
* @method _addAction
* @param {Object} o
* @protected
*/
p._addAction = function(o) {
o.t = this.duration;
this._actions.push(o);
return this;
};
/**
* @method _set
* @param {Object} props
* @param {Object} o
* @protected
*/
p._set = function(props, o) {
for (var n in props) {
o[n] = props[n];
}
};
createjs.TweenMaxJS = createjs.promote(TweenMaxJS, "EventDispatcher");
}()); | heitara/FlashCC-TweenMax | flash-project/libs/TweenMaxJS.js | JavaScript | apache-2.0 | 32,614 |
import App from './App';
import Tag from './components/Tag';
import Listen from './components/Listen';
import Home from './components/Home';
import DeezerChannel from './components/DeezerChannel';
export function configRouter (router) {
router.map({
'/': {
name: 'app',
component: App,
subRoutes: {
'/': {
name: 'home',
component: Home
},
'/tag': {
name: 'tag',
component: Tag
},
'/listen': {
name: 'listen',
component: Listen
}
}
},
'/channel.html': {
name: 'channel',
component: DeezerChannel
}
});
}
| Erilan/average | src/routeConfig.js | JavaScript | apache-2.0 | 669 |
/*jshint globalstrict: true*/ 'use strict';
var configuration = require('grunt-splunk/lib/configuration'),
splunkEnvironment = require('grunt-splunk/lib/environment'),
splunkWatchConfig = require('grunt-splunk/lib/watchConfig'),
path = require('path');
module.exports = function(grunt) {
// Verify environment
if (!splunkEnvironment.splunkHome()) {
grunt.fail.fatal('Could not locate splunk home directory');
}
// Verify configuration
var splunkConfig = configuration.get();
if (!splunkConfig) {
grunt.fail.fatal(
'Could not load configuration for current Splunk instance. Use `splunk-cli configure`.' +
'If `splunk-cli` is not available install it with `npm install splunk-cli`.');
}
// Set splunk application
splunkConfig.splunkApp = '<%= appname %>';
// Specify config for splunk-pack task
splunkConfig.pack = {
sourceDir: __dirname,
output: path.join(__dirname, (splunkConfig.splunkApp + '.tar.gz')),
source: [
'**/*',
'!*.tar.gz'
]
};
// Watch config. Launch jshint for all changed JS files
var watchConfig = {
js: {
files: ['<%= "<" + "%= jshint.files %" + ">" %>'],
tasks: ['jshint']
}
};
// Add watch configuration for splunk app (reload splunk)
watchConfig = splunkWatchConfig.watchForApp(watchConfig, splunkConfig.splunkApp);
// Initialize Splunk config
grunt.config.init({
splunk: splunkConfig,
jshint: {
files: ['Gruntfile.js', 'django/<%= appname %>/static/<%= appname %>/**/*.js'],
options: {
ignores: ['django/<%= appname %>/static/<%= appname %>/bower_components/**/*'],
globals: {
console: true,
module: true,
require: true,
process: true,
Buffer: true,
__dirname: true
}
}
},
watch: watchConfig
});
// Load grunt-splunk
grunt.loadNpmTasks('grunt-splunk');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['watch']);
grunt.registerTask('build', ['splunk-pack']);
};
| outcoldman/generator-splunkapp | app/templates/splunkapp/Gruntfile.js | JavaScript | apache-2.0 | 2,112 |
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/docs/referenceConf.js
/*global jasmine */
var SpecReporter = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome'
},
directConnect: true,
baseUrl: 'http://localhost:8100/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
useAllAngular2AppRoots: true,
beforeLaunch: function() {
require('ts-node').register({
project: 'e2e'
});
},
onPrepare: function() {
jasmine.getEnv().addReporter(new SpecReporter());
}
}; | Arkord/runcanrol | protractor.conf.js | JavaScript | apache-2.0 | 730 |
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* 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.
*/
'use strict';
// MODULES //
var bench = require( '@stdlib/bench' );
var uniform = require( '@stdlib/random/base/uniform' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var Complex128 = require( '@stdlib/complex/float64' );
var real = require( '@stdlib/complex/real' );
var imag = require( '@stdlib/complex/imag' );
var pkg = require( './../package.json' ).name;
var cadd = require( './../lib' );
// MAIN //
bench( pkg, function benchmark( b ) {
var values;
var out;
var z;
var i;
values = [
new Complex128( uniform( -500.0, 500.0 ), uniform( -500.0, 500.0 ) ),
new Complex128( uniform( -500.0, 500.0 ), uniform( -500.0, 500.0 ) )
];
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
z = values[ i%values.length ];
out = cadd( z, z );
if ( typeof out !== 'object' ) {
b.fail( 'should return an object' );
}
}
b.toc();
if ( isnan( real( out ) ) || isnan( imag( out ) ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
});
| stdlib-js/stdlib | lib/node_modules/@stdlib/math/base/ops/cadd/benchmark/benchmark.js | JavaScript | apache-2.0 | 1,621 |
// Copyright 2019 Google Inc.
//
// 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.
/** @fileoverview Multiple Task class file. */
'use strict';
const {nanoid} = require('nanoid');
const {
utils: {apiSpeedControl, getProperValue,},
storage: {StorageFile},
} = require('@google-cloud/nodejs-common');
const {
TaskType,
TaskGroup,
StorageFileConfig,
ErrorOptions,
} = require('../task_config/task_config_dao.js');
const {FIELD_NAMES} = require('../task_log/task_log_dao.js');
const {KnotTask} = require('./knot_task.js');
/**
* `estimateRunningTime` Number of minutes to wait before doing the first task
* status check for the embedded task group.
* `dueTime` Task execution timeout time in minutes. If task group times out, it
* will be marked with 'timeout' error code.
* @typedef {{
* type:TaskType.MULTIPLE,
* appendedParameters:(Object<string,string>|undefined),
* source:{
* csv:{header:string, records:string,},
* }|{
* file:!StorageFileConfig,
* },
* destination:{
* taskId:string,
* target:'pubsub',
* qps:number|undefined,
* }|{
* taskId:string,
* target:'gcs',
* file:!StorageFileConfig,
* },
* multiple:{
* estimateRunningTime:(number|undefined),
* dueTime:(number|undefined),
* }|undefined,
* errorOptions:(!ErrorOptions|undefined),
* next:(!TaskGroup|undefined),
* }}
*/
let MultipleTaskConfig;
/**
* Multiple Task acts as a holder of multiple same tasks (with different
* parameters). Some tasks will generate multiple instances of next tasks, e.g.
* a Google Ads Report task will generate report tasks for each of the Ads
* accounts.
* There are two ways (different values for 'destination.target' in
* `MultipleTaskConfig`) to start those multiple tasks:
* 1. Directly send start task messages to Pub/Sub. This is a simple and
* straightforward approach. However due to Cloud Functions' execution time,
* the distribution time of multiple tasks couldn't be longer than 9
* minutes.
* 2. Through Tentacles' Pub/Sub integration to send the start messages in a
* more manageable manner. This will require extra settings in Tentacles.
*
* Either way, after all these start task messages are sent, this task will act
* as the holder of all those multiple tasks and check the status of them.
*/
class MultipleTask extends KnotTask {
/** @override */
isManualAsynchronous() {
return this.parameters.numberOfTasks > 0;
}
/** @override */
async doTask() {
let records;
if (this.config.source.file) {
records = await this.getRecordsFromFile_(this.config.source.file);
} else if (this.config.source.csv) {
records = this.getRecordsFromCsv_(this.config.source.csv);
} else {
console.error('Unknown source for Multiple Task', this.config.source);
throw new Error('Unknown source for Multiple Task');
}
console.log(records);
const numberOfTasks = records.length;
if (numberOfTasks === 0) {
return {parameters: this.appendParameter({numberOfTasks})};
}
const multipleTag = nanoid();
if (this.config.destination.target === 'pubsub') {
await this.startThroughPubSub_(multipleTag, records);
} else {
await this.startThroughStorage_(multipleTag, records);
}
return {
parameters: this.appendParameter({
[FIELD_NAMES.MULTIPLE_TAG]: multipleTag,
numberOfTasks,
startTime: Date.now(),
}),
};
}
/**
* Starts multiple tasks by sending out task start messages.
* @param {string} tag The multiple task tag to mark task instances.
* @param {!Array<string>} records Array of multiple task instances data. Each
* element is a JSON string of the 'appendedParameters' object for an task
* instance.
* @return {!Promise<boolean>} Whether messages are all sent out successfully.
* @private
*/
startThroughPubSub_(tag, records) {
const qps = getProperValue(this.config.destination.qps, 1, false);
const managedSend = apiSpeedControl(1, 1, qps);
const sendSingleMessage = async (lines, batchId) => {
if (lines.length !== 1) {
throw Error('Wrong number of Pub/Sub messages.');
}
try {
await this.taskManager.startTasks(
this.config.destination.taskId, {[FIELD_NAMES.MULTIPLE_TAG]: tag},
JSON.stringify(
Object.assign({}, this.parameters, JSON.parse(lines[0]))));
return true;
} catch (error) {
console.error(`Pub/Sub message[${batchId}] failed.`, error);
return false;
}
};
return managedSend(sendSingleMessage, records, `multiple_task_${tag}`);
}
/**
* Get records from a given Cloud Storage file.
* @param {!StorageFileConfig} sourceFile
* @return {Promise<!Array<string>>} Array of record (JSON string).
* @private
*/
async getRecordsFromFile_(sourceFile) {
/** @const {StorageFile} */
const storageFile = StorageFile.getInstance(
sourceFile.bucket, sourceFile.name,
{projectId: this.getCloudProject(sourceFile)});
const records = (await storageFile.loadContent()).split('\n')
.filter((record) => !!record); // filter out empty lines.
return records;
}
/**
* Get records from a given Csv setting.
* @param {{
* header:string,
* records:string,
* }} csv setting
* @return {Array<string>} Array of record (JSON string).
* @private
*/
getRecordsFromCsv_({header, records}) {
const fields = header.split(',').map((field) => field.trim());
return records.split('\n').map((line) => {
const record = {}
line.split(',').forEach((value, index) => {
record[fields[index]] = value.trim();
});
return JSON.stringify(record);
});
}
/**
* Writes out a file for Tentacles to start multiple tasks.
* @param {string} tag The multiple task tag to mark task instances.
* @param {!Array<string>} records Array of multiple task instances data. Each
* element is a JSON string of the 'appendedParameters' object for an task
* instance.
* @private
*/
async startThroughStorage_(tag, records) {
const content = records.map((record) => {
return JSON.stringify(Object.assign(
{},
this.parameters,
JSON.parse(record),
{
taskId: this.config.destination.taskId,
[FIELD_NAMES.MULTIPLE_TAG]: tag,
}));
}).join('\n');
/** @type {StorageFileConfig} */
const destination = this.config.destination.file;
const outputFile = StorageFile.getInstance(
destination.bucket, destination.name, {
projectId: destination.projectId,
keyFilename: destination.keyFilename,
});
await outputFile.getFile().save(content);
}
/**
* Return true if the instance number is 0.
* Otherwise return false if there is a 'estimateRunningTime' and the time is
* not over due; throw an out of time error if there is a 'dueTime' and the
* time is over due; or check the status of multiple tasks.
*
* @override
*/
async isDone() {
if (this.parameters.numberOfTasks === 0) return true;
const multipleConfig = this.config.multiple || {};
const shouldCheck = this.shouldCheckTaskStatus(multipleConfig);
const filter = [{
property: FIELD_NAMES.MULTIPLE_TAG,
value: this.parameters[FIELD_NAMES.MULTIPLE_TAG],
}];
return shouldCheck
? this.areTasksFinished(filter, this.parameters.numberOfTasks)
: false;
}
}
module.exports = {
MultipleTaskConfig,
MultipleTask,
}
| GoogleCloudPlatform/cloud-for-marketing | marketing-analytics/activation/data-tasks-coordinator/src/tasks/multiple_task.js | JavaScript | apache-2.0 | 8,160 |
// Copyright 2018, Google, LLC.
// 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.
'use strict';
/**
* Import the GoogleAuth library, and create a new GoogleAuth client.
*/
const {auth} = require('google-auth-library');
/**
* Acquire a client, and make a request to an API that's enabled by default.
*/
async function main() {
const client = await auth.getClient({
scopes: 'https://www.googleapis.com/auth/cloud-platform',
});
const projectId = await auth.getProjectId();
const url = `https://www.googleapis.com/dns/v1/projects/${projectId}`;
const res = await client.request({url});
console.log('DNS Info:');
console.log(res.data);
}
main().catch(console.error);
| JustinBeckwith/google-auth-library-nodejs | samples/adc.js | JavaScript | apache-2.0 | 1,193 |
/**
* Copyright 2017 Tyler Eastman.
*
* 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.
**/
module.exports = function (RED) {
'use strict';
const ftp = require('ftp');
const fs = require('fs');
const path = require('path');
function FtpDownloadServer(n) {
RED.nodes.createNode(this, n);
const credentials = RED.nodes.getCredentials(n.id);
this.options = {
'host': n.host || 'localhost',
'port': n.port || 21,
'user': n.user || 'anonymous',
'password': credentials.password || 'anonymous@',
'connTimeout': n.connTimeout || 10000,
'pasvTimeout': n.pasvTimeout || 10000,
'keepalive': n.keepalive || 10000
};
}
RED.nodes.registerType('ftp-download-server', FtpDownloadServer, {
credentials: {
password: {type: 'password'}
}
});
function FtpDownloadNode(n) {
RED.nodes.createNode(this, n);
const conn = new ftp();
const flow = this.context().flow;
const global = this.context().global;
const node = this;
node.server = n.server;
node.serverConfig = RED.nodes.getNode(node.server);
node.files = n.files;
node.directory = n.directory;
node.filesType = n.filesType || "str";
node.directoryType = n.directoryType || "str";
node.output = n.output;
let fileList = [];
let directory = "";
node.on('input', (msg) => {
// Load the files list from the appropriate variable.
try {
switch (node.filesType) {
case 'msg':
fileList = msg[node.files];
break;
case 'flow':
fileList = flow.get(node.files);
break;
case 'global':
fileList = global.get(node.files);
break;
case 'json':
fileList = JSON.parse(node.files);
break;
default:
fileList = [node.files];
}
if (!Array.isArray(fileList)) {
node.error("Files field must be an array.", msg);
return;
}
}
catch (err) {
node.error("Could not load files variable, type: " + node.filesType + " location: " + node.files, msg);
return;
}
// Load the directory from the appropriate variable.
try {
switch (node.directoryType) {
case 'msg':
directory = msg[node.directory];
break;
case 'flow':
directory = flow.get(node.directory);
break;
case 'global':
directory = global.get(node.directory);
break;
default:
directory = node.directory;
}
}
catch (err) {
node.error("Could not load directory variable, type: " + node.directoryType + " location: " + node.directory, msg);
return;
}
conn.on('ready', () => {
let promise = Promise.resolve([]);
// Download each file sequentially
fileList.forEach((file) => {
promise = promise.then(download(file));
});
promise
.then((filePaths)=> {
msg[node.output] = filePaths;
node.send(msg);
})
.catch((err) => {
msg.payload = {
fileList: fileList,
directory: directory,
caught: err
};
node.error("FTP download failed", msg);
})
});
function download(file) {
return (filePaths) => new Promise((resolve, reject) => {
try {
let source = file;
if(typeof file.src === "string")
source = file.src;
let destination = path.join(directory, path.basename(source));
if(typeof file.dest === "string"){
destination = path.join(directory, file.dest);
}
conn.get(source, (err, stream) => {
if (err)
reject({"paths": filePaths, "error": err});
filePaths.push(destination);
try {
let writestream = fs.createWriteStream(destination);
writestream.on('error', (err) => {
reject({"paths": filePaths, "error": err});
});
stream.once('finish', () => resolve(filePaths));
stream.pipe(writestream);
}
catch (error) {
reject({"paths": filePaths, "error": error});
}
});
}
catch (error) {
reject({"paths": filePaths, "error": error});
}
});
}
conn.on('error', (err) => {
msg.payload = err;
node.error("An error occurred with the FTP library.", msg);
});
try{
conn.connect(node.serverConfig.options);
}
catch (err) {
msg.payload = err;
node.error("Could not connect to the FTP server.", msg);
}
});
node.on('close', () => {
try {
conn.destroy();
}
catch (err) {
// Do nothing as the node is closed anyway.
}
});
}
RED.nodes.registerType('ftp-download', FtpDownloadNode);
};
| teastman/node-red-contrib-ftp-download | ftp-download.js | JavaScript | apache-2.0 | 6,995 |
Input::
//// [/a/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }
//// [/a/b/file1.ts]
import { T } from "module1";
//// [/a/b/node_modules/module1.ts]
export interface T {}
//// [/a/module1.ts]
export interface T {}
//// [/a/b/tsconfig.json]
{
"compilerOptions": {
"moduleResolution": "node"
},
"files": ["/a/b/file1.ts"]
}
/a/lib/tsc.js -w -p /a/b/tsconfig.json
Output::
>> Screen clear
[[90m12:00:21 AM[0m] Starting compilation in watch mode...
[[90m12:00:24 AM[0m] Found 0 errors. Watching for file changes.
Program root files: ["/a/b/file1.ts"]
Program options: {"moduleResolution":2,"watch":true,"project":"/a/b/tsconfig.json","configFilePath":"/a/b/tsconfig.json"}
Program structureReused: Not
Program files::
/a/lib/lib.d.ts
/a/b/node_modules/module1.ts
/a/b/file1.ts
Semantic diagnostics in builder refreshed for::
/a/lib/lib.d.ts
/a/b/node_modules/module1.ts
/a/b/file1.ts
Shape signatures in builder refreshed for::
/a/lib/lib.d.ts (used version)
/a/b/node_modules/module1.ts (used version)
/a/b/file1.ts (used version)
WatchedFiles::
/a/b/tsconfig.json:
{"fileName":"/a/b/tsconfig.json","pollingInterval":250}
/a/b/file1.ts:
{"fileName":"/a/b/file1.ts","pollingInterval":250}
/a/b/node_modules/module1.ts:
{"fileName":"/a/b/node_modules/module1.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/a/b/node_modules:
{"directoryName":"/a/b/node_modules","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
/a/b/node_modules/@types:
{"directoryName":"/a/b/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
//// [/a/b/file1.js]
"use strict";
exports.__esModule = true;
Change:: Change module resolution to classic
Input::
//// [/a/b/tsconfig.json]
{
"compilerOptions": {
"moduleResolution": "classic"
},
"files": ["/a/b/file1.ts"]
}
Output::
>> Screen clear
[[90m12:00:28 AM[0m] File change detected. Starting incremental compilation...
[[90m12:00:34 AM[0m] Found 0 errors. Watching for file changes.
Program root files: ["/a/b/file1.ts"]
Program options: {"moduleResolution":1,"watch":true,"project":"/a/b/tsconfig.json","configFilePath":"/a/b/tsconfig.json"}
Program structureReused: Not
Program files::
/a/lib/lib.d.ts
/a/module1.ts
/a/b/file1.ts
Semantic diagnostics in builder refreshed for::
/a/module1.ts
/a/b/file1.ts
Shape signatures in builder refreshed for::
/a/module1.ts (computed .d.ts)
/a/b/file1.ts (computed .d.ts)
WatchedFiles::
/a/b/tsconfig.json:
{"fileName":"/a/b/tsconfig.json","pollingInterval":250}
/a/b/file1.ts:
{"fileName":"/a/b/file1.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
/a/module1.ts:
{"fileName":"/a/module1.ts","pollingInterval":250}
FsWatches::
/a/b:
{"directoryName":"/a/b","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
FsWatchesRecursive::
/a/b/node_modules/@types:
{"directoryName":"/a/b/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
//// [/a/b/file1.js] file written with same contents
//// [/a/module1.js]
"use strict";
exports.__esModule = true;
| kpreisser/TypeScript | tests/baselines/reference/tscWatch/programUpdates/should-properly-handle-module-resolution-changes-in-config-file.js | JavaScript | apache-2.0 | 4,002 |
import BvButtonGroup from '../button/button-group'
/* istanbul ignore next */
BvButtonGroup.install = (Vue) => {
Vue.component(BvButtonGroup.name, BvButtonGroup)
}
export default BvButtonGroup
| Harveyzhao/Basic-view | src/components/button-group/index.js | JavaScript | apache-2.0 | 199 |
/**
* @author aleeper / http://adamleeper.com/
* @author mrdoob / http://mrdoob.com/
* @author gero3 / https://github.com/gero3
* @author Mugen87 / https://github.com/Mugen87
* @author neverhood311 / https://github.com/neverhood311
*
* Description: A THREE loader for STL ASCII files, as created by Solidworks and other CAD programs.
*
* Supports both binary and ASCII encoded files, with automatic detection of type.
*
* The loader returns a non-indexed buffer geometry.
*
* Limitations:
* Binary decoding supports "Magics" color format (http://en.wikipedia.org/wiki/STL_(file_format)#Color_in_binary_STL).
* There is perhaps some question as to how valid it is to always assume little-endian-ness.
* ASCII decoding assumes file is UTF-8.
*
* Usage:
* var loader = new STLLoader();
* loader.load( './models/stl/slotted_disk.stl', function ( geometry ) {
* scene.add( new THREE.Mesh( geometry ) );
* });
*
* For binary STLs geometry might contain colors for vertices. To use it:
* // use the same code to load STL as above
* if (geometry.hasColors) {
* material = new THREE.MeshPhongMaterial({ opacity: geometry.alpha, vertexColors: THREE.VertexColors });
* } else { .... }
* var mesh = new THREE.Mesh( geometry, material );
*
* For ASCII STLs containing multiple solids, each solid is assigned to a different group.
* Groups can be used to assign a different color by defining an array of materials with the same length of
* geometry.groups and passing it to the Mesh constructor:
*
* var mesh = new THREE.Mesh( geometry, material );
*
* For example:
*
* var materials = [];
* var nGeometryGroups = geometry.groups.length;
*
* var colorMap = ...; // Some logic to index colors.
*
* for (var i = 0; i < nGeometryGroups; i++) {
*
* var material = new THREE.MeshPhongMaterial({
* color: colorMap[i],
* wireframe: false
* });
*
* }
*
* materials.push(material);
* var mesh = new THREE.Mesh(geometry, materials);
*/
import {
BufferAttribute,
BufferGeometry,
FileLoader,
Float32BufferAttribute,
Loader,
LoaderUtils,
Vector3
} from "./build/three.module.js";
var STLLoader = function ( manager ) {
Loader.call( this, manager );
};
STLLoader.prototype = Object.assign( Object.create( Loader.prototype ), {
constructor: STLLoader,
load: function ( url, onLoad, onProgress, onError ) {
var scope = this;
var loader = new FileLoader( scope.manager );
loader.setPath( scope.path );
loader.setResponseType( 'arraybuffer' );
loader.load( url, function ( text ) {
try {
onLoad( scope.parse( text ) );
} catch ( exception ) {
if ( onError ) {
onError( exception );
}
}
}, onProgress, onError );
},
parse: function ( data ) {
function isBinary( data ) {
var expect, face_size, n_faces, reader;
reader = new DataView( data );
face_size = ( 32 / 8 * 3 ) + ( ( 32 / 8 * 3 ) * 3 ) + ( 16 / 8 );
n_faces = reader.getUint32( 80, true );
expect = 80 + ( 32 / 8 ) + ( n_faces * face_size );
if ( expect === reader.byteLength ) {
return true;
}
// An ASCII STL data must begin with 'solid ' as the first six bytes.
// However, ASCII STLs lacking the SPACE after the 'd' are known to be
// plentiful. So, check the first 5 bytes for 'solid'.
// Several encodings, such as UTF-8, precede the text with up to 5 bytes:
// https://en.wikipedia.org/wiki/Byte_order_mark#Byte_order_marks_by_encoding
// Search for "solid" to start anywhere after those prefixes.
// US-ASCII ordinal values for 's', 'o', 'l', 'i', 'd'
var solid = [ 115, 111, 108, 105, 100 ];
for ( var off = 0; off < 5; off ++ ) {
// If "solid" text is matched to the current offset, declare it to be an ASCII STL.
if ( matchDataViewAt( solid, reader, off ) ) return false;
}
// Couldn't find "solid" text at the beginning; it is binary STL.
return true;
}
function matchDataViewAt( query, reader, offset ) {
// Check if each byte in query matches the corresponding byte from the current offset
for ( var i = 0, il = query.length; i < il; i ++ ) {
if ( query[ i ] !== reader.getUint8( offset + i, false ) ) return false;
}
return true;
}
function parseBinary( data ) {
var reader = new DataView( data );
var faces = reader.getUint32( 80, true );
var r, g, b, hasColors = false, colors;
var defaultR, defaultG, defaultB, alpha;
// process STL header
// check for default color in header ("COLOR=rgba" sequence).
for ( var index = 0; index < 80 - 10; index ++ ) {
if ( ( reader.getUint32( index, false ) == 0x434F4C4F /*COLO*/ ) &&
( reader.getUint8( index + 4 ) == 0x52 /*'R'*/ ) &&
( reader.getUint8( index + 5 ) == 0x3D /*'='*/ ) ) {
hasColors = true;
colors = new Float32Array( faces * 3 * 3 );
defaultR = reader.getUint8( index + 6 ) / 255;
defaultG = reader.getUint8( index + 7 ) / 255;
defaultB = reader.getUint8( index + 8 ) / 255;
alpha = reader.getUint8( index + 9 ) / 255;
}
}
var dataOffset = 84;
var faceLength = 12 * 4 + 2;
var geometry = new BufferGeometry();
var vertices = new Float32Array( faces * 3 * 3 );
var normals = new Float32Array( faces * 3 * 3 );
for ( var face = 0; face < faces; face ++ ) {
var start = dataOffset + face * faceLength;
var normalX = reader.getFloat32( start, true );
var normalY = reader.getFloat32( start + 4, true );
var normalZ = reader.getFloat32( start + 8, true );
if ( hasColors ) {
var packedColor = reader.getUint16( start + 48, true );
if ( ( packedColor & 0x8000 ) === 0 ) {
// facet has its own unique color
r = ( packedColor & 0x1F ) / 31;
g = ( ( packedColor >> 5 ) & 0x1F ) / 31;
b = ( ( packedColor >> 10 ) & 0x1F ) / 31;
} else {
r = defaultR;
g = defaultG;
b = defaultB;
}
}
for ( var i = 1; i <= 3; i ++ ) {
var vertexstart = start + i * 12;
var componentIdx = ( face * 3 * 3 ) + ( ( i - 1 ) * 3 );
vertices[ componentIdx ] = reader.getFloat32( vertexstart, true );
vertices[ componentIdx + 1 ] = reader.getFloat32( vertexstart + 4, true );
vertices[ componentIdx + 2 ] = reader.getFloat32( vertexstart + 8, true );
normals[ componentIdx ] = normalX;
normals[ componentIdx + 1 ] = normalY;
normals[ componentIdx + 2 ] = normalZ;
if ( hasColors ) {
colors[ componentIdx ] = r;
colors[ componentIdx + 1 ] = g;
colors[ componentIdx + 2 ] = b;
}
}
}
geometry.addAttribute( 'position', new BufferAttribute( vertices, 3 ) );
geometry.addAttribute( 'normal', new BufferAttribute( normals, 3 ) );
if ( hasColors ) {
geometry.addAttribute( 'color', new BufferAttribute( colors, 3 ) );
geometry.hasColors = true;
geometry.alpha = alpha;
}
return geometry;
}
function parseASCII( data ) {
var geometry = new BufferGeometry();
var patternSolid = /solid([\s\S]*?)endsolid/g;
var patternFace = /facet([\s\S]*?)endfacet/g;
var faceCounter = 0;
var patternFloat = /[\s]+([+-]?(?:\d*)(?:\.\d*)?(?:[eE][+-]?\d+)?)/.source;
var patternVertex = new RegExp( 'vertex' + patternFloat + patternFloat + patternFloat, 'g' );
var patternNormal = new RegExp( 'normal' + patternFloat + patternFloat + patternFloat, 'g' );
var vertices = [];
var normals = [];
var normal = new Vector3();
var result;
var groupVertexes = [];
var groupCount = 0;
var startVertex = 0;
var endVertex = 0;
while ( ( result = patternSolid.exec( data ) ) !== null ) {
startVertex = endVertex;
var solid = result[ 0 ];
while ( ( result = patternFace.exec( solid ) ) !== null ) {
var vertexCountPerFace = 0;
var normalCountPerFace = 0;
var text = result[ 0 ];
while ( ( result = patternNormal.exec( text ) ) !== null ) {
normal.x = parseFloat( result[ 1 ] );
normal.y = parseFloat( result[ 2 ] );
normal.z = parseFloat( result[ 3 ] );
normalCountPerFace ++;
}
while ( ( result = patternVertex.exec( text ) ) !== null ) {
vertices.push( parseFloat( result[ 1 ] ), parseFloat( result[ 2 ] ), parseFloat( result[ 3 ] ) );
normals.push( normal.x, normal.y, normal.z );
vertexCountPerFace ++;
endVertex ++;
}
// every face have to own ONE valid normal
if ( normalCountPerFace !== 1 ) {
console.error( 'THREE.STLLoader: Something isn\'t right with the normal of face number ' + faceCounter );
}
// each face have to own THREE valid vertices
if ( vertexCountPerFace !== 3 ) {
console.error( 'THREE.STLLoader: Something isn\'t right with the vertices of face number ' + faceCounter );
}
faceCounter ++;
}
groupVertexes.push( { startVertex: startVertex, endVertex: endVertex } );
groupCount ++;
}
geometry.addAttribute( 'position', new Float32BufferAttribute( vertices, 3 ) );
geometry.addAttribute( 'normal', new Float32BufferAttribute( normals, 3 ) );
if ( groupCount > 0 ) {
for ( var i = 0; i < groupVertexes.length; i ++ ) {
geometry.addGroup( groupVertexes[ i ].startVertex, groupVertexes[ i ].endVertex, i );
}
}
return geometry;
}
function ensureString( buffer ) {
if ( typeof buffer !== 'string' ) {
return LoaderUtils.decodeText( new Uint8Array( buffer ) );
}
return buffer;
}
function ensureBinary( buffer ) {
if ( typeof buffer === 'string' ) {
var array_buffer = new Uint8Array( buffer.length );
for ( var i = 0; i < buffer.length; i ++ ) {
array_buffer[ i ] = buffer.charCodeAt( i ) & 0xff; // implicitly assumes little-endian
}
return array_buffer.buffer || array_buffer;
} else {
return buffer;
}
}
// start
var binData = ensureBinary( data );
return isBinary( binData ) ? parseBinary( binData ) : parseASCII( ensureString( data ) );
}
} );
export { STLLoader };
| sPyOpenSource/personal-website | public/games/STLLoader.js | JavaScript | apache-2.0 | 10,067 |
/*! jquery.selectBoxIt - v3.8.1 - 2013-10-17
* http://www.selectboxit.com
* Copyright (c) 2013 Greg Franko; Licensed MIT*/
// Immediately-Invoked Function Expression (IIFE) [Ben Alman Blog Post](http://benalman.com/news/2010/11/immediately-invoked-function-expression/) that calls another IIFE that contains all of the plugin logic. I used this pattern so that anyone viewing this code would not have to scroll to the bottom of the page to view the local parameters that were passed to the main IIFE.
;(function (selectBoxIt) {
//ECMAScript 5 Strict Mode: [John Resig Blog Post](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)
"use strict";
// Calls the second IIFE and locally passes in the global jQuery, window, and document objects
selectBoxIt(window.jQuery, window, document);
}
// Locally passes in `jQuery`, the `window` object, the `document` object, and an `undefined` variable. The `jQuery`, `window` and `document` objects are passed in locally, to improve performance, since javascript first searches for a variable match within the local variables set before searching the global variables set. All of the global variables are also passed in locally to be minifier friendly. `undefined` can be passed in locally, because it is not a reserved word in JavaScript.
(function ($, window, document, undefined) {
// ECMAScript 5 Strict Mode: [John Resig Blog Post](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)
"use strict";
// Calling the jQueryUI Widget Factory Method
$.widget("selectBox.selectBoxIt", {
// Plugin version
VERSION: "3.8.1",
// These options will be used as defaults
options: {
// **showEffect**: Accepts String: "none", "fadeIn", "show", "slideDown", or any of the jQueryUI show effects (i.e. "bounce")
"showEffect": "none",
// **showEffectOptions**: Accepts an object literal. All of the available properties are based on the jqueryUI effect options
"showEffectOptions": {},
// **showEffectSpeed**: Accepts Number (milliseconds) or String: "slow", "medium", or "fast"
"showEffectSpeed": "medium",
// **hideEffect**: Accepts String: "none", "fadeOut", "hide", "slideUp", or any of the jQueryUI hide effects (i.e. "explode")
"hideEffect": "none",
// **hideEffectOptions**: Accepts an object literal. All of the available properties are based on the jqueryUI effect options
"hideEffectOptions": {},
// **hideEffectSpeed**: Accepts Number (milliseconds) or String: "slow", "medium", or "fast"
"hideEffectSpeed": "medium",
// **showFirstOption**: Shows the first dropdown list option within the dropdown list options list
"showFirstOption": true,
// **defaultText**: Overrides the text used by the dropdown list selected option to allow a user to specify custom text. Accepts a String.
"defaultText": "",
// **defaultIcon**: Overrides the icon used by the dropdown list selected option to allow a user to specify a custom icon. Accepts a String (CSS class name(s)).
"defaultIcon": "",
// **downArrowIcon**: Overrides the default down arrow used by the dropdown list to allow a user to specify a custom image. Accepts a String (CSS class name(s)).
"downArrowIcon": "",
// **theme**: Provides theming support for Twitter Bootstrap and jQueryUI
"theme": "theme",
// **keydownOpen**: Opens the dropdown if the up or down key is pressed when the dropdown is focused
"keydownOpen": true,
// **isMobile**: Function to determine if a user's browser is a mobile browser
"isMobile": function() {
// Adapted from http://www.detectmobilebrowsers.com
var ua = navigator.userAgent || navigator.vendor || window.opera;
// Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
},
// **native**: Triggers the native select box when a user interacts with the drop down
"native": false,
// **aggressiveChange**: Will select a drop down item (and trigger a change event) when a user navigates to the item via the keyboard (up and down arrow or search), before a user selects an option with a click or the enter key
"aggressiveChange": false,
// **selectWhenHidden: Will allow a user to select an option using the keyboard when the drop down list is hidden and focused
"selectWhenHidden": true,
// **viewport**: Allows for a custom domnode used for the viewport. Accepts a selector. Default is $(window).
"viewport": $(window),
// **similarSearch**: Optimizes the search for lists with many similar values (i.e. State lists) by making it easier to navigate through
"similarSearch": false,
// **copyAttributes**: HTML attributes that will be copied over to the new drop down
"copyAttributes": [
"title",
"rel"
],
// **copyClasses**: HTML classes that will be copied over to the new drop down. The value indicates where the classes should be copied. The default value is 'button', but you can also use 'container' (recommended) or 'none'.
"copyClasses": "button",
// **nativeMousedown**: Mimics native firefox drop down behavior by opening the drop down on mousedown and selecting the currently hovered drop down option on mouseup
"nativeMousedown": false,
// **customShowHideEvent**: Prevents the drop down from opening on click or mousedown, which allows a user to open/close the drop down with a custom event handler.
"customShowHideEvent": false,
// **autoWidth**: Makes sure the width of the drop down is wide enough to fit all of the drop down options
"autoWidth": true,
// **html**: Determines whether or not option text is rendered as html or as text
"html": true,
// **populate**: Convenience option that accepts JSON data, an array, a single object, or valid HTML string to add options to the drop down list
"populate": "",
// **dynamicPositioning**: Determines whether or not the drop down list should fit inside it's viewport
"dynamicPositioning": true,
// **hideCurrent**: Determines whether or not the currently selected drop down option is hidden in the list
"hideCurrent": false
},
// Get Themes
// ----------
// Retrieves the active drop down theme and returns the theme object
"getThemes": function() {
var self = this,
theme = $(self.element).attr("data-theme") || "c";
return {
// Twitter Bootstrap Theme
"bootstrap": {
"focus": "active",
"hover": "",
"enabled": "enabled",
"disabled": "disabled",
"arrow": "caret",
"button": "btn",
"list": "dropdown-menu",
"container": "bootstrap",
"open": "open"
},
// jQueryUI Theme
"jqueryui": {
"focus": "ui-state-focus",
"hover": "ui-state-hover",
"enabled": "ui-state-enabled",
"disabled": "ui-state-disabled",
"arrow": "ui-icon ui-icon-triangle-1-s",
"button": "ui-widget ui-state-default",
"list": "ui-widget ui-widget-content",
"container": "jqueryui",
"open": "selectboxit-open"
},
// jQuery Mobile Theme
"jquerymobile": {
"focus": "ui-btn-down-" + theme,
"hover": "ui-btn-hover-" + theme,
"enabled": "ui-enabled",
"disabled": "ui-disabled",
"arrow": "ui-icon ui-icon-arrow-d ui-icon-shadow",
"button": "ui-btn ui-btn-icon-right ui-btn-corner-all ui-shadow ui-btn-up-" + theme,
"list": "ui-btn ui-btn-icon-right ui-btn-corner-all ui-shadow ui-btn-up-" + theme,
"container": "jquerymobile",
"open": "selectboxit-open"
},
"default": {
"focus": "selectboxit-focus",
"hover": "selectboxit-hover",
"enabled": "selectboxit-enabled",
"disabled": "selectboxit-disabled",
"arrow": "selectboxit-default-arrow",
"button": "selectboxit-btn",
"list": "selectboxit-list",
"container": "selectboxit-container",
"open": "selectboxit-open"
}
};
},
// isDeferred
// ----------
// Checks if parameter is a defered object
isDeferred: function(def) {
return $.isPlainObject(def) && def.promise && def.done;
},
// _Create
// -------
// Sets the Plugin Instance variables and
// constructs the plugin. Only called once.
_create: function(internal) {
var self = this,
populateOption = self.options["populate"],
userTheme = self.options["theme"];
// If the element calling SelectBoxIt is not a select box or is not visible
if(!self.element.is("select")) {
// Exits the plugin
return;
}
// Stores a reference to the parent Widget class
self.widgetProto = $.Widget.prototype;
// The original select box DOM element
self.originalElem = self.element[0];
// The original select box DOM element wrapped in a jQuery object
self.selectBox = self.element;
if(self.options["populate"] && self.add && !internal) {
self.add(populateOption);
}
// All of the original select box options
self.selectItems = self.element.find("option");
// The first option in the original select box
self.firstSelectItem = self.selectItems.slice(0, 1);
// The html document height
self.documentHeight = $(document).height();
self.theme = $.isPlainObject(userTheme) ? $.extend({}, self.getThemes()["default"], userTheme) : self.getThemes()[userTheme] ? self.getThemes()[userTheme] : self.getThemes()["default"];
// The index of the currently selected dropdown list option
self.currentFocus = 0;
// Keeps track of which blur events will hide the dropdown list options
self.blur = true;
// Array holding all of the original select box options text
self.textArray = [];
// Maintains search order in the `search` method
self.currentIndex = 0;
// Maintains the current search text in the `search` method
self.currentText = "";
// Whether or not the dropdown list opens up or down (depending on how much room is on the page)
self.flipped = false;
// If the create method is not called internally by the plugin
if(!internal) {
// Saves the original select box `style` attribute within the `selectBoxStyles` plugin instance property
self.selectBoxStyles = self.selectBox.attr("style");
}
// Creates the dropdown elements that will become the dropdown
// Creates the ul element that will become the dropdown options list
// Add's all attributes (excluding id, class names, and unselectable properties) to the drop down and drop down items list
// Hides the original select box and adds the new plugin DOM elements to the page
// Adds event handlers to the new dropdown list
self._createDropdownButton()._createUnorderedList()._copyAttributes()._replaceSelectBox()._addClasses(self.theme)._eventHandlers();
if(self.originalElem.disabled && self.disable) {
// Disables the dropdown list if the original dropdown list had the `disabled` attribute
self.disable();
}
// If the Aria Accessibility Module has been included
if(self._ariaAccessibility) {
// Adds ARIA accessibillity tags to the dropdown list
self._ariaAccessibility();
}
self.isMobile = self.options["isMobile"]();
if(self._mobile) {
// Adds mobile support
self._mobile();
}
// If the native option is set to true
if(self.options["native"]) {
// Triggers the native select box when a user is interacting with the drop down
this._applyNativeSelect();
}
// Triggers a custom `create` event on the original dropdown list
self.triggerEvent("create");
// Maintains chainability
return self;
},
// _Create dropdown button
// -----------------------
// Creates new dropdown and dropdown elements to replace
// the original select box with a dropdown list
_createDropdownButton: function() {
var self = this,
originalElemId = self.originalElemId = self.originalElem.id || "",
originalElemValue = self.originalElemValue = self.originalElem.value || "",
originalElemName = self.originalElemName = self.originalElem.name || "",
copyClasses = self.options["copyClasses"],
selectboxClasses = self.selectBox.attr("class") || "";
// Creates a dropdown element that contains the dropdown list text value
self.dropdownText = $("<span/>", {
// Dynamically sets the dropdown `id` attribute
"id": originalElemId && originalElemId + "SelectBoxItText",
"class": "selectboxit-text",
// IE specific attribute to not allow the element to be selected
"unselectable": "on",
// Sets the dropdown `text` to equal the original select box default value
"text": self.firstSelectItem.text()
}).
// Sets the HTML5 data attribute on the dropdownText `dropdown` element
attr("data-val", originalElemValue);
self.dropdownImageContainer = $("<span/>", {
"class": "selectboxit-option-icon-container"
});
// Creates a dropdown element that contains the dropdown list text value
self.dropdownImage = $("<i/>", {
// Dynamically sets the dropdown `id` attribute
"id": originalElemId && originalElemId + "SelectBoxItDefaultIcon",
"class": "selectboxit-default-icon",
// IE specific attribute to not allow the element to be selected
"unselectable": "on"
});
// Creates a dropdown to act as the new dropdown list
self.dropdown = $("<span/>", {
// Dynamically sets the dropdown `id` attribute
"id": originalElemId && originalElemId + "SelectBoxIt",
"class": "selectboxit " + (copyClasses === "button" ? selectboxClasses: "") + " " + (self.selectBox.prop("disabled") ? self.theme["disabled"]: self.theme["enabled"]),
// Sets the dropdown `name` attribute to be the same name as the original select box
"name": originalElemName,
// Sets the dropdown `tabindex` attribute to 0 to allow the dropdown to be focusable
"tabindex": self.selectBox.attr("tabindex") || "0",
// IE specific attribute to not allow the element to be selected
"unselectable": "on"
}).
// Appends the default text to the inner dropdown list dropdown element
append(self.dropdownImageContainer.append(self.dropdownImage)).append(self.dropdownText);
// Create the dropdown container that will hold all of the dropdown list dom elements
self.dropdownContainer = $("<span/>", {
"id": originalElemId && originalElemId + "SelectBoxItContainer",
"class": 'selectboxit-container ' + self.theme.container + ' ' + (copyClasses === "container" ? selectboxClasses: "")
}).
// Appends the inner dropdown list dropdown element to the dropdown list container dropdown element
append(self.dropdown);
// Maintains chainability
return self;
},
// _Create Unordered List
// ----------------------
// Creates an unordered list element to hold the
// new dropdown list options that directly match
// the values of the original select box options
_createUnorderedList: function() {
// Storing the context of the widget
var self = this,
dataDisabled,
optgroupClass,
optgroupElement,
iconClass,
iconUrl,
iconUrlClass,
iconUrlStyle,
// Declaring the variable that will hold all of the dropdown list option elements
currentItem = "",
originalElemId = self.originalElemId || "",
// Creates an unordered list element
createdList = $("<ul/>", {
// Sets the unordered list `id` attribute
"id": originalElemId && originalElemId + "SelectBoxItOptions",
"class": "selectboxit-options",
//Sets the unordered list `tabindex` attribute to -1 to prevent the unordered list from being focusable
"tabindex": -1
}),
currentDataSelectedText,
currentDataText,
currentDataSearch,
currentText,
currentOption,
parent;
// Checks the `showFirstOption` plugin option to determine if the first dropdown list option should be shown in the options list.
if (!self.options["showFirstOption"]) {
// Disables the first select box option
self.selectItems.first().attr("disabled", "disabled");
// Excludes the first dropdown list option from the options list
self.selectItems = self.selectBox.find("option").slice(1);
}
// Loops through the original select box options list and copies the text of each
// into new list item elements of the new dropdown list
self.selectItems.each(function(index) {
currentOption = $(this);
optgroupClass = "";
optgroupElement = "";
dataDisabled = currentOption.prop("disabled");
iconClass = currentOption.attr("data-icon") || "";
iconUrl = currentOption.attr("data-iconurl") || "";
iconUrlClass = iconUrl ? "selectboxit-option-icon-url": "";
iconUrlStyle = iconUrl ? 'style="background-image:url(\'' + iconUrl + '\');"': "";
currentDataSelectedText = currentOption.attr("data-selectedtext");
currentDataText = currentOption.attr("data-text");
currentText = currentDataText ? currentDataText: currentOption.text();
parent = currentOption.parent();
// If the current option being traversed is within an optgroup
if(parent.is("optgroup")) {
optgroupClass = "selectboxit-optgroup-option";
if(currentOption.index() === 0) {
optgroupElement = '<span class="selectboxit-optgroup-header ' + parent.first().attr("class") + '"data-disabled="true">' + parent.first().attr("label") + '</span>';
}
}
currentOption.attr("value", this.value);
// Uses string concatenation for speed (applies HTML attribute encoding)
currentItem += optgroupElement + '<li data-id="' + index + '" data-val="' + this.value + '" data-disabled="' + dataDisabled + '" class="' + optgroupClass + " selectboxit-option " + ($(this).attr("class") || "") + '"><a class="selectboxit-option-anchor"><span class="selectboxit-option-icon-container"><i class="selectboxit-option-icon ' + iconClass + ' ' + (iconUrlClass || self.theme["container"]) + '"' + iconUrlStyle + '></i></span>' + (self.options["html"] ? currentText: self.htmlEscape(currentText)) + '</a></li>';
currentDataSearch = currentOption.attr("data-search");
// Stores all of the original select box options text inside of an array
// (Used later in the `searchAlgorithm` method)
self.textArray[index] = dataDisabled ? "": currentDataSearch ? currentDataSearch: currentText;
// Checks the original select box option for the `selected` attribute
if (this.selected) {
// Replaces the default text with the selected option text
self._setText(self.dropdownText, currentDataSelectedText || currentText);
//Set the currently selected option
self.currentFocus = index;
}
});
// If the `defaultText` option is being used
if ((self.options["defaultText"] || self.selectBox.attr("data-text"))) {
var defaultedText = self.options["defaultText"] || self.selectBox.attr("data-text");
// Overrides the current dropdown default text with the value the user specifies in the `defaultText` option
self._setText(self.dropdownText, defaultedText);
self.options["defaultText"] = defaultedText;
}
// Append the list item to the unordered list
createdList.append(currentItem);
// Stores the dropdown list options list inside of the `list` instance variable
self.list = createdList;
// Append the dropdown list options list to the dropdown container element
self.dropdownContainer.append(self.list);
// Stores the individual dropdown list options inside of the `listItems` instance variable
self.listItems = self.list.children("li");
self.listAnchors = self.list.find("a");
// Sets the 'selectboxit-option-first' class name on the first drop down option
self.listItems.first().addClass("selectboxit-option-first");
// Sets the 'selectboxit-option-last' class name on the last drop down option
self.listItems.last().addClass("selectboxit-option-last");
// Set the disabled CSS class for select box options
self.list.find("li[data-disabled='true']").not(".optgroupHeader").addClass(self.theme["disabled"]);
self.dropdownImage.addClass(self.selectBox.attr("data-icon") || self.options["defaultIcon"] || self.listItems.eq(self.currentFocus).find("i").attr("class"));
self.dropdownImage.attr("style", self.listItems.eq(self.currentFocus).find("i").attr("style"));
//Maintains chainability
return self;
},
// _Replace Select Box
// -------------------
// Hides the original dropdown list and inserts
// the new DOM elements
_replaceSelectBox: function() {
var self = this,
height,
originalElemId = self.originalElem.id || "",
size = self.selectBox.attr("data-size"),
listSize = self.listSize = size === undefined ? "auto" : size === "0" || "size" === "auto" ? "auto" : +size,
downArrowContainerWidth,
dropdownImageWidth;
// Hides the original select box
self.selectBox.css("display", "none").
// Adds the new dropdown list to the page directly after the hidden original select box element
after(self.dropdownContainer);
self.dropdownContainer.appendTo('body').
addClass('selectboxit-rendering');
// The height of the dropdown list
height = self.dropdown.height();
// The down arrow element of the dropdown list
self.downArrow = $("<i/>", {
// Dynamically sets the dropdown `id` attribute of the dropdown list down arrow
"id": originalElemId && originalElemId + "SelectBoxItArrow",
"class": "selectboxit-arrow",
// IE specific attribute to not allow the dropdown list text to be selected
"unselectable": "on"
});
// The down arrow container element of the dropdown list
self.downArrowContainer = $("<span/>", {
// Dynamically sets the dropdown `id` attribute for the down arrow container element
"id": originalElemId && originalElemId + "SelectBoxItArrowContainer",
"class": "selectboxit-arrow-container",
// IE specific attribute to not allow the dropdown list text to be selected
"unselectable": "on"
}).
// Inserts the down arrow element inside of the down arrow container element
append(self.downArrow);
// Appends the down arrow element to the dropdown list
self.dropdown.append(self.downArrowContainer);
// Adds the `selectboxit-selected` class name to the currently selected drop down option
self.listItems.removeClass("selectboxit-selected").eq(self.currentFocus).addClass("selectboxit-selected");
// The full outer width of the down arrow container
downArrowContainerWidth = self.downArrowContainer.outerWidth(true);
// The full outer width of the dropdown image
dropdownImageWidth = self.dropdownImage.outerWidth(true);
// If the `autoWidth` option is true
if(self.options["autoWidth"]) {
// Sets the auto width of the drop down
self.dropdown.css({ "width": "auto" }).css({
"width": self.list.outerWidth(true) + downArrowContainerWidth + dropdownImageWidth
});
self.list.css({
"min-width": self.dropdown.width()
});
}
// Dynamically adds the `max-width` and `line-height` CSS styles of the dropdown list text element
self.dropdownText.css({
"max-width": self.dropdownContainer.outerWidth(true) - (downArrowContainerWidth + dropdownImageWidth)
});
// Adds the new dropdown list to the page directly after the hidden original select box element
self.selectBox.after(self.dropdownContainer);
self.dropdownContainer.removeClass('selectboxit-rendering');
if($.type(listSize) === "number") {
// Stores the new `max-height` for later
self.maxHeight = self.listAnchors.outerHeight(true) * listSize;
}
// Maintains chainability
return self;
},
// _Scroll-To-View
// ---------------
// Updates the dropdown list scrollTop value
_scrollToView: function(type) {
var self = this,
currentOption = self.listItems.eq(self.currentFocus),
// The current scroll positioning of the dropdown list options list
listScrollTop = self.list.scrollTop(),
// The height of the currently selected dropdown list option
currentItemHeight = currentOption.height(),
// The relative distance from the currently selected dropdown list option to the the top of the dropdown list options list
currentTopPosition = currentOption.position().top,
absCurrentTopPosition = Math.abs(currentTopPosition),
// The height of the dropdown list option list
listHeight = self.list.height(),
currentText;
// Scrolling logic for a text search
if (type === "search") {
// Increases the dropdown list options `scrollTop` if a user is searching for an option
// below the currently selected option that is not visible
if (listHeight - currentTopPosition < currentItemHeight) {
// The selected option will be shown at the very bottom of the visible options list
self.list.scrollTop(listScrollTop + (currentTopPosition - (listHeight - currentItemHeight)));
}
// Decreases the dropdown list options `scrollTop` if a user is searching for an option above the currently selected option that is not visible
else if (currentTopPosition < -1) {
self.list.scrollTop(currentTopPosition - currentItemHeight);
}
}
// Scrolling logic for the `up` keyboard navigation
else if (type === "up") {
// Decreases the dropdown list option list `scrollTop` if a user is navigating to an element that is not visible
if (currentTopPosition < -1) {
self.list.scrollTop(listScrollTop - absCurrentTopPosition);
}
}
// Scrolling logic for the `down` keyboard navigation
else if (type === "down") {
// Increases the dropdown list options `scrollTop` if a user is navigating to an element that is not fully visible
if (listHeight - currentTopPosition < currentItemHeight) {
// Increases the dropdown list options `scrollTop` by the height of the current option item.
self.list.scrollTop((listScrollTop + (absCurrentTopPosition - listHeight + currentItemHeight)));
}
}
// Maintains chainability
return self;
},
// _Callback
// ---------
// Call the function passed into the method
_callbackSupport: function(callback) {
var self = this;
// Checks to make sure the parameter passed in is a function
if ($.isFunction(callback)) {
// Calls the method passed in as a parameter and sets the current `SelectBoxIt` object that is stored in the jQuery data method as the context(allows for `this` to reference the SelectBoxIt API Methods in the callback function. The `dropdown` DOM element that acts as the new dropdown list is also passed as the only parameter to the callback
callback.call(self, self.dropdown);
}
// Maintains chainability
return self;
},
// _setText
// --------
// Set's the text or html for the drop down
_setText: function(elem, currentText) {
var self = this;
if(self.options["html"]) {
elem.html(currentText);
}
else {
elem.text(currentText);
}
return self;
},
// Open
// ----
// Opens the dropdown list options list
open: function(callback) {
var self = this,
showEffect = self.options["showEffect"],
showEffectSpeed = self.options["showEffectSpeed"],
showEffectOptions = self.options["showEffectOptions"],
isNative = self.options["native"],
isMobile = self.isMobile;
// If there are no select box options, do not try to open the select box
if(!self.listItems.length || self.dropdown.hasClass(self.theme["disabled"])) {
return self;
}
// If the new drop down is being used and is not visible
if((!isNative && !isMobile) && !this.list.is(":visible")) {
// Triggers a custom "open" event on the original select box
self.triggerEvent("open");
if (self._dynamicPositioning && self.options["dynamicPositioning"]) {
// Dynamically positions the dropdown list options list
self._dynamicPositioning();
}
// Uses `no effect`
if(showEffect === "none") {
// Does not require a callback function because this animation will complete before the call to `scrollToView`
self.list.show();
}
// Uses the jQuery `show` special effect
else if(showEffect === "show" || showEffect === "slideDown" || showEffect === "fadeIn") {
// Requires a callback function to determine when the `show` animation is complete
self.list[showEffect](showEffectSpeed);
}
// If none of the above options were passed, then a `jqueryUI show effect` is expected
else {
// Allows for custom show effects via the [jQueryUI core effects](http://http://jqueryui.com/demos/show/)
self.list.show(showEffect, showEffectOptions, showEffectSpeed);
}
self.list.promise().done(function() {
// Updates the list `scrollTop` attribute
self._scrollToView("search");
// Triggers a custom "opened" event when the drop down list is done animating
self.triggerEvent("opened");
});
}
// Provide callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
},
// Close
// -----
// Closes the dropdown list options list
close: function(callback) {
var self = this,
hideEffect = self.options["hideEffect"],
hideEffectSpeed = self.options["hideEffectSpeed"],
hideEffectOptions = self.options["hideEffectOptions"],
isNative = self.options["native"],
isMobile = self.isMobile;
// If the drop down is being used and is visible
if((!isNative && !isMobile) && self.list.is(":visible")) {
// Triggers a custom "close" event on the original select box
self.triggerEvent("close");
// Uses `no effect`
if(hideEffect === "none") {
// Does not require a callback function because this animation will complete before the call to `scrollToView`
self.list.hide();
}
// Uses the jQuery `hide` special effect
else if(hideEffect === "hide" || hideEffect === "slideUp" || hideEffect === "fadeOut") {
self.list[hideEffect](hideEffectSpeed);
}
// If none of the above options were passed, then a `jqueryUI hide effect` is expected
else {
// Allows for custom hide effects via the [jQueryUI core effects](http://http://jqueryui.com/demos/hide/)
self.list.hide(hideEffect, hideEffectOptions, hideEffectSpeed);
}
// After the drop down list is done animating
self.list.promise().done(function() {
// Triggers a custom "closed" event when the drop down list is done animating
self.triggerEvent("closed");
});
}
// Provide callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
},
toggle: function() {
var self = this,
listIsVisible = self.list.is(":visible");
if(listIsVisible) {
self.close();
}
else if(!listIsVisible) {
self.open();
}
},
// _Key Mappings
// -------------
// Object literal holding the string representation of each key code
_keyMappings: {
"38": "up",
"40": "down",
"13": "enter",
"8": "backspace",
"9": "tab",
"32": "space",
"27": "esc"
},
// _Key Down Methods
// -----------------
// Methods to use when the keydown event is triggered
_keydownMethods: function() {
var self = this,
moveToOption = self.list.is(":visible") || !self.options["keydownOpen"];
return {
"down": function() {
// If the plugin options allow keyboard navigation
if (self.moveDown && moveToOption) {
self.moveDown();
}
},
"up": function() {
// If the plugin options allow keyboard navigation
if (self.moveUp && moveToOption) {
self.moveUp();
}
},
"enter": function() {
var activeElem = self.listItems.eq(self.currentFocus);
// Updates the dropdown list value
self._update(activeElem);
if (activeElem.attr("data-preventclose") !== "true") {
// Closes the drop down list options list
self.close();
}
// Triggers the `enter` events on the original select box
self.triggerEvent("enter");
},
"tab": function() {
// Triggers the custom `tab-blur` event on the original select box
self.triggerEvent("tab-blur");
// Closes the drop down list
self.close();
},
"backspace": function() {
// Triggers the custom `backspace` event on the original select box
self.triggerEvent("backspace");
},
"esc": function() {
// Closes the dropdown options list
self.close();
}
};
},
// _Event Handlers
// ---------------
// Adds event handlers to the new dropdown and the original select box
_eventHandlers: function() {
// LOCAL VARIABLES
var self = this,
nativeMousedown = self.options["nativeMousedown"],
customShowHideEvent = self.options["customShowHideEvent"],
currentDataText,
currentText,
focusClass = self.focusClass,
hoverClass = self.hoverClass,
openClass = self.openClass;
// Select Box events
this.dropdown.on({
// `click` event with the `selectBoxIt` namespace
"click.selectBoxIt": function() {
// Used to make sure the dropdown becomes focused (fixes IE issue)
self.dropdown.trigger("focus", true);
// The `click` handler logic will only be applied if the dropdown list is enabled
if (!self.originalElem.disabled) {
// Triggers the `click` event on the original select box
self.triggerEvent("click");
if(!nativeMousedown && !customShowHideEvent) {
self.toggle();
}
}
},
// `mousedown` event with the `selectBoxIt` namespace
"mousedown.selectBoxIt": function() {
// Stores data in the jQuery `data` method to help determine if the dropdown list gains focus from a click or tabstop. The mousedown event fires before the focus event.
$(this).data("mdown", true);
self.triggerEvent("mousedown");
if(nativeMousedown && !customShowHideEvent) {
self.toggle();
}
},
// `mouseup` event with the `selectBoxIt` namespace
"mouseup.selectBoxIt": function() {
self.triggerEvent("mouseup");
},
// `blur` event with the `selectBoxIt` namespace. Uses special blur logic to make sure the dropdown list closes correctly
"blur.selectBoxIt": function() {
// If `self.blur` property is true
if (self.blur) {
// Triggers both the `blur` and `focusout` events on the original select box.
// The `focusout` event is also triggered because the event bubbles
// This event has to be used when using event delegation (such as the jQuery `delegate` or `on` methods)
// Popular open source projects such as Backbone.js utilize event delegation to bind events, so if you are using Backbone.js, use the `focusout` event instead of the `blur` event
self.triggerEvent("blur");
// Closes the dropdown list options list
self.close();
$(this).removeClass(focusClass);
}
},
"focus.selectBoxIt": function(event, internal) {
// Stores the data associated with the mousedown event inside of a local variable
var mdown = $(this).data("mdown");
// Removes the jQuery data associated with the mousedown event
$(this).removeData("mdown");
// If a mousedown event did not occur and no data was passed to the focus event (this correctly triggers the focus event), then the dropdown list gained focus from a tabstop
if (!mdown && !internal) {
setTimeout(function() {
// Triggers the `tabFocus` custom event on the original select box
self.triggerEvent("tab-focus");
}, 0);
}
// Only trigger the `focus` event on the original select box if the dropdown list is hidden (this verifies that only the correct `focus` events are used to trigger the event on the original select box
if(!internal) {
if(!$(this).hasClass(self.theme["disabled"])) {
$(this).addClass(focusClass);
}
//Triggers the `focus` default event on the original select box
self.triggerEvent("focus");
}
},
// `keydown` event with the `selectBoxIt` namespace. Catches all user keyboard navigations
"keydown.selectBoxIt": function(e) {
// Stores the `keycode` value in a local variable
var currentKey = self._keyMappings[e.keyCode],
keydownMethod = self._keydownMethods()[currentKey];
if(keydownMethod) {
keydownMethod();
if(self.options["keydownOpen"] && (currentKey === "up" || currentKey === "down")) {
self.open();
}
}
if(keydownMethod && currentKey !== "tab") {
e.preventDefault();
}
},
// `keypress` event with the `selectBoxIt` namespace. Catches all user keyboard text searches since you can only reliably get character codes using the `keypress` event
"keypress.selectBoxIt": function(e) {
// Sets the current key to the `keyCode` value if `charCode` does not exist. Used for cross
// browser support since IE uses `keyCode` instead of `charCode`.
var currentKey = e.charCode || e.keyCode,
key = self._keyMappings[e.charCode || e.keyCode],
// Converts unicode values to characters
alphaNumericKey = String.fromCharCode(currentKey);
// If the plugin options allow text searches
if (self.search && (!key || (key && key === "space"))) {
// Calls `search` and passes the character value of the user's text search
self.search(alphaNumericKey, true, true);
}
if(key === "space") {
e.preventDefault();
}
},
// `mousenter` event with the `selectBoxIt` namespace .The mouseenter JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser.
"mouseenter.selectBoxIt": function() {
// Trigger the `mouseenter` event on the original select box
self.triggerEvent("mouseenter");
},
// `mouseleave` event with the `selectBoxIt` namespace. The mouseleave JavaScript event is proprietary to Internet Explorer. Because of the event's general utility, jQuery simulates this event so that it can be used regardless of browser.
"mouseleave.selectBoxIt": function() {
// Trigger the `mouseleave` event on the original select box
self.triggerEvent("mouseleave");
}
});
// Select box options events that set the dropdown list blur logic (decides when the dropdown list gets
// closed)
self.list.on({
// `mouseover` event with the `selectBoxIt` namespace
"mouseover.selectBoxIt": function() {
// Prevents the dropdown list options list from closing
self.blur = false;
},
// `mouseout` event with the `selectBoxIt` namespace
"mouseout.selectBoxIt": function() {
// Allows the dropdown list options list to close
self.blur = true;
},
// `focusin` event with the `selectBoxIt` namespace
"focusin.selectBoxIt": function() {
// Prevents the default browser outline border to flicker, which results because of the `blur` event
self.dropdown.trigger("focus", true);
}
});
// Select box individual options events bound with the jQuery `delegate` method. `Delegate` was used because binding indropdownidual events to each list item (since we don't know how many there will be) would decrease performance. Instead, we bind each event to the unordered list, provide the list item context, and allow the list item events to bubble up (`event bubbling`). This greatly increases page performance because we only have to bind an event to one element instead of x number of elements. Delegates the `click` event with the `selectBoxIt` namespace to the list items
self.list.on({
"mousedown.selectBoxIt": function() {
self._update($(this));
self.triggerEvent("option-click");
// If the current drop down option is not disabled
if ($(this).attr("data-disabled") === "false" && $(this).attr("data-preventclose") !== "true") {
// Closes the drop down list
self.close();
}
setTimeout(function() {
self.dropdown.trigger('focus', true);
}, 0);
},
// Delegates the `focusin` event with the `selectBoxIt` namespace to the list items
"focusin.selectBoxIt": function() {
// Removes the hover class from the previous drop down option
self.listItems.not($(this)).removeAttr("data-active");
$(this).attr("data-active", "");
var listIsHidden = self.list.is(":hidden");
if((self.options["searchWhenHidden"] && listIsHidden) || self.options["aggressiveChange"] || (listIsHidden && self.options["selectWhenHidden"])) {
self._update($(this));
}
// Adds the focus CSS class to the currently focused dropdown list option
$(this).addClass(focusClass);
},
// Delegates the `focus` event with the `selectBoxIt` namespace to the list items
"mouseup.selectBoxIt": function() {
if(nativeMousedown && !customShowHideEvent) {
self._update($(this));
self.triggerEvent("option-mouseup");
// If the current drop down option is not disabled
if ($(this).attr("data-disabled") === "false" && $(this).attr("data-preventclose") !== "true") {
// Closes the drop down list
self.close();
}
}
},
// Delegates the `mouseenter` event with the `selectBoxIt` namespace to the list items
"mouseenter.selectBoxIt": function() {
// If the currently moused over drop down option is not disabled
if($(this).attr("data-disabled") === "false") {
self.listItems.removeAttr("data-active");
$(this).addClass(focusClass).attr("data-active", "");
// Sets the dropdown list indropdownidual options back to the default state and sets the focus CSS class on the currently hovered option
self.listItems.not($(this)).removeClass(focusClass);
$(this).addClass(focusClass);
self.currentFocus = +$(this).attr("data-id");
}
},
// Delegates the `mouseleave` event with the `selectBoxIt` namespace to the list items
"mouseleave.selectBoxIt": function() {
// If the currently moused over drop down option is not disabled
if($(this).attr("data-disabled") === "false") {
// Removes the focus class from the previous drop down option
self.listItems.not($(this)).removeClass(focusClass).removeAttr("data-active");
$(this).addClass(focusClass);
self.currentFocus = +$(this).attr("data-id");
}
},
// Delegates the `blur` event with the `selectBoxIt` namespace to the list items
"blur.selectBoxIt": function() {
// Removes the focus CSS class from the previously focused dropdown list option
$(this).removeClass(focusClass);
}
}, ".selectboxit-option");
// Select box individual option anchor events bound with the jQuery `delegate` method. `Delegate` was used because binding indropdownidual events to each list item (since we don't know how many there will be) would decrease performance. Instead, we bind each event to the unordered list, provide the list item context, and allow the list item events to bubble up (`event bubbling`). This greatly increases page performance because we only have to bind an event to one element instead of x number of elements. Delegates the `click` event with the `selectBoxIt` namespace to the list items
self.list.on({
"click.selectBoxIt": function(ev) {
// Prevents the internal anchor tag from doing anything funny
ev.preventDefault();
}
}, "a");
// Original dropdown list events
self.selectBox.on({
// `change` event handler with the `selectBoxIt` namespace
"change.selectBoxIt, internal-change.selectBoxIt": function(event, internal) {
var currentOption,
currentDataSelectedText;
// If the user called the change method
if(!internal) {
currentOption = self.list.find('li[data-val="' + self.originalElem.value + '"]');
// If there is a dropdown option with the same value as the original select box element
if(currentOption.length) {
self.listItems.eq(self.currentFocus).removeClass(self.focusClass);
self.currentFocus = +currentOption.attr("data-id");
}
}
currentOption = self.listItems.eq(self.currentFocus);
currentDataSelectedText = currentOption.attr("data-selectedtext");
currentDataText = currentOption.attr("data-text");
currentText = currentDataText ? currentDataText: currentOption.find("a").text();
// Sets the new dropdown list text to the value of the current option
self._setText(self.dropdownText, currentDataSelectedText || currentText);
self.dropdownText.attr("data-val", self.originalElem.value);
if(currentOption.find("i").attr("class")) {
self.dropdownImage.attr("class", currentOption.find("i").attr("class")).addClass("selectboxit-default-icon");
self.dropdownImage.attr("style", currentOption.find("i").attr("style"));
}
// Triggers a custom changed event on the original select box
self.triggerEvent("changed");
},
// `disable` event with the `selectBoxIt` namespace
"disable.selectBoxIt": function() {
// Adds the `disabled` CSS class to the new dropdown list to visually show that it is disabled
self.dropdown.addClass(self.theme["disabled"]);
},
// `enable` event with the `selectBoxIt` namespace
"enable.selectBoxIt": function() {
// Removes the `disabled` CSS class from the new dropdown list to visually show that it is enabled
self.dropdown.removeClass(self.theme["disabled"]);
},
// `open` event with the `selectBoxIt` namespace
"open.selectBoxIt": function() {
var currentElem = self.list.find("li[data-val='" + self.dropdownText.attr("data-val") + "']"),
activeElem;
// If no current element can be found, then select the first drop down option
if(!currentElem.length) {
// Sets the default value of the dropdown list to the first option that is not disabled
currentElem = self.listItems.not("[data-disabled=true]").first();
}
self.currentFocus = +currentElem.attr("data-id");
activeElem = self.listItems.eq(self.currentFocus);
self.dropdown.addClass(openClass).
// Removes the focus class from the dropdown list and adds the library focus class for both the dropdown list and the currently selected dropdown list option
removeClass(hoverClass).addClass(focusClass);
self.listItems.removeClass(self.selectedClass).
removeAttr("data-active").not(activeElem).removeClass(focusClass);
activeElem.addClass(self.selectedClass).addClass(focusClass);
if(self.options.hideCurrent) {
self.listItems.show();
activeElem.hide();
}
},
"close.selectBoxIt": function() {
// Removes the open class from the dropdown container
self.dropdown.removeClass(openClass);
},
"blur.selectBoxIt": function() {
self.dropdown.removeClass(focusClass);
},
// `mousenter` event with the `selectBoxIt` namespace
"mouseenter.selectBoxIt": function() {
if(!$(this).hasClass(self.theme["disabled"])) {
self.dropdown.addClass(hoverClass);
}
},
// `mouseleave` event with the `selectBoxIt` namespace
"mouseleave.selectBoxIt": function() {
// Removes the hover CSS class on the previously hovered dropdown list option
self.dropdown.removeClass(hoverClass);
},
// `destroy` event
"destroy": function(ev) {
// Prevents the default action from happening
ev.preventDefault();
// Prevents the destroy event from propagating
ev.stopPropagation();
}
});
// Maintains chainability
return self;
},
// _update
// -------
// Updates the drop down and select box with the current value
_update: function(elem) {
var self = this,
currentDataSelectedText,
currentDataText,
currentText,
defaultText = self.options["defaultText"] || self.selectBox.attr("data-text"),
currentElem = self.listItems.eq(self.currentFocus);
if (elem.attr("data-disabled") === "false") {
currentDataSelectedText = self.listItems.eq(self.currentFocus).attr("data-selectedtext");
currentDataText = currentElem.attr("data-text");
currentText = currentDataText ? currentDataText: currentElem.text();
// If the default text option is set and the current drop down option is not disabled
if ((defaultText && self.options["html"] ? self.dropdownText.html() === defaultText: self.dropdownText.text() === defaultText) && self.selectBox.val() === elem.attr("data-val")) {
self.triggerEvent("change");
}
else {
// Sets the original dropdown list value and triggers the `change` event on the original select box
self.selectBox.val(elem.attr("data-val"));
// Sets `currentFocus` to the currently focused dropdown list option.
// The unary `+` operator casts the string to a number
// [James Padolsey Blog Post](http://james.padolsey.com/javascript/terse-javascript-101-part-2/)
self.currentFocus = +elem.attr("data-id");
// Triggers the dropdown list `change` event if a value change occurs
if (self.originalElem.value !== self.dropdownText.attr("data-val")) {
self.triggerEvent("change");
}
}
}
},
// _addClasses
// -----------
// Adds SelectBoxIt CSS classes
_addClasses: function(obj) {
var self = this,
focusClass = self.focusClass = obj.focus,
hoverClass = self.hoverClass = obj.hover,
buttonClass = obj.button,
listClass = obj.list,
arrowClass = obj.arrow,
containerClass = obj.container,
openClass = self.openClass = obj.open;
self.selectedClass = "selectboxit-selected";
self.downArrow.addClass(self.selectBox.attr("data-downarrow") || self.options["downArrowIcon"] || arrowClass);
// Adds the correct container class to the dropdown list
self.dropdownContainer.addClass(containerClass);
// Adds the correct class to the dropdown list
self.dropdown.addClass(buttonClass);
// Adds the default class to the dropdown list options
self.list.addClass(listClass);
// Maintains chainability
return self;
},
// Refresh
// -------
// The dropdown will rebuild itself. Useful for dynamic content.
refresh: function(callback, internal) {
var self = this;
// Destroys the plugin and then recreates the plugin
self._destroySelectBoxIt()._create(true);
if(!internal) {
self.triggerEvent("refresh");
}
self._callbackSupport(callback);
//Maintains chainability
return self;
},
// HTML Escape
// -----------
// HTML encodes a string
htmlEscape: function(str) {
return String(str)
.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'")
.replace(/</g, "<")
.replace(/>/g, ">");
},
// triggerEvent
// ------------
// Trigger's an external event on the original select box element
triggerEvent: function(eventName) {
var self = this,
// Finds the currently option index
currentIndex = self.options["showFirstOption"] ? self.currentFocus : ((self.currentFocus - 1) >= 0 ? self.currentFocus: 0);
// Triggers the custom option-click event on the original select box and passes the select box option
self.selectBox.trigger(eventName, { "selectbox": self.selectBox, "selectboxOption": self.selectItems.eq(currentIndex), "dropdown": self.dropdown, "dropdownOption": self.listItems.eq(self.currentFocus) });
// Maintains chainability
return self;
},
// _copyAttributes
// ---------------
// Copies HTML attributes from the original select box to the new drop down
_copyAttributes: function() {
var self = this;
if(self._addSelectBoxAttributes) {
self._addSelectBoxAttributes();
}
return self;
},
// _realOuterWidth
// ---------------
// Retrieves the true outerWidth dimensions of a hidden DOM element
_realOuterWidth: function(elem) {
if(elem.is(":visible")) {
return elem.outerWidth(true);
}
var self = this,
clonedElem = elem.clone(),
outerWidth;
clonedElem.css({
"visibility": "hidden",
"display": "block",
"position": "absolute"
}).appendTo("body");
outerWidth = clonedElem.outerWidth(true);
clonedElem.remove();
return outerWidth;
}
});
// Stores the plugin prototype object in a local variable
var selectBoxIt = $.selectBox.selectBoxIt.prototype;
// Add Options Module
// ==================
// add
// ---
// Adds drop down options
// using JSON data, an array,
// a single object, or valid HTML string
selectBoxIt.add = function(data, callback) {
this._populate(data, function(data) {
var self = this,
dataType = $.type(data),
value,
x = 0,
dataLength,
elems = [],
isJSON = self._isJSON(data),
parsedJSON = isJSON && self._parseJSON(data);
// If the passed data is a local or JSON array
if(data && (dataType === "array" || (isJSON && parsedJSON.data && $.type(parsedJSON.data) === "array")) || (dataType === "object" && data.data && $.type(data.data) === "array")) {
// If the data is JSON
if(self._isJSON(data)) {
// Parses the JSON and stores it in the data local variable
data = parsedJSON;
}
// If there is an inner `data` property stored in the first level of the JSON array
if(data.data) {
// Set's the data to the inner `data` property
data = data.data;
}
// Loops through the array
for(dataLength = data.length; x <= dataLength - 1; x += 1) {
// Stores the currently traversed array item in the local `value` variable
value = data[x];
// If the currently traversed array item is an object literal
if($.isPlainObject(value)) {
// Adds an option to the elems array
elems.push($("<option/>", value));
}
// If the currently traversed array item is a string
else if($.type(value) === "string") {
// Adds an option to the elems array
elems.push($("<option/>", { text: value, value: value }));
}
}
// Appends all options to the drop down (with the correct object configurations)
self.selectBox.append(elems);
}
// if the passed data is an html string and not a JSON string
else if(data && dataType === "string" && !self._isJSON(data)) {
// Appends the html string options to the original select box
self.selectBox.append(data);
}
else if(data && dataType === "object") {
// Appends an option to the original select box (with the object configurations)
self.selectBox.append($("<option/>", data));
}
else if(data && self._isJSON(data) && $.isPlainObject(self._parseJSON(data))) {
// Appends an option to the original select box (with the object configurations)
self.selectBox.append($("<option/>", self._parseJSON(data)));
}
// If the dropdown property exists
if(self.dropdown) {
// Rebuilds the dropdown
self.refresh(function() {
// Provide callback function support
self._callbackSupport(callback);
}, true);
} else {
// Provide callback function support
self._callbackSupport(callback);
}
// Maintains chainability
return self;
});
};
// parseJSON
// ---------
// Detects JSON support and parses JSON data
selectBoxIt._parseJSON = function(data) {
return (JSON && JSON.parse && JSON.parse(data)) || $.parseJSON(data);
};
// isjSON
// ------
// Determines if a string is valid JSON
selectBoxIt._isJSON = function(data) {
var self = this,
json;
try {
json = self._parseJSON(data);
// Valid JSON
return true;
} catch (e) {
// Invalid JSON
return false;
}
};
// _populate
// --------
// Handles asynchronous and synchronous data
// to populate the select box
selectBoxIt._populate = function(data, callback) {
var self = this;
data = $.isFunction(data) ? data.call() : data;
if(self.isDeferred(data)) {
data.done(function(returnedData) {
callback.call(self, returnedData);
});
}
else {
callback.call(self, data);
}
// Maintains chainability
return self;
};
// Accessibility Module
// ====================
// _ARIA Accessibility
// ------------------
// Adds ARIA (Accessible Rich Internet Applications)
// Accessibility Tags to the Select Box
selectBoxIt._ariaAccessibility = function() {
var self = this,
dropdownLabel = $("label[for='" + self.originalElem.id + "']");
// Adds `ARIA attributes` to the dropdown list
self.dropdownContainer.attr({
// W3C `combobox` description: A presentation of a select; usually similar to a textbox where users can type ahead to select an option.
"role": "combobox",
//W3C `aria-autocomplete` description: Indicates whether user input completion suggestions are provided.
"aria-autocomplete": "list",
"aria-haspopup": "true",
// W3C `aria-expanded` description: Indicates whether the element, or another grouping element it controls, is currently expanded or collapsed.
"aria-expanded": "false",
// W3C `aria-owns` description: The value of the aria-owns attribute is a space-separated list of IDREFS that reference one or more elements in the document by ID. The reason for adding aria-owns is to expose a parent/child contextual relationship to assistive technologies that is otherwise impossible to infer from the DOM.
"aria-owns": self.list[0].id
});
self.dropdownText.attr({
"aria-live": "polite"
});
// Dynamically adds `ARIA attributes` if the new dropdown list is enabled or disabled
self.dropdown.on({
//Select box custom `disable` event with the `selectBoxIt` namespace
"disable.selectBoxIt" : function() {
// W3C `aria-disabled` description: Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.
self.dropdownContainer.attr("aria-disabled", "true");
},
// Select box custom `enable` event with the `selectBoxIt` namespace
"enable.selectBoxIt" : function() {
// W3C `aria-disabled` description: Indicates that the element is perceivable but disabled, so it is not editable or otherwise operable.
self.dropdownContainer.attr("aria-disabled", "false");
}
});
if(dropdownLabel.length) {
// MDN `aria-labelledby` description: Indicates the IDs of the elements that are the labels for the object.
self.dropdownContainer.attr("aria-labelledby", dropdownLabel[0].id);
}
// Adds ARIA attributes to the dropdown list options list
self.list.attr({
// W3C `listbox` description: A widget that allows the user to select one or more items from a list of choices.
"role": "listbox",
// Indicates that the dropdown list options list is currently hidden
"aria-hidden": "true"
});
// Adds `ARIA attributes` to the dropdown list options
self.listItems.attr({
// This must be set for each element when the container element role is set to `listbox`
"role": "option"
});
// Dynamically updates the new dropdown list `aria-label` attribute after the original dropdown list value changes
self.selectBox.on({
// Custom `open` event with the `selectBoxIt` namespace
"open.selectBoxIt": function() {
// Indicates that the dropdown list options list is currently visible
self.list.attr("aria-hidden", "false");
// Indicates that the dropdown list is currently expanded
self.dropdownContainer.attr("aria-expanded", "true");
},
// Custom `close` event with the `selectBoxIt` namespace
"close.selectBoxIt": function() {
// Indicates that the dropdown list options list is currently hidden
self.list.attr("aria-hidden", "true");
// Indicates that the dropdown list is currently collapsed
self.dropdownContainer.attr("aria-expanded", "false");
}
});
// Maintains chainability
return self;
};
// Copy Attributes Module
// ======================
// addSelectBoxAttributes
// ----------------------
// Add's all attributes (excluding id, class names, and the style attribute) from the default select box to the new drop down
selectBoxIt._addSelectBoxAttributes = function() {
// Stores the plugin context inside of the self variable
var self = this;
// Add's all attributes to the currently traversed drop down option
self._addAttributes(self.selectBox.prop("attributes"), self.dropdown);
// Add's all attributes to the drop down items list
self.selectItems.each(function(iterator) {
// Add's all attributes to the currently traversed drop down option
self._addAttributes($(this).prop("attributes"), self.listItems.eq(iterator));
});
// Maintains chainability
return self;
};
// addAttributes
// -------------
// Add's attributes to a DOM element
selectBoxIt._addAttributes = function(arr, elem) {
// Stores the plugin context inside of the self variable
var self = this,
whitelist = self.options["copyAttributes"];
// If there are array properties
if(arr.length) {
// Iterates over all of array properties
$.each(arr, function(iterator, property) {
// Get's the property name and property value of each property
var propName = (property.name).toLowerCase(), propValue = property.value;
// If the currently traversed property value is not "null", is on the whitelist, or is an HTML 5 data attribute
if(propValue !== "null" && ($.inArray(propName, whitelist) !== -1 || propName.indexOf("data") !== -1)) {
// Set's the currently traversed property on element
elem.attr(propName, propValue);
}
});
}
// Maintains chainability
return self;
};
// Destroy Module
// ==============
// Destroy
// -------
// Removes the plugin from the page
selectBoxIt.destroy = function(callback) {
// Stores the plugin context inside of the self variable
var self = this;
self._destroySelectBoxIt();
// Calls the jQueryUI Widget Factory destroy method
self.widgetProto.destroy.call(self);
// Provides callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
};
// Internal Destroy Method
// -----------------------
// Removes the plugin from the page
selectBoxIt._destroySelectBoxIt = function() {
// Stores the plugin context inside of the self variable
var self = this;
// Unbinds all of the dropdown list event handlers with the `selectBoxIt` namespace
self.dropdown.off(".selectBoxIt");
// If the original select box has been placed inside of the new drop down container
if ($.contains(self.dropdownContainer[0], self.originalElem)) {
// Moves the original select box before the drop down container
self.dropdownContainer.before(self.selectBox);
}
// Remove all of the `selectBoxIt` DOM elements from the page
self.dropdownContainer.remove();
// Resets the style attributes for the original select box
self.selectBox.removeAttr("style").attr("style", self.selectBoxStyles);
// Triggers the custom `destroy` event on the original select box
self.triggerEvent("destroy");
// Maintains chainability
return self;
};
// Disable Module
// ==============
// Disable
// -------
// Disables the new dropdown list
selectBoxIt.disable = function(callback) {
var self = this;
if(!self.options["disabled"]) {
// Makes sure the dropdown list is closed
self.close();
// Sets the `disabled` attribute on the original select box
self.selectBox.attr("disabled", "disabled");
// Makes the dropdown list not focusable by removing the `tabindex` attribute
self.dropdown.removeAttr("tabindex").
// Disables styling for enabled state
removeClass(self.theme["enabled"]).
// Enabled styling for disabled state
addClass(self.theme["disabled"]);
self.setOption("disabled", true);
// Triggers a `disable` custom event on the original select box
self.triggerEvent("disable");
}
// Provides callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
};
// Disable Option
// --------------
// Disables a single drop down option
selectBoxIt.disableOption = function(index, callback) {
var self = this, currentSelectBoxOption, hasNextEnabled, hasPreviousEnabled, type = $.type(index);
// If an index is passed to target an indropdownidual drop down option
if(type === "number") {
// Makes sure the dropdown list is closed
self.close();
// The select box option being targeted
currentSelectBoxOption = self.selectBox.find("option").eq(index);
// Triggers a `disable-option` custom event on the original select box and passes the disabled option
self.triggerEvent("disable-option");
// Disables the targeted select box option
currentSelectBoxOption.attr("disabled", "disabled");
// Disables the drop down option
self.listItems.eq(index).attr("data-disabled", "true").
// Applies disabled styling for the drop down option
addClass(self.theme["disabled"]);
// If the currently selected drop down option is the item being disabled
if(self.currentFocus === index) {
hasNextEnabled = self.listItems.eq(self.currentFocus).nextAll("li").not("[data-disabled='true']").first().length;
hasPreviousEnabled = self.listItems.eq(self.currentFocus).prevAll("li").not("[data-disabled='true']").first().length;
// If there is a currently enabled option beneath the currently selected option
if(hasNextEnabled) {
// Selects the option beneath the currently selected option
self.moveDown();
}
// If there is a currently enabled option above the currently selected option
else if(hasPreviousEnabled) {
// Selects the option above the currently selected option
self.moveUp();
}
// If there is not a currently enabled option
else {
// Disables the entire drop down list
self.disable();
}
}
}
// Provides callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
};
// _Is Disabled
// -----------
// Checks the original select box for the
// disabled attribute
selectBoxIt._isDisabled = function(callback) {
var self = this;
// If the original select box is disabled
if (self.originalElem.disabled) {
// Disables the dropdown list
self.disable();
}
// Maintains chainability
return self;
};
// Dynamic Positioning Module
// ==========================
// _Dynamic positioning
// --------------------
// Dynamically positions the dropdown list options list
selectBoxIt._dynamicPositioning = function() {
var self = this;
// If the `size` option is a number
if($.type(self.listSize) === "number") {
// Set's the max-height of the drop down list
self.list.css("max-height", self.maxHeight || "none");
}
// If the `size` option is not a number
else {
// Returns the x and y coordinates of the dropdown list options list relative to the document
var listOffsetTop = self.dropdown.offset().top,
// The height of the dropdown list options list
listHeight = self.list.data("max-height") || self.list.outerHeight(),
// The height of the dropdown list DOM element
selectBoxHeight = self.dropdown.outerHeight(),
viewport = self.options["viewport"],
viewportHeight = viewport.height(),
viewportScrollTop = $.isWindow(viewport.get(0)) ? viewport.scrollTop() : viewport.offset().top,
topToBottom = (listOffsetTop + selectBoxHeight + listHeight <= viewportHeight + viewportScrollTop),
bottomReached = !topToBottom;
if(!self.list.data("max-height")) {
self.list.data("max-height", self.list.outerHeight());
}
// If there is room on the bottom of the viewport to display the drop down options
if (!bottomReached) {
self.list.css("max-height", listHeight);
// Sets custom CSS properties to place the dropdown list options directly below the dropdown list
self.list.css("top", "auto");
}
// If there is room on the top of the viewport
else if((self.dropdown.offset().top - viewportScrollTop) >= listHeight) {
self.list.css("max-height", listHeight);
// Sets custom CSS properties to place the dropdown list options directly above the dropdown list
self.list.css("top", (self.dropdown.position().top - self.list.outerHeight()));
}
// If there is not enough room on the top or the bottom
else {
var outsideBottomViewport = Math.abs((listOffsetTop + selectBoxHeight + listHeight) - (viewportHeight + viewportScrollTop)),
outsideTopViewport = Math.abs((self.dropdown.offset().top - viewportScrollTop) - listHeight);
// If there is more room on the bottom
if(outsideBottomViewport < outsideTopViewport) {
self.list.css("max-height", listHeight - outsideBottomViewport - (selectBoxHeight/2));
self.list.css("top", "auto");
}
// If there is more room on the top
else {
self.list.css("max-height", listHeight - outsideTopViewport - (selectBoxHeight/2));
// Sets custom CSS properties to place the dropdown list options directly above the dropdown list
self.list.css("top", (self.dropdown.position().top - self.list.outerHeight()));
}
}
}
// Maintains chainability
return self;
};
// Enable Module
// =============
// Enable
// ------
// Enables the new dropdown list
selectBoxIt.enable = function(callback) {
var self = this;
if(self.options["disabled"]) {
// Triggers a `enable` custom event on the original select box
self.triggerEvent("enable");
// Removes the `disabled` attribute from the original dropdown list
self.selectBox.removeAttr("disabled");
// Make the dropdown list focusable
self.dropdown.attr("tabindex", 0).
// Disable styling for disabled state
removeClass(self.theme["disabled"]).
// Enables styling for enabled state
addClass(self.theme["enabled"]);
self.setOption("disabled", false);
// Provide callback function support
self._callbackSupport(callback);
}
// Maintains chainability
return self;
};
// Enable Option
// -------------
// Disables a single drop down option
selectBoxIt.enableOption = function(index, callback) {
var self = this, currentSelectBoxOption, currentIndex = 0, hasNextEnabled, hasPreviousEnabled, type = $.type(index);
// If an index is passed to target an indropdownidual drop down option
if(type === "number") {
// The select box option being targeted
currentSelectBoxOption = self.selectBox.find("option").eq(index);
// Triggers a `enable-option` custom event on the original select box and passes the enabled option
self.triggerEvent("enable-option");
// Disables the targeted select box option
currentSelectBoxOption.removeAttr("disabled");
// Disables the drop down option
self.listItems.eq(index).attr("data-disabled", "false").
// Applies disabled styling for the drop down option
removeClass(self.theme["disabled"]);
}
// Provides callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
};
// Keyboard Navigation Module
// ==========================
// Move Down
// ---------
// Handles the down keyboard navigation logic
selectBoxIt.moveDown = function(callback) {
var self = this;
// Increments `currentFocus`, which represents the currently focused list item `id` attribute.
self.currentFocus += 1;
// Determines whether the dropdown option the user is trying to go to is currently disabled
var disabled = self.listItems.eq(self.currentFocus).attr("data-disabled") === "true" ? true: false,
hasNextEnabled = self.listItems.eq(self.currentFocus).nextAll("li").not("[data-disabled='true']").first().length;
// If the user has reached the top of the list
if (self.currentFocus === self.listItems.length) {
// Does not allow the user to continue to go up the list
self.currentFocus -= 1;
}
// If the option the user is trying to go to is disabled, but there is another enabled option
else if (disabled && hasNextEnabled) {
// Blur the previously selected option
self.listItems.eq(self.currentFocus - 1).blur();
// Call the `moveDown` method again
self.moveDown();
// Exit the method
return;
}
// If the option the user is trying to go to is disabled, but there is not another enabled option
else if (disabled && !hasNextEnabled) {
self.currentFocus -= 1;
}
// If the user has not reached the bottom of the unordered list
else {
// Blurs the previously focused list item
// The jQuery `end()` method allows you to continue chaining while also using a different selector
self.listItems.eq(self.currentFocus - 1).blur().end().
// Focuses the currently focused list item
eq(self.currentFocus).focusin();
// Calls `scrollToView` to make sure the `scrollTop` is correctly updated. The `down` user action
self._scrollToView("down");
// Triggers the custom `moveDown` event on the original select box
self.triggerEvent("moveDown");
}
// Provide callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
};
// Move Up
// ------
// Handles the up keyboard navigation logic
selectBoxIt.moveUp = function(callback) {
var self = this;
// Increments `currentFocus`, which represents the currently focused list item `id` attribute.
self.currentFocus -= 1;
// Determines whether the dropdown option the user is trying to go to is currently disabled
var disabled = self.listItems.eq(self.currentFocus).attr("data-disabled") === "true" ? true: false,
hasPreviousEnabled = self.listItems.eq(self.currentFocus).prevAll("li").not("[data-disabled='true']").first().length;
// If the user has reached the top of the list
if (self.currentFocus === -1) {
// Does not allow the user to continue to go up the list
self.currentFocus += 1;
}
// If the option the user is trying to go to is disabled and the user is not trying to go up after the user has reached the top of the list
else if (disabled && hasPreviousEnabled) {
// Blur the previously selected option
self.listItems.eq(self.currentFocus + 1).blur();
// Call the `moveUp` method again
self.moveUp();
// Exits the method
return;
}
else if (disabled && !hasPreviousEnabled) {
self.currentFocus += 1;
}
// If the user has not reached the top of the unordered list
else {
// Blurs the previously focused list item
// The jQuery `end()` method allows you to continue chaining while also using a different selector
self.listItems.eq(this.currentFocus + 1).blur().end().
// Focuses the currently focused list item
eq(self.currentFocus).focusin();
// Calls `scrollToView` to make sure the `scrollTop` is correctly updated. The `down` user action
self._scrollToView("up");
// Triggers the custom `moveDown` event on the original select box
self.triggerEvent("moveUp");
}
// Provide callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
};
// Keyboard Search Module
// ======================
// _Set Current Search Option
// -------------------------
// Sets the currently selected dropdown list search option
selectBoxIt._setCurrentSearchOption = function(currentOption) {
var self = this;
// Does not change the current option if `showFirstOption` is false and the matched search item is the hidden first option.
// Otherwise, the current option value is updated
if ((self.options["aggressiveChange"] || self.options["selectWhenHidden"] || self.listItems.eq(currentOption).is(":visible")) && self.listItems.eq(currentOption).data("disabled") !== true) {
// Calls the `blur` event of the currently selected dropdown list option
self.listItems.eq(self.currentFocus).blur();
// Sets `currentIndex` to the currently selected dropdown list option
self.currentIndex = currentOption;
// Sets `currentFocus` to the currently selected dropdown list option
self.currentFocus = currentOption;
// Focuses the currently selected dropdown list option
self.listItems.eq(self.currentFocus).focusin();
// Updates the scrollTop so that the currently selected dropdown list option is visible to the user
self._scrollToView("search");
// Triggers the custom `search` event on the original select box
self.triggerEvent("search");
}
// Maintains chainability
return self;
};
// _Search Algorithm
// -----------------
// Uses regular expressions to find text matches
selectBoxIt._searchAlgorithm = function(currentIndex, alphaNumeric) {
var self = this,
// Boolean to determine if a pattern match exists
matchExists = false,
// Iteration variable used in the outermost for loop
x,
// Iteration variable used in the nested for loop
y,
// Variable used to cache the length of the text array (Small enhancement to speed up traversing)
arrayLength,
// Variable storing the current search
currentSearch,
// Variable storing the textArray property
textArray = self.textArray,
// Variable storing the current text property
currentText = self.currentText;
// Loops through the text array to find a pattern match
for (x = currentIndex, arrayLength = textArray.length; x < arrayLength; x += 1) {
currentSearch = textArray[x];
// Nested for loop to help search for a pattern match with the currently traversed array item
for (y = 0; y < arrayLength; y += 1) {
// Searches for a match
if (textArray[y].search(alphaNumeric) !== -1) {
// `matchExists` is set to true if there is a match
matchExists = true;
// Exits the nested for loop
y = arrayLength;
}
} // End nested for loop
// If a match does not exist
if (!matchExists) {
// Sets the current text to the last entered character
self.currentText = self.currentText.charAt(self.currentText.length - 1).
// Escapes the regular expression to make sure special characters are seen as literal characters instead of special commands
replace(/[|()\[{.+*?$\\]/g, "\\$0");
currentText = self.currentText;
}
// Resets the regular expression with the new value of `self.currentText`
alphaNumeric = new RegExp(currentText, "gi");
// Searches based on the first letter of the dropdown list options text if the currentText < 3 characters
if (currentText.length < 3) {
alphaNumeric = new RegExp(currentText.charAt(0), "gi");
// If there is a match based on the first character
if ((currentSearch.charAt(0).search(alphaNumeric) !== -1)) {
// Sets properties of that dropdown list option to make it the currently selected option
self._setCurrentSearchOption(x);
if((currentSearch.substring(0, currentText.length).toLowerCase() !== currentText.toLowerCase()) || self.options["similarSearch"]) {
// Increments the current index by one
self.currentIndex += 1;
}
// Exits the search
return false;
}
}
// If `self.currentText` > 1 character
else {
// If there is a match based on the entire string
if ((currentSearch.search(alphaNumeric) !== -1)) {
// Sets properties of that dropdown list option to make it the currently selected option
self._setCurrentSearchOption(x);
// Exits the search
return false;
}
}
// If the current text search is an exact match
if (currentSearch.toLowerCase() === self.currentText.toLowerCase()) {
// Sets properties of that dropdown list option to make it the currently selected option
self._setCurrentSearchOption(x);
// Resets the current text search to a blank string to start fresh again
self.currentText = "";
// Exits the search
return false;
}
}
// Returns true if there is not a match at all
return true;
};
// Search
// ------
// Calls searchAlgorithm()
selectBoxIt.search = function(alphaNumericKey, callback, rememberPreviousSearch) {
var self = this;
// If the search method is being called internally by the plugin, and not externally as a method by a user
if (rememberPreviousSearch) {
// Continued search with history from past searches. Properly escapes the regular expression
self.currentText += alphaNumericKey.replace(/[|()\[{.+*?$\\]/g, "\\$0");
}
else {
// Brand new search. Properly escapes the regular expression
self.currentText = alphaNumericKey.replace(/[|()\[{.+*?$\\]/g, "\\$0");
}
// Searches globally
var searchResults = self._searchAlgorithm(self.currentIndex, new RegExp(self.currentText, "gi"));
// Searches the list again if a match is not found. This is needed, because the first search started at the array indece of the currently selected dropdown list option, and does not search the options before the current array indece.
// If there are many similar dropdown list options, starting the search at the indece of the currently selected dropdown list option is needed to properly traverse the text array.
if (searchResults) {
// Searches the dropdown list values starting from the beginning of the text array
self._searchAlgorithm(0, self.currentText);
}
// Provide callback function support
self._callbackSupport(callback);
// Maintains chainability
return self;
};
// Mobile Module
// =============
// Set Mobile Text
// ---------------
// Updates the text of the drop down
selectBoxIt._updateMobileText = function() {
var self = this,
currentOption,
currentDataText,
currentText;
currentOption = self.selectBox.find("option").filter(":selected");
currentDataText = currentOption.attr("data-text");
currentText = currentDataText ? currentDataText: currentOption.text();
// Sets the new dropdown list text to the value of the original dropdown list
self._setText(self.dropdownText, currentText);
if(self.list.find('li[data-val="' + currentOption.val() + '"]').find("i").attr("class")) {
self.dropdownImage.attr("class", self.list.find('li[data-val="' + currentOption.val() + '"]').find("i").attr("class")).addClass("selectboxit-default-icon");
}
};
// Apply Native Select
// -------------------
// Applies the original select box directly over the new drop down
selectBoxIt._applyNativeSelect = function() {
// Stores the plugin context inside of the self variable
var self = this;
// Appends the native select box to the drop down (allows for relative positioning using the position() method)
self.dropdownContainer.append(self.selectBox);
self.dropdown.attr("tabindex", "-1");
// Positions the original select box directly over top the new dropdown list using position absolute and "hides" the original select box using an opacity of 0. This allows the mobile browser "wheel" interface for better usability.
self.selectBox.css({
"display": "block",
"visibility": "visible",
"width": self._realOuterWidth(self.dropdown),
"height": self.dropdown.outerHeight(),
"opacity": "0",
"position": "absolute",
"top": "0",
"left": "0",
"cursor": "pointer",
"z-index": "999999",
"margin": self.dropdown.css("margin"),
"padding": "0",
"-webkit-appearance": "menulist-button"
});
if(self.originalElem.disabled) {
self.triggerEvent("disable");
}
return this;
};
// Mobile Events
// -------------
// Listens to mobile-specific events
selectBoxIt._mobileEvents = function() {
var self = this;
self.selectBox.on({
"changed.selectBoxIt": function() {
self.hasChanged = true;
self._updateMobileText();
// Triggers the `option-click` event on mobile
self.triggerEvent("option-click");
},
"mousedown.selectBoxIt": function() {
// If the select box has not been changed, the defaultText option is being used
if(!self.hasChanged && self.options.defaultText && !self.originalElem.disabled) {
self._updateMobileText();
self.triggerEvent("option-click");
}
},
"enable.selectBoxIt": function() {
// Moves SelectBoxIt onto the page
self.selectBox.removeClass('selectboxit-rendering');
},
"disable.selectBoxIt": function() {
// Moves SelectBoxIt off the page
self.selectBox.addClass('selectboxit-rendering');
}
});
};
// Mobile
// ------
// Applies the native "wheel" interface when a mobile user is interacting with the dropdown
selectBoxIt._mobile = function(callback) {
// Stores the plugin context inside of the self variable
var self = this;
if(self.isMobile) {
self._applyNativeSelect();
self._mobileEvents();
}
// Maintains chainability
return this;
};
// Remove Options Module
// =====================
// remove
// ------
// Removes drop down list options
// using an index
selectBoxIt.remove = function(indexes, callback) {
var self = this,
dataType = $.type(indexes),
value,
x = 0,
dataLength,
elems = "";
// If an array is passed in
if(dataType === "array") {
// Loops through the array
for(dataLength = indexes.length; x <= dataLength - 1; x += 1) {
// Stores the currently traversed array item in the local `value` variable
value = indexes[x];
// If the currently traversed array item is an object literal
if($.type(value) === "number") {
if(elems.length) {
// Adds an element to the removal string
elems += ", option:eq(" + value + ")";
}
else {
// Adds an element to the removal string
elems += "option:eq(" + value + ")";
}
}
}
// Removes all of the appropriate options from the select box
self.selectBox.find(elems).remove();
}
// If a number is passed in
else if(dataType === "number") {
self.selectBox.find("option").eq(indexes).remove();
}
// If anything besides a number or array is passed in
else {
// Removes all of the options from the original select box
self.selectBox.find("option").remove();
}
// If the dropdown property exists
if(self.dropdown) {
// Rebuilds the dropdown
self.refresh(function() {
// Provide callback function support
self._callbackSupport(callback);
}, true);
} else {
// Provide callback function support
self._callbackSupport(callback);
}
// Maintains chainability
return self;
};
// Select Option Module
// ====================
// Select Option
// -------------
// Programatically selects a drop down option by either index or value
selectBoxIt.selectOption = function(val, callback) {
// Stores the plugin context inside of the self variable
var self = this,
type = $.type(val);
// Makes sure the passed in position is a number
if(type === "number") {
// Set's the original select box value and triggers the change event (which SelectBoxIt listens for)
self.selectBox.val(self.selectItems.eq(val).val()).change();
}
else if(type === "string") {
// Set's the original select box value and triggers the change event (which SelectBoxIt listens for)
self.selectBox.val(val).change();
}
// Calls the callback function
self._callbackSupport(callback);
// Maintains chainability
return self;
};
// Set Option Module
// =================
// Set Option
// ----------
// Accepts an string key, a value, and a callback function to replace a single
// property of the plugin options object
selectBoxIt.setOption = function(key, value, callback) {
var self = this;
//Makes sure a string is passed in
if($.type(key) === "string") {
// Sets the plugin option to the new value provided by the user
self.options[key] = value;
}
// Rebuilds the dropdown
self.refresh(function() {
// Provide callback function support
self._callbackSupport(callback);
}, true);
// Maintains chainability
return self;
};
// Set Options Module
// ==================
// Set Options
// ----------
// Accepts an object to replace plugin options
// properties of the plugin options object
selectBoxIt.setOptions = function(newOptions, callback) {
var self = this;
// If the passed in parameter is an object literal
if($.isPlainObject(newOptions)) {
self.options = $.extend({}, self.options, newOptions);
}
// Rebuilds the dropdown
self.refresh(function() {
// Provide callback function support
self._callbackSupport(callback);
}, true);
// Maintains chainability
return self;
};
// Wait Module
// ===========
// Wait
// ----
// Delays execution by the amount of time
// specified by the parameter
selectBoxIt.wait = function(time, callback) {
var self = this;
self.widgetProto._delay.call(self, callback, time);
// Maintains chainability
return self;
};
})); // End of all modules | lyoniionly/django-cobra | src/cobra/static/cobra/scripts/lib/jquery.selectBoxIt.js | JavaScript | apache-2.0 | 108,934 |
const Bluebird = require('bluebird');
const exec = Bluebird.promisify(require('child_process').exec);
module.exports = {
title: 'Bluetooth tests',
deviceType: {
type: 'object',
required: ['data'],
properties: {
data: {
type: 'object',
required: ['connectivity'],
properties: {
connectivity: {
type: 'object',
required: ['bluetooth'],
properties: {
bluetooth: {
type: 'boolean',
const: true,
},
},
},
},
},
},
},
tests: [
{
title: 'Bluetooth scanning test',
run: async function(test) {
if(process.env.WORKER_TYPE === `qemu`){
test.pass(
'Qemu worker used - skipping bluetooth test',
);
} else {
// get the testbot bluetooth name
let btName = await exec('bluetoothctl show | grep Name');
let btNameParsed = /(.*): (.*)/.exec(btName); // the bluetoothctl command returns "Name: <btname>", so extract the <btname here>
// make testbot bluetooth discoverable
await exec('bluetoothctl discoverable on');
// scan for bluetooth devices on DUT, we retry a couple of times
let scan = '';
await this.context.get().utils.waitUntil(async () => {
test.comment('Scanning for bluetooth devices...');
scan = await this.context
.get()
.worker.executeCommandInHostOS(
'hcitool scan',
this.context.get().link,
);
return scan.includes(btNameParsed[2]);
});
test.is(
scan.includes(btNameParsed[2]),
true,
'DUT should be able to see testbot when scanning for bluetooth devices',
);
test.comment('Checking if BD Address is initialized');
const devMac = await this.context
.get()
.worker.executeCommandInHostOS(
'hcitool dev',
this.context.get().link,
);
test.is(
devMac.includes('AA:AA:AA:AA:AA:AA'),
false,
'BD Address should not be AA:AA:AA:AA:AA:AA',
);
}
},
},
],
};
| resin-os/meta-resin | tests/suites/os/tests/bluetooth/index.js | JavaScript | apache-2.0 | 1,996 |
Ext.define('util.JavaMap', {
singleton: true,
keys: new Array(),
contains: function (key) {
var entry = this.findEntry(key);
return !(entry == null || entry instanceof App.Util.NullKey);
},
get: function (key) {
var entry = this.findEntry(key);
if (!(entry == null || entry instanceof App.Util.NullKey))
return entry.value;
else
return null;
},
put: function (key, value) {
var entry = this.findEntry(key);
if (entry) {
entry.value = value;
} else {
this.addNewEntry(key, value);
}
},
remove: function (key) {
for (var i = 0; i < keys.length; i++) {
var entry = keys[i];
if (entry instanceof App.Util.NullKey) continue;
if (entry.key == key) {
keys[i] = App.Util.NullKey;
}
}
},
findEntry: function (key) {
for (var i = 0; i < keys.length; i++) {
var entry = keys[i];
if (entry instanceof App.Util.NullKey) continue;
if (entry.key == key) {
return entry
}
}
return null;
},
addNewEntry: function (key, value) {
var entry = new Object();
entry.key = key;
entry.value = value;
keys[keys.length] = entry;
}
}); | hyokun31/wisekb-management-platform | wisekb-web/src/main/webapp/flamingo/packages/util/src/JavaMap.js | JavaScript | apache-2.0 | 1,394 |
function initUI(){
$("#products").html(""); //vide le contenu statique
$.getJSON("/chicon/webServices/serviceRelatedWebService.php",{cmd: "getAllServices"},
function(data){
if(data.result['code']==200){
var j = 0;
for( var i in data.result['data'].srvList){
if(j==3){j=0};
if(j==0){
var myRow = $("<div class=row></div>").appendTo("#products");
var myPr = $("<div class='product'></div>").appendTo(myRow);
}else if(j==2){
var myPr = $("<div class='product pr-last'></div>").appendTo(myRow);
}else{
var myPr = $("<div class='product'></div>").appendTo(myRow);
}
myPr.append("<div class='img-box'><div class='box-frame'> </div><img src='"+data.result['data'].srvList[i].icon+"' height=178 width=145 alt='Product Image' /><a href='#' srvId='"+data.result['data'].srvList[i].id+"' class='more' title='Buy'>Buy</a></div><div class='pr-entry'><h4>"+data.result['data'].srvList[i].name+"</h4><p>"+data.result['data'].srvList[i].description+"</p><span class='pr-price'><span>€</span>0<sup>.00</sup></span><a class='addToCartBtn' srvId='"+data.result['data'].srvList[i].id+"' href='#'><img src='css/images/add_to_cart.png' height='30px' width='120px' /></a></div></div>");
j++;
}
$("a.addToCartBtn").click(
function(event){
event.preventDefault();
srvId = $(this).attr("srvId");
disabled = $(this).attr("deadLink");
//Vérifier si l'utilisateur est loggé
if($("#myAccountTab").length){
//Vérifier si le bouton est actif
if(disabled!=1){
addToCart(srvId);
$(this).find("img").attr("src",'css/images/add_to_cart_disabled.png');
$(this).css("cursor","default");
$(this).attr("deadLink","1");
}
}else{
window.alert("Please log in first!");
}
return false;
}
);
$("a.more").click(
function(event){
event.preventDefault();
showDialog(this.getAttribute("srvId"));
return false;
});
}
}
);
$("#detailedServiceDialog").dialog({ //create dialog, but keep it closed
autoOpen: false,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "blind",
duration: 1000
},
position: {
my: "center",
at: "center",
of: "#main",
},
width: "470",
height:"500",
});
}
function showDialog(id){ //load content and open dialog
$("#detailedServiceDialog").load("serviceDetails.html",function(){
initUI_detailed(id);
});
$("#detailedServiceDialog").dialog("open");
} | roiKosmic/chiconServer | chicon/webSite/js/serviceShop.html-1.js | JavaScript | apache-2.0 | 2,648 |
// Provides control sap.ui.dt.test.controls.SimpleScrollControl
/*globals sap*/
sap.ui.define(['jquery.sap.global', 'sap/ui/core/Control'],
function(jQuery, Control) {
"use strict";
/**
* Constructor for a new SimpleScrollControl.
*
* @param {string} [sId] id for the new control, generated automatically if no id is given
* @param {object} [mSettings] initial settings for the new control
*
* @class
* A simple ScrollControl.
* @extends sap.ui.core.Control
*
* @author SAP SE
* @version @version@
*
* @constructor
* @public
* @alias sap.ui.dt.test.controls.SimpleScrollControl
*/
var SimpleScrollControl = Control.extend('sap.ui.dt.test.controls.SimpleScrollControl', {
metadata: {
properties: {
},
aggregations: {
content1: {type: "sap.ui.core.Control", multiple: true, singularName: "content1"},
content2: {type: "sap.ui.core.Control", multiple: true, singularName: "content2"}
},
designtime: {
aggregations: {
content1: {
domRef: function(oElement) {
return oElement.$("content1").get(0);
}
},
content2: {
domRef: function(oElement) {
return oElement.$("content2").get(0);
}
}
},
scrollContainers : [{
domRef : "> .sapUiDtTestSSCScrollContainer",
aggregations : ["content1", "content2"]
}]
}
},
renderer: function(oRm, oCtrl) {
oRm.write("<div");
oRm.writeControlData(oCtrl);
oRm.addClass("sapUiDtTestSSC");
oRm.writeClasses();
oRm.write(">");
oRm.write("<div id='scrollContainer'");
oRm.addClass("sapUiDtTestSSCScrollContainer");
oRm.addStyle("height", "700px");
oRm.addStyle("width", "450px");
oRm.addStyle("overflow", "scroll");
oRm.writeStyles();
oRm.writeClasses();
oRm.write(">");
var aContent = oCtrl.getAggregation("content1", []);
var sId = oCtrl.getId() + "-content1";
oRm.write("<div id='" + sId + "'>");
for (var i = 0; i < aContent.length; i++) {
oRm.renderControl(aContent[i]);
}
oRm.write("</div>");
sId = oCtrl.getId() + "-content2";
oRm.write("<div id='" + sId + "'>");
aContent = oCtrl.getAggregation("content2", []);
for (var j = 0; j < aContent.length; j++) {
oRm.renderControl(aContent[j]);
}
oRm.write("</div>");
oRm.write("</div>");
oRm.write("</div>");
}
});
return SimpleScrollControl;
}, /* bExport= */ true);
| SQCLabs/openui5 | src/sap.ui.dt/test/sap/ui/dt/qunit/testdata/controls/SimpleScrollControl.js | JavaScript | apache-2.0 | 2,396 |
var utils = require('./utils')
module.exports = function ({type, hot, disableExtract, media, mode}) {
let extract = hot !== true && disableExtract !== true;
return {
loaders: utils.cssLoaders({
sourceMap: false,
extract,
type,
media,
mode
})
}
}
| didi/chameleon | packages/chameleon-tool/configs/cml-loader.conf.js | JavaScript | apache-2.0 | 292 |
// JSmolCore.js -- Jmol core capability 9/30/2013 6:43:14 PM
// see JSmolApi.js for public user-interface. All these are private functions
// BH 9/30/2013 6:42:24 PM: pdb.gz switch pdb should only be for www.rcsb.org
// BH 9/17/2013 10:17:51 AM: asynchronous file reading and saving
// BH 8/16/2013 12:02:20 PM: JSmoljQueryExt.js pulled out
// BH 8/16/2013 12:02:20 PM: Jmol._touching used properly
// BH 3/22/2013 5:53:02 PM: Adds noscript option, JSmol.min.core.js
// BH 1/17/2013 5:20:44 PM: Fixed problem with console not getting initial position if no first click
// 1/13/2013 BH: Fixed MSIE not-reading-local-files problem.
// 11/28/2012 BH: Fixed MacOS Safari binary ArrayBuffer problem
// 11/21/2012 BH: restructuring of files as JS... instead of J...
// 11/20/2012 BH: MSIE9 cannot do a synchronous file load cross-domain. See Jmol._getFileData
// 11/4/2012 BH: RCSB REST format change "<structureId>" to "<dimStructure.structureId>"
// 9/13/2012 BH: JmolCore.js chfanges for JSmol doAjax() method -- _3ata()
// 6/12/2012 BH: JmolApi.js: adds Jmol.setInfo(applet, info, isShown) -- third parameter optional
// 6/12/2012 BH: JmolApi.js: adds Jmol.getInfo(applet)
// 6/12/2012 BH: JmolApplet.js: Fixes for MSIE 8
// 6/5/2012 BH: fixes problem with Jmol "javascript" command not working and getPropertyAsArray not working
// 6/4/2012 BH: corrects problem with MSIE requiring mouse-hover to activate applet
// 5/31/2012 BH: added JSpecView interface and api -- see JmolJSV.js
// also changed "jmolJarPath" to just "jarPath"
// jmolJarFile->jarFile, jmolIsSigned->isSigned, jmolReadyFunction->readyFunction
// also corrects a double-loading issue
// 5/14/2012 BH: added AJAX queue for ChemDoodle option with multiple canvases
// 8/12/2012 BH: adds support for MSIE xdr cross-domain request (jQuery.iecors.js)
// allows Jmol applets to be created on a page with more flexibility and extendability
// provides an object-oriented interface for JSpecView and syncing of Jmol/JSpecView
// JSmoljQuery modifies standard jQuery to include binary file transfer
// If you are using jQuery already on your page and you do not need any
// binary file transfer, you can
// required/optional libraries (preferably in the following order):
// jQuery -- at least jQuery.1.9
// JSmoljQueryext.js -- required for binary file transfer; otherwise standard jQuery should be OK
// JSmolCore.js -- required;
// JSmolApplet.js -- required; internal functions for _Applet and _Image; must be after JmolCore
// JSmolControls.js -- optional; internal functions for buttons, links, menus, etc.; must be after JmolCore
// JSmolApi.js -- required; all user functions; must be after JmolCore
// JSmolTHREE.js -- WebGL library required for JSmolGLmol.js
// JSmolGLmol.js -- WebGL version of JSmol.
// JSmolJSV.js -- optional; for creating and interacting with a JSpecView applet
// (requires JSpecViewApplet.jar or JSpecViewAppletSigned.jar
// JSmol.js
// Allows Jmol-like objects to be displayed on Java-challenged (iPad/iPhone)
// or applet-challenged (Android/iPhone) platforms, with automatic switching to
// For your installation, you should consider putting JmolData.jar and jsmol.php
// on your own server. Nothing more than these two files is needed on the server, and this
// allows more options for MSIE and Chrome when working with cross-domain files (such as RCSB or pubChem)
// The NCI and RCSB databases are accessed via direct AJAX if available (xhr2/xdr).
if(typeof(jQuery)=="undefined") alert("Note -- JSmoljQuery is required for JSmol, but it's not defined.")
Jmol = (function(document) {
return {
_jmolInfo: {
userAgent:navigator.userAgent,
version: version = 'Jmol-JSO 13.0'
},
_allowedJmolSize: [25, 2048, 300], // min, max, default (pixels)
/* By setting the Jmol.allowedJmolSize[] variable in the webpage
before calling Jmol.getApplet(), limits for applet size can be overriden.
2048 standard for GeoWall (http://geowall.geo.lsa.umich.edu/home.html)
*/
_applets: {},
_asynchronous: true,
_ajaxQueue: [],
db: {
_databasePrefixes: "$=:",
_fileLoadScript: ";if (_loadScript = '' && defaultLoadScript == '' && _filetype == 'Pdb') { select protein or nucleic;cartoons Only;color structure; select * };",
_nciLoadScript: ";n = ({molecule=1}.length < {molecule=2}.length ? 2 : 1); select molecule=n;display selected;center selected;",
_pubChemLoadScript: "",
_DirectDatabaseCalls:{
"cactus.nci.nih.gov": "%URL",
"www.rcsb.org": "%URL",
"pubchem.ncbi.nlm.nih.gov":"%URL",
"$": "http://cactus.nci.nih.gov/chemical/structure/%FILE/file?format=sdf&get3d=True",
"$$": "http://cactus.nci.nih.gov/chemical/structure/%FILE/file?format=sdf",
"=": "http://www.rcsb.org/pdb/files/%FILE.pdb",
"==": "http://www.rcsb.org/pdb/files/ligand/%FILE.cif",
":": "http://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/%FILE/SDF?record_type=3d"
},
_restQueryUrl: "http://www.rcsb.org/pdb/rest/search",
_restQueryXml: "<orgPdbQuery><queryType>org.pdb.query.simple.AdvancedKeywordQuery</queryType><description>Text Search</description><keywords>QUERY</keywords></orgPdbQuery>",
_restReportUrl: "http://www.pdb.org/pdb/rest/customReport?pdbids=IDLIST&customReportColumns=structureId,structureTitle"
},
_debugAlert: false,
_document: document,
_execLog: "",
_execStack: [],
_isMsie: (navigator.userAgent.toLowerCase().indexOf("msie") >= 0),
_isXHTML: false,
_lastAppletID: null,
_mousePageX: null,
_serverUrl: "http://chemapps.stolaf.edu/jmol/jsmol.jsmol.php",
_touching: false,
_XhtmlElement: null,
_XhtmlAppendChild: false
}
})(document);
(function (Jmol, $) {
// this library is organized into the following sections:
// jQuery interface
// protected variables
// feature detection
// AJAX-related core functionality
// applet start-up functionality
// misc core functionality
// mouse events
////////////////////// jQuery interface ///////////////////////
// hooks to jQuery -- if you have a different AJAX tool, feel free to adapt.
// There should be no other references to jQuery in all the JSmol libraries.
Jmol.$ = function(objectOrId, appletDiv) {
return $(appletDiv ? "#" + objectOrId._id + "_" + appletDiv : objectOrId);
}
Jmol.$after = function (what, s) {
$(what).after(s);
}
Jmol.$ajax = function (info) {
return $.ajax(info);
}
Jmol.$attr = function (id, a, val) {
return $("#" + id).attr(a, val);
}
Jmol.$bind = function(what, list, f) {
return (f ? $(what).bind(list, f) : $(what).unbind(list));
}
Jmol.$appStyle = function(app, div, style) {
return Jmol.$(app, div).css(style);
}
Jmol.$appEvent = function(app, div, evt, f) {
Jmol.$(app, div).off(evt);
if (f)
Jmol.$(app, div).on(evt, f);
}
Jmol.$focus = function(id) {
return $("#" + id).focus();
}
Jmol.$get = function(what, i) {
return $(what).get(i);
}
Jmol.$html = function(id, html) {
return $("#" + id).html(html);
}
Jmol.$offset = function(id) {
return $("#" + id).offset();
}
Jmol.$documentOff = function(evt, id) {
$(document).off(evt, "#" + id);
}
Jmol.$documentOn = function(evt, id, f) {
$(document).on(evt, "#" + id, f);
}
Jmol.$windowOn = function(evt, f) {
return $(window).on(evt, f);
}
Jmol.$prop = function(id, p) {
return $("#" + id).prop(p);
}
Jmol.$resize = function (f) {
return $(window).resize(f);
}
Jmol.$submit = function(id) {
return $("#" + id).submit();
}
Jmol.$val = function (id, v) {
return (arguments.length == 1 ? $("#" + id).val() : $("#" + id).val(v));
}
////////////// protected variables ///////////
Jmol._clearVars = function() {
// only on page closing -- appears to improve garbage collection
delete jQuery;
delete $;
delete Jmol;
if (!java)return;
delete J;
delete JZ;
delete java;
delete Clazz;
delete JavaObject;
delete bhtest;
delete xxxbhparams;
delete xxxShowParams;
delete c$;
delete d$;
delete w$;
delete $_A;
delete $_AB;
delete $_AC;
delete $_AD;
delete $_AF;
delete $_AI;
delete $_AL;
delete $_AS;
delete $_Ab;
delete $_B;
delete $_C;
delete $_D;
delete $_E;
delete $_F;
delete $_G;
delete $_H;
delete $_I;
delete $_J;
delete $_K;
delete $_L;
delete $_M;
delete $_N;
delete $_O;
delete $_P;
delete $_Q;
delete $_R;
delete $_S;
delete $_T;
delete $_U;
delete $_V;
delete $_W;
delete $_X;
delete $_Y;
delete $_Z;
delete $_k;
delete $_s;
delete $t$;
}
////////////// feature detection ///////////////
Jmol.featureDetection = (function(document, window) {
var features = {};
features.ua = navigator.userAgent.toLowerCase()
features.os = function(){
var osList = ["linux","unix","mac","win"]
var i = osList.length;
while (i--){
if (features.ua.indexOf(osList[i])!=-1) return osList[i]
}
return "unknown";
}
features.browser = function(){
var ua = features.ua;
var browserList = ["konqueror","webkit","omniweb","opera","webtv","icab","msie","mozilla"];
for (var i = 0; i < browserList.length; i++)
if (ua.indexOf(browserList[i])>=0)
return browserList[i];
return "unknown";
}
features.browserName = features.browser();
features.browserVersion= parseFloat(features.ua.substring(features.ua.indexOf(features.browserName)+features.browserName.length+1));
features.supportsXhr2 = function() {return ($.support.cors || $.support.iecors)}
features.allowDestroy = (features.browserName != "msie");
features.allowHTML5 = (features.browserName != "msie" || navigator.appVersion.indexOf("MSIE 8") < 0);
//alert(features.allowHTML5 + " " + features.browserName + " " + navigator.appVersion)
features.getDefaultLanguage = function() {
return navigator.language || navigator.userLanguage || "en-US";
};
features._webGLtest = 0;
features.supportsWebGL = function() {
if (!Jmol.featureDetection._webGLtest) {
var canvas;
Jmol.featureDetection._webGLtest = (
window.WebGLRenderingContext
&& ((canvas = document.createElement("canvas")).getContext("webgl")
|| canvas.getContext("experimental-webgl")) ? 1 : -1);
}
return (Jmol.featureDetection._webGLtest > 0);
};
features.supportsLocalization = function() {
//<meta charset="utf-8">
var metas = document.getElementsByTagName('meta');
for (var i= metas.length; --i >= 0;)
if (metas[i].outerHTML.toLowerCase().indexOf("utf-8") >= 0) return true;
return false;
};
features.supportsJava = function() {
if (!Jmol.featureDetection._javaEnabled) {
if (Jmol._isMsie) {
return true;
// sorry just can't deal with intentionally turning off Java in MSIE
} else {
Jmol.featureDetection._javaEnabled = (navigator.javaEnabled() ? 1 : -1);
}
}
return (Jmol.featureDetection._javaEnabled > 0);
};
features.compliantBrowser = function() {
var a = !!document.getElementById;
var os = features.os()
// known exceptions (old browsers):
if (features.browserName == "opera" && features.browserVersion <= 7.54 && os == "mac"
|| features.browserName == "webkit" && features.browserVersion < 125.12
|| features.browserName == "msie" && os == "mac"
|| features.browserName == "konqueror" && features.browserVersion <= 3.3
) a = false;
return a;
}
features.isFullyCompliant = function() {
return features.compliantBrowser() && features.supportsJava();
}
features.useIEObject = (features.os() == "win" && features.browserName == "msie" && features.browserVersion >= 5.5);
features.useHtml4Object = (features.browserName == "mozilla" && features.browserVersion >= 5) ||
(features.browserName == "opera" && features.browserVersion >= 8) ||
(features.browserName == "webkit" && features.browserVersion >= 412.2);
features.hasFileReader = (window.File && window.FileReader);
return features;
})(document, window);
////////////// AJAX-related core functionality //////////////
Jmol._ajax = function(info) {
if (!info.async) {
return Jmol.$ajax(info).responseText;
}
Jmol._ajaxQueue.push(info)
if (Jmol._ajaxQueue.length == 1)
Jmol._ajaxDone()
}
Jmol._ajaxDone = function() {
var info = Jmol._ajaxQueue.shift();
info && Jmol.$ajax(info);
}
Jmol._grabberOptions = [
["$", "NCI(small molecules)"],
[":", "PubChem(small molecules)"],
["=", "RCSB(macromolecules)"]
];
Jmol._getGrabberOptions = function(applet, note) {
// feel free to adjust this look to anything you want
if (Jmol._grabberOptions.length == 0)
return ""
var s = '<input type="text" id="ID_query" onkeypress="13==event.which&&Jmol._applets[\'ID\']._search()" size="32" value="" />';
var b = '<button id="ID_submit" onclick="Jmol._applets[\'ID\']._search()">Search</button></nobr>'
if (Jmol._grabberOptions.length == 1) {
s = '<nobr>' + s + '<span style="display:none">';
b = '</span>' + b;
} else {
s += '<br /><nobr>'
}
s += '<select id="ID_select">'
for (var i = 0; i < Jmol._grabberOptions.length; i++) {
var opt = Jmol._grabberOptions[i];
s += '<option value="' + opt[0] + '" ' + (i == 0 ? 'selected' : '') + '>' + opt[1] + '</option>';
}
s = (s + '</select>' + b).replace(/ID/g, applet._id) + (note ? note : "");
return '<br />' + s;
}
Jmol._getScriptForDatabase = function(database) {
return (database == "$" ? Jmol.db._nciLoadScript : database == ":" ? Jmol.db._pubChemLoadScript : Jmol.db._fileLoadScript);
}
// <dataset><record><structureId>1BLU</structureId><structureTitle>STRUCTURE OF THE 2[4FE-4S] FERREDOXIN FROM CHROMATIUM VINOSUM</structureTitle></record><record><structureId>3EUN</structureId><structureTitle>Crystal structure of the 2[4Fe-4S] C57A ferredoxin variant from allochromatium vinosum</structureTitle></record></dataset>
Jmol._setInfo = function(applet, database, data) {
var info = [];
var header = "";
if (data.indexOf("ERROR") == 0)
header = data;
else
switch (database) {
case "=":
var S = data.split("<dimStructure.structureId>");
var info = ["<table>"];
for (var i = 1; i < S.length; i++) {
info.push("<tr><td valign=top><a href=\"javascript:Jmol.search(" + applet._id + ",'=" + S[i].substring(0, 4) + "')\">" + S[i].substring(0, 4) + "</a></td>");
info.push("<td>" + S[i].split("Title>")[1].split("</")[0] + "</td></tr>");
}
info.push("</table>");
header = (S.length - 1) + " matches";
break;
case "$": // NCI
case ":": // pubChem
break;
default:
return;
}
applet._infoHeader = header;
applet._info = info.join("");
applet._showInfo(true);
}
Jmol._loadSuccess = function(a, fSuccess) {
if (!fSuccess)
return;
Jmol._ajaxDone();
fSuccess(a);
}
Jmol._loadError = function(fError){
Jmol._ajaxDone();
Jmol.say("Error connecting to server.");
null!=fError&&fError()
}
Jmol._isDatabaseCall = function(query) {
return (Jmol.db._databasePrefixes.indexOf(query.substring(0, 1)) >= 0);
}
Jmol._getDirectDatabaseCall = function(query, checkXhr2) {
if (checkXhr2 && !Jmol.featureDetection.supportsXhr2())
return query;
var pt = 2;
var db;
var call = Jmol.db._DirectDatabaseCalls[query.substring(0,pt)];
if (!call)
call = Jmol.db._DirectDatabaseCalls[db = query.substring(0,--pt)];
if (call && db == ":") {
var ql = query.toLowerCase();
if (!isNaN(parseInt(query.substring(1)))) {
query = ":cid/" + query.substring(1);
} else if (ql.indexOf(":smiles:") == 0) {
call += "?POST?smiles=" + query.substring(8);
query = ":smiles";
} else if (ql.indexOf(":cid:") == 0) {
query = ":cid/" + query.substring(5);
} else {
if (ql.indexOf(":name:") == 0)
query = query.substring(5);
else if (ql.indexOf(":cas:") == 0)
query = query.substring(4);
query = ":name/" + encodeURIComponent(query.substring(1));
}
}
query = (call ? call.replace(/\%FILE/, query.substring(pt)) : query);
return query;
}
Jmol._getRawDataFromServer = function(database,query,fSuccess,fError,asBase64,noScript){
var s =
"?call=getRawDataFromDatabase&database=" + database
+ "&query=" + encodeURIComponent(query)
+ (asBase64 ? "&encoding=base64" : "")
+ (noScript ? "" : "&script=" + encodeURIComponent(Jmol._getScriptForDatabase(database)));
return Jmol._contactServer(s, fSuccess, fError);
}
Jmol._getInfoFromDatabase = function(applet, database, query){
if (database == "====") {
var data = Jmol.db._restQueryXml.replace(/QUERY/,query);
var info = {
dataType: "text",
type: "POST",
contentType:"application/x-www-form-urlencoded",
url: Jmol.db._restQueryUrl,
data: encodeURIComponent(data) + "&req=browser",
success: function(data) {Jmol._ajaxDone();Jmol._extractInfoFromRCSB(applet, database, query, data)},
error: function() {Jmol._loadError(null)},
async: Jmol._asynchronous
}
return Jmol._ajax(info);
}
query = "?call=getInfoFromDatabase&database=" + database
+ "&query=" + encodeURIComponent(query);
return Jmol._contactServer(query, function(data) {Jmol._setInfo(applet, database, data)});
}
Jmol._extractInfoFromRCSB = function(applet, database, query, output) {
var n = output.length/5;
if (n == 0)
return;
if (query.length == 4 && n != 1) {
var QQQQ = query.toUpperCase();
var pt = output.indexOf(QQQQ);
if (pt > 0 && "123456789".indexOf(QQQQ.substring(0, 1)) >= 0)
output = QQQQ + "," + output.substring(0, pt) + output.substring(pt + 5);
if (n > 50)
output = output.substring(0, 250);
output = output.replace(/\n/g,",");
var url = Jmol._restReportUrl.replace(/IDLIST/,output);
Jmol._loadFileData(applet, url, function(data) {Jmol._setInfo(applet, database, data) });
}
}
Jmol._loadFileData = function(applet, fileName, fSuccess, fError){
if (Jmol._isDatabaseCall(fileName)) {
Jmol._setQueryTerm(applet, fileName);
fileName = Jmol._getDirectDatabaseCall(fileName, true);
if (Jmol._isDatabaseCall(fileName)) {
// xhr2 not supported (MSIE)
fileName = Jmol._getDirectDatabaseCall(fileName, false);
Jmol._getRawDataFromServer("_",fileName,fSuccess,fError);
return;
}
}
var info = {
dataType: "text",
url: fileName,
async: Jmol._asynchronous,
success: function(a) {Jmol._loadSuccess(a, fSuccess)},
error: function() {Jmol._loadError(fError)}
}
var pt = fileName.indexOf("?POST?");
if (pt > 0) {
info.url = fileName.substring(0, pt);
info.data = fileName.substring(pt + 6);
info.type = "POST";
info.contentType = "application/x-www-form-urlencoded";
}
Jmol._ajax(info);
}
Jmol._contactServer = function(data,fSuccess,fError){
var info = {
dataType: "text",
type: "GET",
url: Jmol._serverUrl + data,
success: function(a) {Jmol._loadSuccess(a, fSuccess)},
error:function() { Jmol._loadError(fError) },
async:fSuccess ? Jmol._asynchronous : false
}
return Jmol._ajax(info);
}
Jmol._setQueryTerm = function(applet, query) {
if (!query || !applet._hasOptions || query.substring(0, 7) == "http://")
return;
if (Jmol._isDatabaseCall(query)) {
var database = query.substring(0, 1);
query = query.substring(1);
if (database == "=" && query.length == 4 && query.substring(0, 1) == "=")
query = query.substring(1);
var d = Jmol._getElement(applet, "select");
if (d.options)
for (var i = 0; i < d.options.length; i++)
if (d[i].value == database)
d[i].selected = true;
}
Jmol._getElement(applet, "query").value = query;
}
Jmol._search = function(applet, query, script) {
arguments.length > 1 || (query = null);
Jmol._setQueryTerm(applet, query);
query || (query = Jmol._getElement(applet, "query").value);
if (query.indexOf("!") == 0) {
// command prompt in this box as well
applet._script(query);
return;
} else if (query) {
query = query.replace(/\"/g, "");
}
applet._showInfo(false);
var database;
if (Jmol._isDatabaseCall(query)) {
database = query.substring(0, 1);
query = query.substring(1);
} else {
database = (applet._hasOptions ? Jmol._getElement(applet, "select").value : "$");
}
if (database == "=" && query.length == 3)
query = "=" + query; // this is a ligand
var dm = database + query;
if (!query || dm.indexOf("?") < 0 && dm == applet._thisJmolModel) {
return;
}
applet._thisJmolModel = dm;
if (database == "$" || database == ":")
applet._jmolFileType = "MOL";
else if (database == "=")
applet._jmolFileType = "PDB";
applet._searchDatabase(query, database, script);
}
Jmol._searchDatabase = function(applet, query, database, script) {
applet._showInfo(false);
if (query.indexOf("?") >= 0) {
Jmol._getInfoFromDatabase(applet, database, query.split("?")[0]);
return true;
}
if (Jmol.db._DirectDatabaseCalls[database]) {
applet._loadFile(database + query, script);
return true;
}
return false;
}
Jmol._syncBinaryOK="?";
Jmol._canSyncBinary = function() {
if (self.VBArray) return (Jmol._syncBinaryOK = false);
if (Jmol._syncBinaryOK != "?") return Jmol._syncBinaryOK;
Jmol._syncBinaryOK = true;
try {
var xhr = new window.XMLHttpRequest();
xhr.open( "text", "http://google.com", false );
if (xhr.hasOwnProperty("responseType")) {
xhr.responseType = "arraybuffer";
} else if (xhr.overrideMimeType) {
xhr.overrideMimeType('text/plain; charset=x-user-defined');
}
} catch( e ) {
System.out.println("JmolCore.js: synchronous binary file transfer is not available");
return Jmol._syncBinaryOK = false;
}
return true;
}
Jmol._binaryTypes = [".gz",".jpg",".png",".zip",".jmol",".bin",".smol",".spartan",".mrc",".pse"]; // mrc? O? others?
Jmol._isBinaryUrl = function(url) {
for (var i = Jmol._binaryTypes.length; --i >= 0;)
if (url.indexOf(Jmol._binaryTypes[i]) >= 0) return true;
return false;
}
Jmol._getFileData = function(fileName) {
// use host-server PHP relay if not from this host
var type = (Jmol._isBinaryUrl(fileName) ? "binary" : "text");
var asBase64 = ((type == "binary") && !Jmol._canSyncBinary());
if (asBase64 && fileName.indexOf("pdb.gz") >= 0 && fileName.indexOf("http://www.rcsb.org/pdb/files/") == 0) {
// avoid unnecessary binary transfer
fileName = fileName.replace(/pdb\.gz/,"pdb");
asBase64 = false;
type = "text";
}
var isPost = (fileName.indexOf("?POST?") >= 0);
if (fileName.indexOf("file:/") == 0 && fileName.indexOf("file:///") != 0)
fileName = "file://" + fileName.substring(5); /// fixes IE problem
var isMyHost = (fileName.indexOf("://") < 0 || fileName.indexOf(document.location.protocol) == 0 && fileName.indexOf(document.location.host) >= 0);
var isDirectCall = Jmol._isDirectCall(fileName);
var cantDoSynchronousLoad = (!isMyHost && $.support.iecors);
if (cantDoSynchronousLoad || asBase64 || !isMyHost && !isDirectCall)
return Jmol._getRawDataFromServer("_",fileName, null, null, asBase64, true);
var info = {dataType:type,async:false};
if (isPost) {
info.type = "POST";
info.url = fileName.split("?POST?")[0]
info.data = fileName.split("?POST?")[1]
} else {
info.url = fileName;
}
var xhr = Jmol.$ajax(info);
if (!xhr.responseText || self.Clazz && Clazz.instanceOf(xhr.response, self.ArrayBuffer)) {
// Safari
return xhr.response;
}
return xhr.responseText;
}
Jmol._isDirectCall = function(url) {
for (var key in Jmol.db._DirectDatabaseCalls) {
if (key.indexOf(".") >= 0 && url.indexOf(key) >= 0)
return true;
}
return false;
}
Jmol._cleanFileData = function(data) {
if (data.indexOf("\r") >= 0 && data.indexOf("\n") >= 0) {
return data.replace(/\r\n/g,"\n");
}
if (data.indexOf("\r") >= 0) {
return data.replace(/\r/g,"\n");
}
return data;
};
Jmol._getFileType = function(name) {
var database = name.substring(0, 1);
if (database == "$" || database == ":")
return "MOL";
if (database == "=")
return (name.substring(1,2) == "=" ? "LCIF" : "PDB");
// just the extension, which must be PDB, XYZ..., CIF, or MOL
name = name.split('.').pop().toUpperCase();
return name.substring(0, Math.min(name.length, 3));
};
Jmol._scriptLoad = function(app, file, params, doload) {
var doscript = (app._isJava || !app._noscript || params.length > 1);
if (doscript)
app._script("zap;set echo middle center;echo Retrieving data...");
if (!doload)
return false;
if (doscript)
app._script("load \"" + file + "\"" + params);
else
app._applet.viewer.openFile(file);
app._checkDeferred("");
return true;
}
Jmol._loadFileAsynchronously = function(fileLoadThread, applet, fileName) {
// we actually cannot suggest a fileName, I believe.
if (!Jmol.featureDetection.hasFileReader)
return fileLoadThread.setData("Local file reading is not enabled in your browser");
if (!applet._localReader) {
var div = '<div id="ID" style="z-index:30000;position:absolute;background:#E0E0E0;left:10px;top:10px"><div style="margin:5px 5px 5px 5px;"><input type="file" id="ID_files" /><button id="ID_loadfile">load</button><button id="ID_cancel">cancel</button></div><div>'
Jmol.$after("#" + applet._id + "_appletdiv", div.replace(/ID/g, applet._id + "_localReader"));
applet._localReader = Jmol.$(applet, "localReader");
}
Jmol.$appEvent(applet, "localReader_loadfile", "click");
Jmol.$appEvent(applet, "localReader_loadfile", "click", function(evt) {
var file = Jmol.$(applet, "localReader_files")[0].files[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) { // DONE == 2
Jmol.$appStyle(applet, "localReader", {display : "none"});
fileLoadThread.setData(file.name, Jmol._toBytes(evt.target.result));
}
};
reader.readAsArrayBuffer(file);
});
Jmol.$appEvent(applet, "localReader_cancel", "click");
Jmol.$appEvent(applet, "localReader_cancel", "click", function(evt) {
Jmol.$appStyle(applet, "localReader", {display: "none"});
fileLoadThread.setData(null, "#CANCELED#");
});
Jmol.$appStyle(applet, "localReader", {display : "block"});
}
Jmol._toBytes = function(data) {
data = new Uint8Array(data);
var b = Clazz.newByteArray(data.length, 0);
for (var i = data.length; --i >= 0;)
b[i] = data[i];
return b;
}
Jmol._doAjax = function(url, postOut, dataOut) {
// called by org.jmol.awtjs2d.JmolURLConnection.doAjax()
url = url.toString();
if (dataOut != null)
return Jmol._saveFile(url, dataOut);
if (postOut)
url += "?POST?" + postOut;
var data = Jmol._getFileData(url)
return Jmol._processData(data, Jmol._isBinaryUrl(url));
}
// Jmol._localFileSaveFunction -- // do something local here; Maybe try the FileSave interface? return true if successful
Jmol._saveFile = function(filename, data) {
var url = Jmol._serverUrl;
if (Jmol._localFileSaveFunction && Jmol._localFileSaveFunction(filename, data))
return "OK";
if (!url)
return "Jmol._serverUrl is not defined";
var isString = (typeof data == "string");
var encoding = (isString ? "" : "base64");
if (!isString)
data = J.io.Base64.getBase64(data).toString();
var filename = filename.substring(filename.lastIndexOf("/") + 1);
var mimetype = (filename.indexOf(".png") >= 0 ? "image/png" : filename.indexOf(".jpg") >= 0 ? "image/jpg" : "");
// Asynchronous output - to be reflected as a download
if (!Jmol._formdiv) {
var sform = '<div id="__jsmolformdiv__" style="display:none">\
<form id="__jsmolform__" method="post" target="_blank" action="">\
<input name="call" value="saveFile"/>\
<input id="__jsmolmimetype__" name="mimetype" value=""/>\
<input id="__jsmolencoding__" name="encoding" value=""/>\
<input id="__jsmolfilename__" name="filename" value=""/>\
<textarea id="__jsmoldata__" name="data"></textarea>\
</form>\
</div>'
Jmol.$after("body", sform);
Jmol._formdiv = "__jsmolform__";
}
Jmol.$attr(Jmol._formdiv, "action", url + "?" + (new Date()).getMilliseconds());
Jmol.$val("__jsmoldata__", data);
Jmol.$val("__jsmolfilename__", filename);
Jmol.$val("__jsmolmimetype__", mimetype);
Jmol.$val("__jsmolencoding__", encoding);
Jmol.$submit("__jsmolform__");
Jmol.$val("__jsmoldata__", "");
Jmol.$val("__jsmolfilename__", "");
return "OK";
}
Jmol._processData = function(data, isBinary) {
if (typeof data == "undefined") {
data = "";
isBinary = false;
}
isBinary &= Jmol._canSyncBinary();
if (!isBinary)
return J.util.SB.newS(data);
var b;
if (Clazz.instanceOf(data, self.ArrayBuffer))
return Jmol._toBytes(data);
b = Clazz.newByteArray(data.length, 0);
for (var i = data.length; --i >= 0;)
b[i] = data.charCodeAt(i) & 0xFF;
// alert("Jmol._processData len=" + b.length + " b[0-5]=" + b[0] + " " +
// b[1]+ " " + b[2] + " " + b[3]+ " " + b[4] + " " + b[5])
return b;
};
////////////// applet start-up functionality //////////////
Jmol._setConsoleDiv = function (d) {
if (!self.Clazz)return;
Clazz.setConsoleDiv(d);
}
Jmol._setJmolParams = function(params, Info, isHashtable) {
var availableValues = "'progressbar','progresscolor','boxbgcolor','boxfgcolor','allowjavascript','boxmessage',\
'messagecallback','pickcallback','animframecallback','appletreadycallback','atommovedcallback',\
'echocallback','evalcallback','hovercallback','language','loadstructcallback','measurecallback',\
'minimizationcallback','resizecallback','scriptcallback','statusform','statustext','statustextarea',\
'synccallback','usecommandthread'";
for (var i in Info)
if(availableValues.indexOf("'" + i.toLowerCase() + "'") >= 0){
if (i == "language" && !Jmol.featureDetection.supportsLocalization())continue;
if (isHashtable)
params.put(i, (Info[i] === true ? Boolean.TRUE: Info[i] === false ? Boolean.FALSE : Info[i]))
else
params[i] = Info[i];
}
}
Jmol._registerApplet = function(id, applet) {
return window[id] = Jmol._applets[id] = Jmol._applets[applet] = applet;
}
Jmol._readyCallback = function (a,b,c,d) {
var app = a.split("_object")[0];
// necessary for MSIE in strict mode -- apparently, we can't call
// jmol._readyCallback, but we can call Jmol._readyCallback. Go figure...
Jmol._applets[app]._readyCallback(a,b,c,d);
}
Jmol._getWrapper = function(applet, isHeader) {
var height = applet._height;
var width = applet._width;
if (typeof height !== "string" || height.indexOf("%") < 0)
height += "px";
if (typeof width !== "string" || width.indexOf("%") < 0)
width += "px";
// id_appletinfotablediv
// id_appletdiv
// id_coverdiv
// id_infotablediv
// id_infoheaderdiv
// id_infoheaderspan
// id_infocheckboxspan
// id_infodiv
// for whatever reason, without DOCTYPE, with MSIE, "height:auto" does not work,
// and the text scrolls off the page.
// So I'm using height:95% here.
// The table was a fix for MSIE with no DOCTYPE tag to fix the miscalculation
// in height of the div when using 95% for height.
// But it turns out the table has problems with DOCTYPE tags, so that's out.
// The 95% is a compromise that we need until the no-DOCTYPE MSIE solution is found.
// (100% does not work with the JME linked applet)
var img = "";
if (applet._coverImage){
var more = " onclick=\"Jmol.coverApplet(ID, false)\" title=\"" + applet._coverTitle + "\"";
var play = "<image id=\"ID_coverclickgo\" src=\"" + applet._j2sPath + "/img/play_make_live.jpg\" style=\"width:25px;height:25px;position:absolute;bottom:10px;left:10px;z-index:10001;opacity:0.5;\"" + more + " />"
img = "<div id=\"ID_coverdiv\" style=\"backgoround-color:red;z-index:10000;width:100%;height:100%;display:inline;position:absolute;top:0px;left:0px\"><image id=\"ID_coverimage\" src=\""
+ applet._coverImage + "\" style=\"width:100%;height:100%\"" + more + "/>" + play + "</div>";
}
var s = (isHeader ? "<div id=\"ID_appletinfotablediv\" style=\"width:Wpx;height:Hpx;position:relative\">IMG<div id=\"ID_appletdiv\" style=\"z-index:9999;width:100%;height:100%;position:absolute:top:0px;left:0px;\">"
: "</div><div id=\"ID_infotablediv\" style=\"width:100%;height:100%;position:absolute;top:0px;left:0px\">\
<div id=\"ID_infoheaderdiv\" style=\"height:20px;width:100%;background:yellow;display:none\"><span id=\"ID_infoheaderspan\"></span><span id=\"ID_infocheckboxspan\" style=\"position:absolute;text-align:right;right:1px;\"><a href=\"javascript:Jmol.showInfo(ID,false)\">[x]</a></span></div>\
<div id=\"ID_infodiv\" style=\"position:absolute;top:20px;bottom:0;width:100%;height:95%;overflow:auto\"></div></div></div>");
return s.replace(/IMG/, img).replace(/Hpx/g, height).replace(/Wpx/g, width).replace(/ID/g, applet._id);
}
Jmol._documentWrite = function(text) {
if (Jmol._document) {
if (Jmol._isXHTML && !Jmol._XhtmlElement) {
var s = document.getElementsByTagName("script");
Jmol._XhtmlElement = s.item(s.length - 1);
Jmol._XhtmlAppendChild = false;
}
if (Jmol._XhtmlElement)
Jmol._domWrite(text);
else
Jmol._document.write(text);
return null;
}
return text;
}
Jmol._domWrite = function(data) {
var pt = 0
var Ptr = []
Ptr[0] = 0
while (Ptr[0] < data.length) {
var child = Jmol._getDomElement(data, Ptr);
if (!child)
break;
if (Jmol._XhtmlAppendChild)
Jmol._XhtmlElement.appendChild(child);
else
Jmol._XhtmlElement.parentNode.insertBefore(child, _jmol.XhtmlElement);
}
}
Jmol._getDomElement = function(data, Ptr, closetag, lvel) {
// there is no "document.write" in XHTML
var e = document.createElement("span");
e.innerHTML = data;
Ptr[0] = data.length;
/*
// unnecessary ?
closetag || (closetag = "");
lvel || (lvel = 0);
var pt0 = Ptr[0];
var pt = pt0;
while (pt < data.length && data.charAt(pt) != "<")
pt++
if (pt != pt0) {
var text = data.substring(pt0, pt);
Ptr[0] = pt;
return document.createTextNode(text);
}
pt0 = ++pt;
var ch;
while (pt < data.length && "\n\r\t >".indexOf(ch = data.charAt(pt)) < 0)
pt++;
var tagname = data.substring(pt0, pt);
var e = (tagname == closetag || tagname == "/" ? ""
: document.createElementNS ? document.createElementNS('http://www.w3.org/1999/xhtml', tagname)
: document.createElement(tagname));
if (ch == ">") {
Ptr[0] = ++pt;
return e;
}
while (pt < data.length && (ch = data.charAt(pt)) != ">") {
while (pt < data.length && "\n\r\t ".indexOf(ch = data.charAt(pt)) >= 0)
pt++;
pt0 = pt;
while (pt < data.length && "\n\r\t =/>".indexOf(ch = data.charAt(pt)) < 0)
pt++;
var attrname = data.substring(pt0, pt).toLowerCase();
if (attrname && ch != "=")
e.setAttribute(attrname, "true");
while (pt < data.length && "\n\r\t ".indexOf(ch = data.charAt(pt)) >= 0)
pt++;
if (ch == "/") {
Ptr[0] = pt + 2;
return e;
} else if (ch == "=") {
var quote = data.charAt(++pt);
pt0 = ++pt;
while (pt < data.length && (ch = data.charAt(pt)) != quote)
pt++;
var attrvalue = data.substring(pt0, pt);
e.setAttribute(attrname, attrvalue);
pt++;
}
}
Ptr[0] = ++pt;
while (Ptr[0] < data.length) {
var child = Jmol._getDomElement(data, Ptr, "/" + tagname, lvel+1);
if (!child)
break;
e.appendChild(child);
}
*/
return e;
}
Jmol._setObject = function(obj, id, Info) {
obj._id = id;
obj.__Info = {};
for (var i in Info)
obj.__Info[i] = Info[i];
obj._width = Info.width;
obj._height = Info.height;
obj._noscript = !obj._isJava && Info.noscript;
obj._console = Info.console;
if (!obj._console)
obj._console = obj._id + "_infodiv";
if (obj._console == "none")
obj._console = null;
obj._color = (Info.color ? Info.color.replace(/0x/,"#") : "#FFFFFF");
obj._disableInitialConsole = Info.disableInitialConsole;
obj._noMonitor = Info.disableJ2SLoadMonitor;
obj._j2sPath = Info.j2sPath;
obj._deferApplet = Info.deferApplet;
obj._deferUncover = Info.deferUncover;
obj._coverImage = !obj._isJava && Info.coverImage;
obj._isCovered = !!obj._coverImage;
obj._coverScript = Info.coverScript;
obj._coverTitle = Info.coverTitle;
if (!obj._coverTitle)
obj._coverTitle = (obj._deferApplet ? "activate 3D model" : "3D model is loading...")
obj._containerWidth = obj._width + ((obj._width==parseFloat(obj._width))? "px":"");
obj._containerHeight = obj._height + ((obj._height==parseFloat(obj._height))? "px":"");
obj._info = "";
obj._infoHeader = obj._jmolType + ' "' + obj._id + '"'
obj._hasOptions = Info.addSelectionOptions;
obj._defaultModel = Info.defaultModel;
obj._readyScript = (Info.script ? Info.script : "");
obj._readyFunction = Info.readyFunction;
if (obj._coverImage && !obj._deferApplet)
obj._readyScript += ";javascript " + id + "._displayCoverImage(false)";
obj._src = Info.src;
}
Jmol._addDefaultInfo = function(Info, DefaultInfo) {
for (var x in DefaultInfo)
if (typeof Info[x] == "undefined")
Info[x] = DefaultInfo[x];
}
Jmol._syncedApplets = [];
Jmol._syncedCommands = [];
Jmol._syncedReady = [];
Jmol._syncReady = false;
Jmol._isJmolJSVSync = false;
Jmol._setReady = function(applet) {
Jmol._syncedReady[applet] = 1;
var n = 0;
for (var i = 0; i < Jmol._syncedApplets.length; i++) {
if (Jmol._syncedApplets[i] == applet._id) {
Jmol._syncedApplets[i] = applet;
Jmol._syncedReady[i] = 1;
} else if (!Jmol._syncedReady[i]) {
continue;
}
n++;
}
if (n != Jmol._syncedApplets.length)
return;
Jmol._setSyncReady();
}
Jmol._setDestroy = function(applet) {
//MSIE bug responds to any link click even if it is just a JavaScript call
if (Jmol.featureDetection.allowDestroy)
Jmol.$windowOn('beforeunload', function () { Jmol._destroy(applet); } );
}
Jmol._destroy = function(applet) {
try {
if (applet._applet) applet._applet.destroy();
applet._applet = null;
Jmol._unsetMouse(applet._canvas)
applet._canvas = null;
var n = 0;
for (var i = 0; i < Jmol._syncedApplets.length; i++) {
if (Jmol._syncedApplets[i] == applet)
Jmol._syncedApplets[i] = null;
if (Jmol._syncedApplets[i])
n++;
}
if (n > 0)
return;
Jmol._clearVars();
} catch(e){}
}
////////////// misc core functionality //////////////
Jmol._setSyncReady = function() {
Jmol._syncReady = true;
var s = ""
for (var i = 0; i < Jmol._syncedApplets.length; i++)
if (Jmol._syncedCommands[i])
s += "Jmol.script(Jmol._syncedApplets[" + i + "], Jmol._syncedCommands[" + i + "]);"
setTimeout(s, 50);
}
Jmol._mySyncCallback = function(app,msg) {
if (!Jmol._syncReady || !Jmol._isJmolJSVSync)
return 1; // continue processing and ignore me
for (var i = 0; i < Jmol._syncedApplets.length; i++) {
if (msg.indexOf(Jmol._syncedApplets[i]._syncKeyword) >= 0) {
Jmol._syncedApplets[i]._syncScript(msg);
}
}
return 0 // prevents further Jmol sync processing
}
Jmol._getElement = function(applet, what) {
var d = document.getElementById(applet._id + "_" + what);
return (d || {});
}
Jmol._evalJSON = function(s,key){
s = s + "";
if(!s)
return [];
if(s.charAt(0) != "{") {
if(s.indexOf(" | ") >= 0)
s = s.replace(/\ \|\ /g, "\n");
return s;
}
var A = (new Function( "return " + s ) )();
return (!A ? null : key && A[key] != undefined ? A[key] : A);
}
Jmol._sortMessages = function(A){
/*
* private function
*/
function _sortKey0(a,b){
return (a[0]<b[0]?1:a[0]>b[0]?-1:0);
}
if(!A || typeof (A) != "object")
return [];
var B = [];
for(var i = A.length - 1; i >= 0; i--)
for(var j = 0, jj= A[i].length; j < jj; j++)
B[B.length] = A[i][j];
if(B.length == 0)
return;
B = B.sort(_sortKey0);
return B;
}
//////////////////// mouse events //////////////////////
Jmol._jsGetMouseModifiers = function(ev) {
var modifiers = 0;
switch (ev.button) {
case 0:
modifiers = 16;//J.api.Event.MOUSE_LEFT;
break;
case 1:
modifiers = 8;//J.api.Event.MOUSE_MIDDLE;
break;
case 2:
modifiers = 4;//J.api.Event.MOUSE_RIGHT;
break;
}
if (ev.shiftKey)
modifiers += 1;//J.api.Event.SHIFT_MASK;
if (ev.altKey)
modifiers += 8;//J.api.Event.ALT_MASK;
if (ev.ctrlKey)
modifiers += 2;//J.api.Event.CTRL_MASK;
return modifiers;
}
Jmol._jsGetXY = function(canvas, ev) {
if (!canvas.applet._ready || Jmol._touching && ev.type.indexOf("touch") < 0)
return false;
ev.preventDefault();
var offsets = Jmol.$offset(canvas.id);
var x, y;
var oe = ev.originalEvent;
Jmol._mousePageX = ev.pageX;
Jmol._mousePageY = ev.pageY;
if (oe.targetTouches && oe.targetTouches[0]) {
x = oe.targetTouches[0].pageX - offsets.left;
y = oe.targetTouches[0].pageY - offsets.top;
} else if (oe.changedTouches) {
x = oe.changedTouches[0].pageX - offsets.left;
y = oe.changedTouches[0].pageY - offsets.top;
} else {
x = ev.pageX - offsets.left;
y = ev.pageY - offsets.top;
}
return (x == undefined ? null : [Math.round(x), Math.round(y), Jmol._jsGetMouseModifiers(ev)]);
}
Jmol._gestureUpdate = function(canvas, ev) {
ev.stopPropagation();
ev.preventDefault();
var oe = ev.originalEvent;
switch (ev.type) {
case "touchstart":
Jmol._touching = true;
break;
case "touchend":
Jmol._touching = false;
break;
}
if (!oe.touches || oe.touches.length != 2) return false;
switch (ev.type) {
case "touchstart":
canvas._touches = [[],[]];
break;
case "touchmove":
var offsets = Jmol.$offset(canvas.id);
var t0 = canvas._touches[0];
var t1 = canvas._touches[1];
t0.push([oe.touches[0].pageX - offsets.left, oe.touches[0].pageY - offsets.top]);
t1.push([oe.touches[1].pageX - offsets.left, oe.touches[1].pageY - offsets.top]);
var n = t0.length;
if (n > 3) {
t0.shift();
t1.shift();
}
if (n >= 2)
canvas.applet._processGesture(canvas._touches);
break;
}
return true;
}
Jmol._jsSetMouse = function(canvas) {
Jmol.$bind(canvas, 'mousedown touchstart', function(ev) {
ev.stopPropagation();
ev.preventDefault();
canvas.isDragging = true;
if ((ev.type == "touchstart") && Jmol._gestureUpdate(canvas, ev))
return false;
Jmol._setConsoleDiv(canvas.applet._console);
var xym = Jmol._jsGetXY(canvas, ev);
if(!xym)
return false;
if (ev.button != 2 && canvas.applet._popups)
Jmol.Menu.hidePopups(canvas.applet._popups);
canvas.applet._processEvent(501, xym); //J.api.Event.MOUSE_DOWN
return false;
});
Jmol.$bind(canvas, 'mouseup touchend', function(ev) {
ev.stopPropagation();
ev.preventDefault();
canvas.isDragging = false;
if (ev.type == "touchend" && Jmol._gestureUpdate(canvas, ev))
return false;
var xym = Jmol._jsGetXY(canvas, ev);
if(!xym) return false;
canvas.applet._processEvent(502, xym);//J.api.Event.MOUSE_UP
return false;
});
Jmol.$bind(canvas, 'mousemove touchmove', function(ev) { // touchmove
ev.stopPropagation();
ev.preventDefault();
var isTouch = (ev.type == "touchmove");
if (isTouch && Jmol._gestureUpdate(canvas, ev))
return false;
var xym = Jmol._jsGetXY(canvas, ev);
if(!xym) return false;
if (!canvas.isDragging)
xym[2] = 0;
canvas.applet._processEvent((canvas.isDragging ? 506 : 503), xym); // J.api.Event.MOUSE_DRAG : J.api.Event.MOUSE_MOVE
return false;
});
Jmol.$bind(canvas, 'DOMMouseScroll mousewheel', function(ev) { // Zoom
ev.stopPropagation();
ev.preventDefault();
// Webkit or Firefox
canvas.isDragging = false;
var oe = ev.originalEvent;
var scroll = (oe.detail ? oe.detail : oe.wheelDelta);
var modifiers = Jmol._jsGetMouseModifiers(ev);
canvas.applet._processEvent(-1,[scroll < 0 ? -1 : 1,0,modifiers]);
return false;
});
// context menu is fired on mouse down, not up, and it's handled already anyway.
Jmol.$bind(canvas, "contextmenu", function() {return false;});
Jmol.$bind(canvas, 'mouseout', function(ev) {
if (canvas.applet._applet)
canvas.applet._applet.viewer.startHoverWatcher(false);
canvas.isDragging = false;
});
Jmol.$bind(canvas, 'mouseenter', function(ev) {
if (canvas.applet._applet)
canvas.applet._applet.viewer.startHoverWatcher(true);
if (ev.buttons === 0 || ev.which === 0) {
canvas.isDragging = false;
var xym = Jmol._jsGetXY(canvas, ev);
if (!xym) return false;
canvas.applet._processEvent(502, xym);//J.api.Event.MOUSE_UP
}
});
if (canvas.applet._is2D)
Jmol.$resize(function() {
if (!canvas.applet)
return;
canvas.applet._resize();
});
Jmol.$bind('body', 'mouseup touchend', function(ev) {
if (canvas.applet)
canvas.isDragging = false;
});
}
Jmol._jsUnsetMouse = function(canvas) {
canvas.applet = null;
Jmol.$bind(canvas, 'mousedown touchstart mousemove touchmove mouseup touchend DOMMouseScroll mousewheel contextmenu mouseout mouseenter', null);
}
Jmol._setDraggable = function(Obj) {
var proto = Obj.prototype;
// for menus and console
proto.setContainer = function(container) {
this.container = container;
this.isDragging = false;
this.ignoreMouse = false;
var me = this;
container.bind('mousedown touchstart', function(ev) {
if (me.ignoreMouse) {
me.ignoreMouse = false;
return true;
}
me.isDragging = true;
me.pageX = ev.pageX;
me.pageY = ev.pageY;
return false;
});
container.bind('mousemove touchmove', function(ev) {
if (me.isDragging) {
me.mouseMove(ev);
return false;
}
});
container.bind('mouseup touchend', function(ev) {
me.mouseUp(ev);
});
};
proto.mouseUp = function(ev) {
if (this.isDragging) {
this.pageX0 += (ev.pageX - this.pageX);
this.pageY0 += (ev.pageY - this.pageY);
this.isDragging = false;
return false;
}
}
proto.setPosition = function() {
if (Jmol._mousePageX === null) {
var id = this.applet._id + "_" + (this.applet._is2D ? "canvas2d" : "canvas");
var offsets = Jmol.$offset(id);
Jmol._mousePageX = offsets.left;
Jmol._mousePageY = offsets.top;
}
this.pageX0 = Jmol._mousePageX;
this.pageY0 = Jmol._mousePageY;
var pos = { top: Jmol._mousePageY + 'px', left: Jmol._mousePageX + 'px' };
this.container.css(pos);
};
proto.mouseMove = function(ev) {
if (!this.isDragging)
return;
var x = this.pageX0 + (ev.pageX - this.pageX);
var y = this.pageY0 + (ev.pageY - this.pageY);
this.container.css({ top: y + 'px', left: x + 'px' })
};
proto.dragBind = function(isBind) {
this.container.unbind('mousemoveoutjsmol');
this.container.unbind('touchmoveoutjsmol');
this.container.unbind('mouseupoutjsmol');
this.container.unbind('touchendoutjsmol');
if (isBind) {
var me = this;
this.container.bind('mousemoveoutjsmol touchmoveoutjsmol', function(evspecial, target, ev) {
me.mouseMove(ev);
});
this.container.bind('mouseupoutjsmol touchendoutjsmol', function(evspecial, target, ev) {
me.mouseUp(ev);
});
}
};
}
})(Jmol, jQuery);
| DeepLit/WHG | root/static/js/jsmol/js/JSmolCore.js | JavaScript | apache-2.0 | 49,790 |
var __extends = this.__extends || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
__.prototype = b.prototype;
d.prototype = new __();
};
var q = require("Q");
var M = (function (_super) {
__extends(M, _super);
function M() {
_super.apply(this, arguments);
}
return M;
})(q);
| mbrowne/typescript-dci | tests/baselines/reference/exportAssignmentOfGenericType1.commonjs.js | JavaScript | apache-2.0 | 398 |
function ignoreInput() {
document.getElementById("personalQuestionReciverName").value = "";
document.getElementById("personalQuestion").value = "";
} | MyCapitaine/Personal-health-management-system | view/script/PersonalMsg.js | JavaScript | apache-2.0 | 152 |
// All material copyright ESRI, All Rights Reserved, unless otherwise specified.
// See http://js.arcgis.com/3.11/esri/copyright.txt for details.
//>>built
define("esri/nls/jsapi_zh-tw",{"esri/nls/jsapi":{findHotSpotsTool:{hotspotsPointDefine:"Analyze \x3cb\x3e${layername}\x3c/b\x3e to find statistically significant hot and cold spots ",itemTags:"Analysis Result, Hot Spots, ${layername}, ${fieldname}",itemSnippet:"Analysis Feature Service generated from Find Hot Spots",defineBoundingLabel:"Define where incidents are possible",blayerName:"Drawn Boundaries",Options:"Options",hotspots:"Hot Spots",defaultAggregationOption:"Select aggregation areas",itemDescription:"Feature Service generated from running the Find Hot Spots solution.",
chooseAttributeLabel:"Choose an analysis field",provideAggLabel:"Provide aggregation areas for summing incidents",hotspotsPolyDefine:"Analyze \x3cb\x3e${layername}\x3c/b\x3e to find statistically significant hot and cold spots of ",defaultBoundingOption:"Select bounding areas",fieldLabel:"with or without an analysis field",noAnalysisField:"No Analysis Field",outputLayerName:"Hot Spots ${layername}"},expressionGrid:{viewGrid:"View Grid",expression:"Expression",editExpr:"Edit Expression",addExprDescription:"Click Add Expression to begin building your query.",
viewText:"View Text",duplicateExpression:"This Expression already exists",addExpr:"Add Expression"},expressionForm:{completelyContains:"completely contains",notTouches:"does not touch",notIntersects:"does not intersect",whereLabel:"where",notContains:"does not completely contain",from:"from",within:"completely within",touches:"touches",where:"where (attribute query)",notWithin:"not completely within",notCrossesOutline:"not crossed by the outline of",contains:"completely contains",notWithinDistance:"not within a distance of",
crossesOutline:"crossed by the outline of",withinDistance:"within a distance of",notIdentical:"are not identical to",inValidAttributeFilterMessage:"Layer ${layername} does not contain any attributes that can be used in an attribute query.",notCompletelyWithin:"not completely within",identical:"are identical to",intersects:"intersects",notCompletelyContains:"does not completely contain",completelyWithin:"completely within"},FindNearestTool:{chooseLayerInfoLabel:"Both input layers must contain points to enable Driving distance and Driving time options",
limitSearchRangeCheck:"Limit the search range to",addStats:"For each location in \x3cb\x3e${summaryLayerName}\x3c/b\x3e",itemDescription:"Feature Service generated from running the Find Nearest solution. Nearest ${sumNearbyLayerName}",outputConnectingLayerName:"Nearest ${layer} to ${sumNearbyLayerName} (Lines)",forEachLocationLabel:"For each location in \x3cb\x3e${sumNearbyLayerName}\x3c/b\x3e",findNearestLabel:"Limit the number of nearest locations to:",straightLineDistance:"Line distance",resultLabel1:"Nearest locations layer",
resultLabel2:"Connecting lines layer",outputLayerName:"Nearest ${layer} to ${sumNearbyLayerName}",findNearLabel:"Find the nearest locations by measuring",groupByLabel:"Choose field to group by (optional)",itemTags:"Analysis Result, Find Nearest, ${sumNearbyLayerName}, ${summaryLayerName}",summarizeDefine:"For each location in \x3cb\x3e${sumNearbyLayerName}\x3c/b\x3e, find its nearest locations.",itemSnippet:"Analysis Feature Service generated from Find Nearest",findLocationsIn:"Find the nearest locations in:",
chooseLayer:"Choose a layer",outputLayersLabel:"Result layer names",removeAttrStats:"Remove Attribute Statistics"},identity:{noAuthService:"Unable to access the authentication service.",lblCancel:"Cancel",lblUser:"User Name:",title:"Sign in",forbidden:"The username and password are valid, but you don't have access to this resource.",errorMsg:"Invalid username/password. Please try again.",lblItem:"item",lblOk:"OK",info:"Please sign in to access the item on ${server} ${resource}",lblSigning:"Signing in...",
invalidUser:"The username or password you entered is incorrect.",lblPwd:"Password:"},enrichLayerTool:{vzCountryCode:"Venezuela",norwayCountryCode:"Norway",itemSnippet:"Analysis Feature Service generated from Enrich layer",albaniaCountryCode:"Albania",gBSpend:"United Kigdom Spending",joCountryCode:"Jordan",raceAndEthnicity:"Race And Ethnicity",croatiaCountryCode:"Croatia",householdsByIncome:"Households by Income",moCountryCode:"Morocco",hungaryCountryCode:"Hungary",keyWEFacts:"Key Western Europe Facts",
iNFacts:"India Facts",landscapeFacts:"Landscape Facts",peruCountryCode:"Peru",spainCountryCode:"Spain",mauritiusCountryCode:"Mauritius",botswanaCountryCode:"Botswana",czechCountryCode:"Czech Republic",usCountryCode:"United States",gBFacts:"United Kingdom Facts",bESpend:"Belgium Spending",ukrCountryCode:"Ukraine",coCountryCode:"Costa Rica",belgiumCountryCode:"Belgium",nigeriaCountryCode:"Nigeria",niCountryCode:"Nicaragua",kazakhstanCountryCode:"Kazakhstan",dESpend:"Germany Spending",globalCode:"Global",
straightLineDistance:"Line distance",denmarkCountryCode:"Denmark",canadaCountryCode:"Canada",lUSpend:"Luxembourg Spending",fISpend:"Finland Spending",selectedVars:"Selected Variables",bEFacts:"Belgium Facts",moldovaCountryCode:"Moldova",tRSpend:"Turkey Spending",namibiaCountryCode:"Namibia",waterWetlands:"Water Wetlands",bulgariaCountryCode:"Bulgaria",ukCountryCode:"United Kingdom",austriaCountryCode:"Austria",aTSpend:"Austria Spending",finlandCountryCode:"Finland",mgCountryCode:"Mongolia",omCountryCode:"Oman",
netherlandsCountryCode:"Netherlands",syCountryCode:"Syria",dEFacts:"Germany Facts",iESpend:"Ireland Spending",kzCountryCode:"Kyrgyzstan",lUFacts:"Luxembourg Facts",fIFacts:"Finland Facts",lISpend:"Liechtenstein Spending",tRFacts:"Turkey Facts",tnCountryCode:"Tunisia",polandCountryCode:"Poland",vtCountryCode:"Vietnam",malawiCountryCode:"Malawi",cHSpend:"Switzerland Spending",latviaCountryCode:"Latvia",aTFacts:"Austria Facts",infrastructure:"Infrastructure",indonesiaCountryCode:"Indonesia",icelandCountryCode:"Iceland",
husByOccupancy:"Housing Units By Occupancy",leCountryCode:"Lesotho",montenegroCountryCode:"Montenegro",keyUSFacts:"Key US Facts",uaeCountryCode:"United Arab Emirates",iEFacts:"Ireland Facts",rUSpend:"Russia Spending",luxembourgCountryCode:"Luxembourg",switzerlandCountryCode:"Switzerland",azCountryCode:"Azerbaijan",lIFacts:"Liechtenstein Facts",slCountryCode:"Slovakia",iTSpend:"Italy Spending",nzCountryCode:"New Zealand",qaCountryCode:"Qatar",wealth:"Wealth Facts",sgCountryCode:"Singapore",cHFacts:"Switzerland Facts",
andCountryCode:"Andorra",jPSpend:"Japan Spending",sriCountryCode:"Sri Lanka",outputLayerName:"Enriched ${layername}",lithuaniaCountryCode:"Lithuania",selectCountryLabel:"Select country",rUFacts:"Russia Facts",irelandCountryCode:"Ireland",eeCountryCode:"Estonia",kwCountryCode:"Kuwait",keyGlobalFacts:"Key Global Facts",iTFacts:"Italy Facts",sESpend:"Sweden Spending",krCountryCode:"South Korea",jPFacts:"Japan Facts",liechtensteinCountryCode:"Liechtenstein",itemTags:"Analysis Result, Enrich Layer, ${inputLayerName}",
ghanaCountryCode:"Ghana",eSSpend:"Spain Spending",puertoCountryCode:"Puerto Rico",tapestry:"Tapestry",lbCountryCode:"Lebanon",tzCountryCode:"Tanzania",reunionCountryCode:"Reunion",pTSpend:"Portugal Spending",selectDataVar:"Select Variables",nLSpend:"Netherlands Spending",hoCountryCode:"Honduras",clickDataVar:"Click Select Variables to open Data Browser and browse for variables",sEFacts:"Sweden Facts",australiaCountryCode:"Australia",romaniaCountryCode:"Romania",siCountryCode:"Slovenia",sdCountryCode:"Sudan",
dKSpend:"Denmark Spending",chooseDataCollectionLabel:"Show available data for:",eSFacts:"Spain Facts",mkCountryCode:"The Former Yugoslav Republic of Macedonia",pTFacts:"Portugal Facts",elCountryCode:"El Salvador",grCountryCode:"Georgia",cyprusCountryCode:"Cyprus",nLFacts:"Netherlands Facts",egCountryCode:"Egypt",bosniaCountryCode:"Bosnia and Herzegovina",landCover:"Land Cover",franceCountryCode:"France",dKFacts:"Denmark Facts",thCountryCode:"Thailand",ugandaCountryCode:"Uganda",turkeyCountryCode:"Turkey",
maltaCountryCode:"Malta",bRSpend:"Brazil Spending",italyCountryCode:"Italy",keyCanFacts:"Key Canada Facts",pkCountryCode:"Pakistan",twCountryCode:"Taiwan",safCountryCode:"South Africa",policy:"Policy Facts",algCountryCode:"Algeria",chinaCountryCode:"China",germanyCountryCode:"Germany",nOSpend:"Norway Spending",malaysiaCountryCode:"Malaysia",saCountryCode:"Saudi Arabia",ugCountryCode:"Uruguay",russiaCountryCode:"Russia",portugalCountryCode:"Portugal",coteCountryCode:"Cote d'Ivoire",bRFacts:"Brazil Facts",
mozambiqueCountryCode:"Mozambique",soils:"Soils",mexicoCountryCode:"Mexico",szCountryCode:"Swaziland",chCountryCode:"Chile",gRSpend:"Greece Spending",kenyaCountryCode:"Kenya",gtCountryCode:"Guatemala",zmCountryCode:"Zambia",fRSpend:"France Spending",enrichDefine:"Enrich \x3cb\x3e${inputLayerName}\x3c/b\x3e",nOFacts:"Norway Facts",defAreasLabel:"Define areas to enrich",belarusCountryCode:"Belarus",colombiaCountryCode:"Colombia",bahrainCountryCode:"Bahrain",swedenCountryCode:"Sweden",japanCountryCode:"Japan",
indiaCountryCode:"India",israelCountryCode:"Israel",greeceCountryCode:"Greece",publicLands:"Public Lands",itemDescription:"Feature Service generated from running the Enrich layer solution. ${inputLayerName} were enriched",gRFacts:"Greece Facts",keyWESpend:"Key Western Europe Spending",iNSpend:"India Spending",argCountryCode:"Argentina",age:"Age",rsCountryCode:"Serbia",fRFacts:"France Facts",baCountryCode:"Bangladesh",phCountryCode:"Philippines",brazilCountryCode:"Brazil"},filterDlg:{dateOperatorInTheLast:"in the last",
hint:"Hint",uniqueValueTooltip:"Pick from unique values in selected field",dateOperatorDays:"days",emptyString:"empty string",numberOperatorIsNot:"is not",numberOperatorIsBlank:"is blank",dateOperatorMonths:"months",dateOperatorWeeks:"weeks",addSetTooltip:"Add a set to contain expressions",all:"All",edit:"Edit",matchMsgSet:"${any_or_all} of the following expressions in this set are true",stringOperatorStartsWith:"starts with",view:"View",error:{cantParseExpression:"Filter cannot be shown because one or more of its expressions cannot be parsed. To edit the filter expressions, clear the filter and create a new filter interactively.",
missingValue:"there's a missing value in one of the expressions",noFilterFields:"Layer ${name} has no fields that can be used for filtering.",generateRendererFailed:"Unique values could not be determined for the selected field.",noUniqueValues:"The specified field has has no values."},toNewLayer:"To a new layer",uniqueValues:"Unique",askForValues:"Ask for values",stringOperatorIsNotBlank:"is not blank",numberOperatorIsAtMost:"is at most",deleteSet:"Delete this set",applyFilterBtn:"Apply Filter",stringOperatorDoesNotContain:"does not contain",
prompt:"Prompt",change:"Change",expressionTemplate:"${field_dropdown} ${operator_dropdown} ${values_input}",andBetweenValues:"and",stringOperatorIsBlank:"is blank",dateOperatorIsNotOn:"is not on",numberOperatorIsAtLeast:"is at least",stringOperatorEndsWith:"ends with",valueTooltip:"Enter value",and:"and",dateOperatorIsNotBetween:"is not between",numberOperatorIsNotBlank:"is not blank",stringOperatorIs:"is",fieldTooltip:"Pick from existing field",dateOperatorIsBetween:"is between",any:"Any",newLayerName:"New layer name",
dateOperatorNotInTheLast:"not in the last",or:"or",value:"Value",dateOperatorIsBlank:"is blank",dateOperatorIsBefore:"is before",dateOperatorIsOn:"is on",friendlyDatePattern:"MM/dd/yyyy",addExpression:"Add an expression to this set",addAnotherExpression:"Add another expression",filter:"Filter",field:"Field",friendlyAnd:"All of these expressions must be true:",addSet:"Add a set",numberOperatorIsLessThan:"is less than",showFilterExpression:"Show filter's expressions",numberOperatorIsNotBetween:"is not between",
dateOperatorIsAfter:"is after",numberOperatorIsGreaterThan:"is greater than",friendlyOr:"Any of these expressions must be true:",numberOperatorIsBetween:"is between",applyFilter:"Apply Filter",promptMsg:"Provide a prompt and some hint text to present this filter interactively to others",dateOperatorIsNotBlank:"is not blank",create:"Create",match1Msg:"Display features in the layer that match the following expression",stringOperatorIsNot:"is not",removeFilterBtn:"Remove Filter",deleteExpression:"Delete this expression",
numberOperatorIs:"is",matchMsg:"Display features in the layer that match ${any_or_all} of the following expressions",stringOperatorContains:"contains",toThisLayer:"To this layer"},layers:{FeatureLayer:{createUserHours:"Created by ${userId} ${hours} hours ago",editUserMinutes:"Edited by ${userId} ${minutes} minutes ago",editHour:"Edited an hour ago",editMinute:"Edited a minute ago",editUserMinute:"Edited by ${userId} a minute ago",editSeconds:"Edited seconds ago",createUserFull:"Created by ${userId} on ${formattedDate} at ${formattedTime}",
editWeekDay:"Edited on ${weekDay} at ${formattedTime}",createUserMinutes:"Created by ${userId} ${minutes} minutes ago",createUserHour:"Created by ${userId} an hour ago",editUserSeconds:"Edited by ${userId} seconds ago",editUserWeekDay:"Edited by ${userId} on ${weekDay} at ${formattedTime}",editUserFull:"Edited by ${userId} on ${formattedDate} at ${formattedTime}",createFull:"Created on ${formattedDate} at ${formattedTime}",editUser:"Edited by ${userId}",noOIDField:"objectIdField is not set [url: ${url}]",
editUserHour:"Edited by ${userId} an hour ago",createHour:"Created an hour ago",updateError:"an error occurred while updating the layer",createUserWeekDay:"Created by ${userId} on ${weekDay} at ${formattedTime}",invalidParams:"query contains one or more unsupported parameters",editHours:"Edited ${hours} hours ago",noGeometryField:"unable to find a field of type 'esriFieldTypeGeometry' in the layer 'fields' information. If you are using a map service layer, features will not have geometry [url: ${url}]",
createUserMinute:"Created by ${userId} a minute ago",createUser:"Created by ${userId}",createMinute:"Created a minute ago",createMinutes:"Created ${minutes} minutes ago",fieldNotFound:"unable to find '${field}' field in the layer 'fields' information [url: ${url}]",createHours:"Created ${hours} hours ago",editUserHours:"Edited by ${userId} ${hours} hours ago",editMinutes:"Edited ${minutes} minutes ago",createSeconds:"Created seconds ago",createUserSeconds:"Created by ${userId} seconds ago",createWeekDay:"Created on ${weekDay} at ${formattedTime}",
editFull:"Edited on ${formattedDate} at ${formattedTime}"},dynamic:{imageError:"Unable to load image"},tiled:{tileError:"Unable to load tile"},imageParameters:{deprecateBBox:"Property 'bbox' deprecated. Use property 'extent'."},agstiled:{deprecateRoundrobin:"Constructor option 'roundrobin' deprecated. Use option 'tileServers'."},graphics:{drawingError:"Unable to draw graphic "}},dissolveBoundaries:{chooseDissolveLabel:"Choose dissolve method",sameAttributeAreasLabel:"Areas with same field value",
itemTags:"Analysis Result, Dissolve Boundaries, ${layername}",itemSnippet:"Analysis Feature Service generated from Dissolve Boundaries",summarizeLabel:"Add statistic (optional)",overlappingAreasLabel:"Areas that overlap or are adjacent",dissolveBoundariesDefine:"Dissolve \x3cb\x3e${layername}\x3c/b\x3e",itemDescription:"Feature Service generated from running the Dissolve Boundaries solution.",resultLabel:"Result layer name",outputLayerName:"Dissolve ${layername}"},summarizeWithinTool:{removeAttrStats:"Remove Attribute Statistics",
itemTags:"Analysis Result, Summarize Within, ${sumWithinLayerName}, ${summaryLayerName}",sumLabel:"Summarize",groupByLabel:"Choose field to group by (optional)",itemSnippet:"Analysis Feature Service generated from Summarize Within",addStats:"Add statistics from \x3cb\x3e${summaryLayerName}\x3c/b\x3e",summarizeMetricPoly:"Sum Area in",itemDescription:"Feature Service generated from running the Summarize Within solution. ${summaryLayerName} were summarized within ${sumWithinLayerName}",summarizeMetricLine:"Length of lines in",
summarizeDefine:"For Features within \x3cb\x3e${sumWithinLayerName}\x3c/b\x3e",outputLayerName:"Summarize ${summaryLayerName} within ${sumWithinLayerName}",summarizeMetricPoint:"Count of points",addStatsLabel:"Attribute statistics"},mergeLayers:{mergeFieldsLabel:"Modify merging fields (optional)",itemTags:"Analysis Result, Merge Layers, ${layername}",itemSnippet:"Analysis Feature Service generated from Merge Layers",fieldTypeMatchValidationMsg:"Fields to be matched must have the same type. Transformation of types is supported (for example, double to integer, integer to string) except for string to numeric.",
itemDescription:"Feature Service generated from running the Merge Layers solution.",mergeLayersDefine:"Merge \x3cb\x3e${layername}\x3c/b\x3e with",match:"Match",remove:"Remove",chooseMergeLayer:"Choose layer",operation:"Operation",rename:"Rename",resultLabel:"Result layer name",outputLayerName:"Merge ${layername} ${mergelayername}"},virtualearth:{vetiledlayer:{bingMapsKeyNotSpecified:"BingMapsKey must be provided."},vegeocode:{bingMapsKeyNotSpecified:"BingMapsKey must be provided.",requestQueued:"Server token not retrieved. Queing request to be executed after server token retrieved."}},
geoenrichment:{task:{GeoenrichmentTask:{noData:"There is no data for the selected area"}},dijit:{DataCollectionsPage:{from:"from '${categoryName}'",categoryName:"${categoryName} Variables",mapPopVar:"Choose a Popular Variable",noResults:"No results found for '${seachKey}'.",keepBrowse:"Keep Browsing",showAll:"Show all ${categoryName} Variables",search:"search within the current category"},BufferOptions:{driveTime:"Drive Times",units:{esriDriveTimeUnitsMinutes:"minutes",esriMiles:"miles",esriKilometers:"kilometers",
esriMeters:"meters",esriFeet:"feet"},driveDistance:"Drive Distance",radius:"Radius:",buffer:"Buffer:",ring:"Ring",time:"Time:",studyArea:"Show data for:",distance:"Distance:"},WizardButtons:{cancel:"Cancel",next:"Next",ok:"OK",back:"Back",apply:"Apply"},ShoppingCart:{selectedVars:"Selected Variables",noVariables:"No variables have yet been selected"},RelatedVariables:{lowLabel2:"The smallest group: ${alias}",valueCol:"Value",difCol:"Difference",chartLabel:"Bars show deviation from",highLabel2:"The largest group: ${alias}",
indicatorCol:"Indicator"},DataBrowser:{title:"Data Browser"},EnrichOptionsPage:{creditsCalc:"calculating...",bufferRing:"1 mile circle around locations",varsPerRowTooltip:"This operation will enrich each row with ${varCount} variables and will cost ${credits} per row.",totalVarsTooltip:"This operation will enrich ${rowCount} rows with ${varCount} variables and will cost ${credits}.",bufferPolygon:"input polygons (buffer unavailable)",back:"Back",finish:"Add data to system",edit:"edit",customize:"customize",
totalVars:"Total Variables: ${varCount} (${credits})",credits:"${credits} credits",noColumn:"\x3cNone\x3e",varName:"Variable Name",overwriteExisting:"Existing column values will be overwritten",newColumn:"\x3cCreate New\x3e",column:"Column",selectedVariables:"Selected Variables:",bufferOptions:"Show data for:",varsPerRow:"Variables per Row: ${varCount} (${credits})"},VariableInfo:{source:"Source",vintage:"Vintage",variable:"Variable",name:"Name"},bufferTitle:{pointRing:{esriKilometers:"${radius}-km ring",
esriMiles:"${radius}-mile ring",esriMeters:"${radius}-meter ring",esriFeet:"${radius}-feet ring"},lineBuffer:{esriKilometers:"${radius}-km buffer",esriMiles:"${radius}-mile buffer",esriMeters:"${radius}-meter buffer",esriFeet:"${radius}-feet buffer"},polygon:"This area",pointDriveTime:{esriDriveTimeUnitsMinutes:"${radius}-minute drive time",esriKilometers:"${radius}-km drive distance",esriMiles:"${radius}-mile drive distance",esriMeters:"${radius}-meter drive distance",esriFeet:"${radius}-feet drive distance"},
stdGeo:"Intersecting ${level} feature"},EnrichConfig:{title:"Enrich Layer"},DataVariablesPage:{vars:"variables"},DataCategoriesPage:{loading:"Loading...",global:"Global",noResults:"No results found for '${seachKey}'.",search:"search for a variable name"},AgePyramid:{compLabel:"Dots show comparison to",maxLabel:"The largest group:",minLabel:"The smallest group:",menLabel:"Men",womenLabel:"Women"},OneVar:{same:"which is the same as the average for ${site}",subtitleSite2:"for this area ",subtitleVar2:"${alias} is ",
lessThan:"which is less than the average for ${site}",moreThan:"which is more than the average for ${site}",valueCol:"Value",areaCol:"Area"},Tapestry:{raceEthnicityLabel:"Race / Ethnicity:",hhLabel:"households",adultsLabel:"adults",medianAgeLabel:"Median Age:",hhTypeLabel:"Household Type:",educationLabel:"Education:",incomeLabel:"Income:",employmentLabel:"Employment:",residentialLabel:"Residential:"},InfographicsMainPage:{chooseCountry:"Show available data for: ",add:"Add",cancel:"Cancel",mainTitle:"Configure Infographics",
addVariables:"Add more variables...",ok:"OK",dark:"Dark",chooseTheme:"Select color theme:",light:"Light",loading:"Loading...",chooseDataCollection:"Choose from popular data collections: "}}},toolbars:{draw:{addShape:"Click to add a shape, or press down to start and let go to finish",finish:"Double-click to finish",invalidType:"Unsupported geometry type",resume:"Click to continue drawing",addPoint:"Click to add a point",freehand:"Press down to start and let go to finish",complete:"Double-click to complete",
start:"Click to start drawing",addMultipoint:"Click to start adding points",convertAntiClockwisePolygon:"Polygons drawn in anti-clockwise direction will be reversed to be clockwise."},edit:{invalidType:"Unable to activate the tool. Check if the tool is valid for the given geometry type.",deleteLabel:"Delete"}},deriveNewLocations:{outputLayerName:"New Locations",itemTags:"Analysis Result, Derive New Locations, ${analysisLayerName}",itemSnippet:"Analysis Feature Service generated from Find Existing Locations",
findExpLabel:"Derive new locations that match the following expression(s)",itemDescription:"Feature Service generated from running the Derive New Locations solutions."},widgets:{timeSlider:{NLS_previous:"Previous",NLS_play:"Play/Pause",NLS_next:"Next",NLS_invalidTimeExtent:"TimeExtent not specified, or in incorrect format.",NLS_first:"First"},renderingRule:{rendererLabelTitle:"Renderer",numStdDevEndLabelTitle:"standard deviations.",minPercentLabelTitle:"Exclude bottom:",bandCombinationLabelTitle:"RGB composite",
stretchMethodLabel:"Stretch Type:",minMaxDescLabelTitle:"Trim extreme pixel values",imageEnhancementLabelTitle:"Image Enhancement",stretchMethodNoneDesc:"No additional enhancements applied.",draLabelTitle:"Dynamic range adjustment",percentClipStretchAlias:"Percent Clip",gammaLabelTitle:"Gamma:",userDefinedRendererTitle:"User Defined Renderer",stdDevStretchAlias:"Standard Deviation",numStdDevLabelTitle:"Trim extreme pixel values beyond",percentLabelTitle:"%",userDefinedRendererDesc:"A user defined renderer. Use different bands for inputs to the Red, Green, and Blue channels (multi-band services only). Apply different radiometric enhancement algorithms to make image look better.",
maxPercentLabelTitle:"Exclude top:",minMaxStretchAlias:"Minimum and Maximum",noneStretchAlias:"None",stretchDescLabel:"Apply contrast enhancements to improve the image display.",bandNamesRequestMsg:"Requesting band information...",stretchMethodMinMaxDesc:"Stretch to the entire range of pixel values.",minGammaLabel:"0.1",maxGammaLabel:"10"},attributeInspector:{NLS_title:"Edit Attributes",NLS_validationFlt:"Value must be a float.",NLS_noFeaturesSelected:"No features selected",NLS_validationInt:"Value must be an integer.",
NLS_next:"Next",NLS_errorInvalid:"Invalid",NLS_previous:"Previous",NLS_first:"First",NLS_deleteFeature:"Delete",NLS_of:"of",NLS_last:"Last"},templatePicker:{loading:"Loading..",creationDisabled:"Feature creation is disabled for all layers."},locateButton:{locate:{tracking:"Track location",title:"Find my location",stopTracking:"Stop tracking location",button:"My Location"}},scalebar:{ft:"ft",km:"km",mi:"mi",m:"m"},layerSwipe:{title:"Drag to see underlying layer"},HistogramTimeSlider:{NLS_play:"Play/Pause",
NLS_fullRange:"full range",NLS_range:"Range",NLS_invalidTimeExtent:"TimeExtent not specified, or in incorrect format.",NLS_overview:"OVERVIEW",NLS_cumulative:"Cumulative"},basemapToggle:{toggle:"Toggle basemap",basemapLabels:{streets:"Streets",oceans:"Oceans",osm:"OpenStreetMap",hybrid:"Hybrid",satellite:"Satellite",topo:"Topographic",gray:"Gray","national-geographic":"National Geographic"}},measurement:{NLS_geometry_service_error:"Geometry Service Error",NLS_length_kilometers:"Kilometers",NLS_length_nautical_miles:"Nautical Miles",
NLS_area_sq_miles:"Sq Miles",NLS_length_yards:"Yards",NLS_distance:"Distance",NLS_GeoRef:"GeoRef",NLS_area_acres:"Acres",NLS_resultLabel:"Measurement Result",NLS_MGRS:"MGRS",NLS_length_miles:"Miles",NLS_area_hectares:"Hectares",NLS_area_sq_nautical_miles:"Sq Nautical Miles",NLS_deg_min_sec:"DMS",NLS_area:"Area",NLS_UTM:"UTM",NLS_GARS:"GARS",NLS_area_sq_meters:"Sq Meters",NLS_USNG:"USNG",NLS_latitude:"Latitude",NLS_area_sq_kilometers:"Sq Kilometers",NLS_area_sq_feet:"Sq Feet",NLS_longitude:"Longitude",
NLS_calculating:"Calculating...",NLS_location:"Location",NLS_decimal_degrees:"Degrees",NLS_length_feet:"Feet",NLS_area_sq_yards:"Sq Yards",NLS_length_meters:"Meters",NLS_map_coordinate:"Map Coordinate"},geocodeMatch:{matchedUC:"Matched",idProperty:"id",unmatchedLC:"unmatched",unmatchedUC:"Unmatched",match:{columnLabelAddress:"Address",columnLabelType:"Type",defaultMatchType:"DefaultMatch",mapAllCandidatesLabel:"Map All Suggestions",userCreatedLabel:"User Created",tableOptionsLabel:"Options",columnLabelScore:"Score",
defaultSortOrderLabel:"Default Sort Order",noDataMsg:"No Results."},customLabel:"Custom",gridTitle:"Suggestions",popup:{locationTitle:"Location",optionsTitle:"Match Options:",checkBoxAddress:"Suggested Address",loadingPH:"Searching...",yTitle:"Y: ",discardButtonLabel:"Discard",xTitle:"X: ",checkBoxLocation:"Location (X, Y)",matchButtonLabel:"Match",addressTitle:"Suggested Address",noAddress:"No Address Found."},matchedLC:"matched"},mosaicRule:{queryOperatorLabel:"Operator:",averageAlias:"Average of pixel values",
refreshLockRasterIdsLabel:"Refresh",selectAllLabel:"Select All",lockRasterRequestErrorMsg:"Error searching...",maxAlias:"Maximum of pixel values",nadirAlias:"Sensor location closest to view center",mosaicruleNotApplicable:"The image layer contains only one image and does not support changing image display order.",descendingLabel:"Reverse the order",byAttributeAlias:"An attribute",northWestAlias:"Fixed order with most North West on top",lockRasterRequestDoneMsg:"Done...",lockRasterRequestNoRasterMsg:"No rasters found...",
mosaicOperatorLabel:"Resolve overlapping pixels by:",centerAlias:"Image center closest to view center",mosaicMethodLabel:"Prioritize imagery based on:",seamlineAlias:"Defined Seamlines",viewPointAlias:"View point",minAlias:"Minimum of pixel values",lockRasterIdLabel:"Image IDs:",blendAlias:"Blend pixel values",noneAlias:"Only scale",orderValueLabel:"Highest priority value:",queryFieldLabel:"Field:",firstAlias:"Only highest priority",orderFieldNotFound:"Not Available",lockRasterRequestMsg:"Searching...",
lockRasterAlias:"A list of images",queryLabel:"Filter your images:",orderFieldLabel:"Attribute:",queryValueLabel:"Value:",lastAlias:"Only Lowest priority"},directions:{addDestination:"Add destination",printNotes:"Enter notes here",travelMode:{car:"By Car",truck:"By Truck",walking:"Walking"},useTraffic:"Use traffic",printDisclaimer:"Directions are provided for planning purposes only and are subject to \x3ca href\x3d'http://www.esri.com/legal/software-license' target\x3d'_blank'\x3eEsri's terms of use\x3c/a\x3e. Dynamic road conditions can exist that cause accuracy to differ from your directions and must be taken into account along with signs and legal restrictions. You assume all risk of use.",
error:{maximumStops:"The maximum number of stops has been reached",cantRemoveStop:"Failed to remove stop.",notEnoughStops:"Enter an origin and a destination.",invalidStopType:"Invalid stop type",locator:"Location could not be found.",noAddresses:"No addresses were returned.",unknownStop:"Location '\x3cname\x3e' could not be found.",noStops:"No stops were given to be added.",routeTask:"Unable to route to these addresses.",locatorUndefined:"Unable to reverse geocode. Locator URL is undefined.",cantFindRouteServiceDescription:"Route service description was not reached or recognized. Please check service URL and/or user credentials, if specified.",
maxWalkingDistance:"The distance between any inputs must be less than 50 miles (80 kilometers) when walking.",nonNAmTruckingMode:"Calculating trucking routes outside of North and Central America is not currently supported."},viewFullRoute:"Zoom to full route",units:{KILOMETERS:{name:"kilometers",abbr:"km"},MILES:{name:"miles",abbr:"mi"},METERS:{name:"meters",abbr:"m"},NAUTICAL_MILES:{name:"nautical miles",abbr:"nm"}},impedance:{shortest:"Shortest",fastest:"Fastest"},clearDirections:"Clear",unlocatedStop:"\x3cunknown location\x3e",
time:{minute:"minute",minutes:"minutes",hour:"hour",hours:"hours"},findOptimalOrder:"Optimize order",getDirections:"Get Directions",hideOptions:"Hide options",reverseDirections:"Reverse directions",print:"Print",showOptions:"Show more options",returnToStart:"Return to start"},Geocoder:{main:{geocoderMenuButtonTitle:"Change Geocoder",untitledGeocoder:"Untitled geocoder",clearButtonTitle:"Clear Search",searchButtonTitle:"Search",geocoderMenuCloseTitle:"Close Menu",geocoderMenuHeader:"Search in"},esriGeocoderName:"Esri World Geocoder"},
homeButton:{home:{button:"Home",title:"Default extent"}},bookmarks:{NLS_add_bookmark:"Add Bookmark",NLS_new_bookmark:"Untitled",NLS_bookmark_edit:"Edit",NLS_bookmark_remove:"Remove"},editor:{tools:{NLS_pointLbl:"Point",NLS_reshapeLbl:"Reshape",NLS_arrowLeftLbl:"Left Arrow",NLS_triangleLbl:"Triangle",NLS_autoCompleteLbl:"Auto Complete",NLS_arrowDownLbl:"Down Arrow",NLS_selectionRemoveLbl:"Subtract from selection",NLS_unionLbl:"Union",NLS_freehandPolylineLbl:"Freehand Polyline",NLS_rectangleLbl:"Rectangle",
NLS_ellipseLbl:"Ellipse",NLS_attributesLbl:"Attributes",NLS_arrowUpLbl:"Up Arrow",NLS_arrowRightLbl:"Right Arrow",NLS_undoLbl:"Undo",NLS_arrowLbl:"Arrow",NLS_cutLbl:"Cut",NLS_polylineLbl:"Polyline",NLS_selectionClearLbl:"Clear selection",NLS_polygonLbl:"Polygon",NLS_selectionUnionLbl:"Union",NLS_freehandPolygonLbl:"Freehand Polygon",NLS_deleteLbl:"Delete",NLS_extentLbl:"Extent",NLS_selectionNewLbl:"New selection",NLS_circleLbl:"Circle",NLS_redoLbl:"Redo",NLS_selectionAddLbl:"Add to selection"}},attachmentEditor:{NLS_error:"There was an error.",
NLS_attachments:"Attachments:",NLS_none:"None",NLS_add:"Add",NLS_fileNotSupported:"This file type is not supported."},print:{NLS_printing:"Printing",NLS_printout:"Printout",NLS_print:"Print"},legend:{NLS_currentObservations:"Current observations",NLS_polygons:"Polygons",NLS_lines:"Lines",NLS_noLegend:"No legend",NLS_dotValue:"1 Dot \x3d ${value} ${unit}",NLS_previousObservations:"Previous observations",NLS_points:"Points",NLS_creatingLegend:"Creating legend"},overviewMap:{NLS_invalidSR:"spatial reference of the given layer is not compatible with the main map",
NLS_invalidType:"unsupported layer type. Valid types are 'TiledMapServiceLayer' and 'DynamicMapServiceLayer'",NLS_noMap:"'map' not found in input parameters",NLS_hide:"Hide Map Overview",NLS_drag:"Drag To Change The Map Extent",NLS_maximize:"Maximize",NLS_noLayer:"main map does not have a base layer",NLS_restore:"Restore",NLS_show:"Show Map Overview"},popup:{NLS_attach:"Attachments",NLS_nextFeature:"Next feature",NLS_moreInfo:"More info",NLS_searching:"Searching",NLS_maximize:"Maximize",NLS_noAttach:"No attachments found",
NLS_noInfo:"No information available",NLS_pagingInfo:"(${index} of ${total})",NLS_restore:"Restore",NLS_prevFeature:"Previous feature",NLS_nextMedia:"Next media",NLS_close:"Close",NLS_zoomTo:"Zoom to",NLS_prevMedia:"Previous media"},textSymbolEditor:{symbolConfiguration:"Symbol Configuration",alignment:"Alignment",color:"Color"},geocodeReview:{columnLabelAddress:"Address",unmatchedTotal:"Unmatched (${count} Total)",matchedUC:"Matched",idProperty:"id",reviewedUC:"Reviewed",of:"of",review:{columnOriginalLocation:"Original Location",
noDataMsg1:"No Unmatched Features",noDataMsg2:"No Matched Features",columnSelectedLocation:"Selected Location",noDataMsg3:"No Reviewed Features",columnOriginalAddress:"Original Address",columnSelectedAddress:"Selected Address"},matchedTotal:"Matched (${count} Total)",unmatchedRemaining:"Unmatched (${count1} of ${count2} Remaining)",unmatchedLC:"unmatched",totalUC:"Total",unmatchedUC:"Unmatched",customLabel:"Custom",reviewedTotal:"Reviewed (${count} Total)",remainingUC:"Remaining",matchedLC:"matched"}},
findExistingLocations:{outputLayerName:"Find Locations in ${analysisLayerName}",itemTags:"Analysis Result, Find Existing Locations, ${analysisLayerName}",itemSnippet:"Analysis Feature Service generated from Find Existing Locations",findExpLabel:"Find the \x3cb\x3e${analysisLayerName}\x3c/b\x3e features that match the following expression(s)",itemDescription:"Feature Service generated from running the Find Existing Locations solutions for ${analysisLayerName}."},tasks:{gp:{gpDataTypeNotHandled:"GP Data type not handled."},
query:{invalid:"Unable to perform query. Please check your parameters."},na:{route:{routeNameNotSpecified:"'RouteName' not specified for at least 1 stop in stops FeatureSet."}}},bufferTool:{sizeHelp:"To create multiple buffers, enter distances separated by spaces (2 3 5).",typeLabel:"Buffer type",disks:"Disks",round:"Round",right:"Right",distanceMsg:"Only numeric values are allowed",itemDescription:"Feature Service generated from running the Buffer Features solution. Input from ${layername} were buffered by ${distance_field} ${units}",
resultLabel:"Result layer name",around:"Around",sideType:"Side type",flat:"Flat",multipleDistance:"Multiple distance buffers should be",outputLayerName:"Buffer of ${layername}",rings:"Rings",sizeLabel:"Enter buffer size",itemTags:"Analysis Result, Buffer, ${layername}",areaofInputPoly:"Area of input polygons in buffer polygons",left:"Left",bufferDefine:"Create buffers from \x3cb\x3e${layername}\x3c/b\x3e",distance:"Distance",itemSnippet:"Analysis Feature Service generated from Buffer",endType:"End type",
field:"Field",optionsLabel:"Options",include:"Include",exclude:"Exclude",dissolve:"Dissolve",overlap:"Overlap"},io:{proxyNotSet:"esri.config.defaults.io.proxyUrl is not set. If making a request to a CORS enabled server, please push the domain into esri.config.defaults.io.corsEnabledServers."},interpolatePointsTool:{outputPredictionErrors:"Output prediction errors",pointlayerName:"Drawn Prediction Points",classBreaksHelp:"Enter break values spearated by spaces: (10 20 30)",itemDescription:"Feature Service generated from running the Interpolate Points solution.",
choosePointLayer:"Choose point layer",speed:"Speed",equalInterval:"Equal Interval",classesCountLabel:"Number of classes",classBreakValues:"Class break values",geometricInterval:"Geometric Interval",classifyLabel:"Classify by",accuracy:"Accuracy",interpolationMethod:"Interpolation method",outputLayerName:"${layername} Prediction",interpolateWithin:"Clip output to",predictLocLabel:"Predict at these locations",toolDefine:"Interpolate values from \x3cb\x3e${layername}\x3c/b\x3e",itemTags:"Analysis Result, Interpolate Points, ${layername}, ${fieldname}",
itemSnippet:"Analysis Feature Service generated from Interpolate Points",optimizeFor:"Optimize for",quantile:"Equal Area",defaultBoundingOption:"Choose study area",manual:"Manual",selectAttributesLabel:"Choose field to interpolate"},map:{deprecateShiftDblClickZoom:"Map.(enable/disable)ShiftDoubleClickZoom deprecated. Shift-Double-Click zoom behavior will not be supported.",deprecateReorderLayerString:"Map.reorderLayer(/*String*/ id, /*Number*/ index) deprecated. Use Map.reorderLayer(/*Layer*/ layer, /*Number*/ index)."},
extractDataTool:{kml:"KML (.kmz or .zip)",filegdb:"File Geodatabase (.zip)",itemDescription:"File generated from running the Extract Data solution.",layersToExtract:"Layers to extract",outputDataFormat:"Output data format",linesCSVValidationMsg:"Line and area layers cannot be extracted to CSV. Choose a different format or uncheck all line and area layers.",outputfileName:"Extract Data ${datetime}",clipFtrs:"Clip features",sameAsDisplay:"Same as Display",itemTags:"Analysis Result, Extract Data",sameAsLayer:"Same as ${layername}",
csvPoints:"CSV (.csv or .zip) ",itemSnippet:"Analysis File item generated from Extract Data",selectFtrs:"Select features",runAnalysisMsg:"Data is being extracted and will be available in My Content.",studyArea:"Study area",shpFile:"Shapefile (.zip)",lyrpkg:"Layer Package (.lpk)"},analysisTools:{aggregateTool:"Aggregate Points",createDensitySurface:"Create density surface",createBuffers:"Create Buffers",saveResultIn:"Save result in",extractData:"Extract Data",dataEnrichment:"Data Enrichment",dissolveBoundaries:"Dissolve Boundaries",
analyzePatterns:"Analyze Patterns",mergeLayers:"Merge Layers",summarizeWithin:"Summarize Within",deriveNewLocations:"Derive New Locations",pubRoleMsg:"Your online account has not been assigned to the Publisher role.",findLocations:"Find Locations",findExistingLocations:"Find Existing Locations",bufferTool:"Buffer Data",emptyResultInfoMsg:"The result of your analysis did not return any features. No layer will be created.",invalidServiceName:'The result layer name contains one or more invalid characters (\x3c, \x3e, #, %, :, ", ?, \x26, +, /, or \\).',
summarizeData:"Summarize Data",enrichLayer:"Enrich Layer",connectOriginsToDestinations:"Connect Origins to Destinations",planRoutes:"Plan Routes",useMapExtent:"Use current map extent",aggregatePoints:"Aggregate Points",generateFleetPlan:"Generate Fleet-routing plan",servNameExists:"A result layer already exists with this name. Result layers must be named uniquely across the organization. Please use a different name.",calculateDensity:"Calculate Density",findHotSpots:"Find Hot Spots",fieldCalculator:"Field Calculator",
performAnalysis:"Perform Analysis",summarizeNearby:"Summarize Nearby",findSimilarLocations:"Find Similar Locations",overlayLayers:"Overlay Layers",outputLayerLabel:"Result layer name",bufferToolName:"Create Buffers",findRoute:"Find Route",exploreCorrelations:"Explore Correlations",findNearest:"Find Nearest",useProximity:"Use Proximity",manageData:"Manage Data",createDriveTimeAreas:"Create Drive-Time Areas",orgUsrMsg:"You must be a member of an organization to run this service.",interpolatePoints:"Interpolate Points",
aggregateToolName:"Aggregate Points",outputFileName:"Output file name",invalidServiceNameLength:"The result layer name length should be less than 98 characters.",requiredValue:"This value is required."},common:{creditTitle:"Credit Usage Report",inches:"Inch(es)",input:"Input",share:"Share",apply:"Apply",cancel:"Cancel",minimum:"Minimum",chooseSummarizeLabel:"Choose layer to summarize",lines:"Lines",noLabel:"No",sqMiles:"Square Miles",ungroupLabel:"Ungroup",basic:"Basic",deleteLabel:"Delete",runAnalysis:"Run Analysis",
thursday:"Thursday",validateRouteIdMsg:"Layers must have the same number of records, or one layer must have one record only.",edit:"Edit",nautMiles:"Nautical Miles",sum:"Sum",standardDev:"Std Deviation",miles:"Miles",maximum:"Maximum",saturday:"Saturday",sixLabel:"6.",statistic:"Statistic",average:"Average",statsRequiredMsg:"At least one of the statistics parameters is required.",degree:"Decimal Degree(s)",done:"Done",outputLabel:"Output:",acres:"Acres",meters:"Meters",selectAll:"Select All",sqKm:"Square Kilometers",
wednesday:"Wednesday",fiveLabel:"5.",showCredits:"Show credits",minutesSmall:"min",movePoint:"Click to move the point",friday:"Friday",fourLabel:"4.",next:"Next",minutes:"Minutes",straightLineDistance:"Line distance",addPercentageLabel:"Add percentages",warning:"Warning",minority:"Minority",and:"and",selectAttribute:"Select attribute",yesLabel:"Yes",sevenLabel:"7.",hours:"Hours",today:"Today",feet:"Feet",close:"Close",groupLabel:"Group",queryLabel:"Query",monday:"Monday",remove:"Remove",twoLabel:"2.",
help:"Help",ok:"OK",open:"Open",points:"Points",advanced:"Advanced",submit:"Submit",or:"or",attribute:"Field",drawnBoundary:"Drawn Boundary",arcgis:"ArcGIS",majority:"Majority",titleLabel:"Title:",yards:"Yards",hoursSmall:"hr",sqFeet:"Square Feet",nowLabel:"Now",comingSoonLabel:"Coming Soon!",save:"Save",errorTitle:"Error",hrsLabel:"hrs",sunday:"Sunday",intermediate:"Intermediate",seconds:"Seconds",polygons:"Polygons",upload:"Upload",threeLabel:"3.",sqMeters:"Square Meters",secondsSmall:"sec",add:"Add",
addMinMajorityLable:"Add minority, majority",create:"Create",outputnameMissingMsg:"Output name is required",areas:"Areas",pointsUnit:"Point(s)",oneLabel:"1.",kilometers:"Kilometers",selectLabel:"Select",previous:"Previous",unselectAll:"Unselect All",addPoint:"Click to add a point",newLabel:"New",hectares:"Hectares",analysisLayers:"Analysis layers:",learnMore:"Learn More",tuesday:"Tuesday"},aggregatePointsTool:{removeAttrStats:"Remove Attribute Statistics",itemTags:"Analysis Result, Aggregate Points, ${pointlayername}, ${polygonlayername}",
groupByLabel:"Choose field to group by (optional)",itemSnippet:"Analysis Feature Service generated from Aggregate Points",chooseAreaLabel:"Choose area",aggregateDefine:"Count \x3cb\x3e${layername}\x3c/b\x3e within",itemDescription:"Feature Service generated from running the Aggregate Points solutions. Points from ${pointlayername} were aggregated to ${polygonlayername}",keepPolygonLabel:"Keep areas with no points",outputLayerName:"Aggregation of ${pointlayername} to ${polygonlayername}",addStatsLabel:"Add statistic (optional)"},
planRoutesTool:{startEndPtsValidMsg:"Start or end points not set",vehicles:"Vehicles",itemDescription:"Feature Service generated from running the Plan Routes solution.",routeId:"Route ID field",limitMaxTime:"Limit the total route time per vehicle",startRoutesLabel:"Routes begin at",maxPtsRoute:"Maximum number of stops per vehicle",timeSpentLabel:"Time spent at each stop",selectStartLoc:"Select starting location",createEndLoc:"Add point to map",outputLayerName:"Routes to ${layername}",specifyStartTime:"Start time for all routes",
toolDefine:"Route vehicles to stops in \x3cb\x3e${layername}\x3c/b\x3e",defineRoutesLabel:"Define routes",itemTags:"Analysis Result, Plan Routes, ${layername}",stops:"Stops",stopsLabel:"Your layer has ${numStops} stops.",selectRouteId:"Select RouteID",endRoutesLabel:"Routes end at",numRoutes:"Maximum number of vehicles to route",stopsLabelByExtent:"The current map extent shows ${numStops} stops.",createStartLoc:"Add point to map",selectEndLoc:"Select ending location",itemSnippet:"Analysis Feature Service generated from Plan Routes",
returnToStart:"Return to start",routes:"Routes"},creditEstimator:{ntwCreditsReqLabel:"Network credits required:",analysisLayersLabel:"Analysis layers:",totalRecordsLabel:"Total records:",EnrichCreditsLabel:"Enrichment credits required",creditsAvailLabel:"Credits available:",creditsReqLabel:"Credits required:"},findSimilarLocations:{itemDescription:"Feature Service generated from running the Find Similar Locations solutions for ${analysisLayerName}.",labelTwoText:"Search for similar locations in",
labelOneText:"You may use all locations or make a selection",labelFourText:"Show me:",allResults:"all locations from most to least similar",useAllFtrs:"Use all features",reqSelectionMsg:"You must select the feature(s) to match by making an interactive selection or by constructing a query.",outputLayerName:"Most Similar ${analysisLayerName}",justShowTop:"the top",selectSearchLayer:"Select the search layer",noFieldMatchMsg:"Search layer and input layer do not have any fields in common.",toolDefine:"Find locations that are similar to: \x3cb\x3e${layername}\x3c/b\x3e",
itemTags:"Analysis Result, Find Similar Locations, ${analysisLayerName}",labelThreeText:"Base similarity on",query:"Query",selectedFeaturesLabel:"${total} feature(s) selected",itemSnippet:"Analysis Feature Service generated from Find Similar Locations",selectTargetFtrs:"Select one or more target features"},geometry:{deprecateToMapPoint:"esri.geometry.toMapPoint deprecated. Use esri.geometry.toMapGeometry.",deprecateToScreenPoint:"esri.geometry.toScreenPoint deprecated. Use esri.geometry.toScreenGeometry."},
driveTimes:{seeAvailability:"See availability.",truckingTime:"Trucking Time",liveTimeHoursLabel:"Live traffic +${hour} hr",liveSingularTimeLabel:"Live traffic +1 hr ${minute} min",itemDescription:"Feature Service generated from running the Create Drive Times solution.",drivingDistance:"Driving Distance",resultLabel:"Result layer name",trucking:"Truck",driving:"Drive",split:"Split",walkingDistance:"Walking Distance",walking:"Walk",measureHelp:"To output multiple areas for each point, type sizes separated by spaces (2 3.5 5).",
liveTimeMinutesLabel:"Live traffic +${minute} min",outputLayerName:"Drive from ${layername} (${breakValues} ${breakUnits})",outputModeLayerName:"${mode} from ${layername} (${breakValues} ${breakUnits})",liveTimeLabel:"Live traffic +${hour} hr ${minute} min",toolDefine:"Create areas around \x3cb\x3e${layername}\x3c/b\x3e",trafficLabel:"Use traffic",liveTrafficLabel:"Live traffic",itemTags:"Analysis Result, Drive Times, ${layername}",truckingDistance:"Trucking Distance",measureLabel:"Measure",typicalTraffCdtnLabel:"Traffic based on typical conditions for",
itemSnippet:"Analysis Feature Service generated from Create Drive Times",drivingTime:"Driving Time",liveSingularHourTimeLabel:"Live traffic +1 hr",timeOfDeparture:"Time of departure",walkingTime:"Walking Time",areaLabel:"Areas from different points"},routeOriginDestinationPairsTool:{includeSegments:"Include individual road segments.",originTripId:"Route ID field in origins",toolDefine:"Route between pairs of points originating from \x3cb\x3e${layername}\x3c/b\x3e",destnTripId:"Route ID field in destinations",
pairPoints:"Pair points into routes by matching IDs",inValidNumberRecordsMsg:"Layers must have the same number of records, or one layer must have one record only.",labelOne:"Route to destinations in"},_localized:{},arcgis:{utils:{geometryServiceError:"Provide a geometry service to open Web Map.",showing:"Showing ${fieldAlias}",baseLayerError:"Unable to load the base map layer"}},analysisMsgCodes:{SS_84485:"There were ${NumFeatures} valid input features.",SS_84489:"Analysis was performed on all aggregation areas.",
AO_728:"The analysisField ${fieldName} you specified does not exist in the analysisLayer.",SS_84490:"The aggregation process resulted in ${AggNumFeatures} weighted areas.",SS_84491:"There were ${NumFeatures} valid input aggregation areas.",SS_84492:"The total study area was ${Area}.",SS_84493:"There was 1 outlier location; it was not used to compute ${AggregationType}.",SS_84261_0:"Mean",AO_539:"Expression is invalid.",AO_100001:"Aggregate Points failed.",AO_100002:"The geometry type of Point Layer must be points.",
AO_100003:"The geometry type of Polygon Layer must be polygons.",AO_735:"Please provide at least one valid analysis field to base similarity on.",AO_100004:"The field ${fieldName} provided for Summary Fields does not exist.",AO_100005:"The field ${fieldName} provided for Summary Fields is not numeric.",AO_100006:"The summary type ${summary} provided for field ${fieldName} is invalid.",AO_100007:"Find Hot Spots failed.",AO_100008:"The geometry type for the boundingPolygonLayer must be polygon.",
AO_100009:"The geometry type of Analysis Layer must be points or polygons.",GPEXT_001:"Invalid parameter ${name} value",GPEXT_002:"Parameter missing ${name}",GPEXT_003:"Invalid parameter ${name}:property ${propname} is missing",GPEXT_004:"Invalid layer parameter property ${propname} is missing",GPEXT_005:"Failed to access url ${url}",GPEXT_006:"Accessing url ${url} returned error ${error}",GPEXT_007:"Invalid item ${id}",GPEXT_008:"Failed to create service ${name}",GPEXT_009:"Failed to add layer ${lname} to service ${name}",
AO_100010:"The geometry type of Aggregation Polygon Layer must be polygon.",AO_100011:"Must provide an Analysis Field for polygon Analysis Layer.",AO_100012:"Create Buffers failed.",AO_100013:"Overlay Layers failed.",AO_100014:"Summarize Within failed.",AO_100015:"The geometry type of Summarize Layer input must be point, line, or polygons.",AO_100016:"The geometry type of Summarize Layer input must be point or line.",AO_100017:"The geometry type of Summarize Layer input must be point.",AO_100018:"Sum Units ${sumUnits} is not applicable for ${shapeType} shape type.",
AO_100019:"At least one of the parameters, Summarize Shape or Summary Fields is required.",GPEXT_010:"Failed to parse layer JSON",GPEXT_011:"Layer ${url} does not have Extract capability",GPEXT_012:"Invalid External Operation",GPEXT_013:"This tool uses the Geoenrichment Service. Please refer to ArcGIS Online Service Credit Estimator for more details.",AO_1115:"Layer description property must be set for ${layerName}.",GPEXT_014:"This tool uses Network Analysis Services. Please refer to ArcGIS Online Service Credit Estimator for more details.",
GPEXT_015:"Select appropriate helper services url from Portal for requested operation.",GPEXT_016:"Invalid layer object.",GPEXT_017:"Service ${name} already exists.",AO_100020:"Enrich Layer failed.",AO_100021:"The geometry type of Input Layer must be point, line or polygon.",AO_100022:"Units ${units} is not supported for Buffer type ${bufferType}.",AO_100023:"Unable to enrich layer for input spatial reference ${spref}.",AO_100024:"The number of features in ${inputLayer} is zero.",AO_100025:"Summarize Nearby failed.",
AO_100026:"Extract Data failed.",AO_100027:"Dissolve Boundaries failed.",AO_100028:"Create Drive Time Areas failed.",AO_100029:"Merge Layers failed.",AO_366:"Invalid geometry type.",AO_100030:"Find Nearest failed.",AO_100031:"The number of nearest locations to find can not be greater than 100.",AO_100032:"The number of features in ${analysisLayer} is zero.",AO_100033:"The number of features in ${nearLayer} is zero.",AO_100034:"The number of features in ${analysisLayer} can not be greater than 1000.",
AO_100035:"The number of features in ${nearLayer} can not be greater than 1000.",AO_100036:"The ${analysisLayer} layer must have a point geometry type when using DrivingTime or DrivingDistance as the measurement type.",AO_100037:"The ${nearLayer} layer must have a point geometry type when using DrivingTime or DrivingDistance as the measurement type.",AO_800:"The value is not a member of SUM | MEAN | MIN | MAX | RANGE | STD | COUNT | FIRST | LAST.",AO_100038:"The search cutoff cannot be less than zero.",
AO_100039:"The ${inputLayer} must have a point geometry type.",SS_84272_0:"Max",AO_100040:"The number of features in ${inputLayer} can not be greater than ${max}.",AO_100041:"Buffer type parameter is supported only for layers containing points or lines.",AO_1533:"We were not able to compute hot and cold spots for the data provided.\u00a0 If appropriate, try specifying an Analysis Field.",AO_100042:"The geometry type ${shapeType} of Nearby Layer is not supported for Near type ${nearType}",AO_1534:"Hot and cold spots cannot be computed when the number of points in every polygon area is identical. Try different polygon areas or different analysis options.",
AO_100043:"Units ${units} is not supported for Near type ${nearType}.",AO_1535:"The analysis option you selected requires a minimum of ${minNumFeatures} aggregation areas.",AO_100044:"Distance value should be greater than 0",AO_1536:"The analysis options you selected require a minimum of ${minNumIncidents} points to compute hot and cold spots.",AO_100045:"Distance and units are required when Buffer type is specified",AO_100046:"Failed to access GeoEnrichment server.",AO_100047:"Enrichment may not be available for some features.",
AO_100048:"The input layer ${inputLayer} contains multipoint geometry and has been converted to single point geometry.",AO_100049:"No features in the processing extent for any input layers.",AO_385:"The LINE option is not valid with point features.",AO_100050:"No fields exist in the input layer for data extraction.",AO_100051:"No features in the processing extent for any input layers and none of the input layers have fields for data extraction. ",AO_100052:"The field name ${fieldName} does not exist in the ${paramName}.",
AO_100053:"Required keys ${missingKeys} are missing in attribute expression ${expression}.",AO_100054:"Required keys ${missingKeys} are missing in spatial relationship expression ${expression}.",AO_100055:"Invalid expression; malformed JSON.",SS_84428:"Initial Data Assessment.",AO_100056:"Invalid layer index in expression ${expression}.",AO_100057:"Layer index exceeds the number of input layers in expression ${expression}.",AO_100058:"${spatialRel} spatial relationship does not support ${lyrGeomType}/${selLyrGeomType} geometry types for layer/selectingLayer in expression ${expression}.",
AO_100059:"Invalid spatial relationship {spatialRel} in expression ${expression}.",AO_1156:"A field value was incompatible with the field type.",AO_100060:"Query expression failed in expression ${expression}.",AO_100061:"FindExistingLocations failed.",SS_84434:"There were ${NumOutliers} outlier locations; these were not used to compute ${AggregationType}.",AO_438:"Overlay not polygon.",AO_100062:"Invalid distance and/or units in expression ${expression}",AO_100063:"PlanRoutes failed.",AO_100064:"The number of features in ${stopsLayer} is zero.",
SS_84437:"There were no locational outliers.",AO_100065:"The number of features in ${startLayer} is zero.",AO_100066:"The maximum number of vehicles to route cannot be less than zero and greater than ${max}.",SS_84262_0:"Std. Dev.",AO_100067:"The maximum number of stops per vehicle cannot be less than zero and greater than ${max}.",AO_100068:"The number of features in ${stopsLayer} cannot be greater than ${max}.",AO_100069:"The number of features in ${startLayer} cannot be greater than ${max}.",AO_100100:"The features in ${inputLayer} are not within the data coverage area. See availability at ${url}.",
AO_100101:"No features in ${inputLayer} are within a distance of ${max} kilometers from streets.",AO_100102:"All features in ${inputLayer} must be in the same time zone when using traffic and creating areas with dissolve or split options.",AO_100103:"The ${measureType} value cannot be greater than ${max} ${breakUnits}.",AO_100104:"InterpolatePoints failed.",AO_100105:"CalculateDensity failed",AO_100106:"Field ${fieldName} is not numeric.",AO_12:"Field to add already exists.",AO_100107:"Field ${fieldName} does not have any positive values.",
AO_100108:"Field ${fieldName} has negative values, only positive values will be considered for calculating density.",AO_100109:"The geometry type for the input layer must be points or lines.",AO_40039:"Not enough data to compute method.",AO_100070:"The number of features in ${endLayer} cannot be greater than ${max}.",AO_100071:"The ${stopsLayer} layer must have a point geometry type.",SS_84444:"Incident Aggregation",AO_641:"This tool requires at least ${numFeatures} feature(s) to compute results.",
AO_100072:"The ${startLayer} layer must have a point geometry.",AO_100073:"The ${endLayer} layer must have a point geometry.",SS_84446:"${VarName} Properties:",AO_100074:"The time spent at each stop cannot be less than zero.",AO_100075:"The total route time per vehicle should be greater than zero and less than one year (525600 minutes).",AO_100076:"The ${endLayer} should not be specified if return to start is true.",SS_84449:"A fishnet polygon mesh was created for aggregating points.",AO_100077:"Find Similar Locations failed.",
AO_100078:"Invalid field name in expression ${expression}",AO_100079:"Derive New Locations failed.",AO_100110:"Your user role doesn\u2019t include the geoEnrichment privilege",AO_100111:"Your user role doesn\u2019t include the network analysis privilege",AO_100112:"Your user role doesn't include the publish hosted features privilege",AO_100113:"None of the stops were assigned to any routes. Check the Status and Violated Constraints fields in the output unassigned stops layer for more information.",
AO_100114:"The time spent at each stop, ${stopServiceTime} minutes, must be less than the total route time per vehicle, ${maxRouteTime} minutes.",AO_100115:"Some stops were not assigned to any routes. Check the Violated Constraints field in the output unassigned stops layer for more information.",AO_100116:"Only ${routesUsed} out of ${routeCount} routes are needed to reach all stops. If you want to use more routes, run Plan Routes again but reduce the limits on the maximum number of stops or the total route time per vehicle.",
AO_100117:"Driving a truck is currently not supported outside of North America and Central America.",AO_40040:"Data is distributed along a straight line and cannot be processed.",AO_100118:"Your user role doesn't include the create, update and delete content privilege.",AO_26:"Buffer distance is zero.",SS_84450:"The polygon cell size was ${SnapInfo}.",AO_1570:"The analysis option you selected requires a minimum of ${minNumIncidents} points to be inside the bounding polygon area(s).",SS_84451:"Analysis was based on the number of points in each fishnet polygon cell.",
AO_1571:"The analysis options you selected require a minimum of ${minNumFeatures} features with valid data in the analysis field in order to compute hot and cold spots.\t",SS_84452:"Analysis was performed on all fishnet polygon cells containing at least one point.",AO_1572:"There is not enough variation in point locations to compute hot and cold spots.\u00a0 Coincident points, for example, reduce spatial variation.\u00a0 You can try providing a bounding area, aggregation areas (a minimum of 30), or an Analysis Field.",
AO_100080:"Connect Origins To Destinations failed.",SS_84453:"Analysis was performed on all fishnet polygon cells within the bounding area layer.",AO_1573:"There is not enough variation among the points within the bounding polygon area(s).\u00a0 You can try providing larger boundaries.",AO_100081:"Field Calculator failed.",AO_1574:"The analysis option you selected requires a minimum of ${minNumIncidents} points to be inside the aggregation polygons.",AO_100082:"A field name and an expression are required.",
AO_1575:"All of the values for your analysis field are likely the same.\u00a0 Hot and cold spots cannot be computed when there is no variation in the field being analyzed.",AO_100083:"A field type is required for creating a new field.",AO_100084:"Field type is required to be String, Integer, Double or Date.",SS_84457:"Points were aggregated to the fishnet polygon cells falling within the bounding areas provided.",SS_84458:"Analysis was based on the number of points in each polygon cell.",SS_84459:"Scale of Analysis",
AO_100088:"Field(s) ${attribute} must be in both the reference and candidate search layers.",AO_100089:"The following fields lack sufficient variation for use in this analysis: ${attribute}.",AO_109:"The buffer distance cannot be negative for lines and points.",SS_84461:"The optimal fixed distance band selected was based on peak clustering found at ${DistanceInfo}.",AO_100090:"This tool requires at least 2 candidate search locations that are not also reference locations.",AO_100091:"The geometry type of ${paramName} must be Points",
AO_468:"Input shape types are not equal.",SS_84464:"The optimal fixed distance band was based on the average distance to ${NumNeighs} nearest neighbors: ${DistanceInfo}.",AO_100092:"The geometry type of boundingPolygonLayer must be Polygons",SS_84465:"The optimal fixed distance band was based on one standard distance of the features from the geometric mean: ${DistanceInfo}.",AO_100093:"The classification type Manual requires classbreaks value.",SS_84466:"Hot Spot Analysis",AO_100094:"The maximum number of vehicles to route must be equal to the number of features in ${startLayer}.",
AO_100095:"The number of features in ${endLayer} must be equal to the number of features in ${startLayer}.",AO_100096:"The ${startLayerRouteIDField} in ${startLayer} does not have unique values.",AO_1589:"This tool requires a minimum of 2 locations to search.",AO_100097:"The ${endLayerRouteIDField} in ${endLayer} does not have unique values.",AO_100098:"The values in ${startLayerRouteIDField} in ${startLayer} does not have a one-to-one match with the values in ${endLayerRouteIDField} in ${endLayer}.",
AO_100099:"All break values must be greater than zero.",AO_84426:"Must provide polygons for aggregating incidents into counts for this incident data aggregation method.",SS_84271_0:"Min",AO_906:"Zero variance: all of the values for your input field are likely the same.",AO_40069:"The variance of the data is too small to be calculated.",SS_84470:"${NumSignificant} output features are statistically significant based on a FDR correction for multiple testing and spatial dependence.",SS_84471:"Output",
SS_00002:"The following report outlines the workflow used to optimize your Find Hot Spots result:",SS_84476:"Red output features represent hot spots where high ${FieldName} cluster.",SS_84477:"Blue output features represent cold spots where low ${FieldName} cluster.",AO_1599:"Too few records for analysis. This tool requires at least 1 reference location in the Input Layer to compute results."},calculateDensityTool:{outputAerealUnits:"Output area units",chooseCountField:"No count field",toolDefine:"Calculate density values from \x3cb\x3e${layername}\x3c/b\x3e",
itemTags:"Analysis Result, Calculate Density, ${layername}, ${fieldname}",itemSnippet:"Analysis Feature Service generated from Calculate Density",itemDescription:"Feature Service generated from running the Calculate Density solution.",naturalBreaks:"Natural Breaks",selectAttributesLabel:"Use a count field (optional)",standardDeviation:"Standard Deviation",searchDistance:"Search Distance",outputLayerName:"${layername} Density"},overlayLayersTool:{itemTags:"Analysis Result, Overlay layers, ${layername}",
unionOutputLyrName:"Union of ${layername} and ${overlayname}",itemSnippet:"Analysis Feature Service generated from Overlay layers",eraseOutputLyrName:"Erase ${layername} with ${overlayname}",chooseOverlayMethod:"Choose overlay method",itemDescription:"Feature Service generated from running the Overlay layers solution.",union:"Union",overlayDefine:"Overlay \x3cb\x3e${layername}\x3c/b\x3e with",intersectOutputLyrName:"Intersect of ${layername} and ${overlayname}",overlayLayerPolyMsg:"The Overlay layer should be a Polygon Layer for Union overlay",
chooseOutputType:"Choose output type",notSupportedEraseOverlayMsg:"This Overlay layer is not supported for Erase overlay. Defaults to Intersect overlay.",intersect:"Intersect",erase:"Erase",chooseOverlayLayer:"Choose overlay layer"},summarizeNearbyTool:{removeAttrStats:"Remove Attribute Statistics",itemTags:"Analysis Result, Summarize Nearby, ${sumNearbyLayerName}, ${summaryLayerName}",sumLabel:"Summarize",groupByLabel:"Choose field to group by (optional)",itemSnippet:"Analysis Feature Service generated from Summarize Nearby",
addStats:"Add statistics from \x3cb\x3e${summaryLayerName}\x3c/b\x3e",summarizeMetricPoly:"Total Area",chooseLayer:"Choose layer to summarize",itemDescription:"Feature Service generated from running the Summarize Nearby solution. ${sumNearbyLayerName} were summarized nearby ${summaryLayerName}",summarizeMetricLine:"Total Length",summarizeDefine:"Find what is nearby \x3cb\x3e${sumNearbyLayerName}\x3c/b\x3e",findNearLabel:"Find nearest features using a",outputLayerName:"Summarize ${summaryLayerName} in ${sumNearbyLayerName}",
summarizeMetricPoint:"Count of points",addStatsLabel:"Attribute statistics"},calculateFields:{addFieldTitle:"Add Field",inValidFieldStartCharMsg:"The field name cannot start with one of these invalid characters \x3cbr/\x3e(`~@#$%^\x26*()-+\x3d|\\\x3c\x3e?/{}.!'[]:;\n\r_012356789).",operators:"Operators",deleteField:"Delete Field",typeLabel:"Type:",lyrUpdateCapMsg:"Either update capability is not enabled on the layer ${layername} or, you do not have access to update features on this layer",numeric:"Numeric",
close:"Close",helpers:"Helpers",clear:"Clear",lyrSupportCalMsg:"This layer ${layername} does not support calculate fields",fieldReqMsg:"A calculate field has not been provided",lengthLabel:"Length:",layerReqMsg:"A layer is required parameter for calculate field",expBuilderTitle:"Expression Builder",aliasLabel:"Alias:",deleteLabel:"Delete",defaultValueLabel:"Default Value:",addNewField:"Add New Field",deleteFieldConfirm:"Are you sure you want to delete '${field}' field from this layer?",integerLabel:"Integer",
nameLabel:"Name:",inValidFielNameCharMsg:"The field name contains one or more invalid characters \x3cbr/\x3e(`~@#$%^\x26*()-+\x3d|\\\x3c\x3e?/{.!'[]:\n\r).",validate:"Validate",functions:"Functions",exprFailedMsg:"Calculate for the expression '${expr}' failed.",calculate:"Calculate",invalidSqlkeywordsMsg:"The field name cannot be the same as an SQL keyword.",availableFields:"Available Fields",doubleLabel:"Double",firstOperatorMsg:"Operator '${operator}' cannot start an expression",dateLabel:"Date",
selectCalField:"Choose field to calculate:",optional:"(Optional)",exprLabel:"${fieldName} \x3d",stringLabel:"String",completeHelperMsg:"Complete the helper method added previously",add:"Add",successMsg:"Successfully updated ${count} features ",fields:"Fields"}},"dojo/cldr/nls/gregorian":{"dateTimeFormats-appendItem-Year":"{1} {0}","field-tue-relative+-1":"\u4e0a\u9031\u4e8c","field-year":"\u5e74","dayPeriods-format-wide-weeHours":"\u51cc\u6668","dateFormatItem-Hm":"HH:mm","field-wed-relative+0":"\u672c\u9031\u4e09",
"field-wed-relative+1":"\u4e0b\u9031\u4e09","dayPeriods-format-wide-night":"\u665a\u4e0a","dateFormatItem-ms":"mm:ss","timeFormat-short":"ah:mm","field-minute":"\u5206\u9418","dateTimeFormat-short":"{1} {0}","field-day-relative+0":"\u4eca\u5929","field-day-relative+1":"\u660e\u5929","field-day-relative+2":"\u5f8c\u5929","field-tue-relative+0":"\u672c\u9031\u4e8c","field-tue-relative+1":"\u4e0b\u9031\u4e8c","dayPeriods-format-narrow-am":"\u4e0a\u5348","dateFormatItem-MMMd":"M\u6708d\u65e5","dayPeriods-format-abbr-am":"AM",
"dayPeriods-format-narrow-earlyMorning":"\u6e05\u6668","field-week-relative+0":"\u672c\u9031","field-month-relative+0":"\u672c\u6708","field-week-relative+1":"\u4e0b\u9031","field-month-relative+1":"\u4e0b\u500b\u6708","timeFormat-medium":"ah:mm:ss","dateFormatItem-MMMMdd":"M\u6708dd\u65e5","field-second-relative+0":"\u73fe\u5728","dayPeriods-format-wide-afternoon":"\u4e0b\u5348","dateTimeFormats-appendItem-Second":"{0} ({2}: {1})","months-standAlone-narrow":"1 2 3 4 5 6 7 8 9 10 11 12".split(" "),
eraNames:["\u897f\u5143\u524d","\u516c\u5143\u524d","\u897f\u5143","\u516c\u5143"],"dateFormatItem-GyMMMEd":"G y \u5e74 M \u6708 d \u65e5E","field-day":"\u65e5","field-year-relative+-1":"\u53bb\u5e74","dayPeriods-format-wide-am":"\u4e0a\u5348","dayPeriods-format-narrow-midDay":"\u4e2d\u5348","field-wed-relative+-1":"\u4e0a\u9031\u4e09","dateTimeFormat-medium":"{1} {0}","field-second":"\u79d2","days-standAlone-narrow":"\u65e5\u4e00\u4e8c\u4e09\u56db\u4e94\u516d".split(""),"dateFormatItem-Ehms":"E a h:mm:ss",
"dateFormat-long":"y\u5e74M\u6708d\u65e5","dateFormatItem-GyMMMd":"G y \u5e74 M \u6708 d \u65e5","dateFormatItem-yMMMEd":"y\u5e74M\u6708d\u65e5E",$locale:"zh-hant-tw","quarters-standAlone-wide":["\u7b2c1\u5b63","\u7b2c2\u5b63","\u7b2c3\u5b63","\u7b2c4\u5b63"],"days-format-narrow":"\u65e5\u4e00\u4e8c\u4e09\u56db\u4e94\u516d".split(""),"dateTimeFormats-appendItem-Timezone":"{0} {1}","field-mon-relative+-1":"\u4e0a\u9031\u4e00","dateFormatItem-GyMMM":"G y \u5e74 M \u6708","field-month":"\u6708","dateFormatItem-MMM":"LLL",
"field-dayperiod":"\u4e0a\u5348/\u4e0b\u5348","dayPeriods-format-narrow-pm":"\u4e0b\u5348","dateFormat-medium":"y\u5e74M\u6708d\u65e5",eraAbbr:["\u897f\u5143\u524d","\u516c\u5143\u524d","\u897f\u5143","\u516c\u5143"],"quarters-standAlone-abbr":["\u7b2c1\u5b63","\u7b2c2\u5b63","\u7b2c3\u5b63","\u7b2c4\u5b63"],"dayPeriods-format-abbr-pm":"PM","field-mon-relative+0":"\u672c\u9031\u4e00","field-mon-relative+1":"\u4e0b\u9031\u4e00","months-format-narrow":"1 2 3 4 5 6 7 8 9 10 11 12".split(" "),"days-format-short":"\u5468\u65e5 \u5468\u4e00 \u5468\u4e8c \u5468\u4e09 \u5468\u56db \u5468\u4e94 \u5468\u516d".split(" "),
"quarters-format-narrow":["1","2","3","4"],"dayPeriods-format-wide-pm":"\u4e0b\u5348","field-sat-relative+-1":"\u4e0a\u9031\u516d","dateTimeFormats-appendItem-Hour":"{0} ({2}: {1})","dateTimeFormat-long":"{1} {0}","dateFormatItem-Md":"M/d","field-hour":"\u5c0f\u6642","dateFormatItem-yQQQQ":"y\u5e74QQQQ","months-format-wide":"1\u6708 2\u6708 3\u6708 4\u6708 5\u6708 6\u6708 7\u6708 8\u6708 9\u6708 10\u6708 11\u6708 12\u6708".split(" "),"dateFormat-full":"y\u5e74M\u6708d\u65e5EEEE","field-month-relative+-1":"\u4e0a\u500b\u6708",
"dayPeriods-format-wide-earlyMorning":"\u6e05\u6668","dateFormatItem-Hms":"HH:mm:ss","field-fri-relative+0":"\u672c\u9031\u4e94","field-fri-relative+1":"\u4e0b\u9031\u4e94","dayPeriods-format-narrow-noon":"\u4e2d\u5348","dayPeriods-format-narrow-morning":"\u4e0a\u5348","dayPeriods-format-wide-morning":"\u4e0a\u5348","dateTimeFormats-appendItem-Quarter":"{0} ({2}: {1})",_localized:{},"field-week-relative+-1":"\u4e0a\u9031","dateFormatItem-Ehm":"E a h:mm","months-format-abbr":"1\u6708 2\u6708 3\u6708 4\u6708 5\u6708 6\u6708 7\u6708 8\u6708 9\u6708 10\u6708 11\u6708 12\u6708".split(" "),
"timeFormat-long":"zah\u6642mm\u5206ss\u79d2","dateFormatItem-yMMM":"y\u5e74M\u6708","dateFormat-short":"y/M/d","days-standAlone-wide":"\u661f\u671f\u65e5 \u661f\u671f\u4e00 \u661f\u671f\u4e8c \u661f\u671f\u4e09 \u661f\u671f\u56db \u661f\u671f\u4e94 \u661f\u671f\u516d".split(" "),"dateTimeFormats-appendItem-Era":"{1} {0}","dateFormatItem-H":"H\u6642","dateFormatItem-M":"M\u6708","months-standAlone-wide":"1\u6708 2\u6708 3\u6708 4\u6708 5\u6708 6\u6708 7\u6708 8\u6708 9\u6708 10\u6708 11\u6708 12\u6708".split(" "),
"field-sun-relative+-1":"\u4e0a\u9031\u65e5","days-standAlone-abbr":"\u5468\u65e5 \u5468\u4e00 \u5468\u4e8c \u5468\u4e09 \u5468\u56db \u5468\u4e94 \u5468\u516d".split(" "),"dateTimeFormat-full":"{1}{0}","dateFormatItem-hm":"ah:mm","dayPeriods-format-wide-midDay":"\u4e2d\u5348","dateFormatItem-d":"d\u65e5","field-weekday":"\u9031\u5929","field-sat-relative+0":"\u672c\u9031\u516d","dateFormatItem-h":"ah\u6642","field-sat-relative+1":"\u4e0b\u9031\u516d","months-standAlone-abbr":"1\u6708 2\u6708 3\u6708 4\u6708 5\u6708 6\u6708 7\u6708 8\u6708 9\u6708 10\u6708 11\u6708 12\u6708".split(" "),
"dateFormatItem-yMM":"y-MM","timeFormat-full":"zzzzah\u6642mm\u5206ss\u79d2","dateFormatItem-MEd":"M/d\uff08E\uff09","dateFormatItem-y":"y\u5e74","field-thu-relative+0":"\u672c\u9031\u56db","field-thu-relative+1":"\u4e0b\u9031\u56db","dateFormatItem-hms":"ah:mm:ss","dateTimeFormats-appendItem-Day":"{0} ({2}: {1})","dayPeriods-format-abbr-noon":"noon","dateTimeFormats-appendItem-Week":"{0} ({2}: {1})","field-thu-relative+-1":"\u4e0a\u9031\u56db","dateFormatItem-yMd":"y/M/d","field-week":"\u9031","quarters-standAlone-narrow":["1",
"2","3","4"],"quarters-format-wide":["\u7b2c1\u5b63","\u7b2c2\u5b63","\u7b2c3\u5b63","\u7b2c4\u5b63"],"dayPeriods-format-narrow-weeHours":"\u51cc\u6668","dateFormatItem-Ed":"d\u65e5\uff08E\uff09","dayPeriods-format-narrow-afternoon":"\u4e0b\u5348","dateTimeFormats-appendItem-Day-Of-Week":"{0} {1}","days-standAlone-short":"\u5468\u65e5 \u5468\u4e00 \u5468\u4e8c \u5468\u4e09 \u5468\u56db \u5468\u4e94 \u5468\u516d".split(" "),"quarters-format-abbr":["\u7b2c1\u5b63","\u7b2c2\u5b63","\u7b2c3\u5b63","\u7b2c4\u5b63"],
"field-year-relative+0":"\u4eca\u5e74","field-year-relative+1":"\u660e\u5e74","field-fri-relative+-1":"\u4e0a\u9031\u4e94",eraNarrow:["\u897f\u5143\u524d","\u516c\u5143\u524d","\u897f\u5143","\u516c\u5143"],"dayPeriods-format-wide-noon":"\u4e2d\u5348","dateFormatItem-yQQQ":"y\u5e74QQQ","days-format-wide":"\u661f\u671f\u65e5 \u661f\u671f\u4e00 \u661f\u671f\u4e8c \u661f\u671f\u4e09 \u661f\u671f\u56db \u661f\u671f\u4e94 \u661f\u671f\u516d".split(" "),"dayPeriods-format-narrow-night":"\u665a\u4e0a","dateTimeFormats-appendItem-Month":"{0} ({2}: {1})",
"dateFormatItem-EHm":"E HH:mm","field-zone":"\u6642\u5340","dateFormatItem-yM":"y/M","dateFormatItem-yMMMM":"y\u5e74M\u6708","dateFormatItem-MMMEd":"M\u6708d\u65e5E","dateFormatItem-EHms":"E HH:mm:ss","dateFormatItem-yMEd":"y/M/d\uff08E\uff09","field-day-relative+-1":"\u6628\u5929","field-day-relative+-2":"\u524d\u5929","days-format-abbr":"\u5468\u65e5 \u5468\u4e00 \u5468\u4e8c \u5468\u4e09 \u5468\u56db \u5468\u4e94 \u5468\u516d".split(" "),"field-sun-relative+0":"\u672c\u9031\u65e5","dateFormatItem-MMdd":"MM/dd",
"field-sun-relative+1":"\u4e0b\u9031\u65e5","dateFormatItem-yMMMd":"y\u5e74M\u6708d\u65e5","dateTimeFormats-appendItem-Minute":"{0} ({2}: {1})","dateFormatItem-Gy":"G y \u5e74","field-era":"\u5e74\u4ee3"},"dojo/cldr/nls/number":{scientificFormat:"#E0","currencySpacing-afterCurrency-currencyMatch":"[:^S:]",infinity:"\u221e",$locale:"zh-hant-tw",superscriptingExponent:"\u00d7",list:";",percentSign:"%",minusSign:"-","currencySpacing-beforeCurrency-surroundingMatch":"[:digit:]",_localized:{},"decimalFormat-short":"000T",
"currencySpacing-afterCurrency-insertBetween":"\u00a0",nan:"\u975e\u6578\u503c",plusSign:"+","currencySpacing-afterCurrency-surroundingMatch":"[:digit:]",currencyFormat:"\u00a4#,##0.00;(\u00a4#,##0.00)","currencySpacing-beforeCurrency-currencyMatch":"[:^S:]",perMille:"\u2030",group:",",percentFormat:"#,##0%","decimalFormat-long":"000\u5146",decimalFormat:"#,##0.###",decimal:".","currencySpacing-beforeCurrency-insertBetween":"\u00a0",exponential:"E"}}); | aconyteds/Esri-Ozone-Map-Widget | vendor/js/esri/arcgis_js_api/library/3.11/3.11compact/esri/nls/jsapi_zh-tw.js | JavaScript | apache-2.0 | 74,168 |
/a/lib/tsc.js -w /user/username/projects/myproject/a.ts --skipLibCheck
//// [/user/username/projects/myproject/a.ts]
interface Document {
fullscreen: boolean;
}
var y: number;
//// [/a/lib/lib.d.ts]
/// <reference no-default-lib="true"/>
interface Boolean {}
interface Function {}
interface CallableFunction {}
interface NewableFunction {}
interface IArguments {}
interface Number { toExponential: any; }
interface Object {}
interface RegExp {}
interface String { charAt: any; }
interface Array<T> { length: number; [n: number]: T; }
interface Document {
readonly fullscreen: boolean;
}
//// [/user/username/projects/myproject/a.js]
var y;
Output::
>> Screen clear
12:00:19 AM - Starting compilation in watch mode...
a.ts(2,5): error TS2687: All declarations of 'fullscreen' must have identical modifiers.
12:00:22 AM - Found 1 error. Watching for file changes.
Program root files: ["/user/username/projects/myproject/a.ts"]
Program options: {"watch":true,"skipLibCheck":true}
Program files::
/a/lib/lib.d.ts
/user/username/projects/myproject/a.ts
Semantic diagnostics in builder refreshed for::
/a/lib/lib.d.ts
/user/username/projects/myproject/a.ts
WatchedFiles::
/user/username/projects/myproject/a.ts:
{"fileName":"/user/username/projects/myproject/a.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/myproject/node_modules/@types:
{"directoryName":"/user/username/projects/myproject/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
Change:: Remove document declaration from file
//// [/user/username/projects/myproject/a.ts]
var x: string;
var y: number;
//// [/user/username/projects/myproject/a.js]
var x;
var y;
Output::
>> Screen clear
12:00:26 AM - File change detected. Starting incremental compilation...
12:00:30 AM - Found 0 errors. Watching for file changes.
Program root files: ["/user/username/projects/myproject/a.ts"]
Program options: {"watch":true,"skipLibCheck":true}
Program files::
/a/lib/lib.d.ts
/user/username/projects/myproject/a.ts
Semantic diagnostics in builder refreshed for::
/user/username/projects/myproject/a.ts
WatchedFiles::
/user/username/projects/myproject/a.ts:
{"fileName":"/user/username/projects/myproject/a.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/myproject/node_modules/@types:
{"directoryName":"/user/username/projects/myproject/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
Change:: Rever the file to contain document declaration
//// [/user/username/projects/myproject/a.ts]
interface Document {
fullscreen: boolean;
}
var y: number;
//// [/user/username/projects/myproject/a.js]
var y;
Output::
>> Screen clear
12:00:34 AM - File change detected. Starting incremental compilation...
a.ts(2,5): error TS2687: All declarations of 'fullscreen' must have identical modifiers.
12:00:38 AM - Found 1 error. Watching for file changes.
Program root files: ["/user/username/projects/myproject/a.ts"]
Program options: {"watch":true,"skipLibCheck":true}
Program files::
/a/lib/lib.d.ts
/user/username/projects/myproject/a.ts
Semantic diagnostics in builder refreshed for::
/user/username/projects/myproject/a.ts
WatchedFiles::
/user/username/projects/myproject/a.ts:
{"fileName":"/user/username/projects/myproject/a.ts","pollingInterval":250}
/a/lib/lib.d.ts:
{"fileName":"/a/lib/lib.d.ts","pollingInterval":250}
FsWatches::
FsWatchesRecursive::
/user/username/projects/myproject/node_modules/@types:
{"directoryName":"/user/username/projects/myproject/node_modules/@types","fallbackPollingInterval":500,"fallbackOptions":{"watchFile":"PriorityPollingInterval"}}
exitCode:: ExitStatus.undefined
| minestarks/TypeScript | tests/baselines/reference/tscWatch/programUpdates/updates-errors-in-lib-file/when-non-module-file-changes/with-skipLibCheck.js | JavaScript | apache-2.0 | 4,133 |
module.exports = function(grunt) {
var config = {
pkg: grunt.file.readJSON('package.json'),
jshint: {
all: [
'Gruntfile.js',
'*.js',
'pdf417/*.js',
'pdf417/decoder/*.js',
'pdf417/detector/*.js',
'pdf417/decoder/ec/*.js',
'common/*.js',
'common/detector/*.js'
]
},
concat: {
dist: {
options: {
banner: '(function(exports, Error, Uin8Array, Uint32Array, BigInteger, undefined){\n',
footer: "\n}(module.exports, Error, Uint8Array, Uint32Array, require('big-integer')));\n"
},
src: [
'SupportClass.js',
'ResultMetadataType.js',
'BarcodeFormat.js',
'Result.js',
'DecodeHintType.js',
'BinaryBitmap.js',
'Binarizer.js',
'ResultPoint.js',
'LuminanceSource.js',
'InvertedLuminanceSource.js',
'BaseLuminanceSource.js',
'BitmapLuminanceSource.js',
'common/DecoderResult.js',
'common/BitArray.js',
'common/BitMatrix.js',
'common/detector/MathUtils.js',
'common/ECI.js',
'common/CharacterSetECI.js',
'common/GlobalHistogramBinarizer.js',
'common/HybridBinarizer.js',
'pdf417/PDF417ResultMetadata.js',
'pdf417/PDF417Common.js',
'pdf417/detector/PDF417DetectorResult.js',
'pdf417/detector/Detector.js',
'pdf417/decoder/ec/ModulusPoly.js',
'pdf417/decoder/ec/ModulusGF.js',
'pdf417/decoder/ec/ErrorCorrection.js',
'pdf417/decoder/BarcodeMetadata.js',
'pdf417/decoder/BarcodeValue.js',
'pdf417/decoder/BoundingBox.js',
'pdf417/decoder/Codeword.js',
'pdf417/decoder/DecodedBitStreamParser.js',
'pdf417/decoder/DetectionResult.js',
'pdf417/decoder/DetectionResultColumn.js',
'pdf417/decoder/DetectionResultRowIndicatorColumn.js',
'pdf417/decoder/PDF417CodewordDecoder.js',
'pdf417/decoder/PDF417ScanningDecoder.js',
'pdf417/PDF417Reader.js'
],
dest: 'dist/zxing-pdf417.js'
}
},
uglify: {
dist: {
src: 'dist/zxing-pdf417.js',
dest: 'dist/zxing-pdf417.min.js'
}
}
};
grunt.initConfig(config);
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('default', [/*'jshint', */'concat', 'uglify']);
};
| coinme/js-zxing-pdf417 | Gruntfile.js | JavaScript | apache-2.0 | 2,665 |
'use strict';
describe('farmbuild.soilSampleImporter module', function() {
beforeEach(function() {
fixture.setBase('src/unit-test-data')
})
// instantiate service
var soilSampleImporterSession, soilSampleImporter,
milkSold, fertilizersPurchased,
susanFarmJson = 'farmdata-susan.json',
$log;
beforeEach(module('farmbuild.soilSampleImporter', function($provide) {
$provide.value('$log', console);
}));
afterEach(function() {
fixture.cleanup()
});
});
| FarmBuild/farmbuild-soil-sample-importer | src/session/index.spec.js | JavaScript | apache-2.0 | 494 |
/*
* 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.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*/
/*
* Dependencies
*/
var logService = require( "../services/log-service.js" );
var argument = require( "../utils/argument-assertion-util.js" );
var objectUtil = require( "../utils/object-util.js" );
/*
* Private
*/
var observers = {
};
var KEY_DIRECTORY_FOUND = "KEY_DIRECTORY_FOUND";
var KEY_FILE_FOUND = "KEY_FILE_FOUND";
var KEY_FILE_READ = "KEY_FILE_READ";
var KEY_ON_FILE_READ = "KEY_ON_FILE_READ";
var KEY_ON_HTML_PROPERTY_VALUE_READ = "KEY_ON_HTML_PROPERTY_VALUE_READ";
var KEY_ON_CSS_FILE_READ = "KEY_ON_CSS_FILE_READ";
var KEY_ON_CSS_PROPERTY_AND_ATTRIBUTE_READ = "KEY_ON_CSS_PROPERTY_AND_ATTRIBUTE_READ";
var KEY_ON_HTML_FILE_READ = "KEY_ON_HTML_FILE_READ";
var KEY_ON_LESS_FILE_READ = "KEY_ON_LESS_FILE_READ";
var KEY_ON_CSS_COMMENT_READ = "KEY_ON_CSS_COMMENT_READ";
var KEY_ON_JAVASCRIPT_FILE_READ = "KEY_ON_JAVASCRIPT_FILE_READ";
var KEY_JAVASCRIPT_FILE_LINE_READ = "KEY_JAVASCRIPT_FILE_LINE_READ";
function addObserver ( observerFunction, key ) {
if ( !objectUtil.isFunction( observerFunction ) ) {
throw new Error( "Got an observer that is not a function." );
}
if ( !objectUtil.isFunction( observerFunction ) ) {
throw new Error( "Got an observer that is not a function." );
}
if ( !observers[key] ) {
logService.log( "Creating a new array for observers associated with the key \"" + key + "\"." );
observers[key] =
[
];
}
observers[key].push( observerFunction );
logService.log( "Added new observer for \"" + key + "\"." );
}
function notifyAll ( key ) {
// Delete the first argument (meaning the 'observer' argument)
delete arguments[0];
// Make it into an array, removing the dummy first argument
var arguments = Array.prototype.slice.call( arguments, 1 );
for ( var i in observers[key] ) {
var observerFunction = observers[key][i];
// Call the observer, using our crippled argument list
observerFunction.apply( this, arguments );
}
};
/*
* Public functions
*/
/**
* Upon a directory was found.
*
* @param directory The directory name.
*/
exports.onDirectoryFound = function ( observer ) {
addObserver( observer, KEY_DIRECTORY_FOUND );
}
/**
* Notify observers that a directory was found.
*
* @param directory the directory name.
*/
exports.directoryFound = function ( reporters, directoriesToIgnore, basePath, fullPath, directoryName, responseFunction ) {
notifyAll( KEY_DIRECTORY_FOUND, reporters, directoriesToIgnore, basePath, fullPath, directoryName, responseFunction );
};
// ------------- all above is confirmed
{
exports.onFileFound = function ( observer ) {
addObserver( observer, KEY_FILE_FOUND );
};
exports.fileFound = function ( reporters, path, fileName, file, responseFunction ) {
argument.isObject( reporters );
argument.isString( path );
argument.isString( fileName );
argument.isString( file );
argument.isFunction( responseFunction );
notifyAll( KEY_FILE_FOUND, reporters, path, fileName, file, responseFunction );
};
}
{
exports.onFileRead = function ( observer ) {
addObserver( observer, KEY_ON_FILE_READ );
};
exports.fileRead = function ( reporters, file, fileContents, responseFunction ) {
notifyAll( KEY_ON_FILE_READ, reporters, file, fileContents, responseFunction );
};
}
{
exports.onCSSFileRead = function ( observer ) {
addObserver( observer, KEY_ON_CSS_FILE_READ );
}
exports.CSSFileRead = function ( reporters, file, fileContents, responseFunction ) {
argument.isObject( reporters, "Reporters is undefined." );
argument.isString( file, "File is undefined." );
argument.isString( fileContents, "File contents is undefined." );
argument.isFunction( responseFunction, "Reponse function is undefined." );
notifyAll( KEY_ON_CSS_FILE_READ, reporters, file, fileContents, responseFunction );
}
}
{
exports.onJavaScriptFileLineRead = function ( observer ) {
addObserver( observer, KEY_JAVASCRIPT_FILE_LINE_READ );
}
exports.JavaScriptFileLineRead = function ( file, lineNumber, lineContents, responseFunction ) {
notifyAll( KEY_JAVASCRIPT_FILE_LINE_READ, file, lineNumber, lineContents, responseFunction );
}
}
{
exports.onHTMLFileRead = function ( observer ) {
addObserver( observer, KEY_ON_HTML_FILE_READ );
};
exports.HTMLFileRead = function ( reporters, file, fileContents, responseFunction ) {
argument.isObject( reporters, "Reporter is undefined." );
argument.isString( file, "File is undefined." );
argument.isString( fileContents, "File contents" );
argument.isFunction( responseFunction, "Response function is undefined." );
notifyAll( KEY_ON_HTML_FILE_READ, reporters, file, fileContents, responseFunction );
};
}
{
exports.onJavaScriptFileRead = function ( observer ) {
addObserver( observer, KEY_ON_JAVASCRIPT_FILE_READ );
}
exports.JavaScriptFileRead = function ( file, fileContents, responseFunction ) {
notifyAll( KEY_ON_JAVASCRIPT_FILE_READ, file, fileContents, responseFunction );
}
}
{
exports.onLESSFileRead = function ( observer ) {
addObserver( observer, KEY_ON_LESS_FILE_READ );
}
exports.LESSFileRead = function ( reporters, file, fileContents, responseFunction ) {
notifyAll( KEY_ON_LESS_FILE_READ, reporters, file, fileContents, responseFunction );
}
}
{
exports.onHTMLPropertyValueRead = function ( observer ) {
addObserver( observer, KEY_ON_HTML_PROPERTY_VALUE_READ );
};
exports.HTMLPropertyValueRead = function ( reporters, file, elementName, property, value, responseFunction ) {
argument.isObject( reporters, "Reporter is undefined." );
argument.isString( file, "File is undefined." );
argument.isString( elementName, "Element name is undefined" );
argument.isString( property, "Property is undefined." );
argument.isString( property, "Property is undefined." );
argument.isString( value, "Value is undefined." );
argument.isFunction( responseFunction, "Response function is undefined." );
notifyAll( KEY_ON_HTML_PROPERTY_VALUE_READ, reporters, file, elementName, property, value, responseFunction );
};
}
{
exports.onCSSPropertyAndAttributeRead = function ( observer ) {
addObserver( observer, KEY_ON_CSS_PROPERTY_AND_ATTRIBUTE_READ );
};
exports.CSSPropertyAndAttributeRead = function ( file, selectors, property, value, responseFunction ) {
notifyAll( KEY_ON_CSS_PROPERTY_AND_ATTRIBUTE_READ, file, selectors, property, value, responseFunction );
};
}
{
exports.onCSSCommentRead = function ( observer ) {
addObserver( observer, KEY_ON_CSS_COMMENT_READ );
}
exports.CSSCommentRead = function ( file, comment, responseFunction ) {
notifyAll( KEY_ON_CSS_COMMENT_READ, file, comment, responseFunction );
}
} | corgrath/abandoned-planemo.js | src/services/observer-service.js | JavaScript | apache-2.0 | 7,276 |
var guiData = null;
var guiDataChanged = false;
var gui;
function initGui() {
//obj = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 1, 10000 );
// @Todo: make it work with enabled controllers, not sure which one should come first
if (typeof(trackballControls.object) != 'object') {
return;
}
var object = trackballControls.object;
guiData = object;
gui = new dat.gui.GUI();
gui.remember(object);
gui.remember(object.position);
gui.remember(object.rotation);
gui.remember(object.quaternion);
gui.remember(object.scale);
object.separation = 6;
gui.add( object , 'separation' , -10 , 10 ).onFinishChange(function(v){updateGuiData( this,v )});
gui.add( object , 'aspect' , 1 , 10 ).onFinishChange(function(v){updateGuiData( this,v )});
gui.add( object , 'fov' , 1 , 1000 ).onFinishChange(function(v){updateGuiData( this,v )});
gui.add( object , 'filmGauge' , 1 , 60 ).onFinishChange(function(v){updateGuiData( this,v )});
gui.add( object , 'filmOffset' , 0 , 10 ).onFinishChange(function(v){updateGuiData( this,v )});
gui.add( object , 'near' , 1 , 20 ).onFinishChange(function(v){updateGuiData( this,v )});
gui.add( object , 'far' , 1 , 20000 ).onFinishChange(function(v){updateGuiData( this,v )});
gui.add( object , 'focus' , 1 , 20 ).onFinishChange(function(v){updateGuiData( this,v )});
gui.add( object , 'zoom' , 0 , 10 ).onFinishChange(function(v){updateGuiData( this,v )});
var position = gui.addFolder('position');
position.add( object.position , 'x', -10000, 10000).onFinishChange(function(v){updateGuiDataPosition( this,v )});
position.add( object.position , 'y', -10000, 10000).onFinishChange(function(v){updateGuiDataPosition( this,v )});
position.add( object.position , 'z', -10000, 10000).onFinishChange(function(v){updateGuiDataPosition( this,v )});
var rotation = gui.addFolder('rotation');
rotation.add( object.rotation , 'x', 0, 100).onFinishChange(function(v){updateGuiDataRotation( this,v )});
rotation.add( object.rotation , 'y', 0, 100).onFinishChange(function(v){updateGuiDataRotation( this,v )});
rotation.add( object.rotation , 'z', 0, 100).onFinishChange(function(v){updateGuiDataRotation( this,v )});
var up = gui.addFolder('up');
up.add( object.up , 'x', 0, 10).onFinishChange(function(v){updateGuiDataUp( this,v )});
up.add( object.up , 'y', 0, 10).onFinishChange(function(v){updateGuiDataUp( this,v )});
up.add( object.up , 'z', 0, 10).onFinishChange(function(v){updateGuiDataUp( this,v )});
var quaternion = gui.addFolder('quaternion');
quaternion.add( object.quaternion , '_w', 0, 10).onFinishChange(function(v){updateGuiDataQuaternion( this,v )});
quaternion.add( object.quaternion , '_x', 0, 10).onFinishChange(function(v){updateGuiDataQuaternion( this,v )});
quaternion.add( object.quaternion , '_y', 0, 10).onFinishChange(function(v){updateGuiDataQuaternion( this,v )});
quaternion.add( object.quaternion , '_z', 0, 10).onFinishChange(function(v){updateGuiDataQuaternion( this,v )});
var scale = gui.addFolder('scale');
scale.add( object.scale , 'x', 1, 1000).onFinishChange(function(v){updateGuiDataScale( this,v )});
scale.add( object.scale , 'y', 1, 1000).onFinishChange(function(v){updateGuiDataScale( this,v )});
scale.add( object.scale , 'z', 1, 1000).onFinishChange(function(v){updateGuiDataScale( this,v )});
}
function updateObjectProperties() {
if (guiData && !gui.closed && guiDataChanged) {
//@todo make it work with other controllers
var guiTarget = trackballControls.object;
guiTarget.aspect = guiData.aspect;
guiTarget.fov = guiData.fov;
guiTarget.filmGauge = guiData.filmGauge;
guiTarget.filmOffset = guiData.filmOffset;
guiTarget.far = guiData.far;
guiTarget.near = guiData.near;
guiTarget.focus = guiData.focus;
guiTarget.zoom = guiData.zoom;
guiTarget.position.x = guiData.position.x;
guiTarget.position.z = guiData.position.z;
guiTarget.position.y = guiData.position.y;
guiTarget.up.x = guiData.up.x;
guiTarget.up.z = guiData.up.z;
guiTarget.up.y = guiData.up.y;
guiTarget.rotation.x = guiData.rotation.x;
guiTarget.rotation.z = guiData.rotation.z;
guiTarget.rotation.y = guiData.rotation.y;
guiTarget.quaternion._w = guiData.quaternion._w;
guiTarget.quaternion._x = guiData.quaternion._x;
guiTarget.quaternion._z = guiData.quaternion._z;
guiTarget.quaternion._y = guiData.quaternion._y;
guiTarget.scale.x = guiData.scale.x;
guiTarget.scale.z = guiData.scale.z;
guiTarget.scale.y = guiData.scale.y;
guiDataChanged = false;
}
updateGui({}); //enabling gui breaks trackball controls
}
function updateGui( guiFolderContents ) {
if ( typeof(gui) != 'object' ) {
initGui();
return;
}
if (gui.closed) {
return;
}
if ( Object.keys(guiFolderContents).length == 0 ) {
var isFolder = false;
guiObj = gui.__controllers;
} else {
var isFolder = true;
guiObj = guiFolderContents;
}
// Do properties
jQuery.each( guiObj, function ( i, controller ) {
var property = controller.property;
if ( !guiDataChanged ) {
//@todo make it work with other controls
if ( isFolder ) {
//if (controller.object[property] != trackballControls.object[guiObj.parent][property]) {
controller.setValue( trackballControls.object[guiObj.parent][property] );
//}
} else {
if (controller.object[property] != trackballControls.object[property]) {
controller.setValue( trackballControls.object[property] );
}
}
}
} );
// Do folders now
if (!isFolder) {
jQuery.each( gui.__folders, function ( i, guiFolder ) {
guiFolder.__controllers.parent = i;
updateGui( guiFolder.__controllers );
} );
}
}
function updateGuiDataItem(folder, property, value) {
if (folder == null) {
if (guiData[property] != value) {
guiData[property] = value;
guiDataChanged = true;
}
} else {
if (guiData[folder][property] != value) {
guiData[folder][property] = value;
guiDataChanged = true;
}
}
}
function updateGuiData( change, value ) {
var folder = null;
updateGuiDataItem(folder, change.property, value);
}
function updateGuiDataPosition( change , value ){
updateGuiDataItem('position', change.property, value);
}
function updateGuiDataUp( change , value ){
updateGuiDataItem('up', change.property, value);
}
function updateGuiDataRotation( change , value ){
updateGuiDataItem('rotation', change.property, value);
}
function updateGuiDataQuaternion( change , value ){
updateGuiDataItem('quaternion', change.property, value);
}
function updateGuiDataScale( change , value ){
updateGuiDataItem('scale', change.property, value);
}
| marcelovani/xhprof | xhprof_html/themes/VR/js/vrGui.js | JavaScript | apache-2.0 | 6,626 |
import { setPropertiesFromJSON } from '../../json-helper';
/**
* Generated class for shr.skin.SupportSurfaceCategory.
*/
class SupportSurfaceCategory {
/**
* Get the value (aliases codeableConcept).
* @returns {CodeableConcept} The shr.core.CodeableConcept
*/
get value() {
return this._codeableConcept;
}
/**
* Set the value (aliases codeableConcept).
* @param {CodeableConcept} value - The shr.core.CodeableConcept
*/
set value(value) {
this._codeableConcept = value;
}
/**
* Get the CodeableConcept.
* @returns {CodeableConcept} The shr.core.CodeableConcept
*/
get codeableConcept() {
return this._codeableConcept;
}
/**
* Set the CodeableConcept.
* @param {CodeableConcept} codeableConcept - The shr.core.CodeableConcept
*/
set codeableConcept(codeableConcept) {
this._codeableConcept = codeableConcept;
}
/**
* Deserializes JSON data to an instance of the SupportSurfaceCategory class.
* The JSON must be valid against the SupportSurfaceCategory JSON schema, although this is not validated by the function.
* @param {object} json - the JSON data to deserialize
* @returns {SupportSurfaceCategory} An instance of SupportSurfaceCategory populated with the JSON data
*/
static fromJSON(json={}) {
const inst = new SupportSurfaceCategory();
setPropertiesFromJSON(inst, json);
return inst;
}
}
export default SupportSurfaceCategory;
| standardhealth/flux | src/model/shr/skin/SupportSurfaceCategory.js | JavaScript | apache-2.0 | 1,450 |
// Copyright 2011 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
(function(global, utils) {
"use strict";
%CheckIsBootstrapping();
// ----------------------------------------------------------------------------
// Imports
var GlobalFunction = global.Function;
var GlobalObject = global.Object;
var ToNameArray;
utils.Import(function(from) {
ToNameArray = from.ToNameArray;
});
//----------------------------------------------------------------------------
function ProxyCreate(handler, proto) {
if (!IS_SPEC_OBJECT(handler))
throw MakeTypeError(kProxyHandlerNonObject, "create")
if (IS_UNDEFINED(proto))
proto = null
else if (!(IS_SPEC_OBJECT(proto) || IS_NULL(proto)))
throw MakeTypeError(kProxyProtoNonObject)
return %CreateJSProxy(handler, proto)
}
function ProxyCreateFunction(handler, callTrap, constructTrap) {
if (!IS_SPEC_OBJECT(handler))
throw MakeTypeError(kProxyHandlerNonObject, "createFunction")
if (!IS_CALLABLE(callTrap))
throw MakeTypeError(kProxyTrapFunctionExpected, "call")
if (IS_UNDEFINED(constructTrap)) {
constructTrap = DerivedConstructTrap(callTrap)
} else if (IS_CALLABLE(constructTrap)) {
// Make sure the trap receives 'undefined' as this.
var construct = constructTrap
constructTrap = function() {
return %Apply(construct, UNDEFINED, arguments, 0, %_ArgumentsLength());
}
} else {
throw MakeTypeError(kProxyTrapFunctionExpected, "construct")
}
return %CreateJSFunctionProxy(
handler, callTrap, constructTrap, GlobalFunction.prototype)
}
// -------------------------------------------------------------------
// Proxy Builtins
function DerivedConstructTrap(callTrap) {
return function() {
var proto = this.prototype
if (!IS_SPEC_OBJECT(proto)) proto = GlobalObject.prototype
var obj = { __proto__: proto };
var result = %Apply(callTrap, obj, arguments, 0, %_ArgumentsLength());
return IS_SPEC_OBJECT(result) ? result : obj
}
}
function DelegateCallAndConstruct(callTrap, constructTrap) {
return function() {
return %Apply(%_IsConstructCall() ? constructTrap : callTrap,
this, arguments, 0, %_ArgumentsLength())
}
}
function DerivedGetTrap(receiver, name) {
var desc = this.getPropertyDescriptor(name)
if (IS_UNDEFINED(desc)) { return desc }
if ('value' in desc) {
return desc.value
} else {
if (IS_UNDEFINED(desc.get)) { return desc.get }
// The proposal says: desc.get.call(receiver)
return %_CallFunction(receiver, desc.get)
}
}
function DerivedSetTrap(receiver, name, val) {
var desc = this.getOwnPropertyDescriptor(name)
if (desc) {
if ('writable' in desc) {
if (desc.writable) {
desc.value = val
this.defineProperty(name, desc)
return true
} else {
return false
}
} else { // accessor
if (desc.set) {
// The proposal says: desc.set.call(receiver, val)
%_CallFunction(receiver, val, desc.set)
return true
} else {
return false
}
}
}
desc = this.getPropertyDescriptor(name)
if (desc) {
if ('writable' in desc) {
if (desc.writable) {
// fall through
} else {
return false
}
} else { // accessor
if (desc.set) {
// The proposal says: desc.set.call(receiver, val)
%_CallFunction(receiver, val, desc.set)
return true
} else {
return false
}
}
}
this.defineProperty(name, {
value: val,
writable: true,
enumerable: true,
configurable: true});
return true;
}
function DerivedHasTrap(name) {
return !!this.getPropertyDescriptor(name)
}
function DerivedHasOwnTrap(name) {
return !!this.getOwnPropertyDescriptor(name)
}
function DerivedKeysTrap() {
var names = this.getOwnPropertyNames()
var enumerableNames = []
for (var i = 0, count = 0; i < names.length; ++i) {
var name = names[i]
if (IS_SYMBOL(name)) continue
var desc = this.getOwnPropertyDescriptor(TO_STRING(name))
if (!IS_UNDEFINED(desc) && desc.enumerable) {
enumerableNames[count++] = names[i]
}
}
return enumerableNames
}
function DerivedEnumerateTrap() {
var names = this.getPropertyNames()
var enumerableNames = []
for (var i = 0, count = 0; i < names.length; ++i) {
var name = names[i]
if (IS_SYMBOL(name)) continue
var desc = this.getPropertyDescriptor(TO_STRING(name))
if (!IS_UNDEFINED(desc)) {
if (!desc.configurable) {
throw MakeTypeError(kProxyPropNotConfigurable,
this, name, "getPropertyDescriptor")
}
if (desc.enumerable) enumerableNames[count++] = names[i]
}
}
return enumerableNames
}
function ProxyEnumerate(proxy) {
var handler = %GetHandler(proxy)
if (IS_UNDEFINED(handler.enumerate)) {
return %Apply(DerivedEnumerateTrap, handler, [], 0, 0)
} else {
return ToNameArray(handler.enumerate(), "enumerate", false)
}
}
//-------------------------------------------------------------------
var Proxy = new GlobalObject();
%AddNamedProperty(global, "Proxy", Proxy, DONT_ENUM);
//Set up non-enumerable properties of the Proxy object.
utils.InstallFunctions(Proxy, DONT_ENUM, [
"create", ProxyCreate,
"createFunction", ProxyCreateFunction
])
// -------------------------------------------------------------------
// Exports
utils.Export(function(to) {
to.ProxyDelegateCallAndConstruct = DelegateCallAndConstruct;
to.ProxyDerivedHasOwnTrap = DerivedHasOwnTrap;
to.ProxyDerivedKeysTrap = DerivedKeysTrap;
});
%InstallToContext([
"derived_get_trap", DerivedGetTrap,
"derived_has_trap", DerivedHasTrap,
"derived_set_trap", DerivedSetTrap,
"proxy_enumerate", ProxyEnumerate,
]);
})
| dreamllq/node | deps/v8/src/proxy.js | JavaScript | apache-2.0 | 5,850 |
exports.ProxyServer = require('./proxyserver/ProxyServer');
exports.Host = require('./Host');
| enmasseio/remoteobjects | lib/remoteobjects.js | JavaScript | apache-2.0 | 94 |
// Read configs, init loggers, init apps, fills N object.
'use strict';
const cluster = require('cluster');
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const Promise = require('bluebird');
const npm = require('npm');
const _ = require('lodash');
const log4js = require('log4js');
const validator = require('is-my-json-valid');
const yaml = require('js-yaml');
const wire = require('event-wire');
const glob = require('glob').sync;
const mkdirp = require('mkdirp').sync;
const Application = require('./application');
const stopwatch = require('../init/utils/stopwatch');
////////////////////////////////////////////////////////////////////////////////
// merge configs, respecting `~override: true` instructions
function mergeConfigs(dst, src) {
_.forEach(src || {}, (value, key) => {
// if destination exists & already has `~override` flag, keep it intact
if (_.isObject(dst[key]) && dst[key]['~override']) return;
// if source has `~override` flag - override whole value in destination
if (value && value['~override']) {
dst[key] = value;
return;
}
// if both nodes are arrays, concatenate them
if (_.isArray(value) && _.isArray(dst[key])) {
value.forEach(v => { dst[key].push(v); });
return;
}
// if both nodes are objects - merge recursively
if (_.isObject(value) && _.isObject(dst[key])) {
mergeConfigs(dst[key], value);
return;
}
// destination node does not exist - create
// or both nodes are of different types - override.
dst[key] = value;
return;
});
return dst;
}
// Remove `~override` flag recursively
function cleanupConfigs(cfg) {
if (!_.isPlainObject(cfg)) return;
if (cfg['~override']) delete cfg['~override'];
_.forEach(cfg, cleanupConfigs);
}
// reads all *.yml files from `dir` and merge resulting objects into single one
function loadConfigs(root) {
let config = {};
glob('**/*.yml', {
cwd: root
})
.sort() // files order can change, but we shuld return the same result always
.map(file => path.join(root, file))
.forEach(file => {
mergeConfigs(config, yaml.safeLoad(fs.readFileSync(file, 'utf8'), { filename: file }));
});
cleanupConfigs(config);
return config;
}
// Returns an object with keys:
//
// `responderName` (string)
// `splittedMethod` (array)
//
// Each one may be `null` which means 'any'.
//
// 'rpc@' => { responderName: 'rpc', splittedMethod: null }
// 'http@forum.index' => { responderName: 'http', splittedMethod: [ 'forum', 'index' ] }
// 'blogs' => { responderName: null, splittedMethod: [ 'blogs' ] }
//
function parseLoggerName(name) {
let responderName, splittedMethod, parts = name.split('@');
if (parts.length === 1) {
responderName = null;
splittedMethod = name.split('.');
} else if (parts.length === 2) {
responderName = parts[0];
splittedMethod = parts[1].split('.');
} else {
// Bad name format. Only one @ symbol is allowed.
return null;
}
if (_.compact(splittedMethod).length === 0) {
splittedMethod = null;
}
return { responderName, splittedMethod };
}
// Application in list could be defined as plain object or string:
//
// - { "nodeca.site": "https://github.com/nodeca/nodeca.site" }
// - nodeca.users
//
// return `nodeca.users`, `nodeca.site`, etc.
//
function getAppName(app) {
if (_.isPlainObject(app)) {
let keys = Object.keys(app);
if (keys.length === 1) {
return keys[0];
}
throw new Error('Ill-formed list of applications.');
}
return String(app);
}
// Check list of applications, if application is
// missed - try to install it via npm.
//
const installAppsIfMissed = Promise.coroutine(function* (apps) {
let appName, appNpmPath;
for (let app of apps) {
if (_.isPlainObject(app)) {
appName = getAppName(app);
appNpmPath = app[appName];
} else {
appName = appNpmPath = String(app);
}
try {
require.resolve(appName);
} catch (__) {
yield Promise.fromCallback(cb => npm.load({}, cb));
/*eslint-disable no-loop-func*/
yield Promise.fromCallback(cb => npm.commands.install([ appNpmPath ], cb));
}
}
});
////////////////////////////////////////////////////////////////////////////////
// Init `N.wire` with time tracking
//
// override:
//
// - on
// - off
//
function initWire(N) {
N.wire = wire({
p: Promise,
co: (fn, params) => Promise.coroutine(fn)(params)
});
function findPuncher(params) {
// Try find puncher
return _.get(params, 'extras.puncher') ||
_.get(params, 'env.extras.puncher');
}
N.wire.hook('eachBefore', function (handler, params) {
let puncher = findPuncher(params);
if (puncher) puncher.start(handler.name);
});
N.wire.hook('eachAfter', function (handler, params) {
let puncher = findPuncher(params);
if (puncher) puncher.stop();
});
}
function initScope(N) {
// provide some empty structures
N.client = {};
N.views = {};
// Storage for validators (each key is a `apiPath`)
let validateFn = {};
// Additional format extentions
let validateFormatExt = {
mongo: /^[0-9a-f]{24}$/
};
/**
* N.validate(apiPath, schema) -> Void
* N.validate(schema) -> Void
* - apiPath (String): server api path relative to the current api node
* - schema (Object): validation schema (for proprties only)
*
* Add validation schema for params of apiPath.
*
* ##### Schema
*
* You can provide full JSON-Schema compatible object:
*
* {
* properties: {
* id: { type: 'integer', minimal: 1 }
* },
* additionalProperties: false
* }
*
* But for convenience we provide a syntax sugar for this situation, so the
* above is long-hand syntax of:
*
* {
* id: { type: 'integer', minimal: 1 }
* }
**/
N.validate = function (apiPath, schema) {
if (!schema || !schema.properties) {
schema = {
properties: schema,
additionalProperties: false
};
}
validateFn[apiPath] = validator(schema, {
formats: validateFormatExt,
verbose: true
});
};
/** internal
* N.validate.test(apiPath, params) -> Object|Null
*
* Runs revalidate of apiPath for given params. Returns structure with
* `valid:Boolean` and `errors:Array` properties or `Null` if apiPath has no
* schema.
**/
N.validate.test = function (apiPath, params) {
if (validateFn[apiPath]) {
if (validateFn[apiPath](params)) return { valid: true, errors: [] };
return { valid: false, errors: validateFn[apiPath].errors };
}
return null;
};
}
function initConfig(N, mainConfig) {
//
// Create empty object that we'll fill in a second
//
N.config = {};
//
// Start reading configs:
//
// - Main app config stored into mainConfig
// - Sub-apps configs got merged into N.config
// - After all mainConfig got merged into N.config
//
// read configs of sub-applications
if (mainConfig.applications && mainConfig.applications.length) {
_.forEach(mainConfig.applications, app => {
let root = path.join(path.dirname(require.resolve(getAppName(app))), '/config');
mergeConfigs(N.config, loadConfigs(root));
});
}
// merge in main config and resolve `per-environment` configs
mergeConfigs(N.config, mainConfig);
// set application environment
N.environment = process.env.NODECA_ENV || N.config.env_default || 'development';
// do global expansion first
// merge `^all` branch
if (N.config['^all']) {
mergeConfigs(N.config, N.config['^all']);
delete N.config['^all'];
}
// expand environment-dependent configs
_.forEach(N.config, (val, key) => {
if (key[0] === '^') {
delete N.config[key];
if (N.environment === key.substr(1)) {
mergeConfigs(N.config, val);
}
}
});
//
// Post-process config.
//
N.config.options = N.config.options || {};
}
function initLogger(N) {
let mainRoot = N.mainApp.root,
config = _.assign({}, N.config.logger),
options = _.assign({ file: { logSize: 10, backups: 5 } }, config.options),
// common logging level (minimal threshold)
baseLevel = log4js.levels.toLevel(options.level, log4js.levels.ALL),
// should it log everything to console or not
logToConsole = (N.environment !== 'production'),
// cache of initialized appenders
appenders = {},
// real loggers created for each entry in the config
loggers = [],
// cache of met channels, maps full channel names to corresponding loggers
channels = {};
// Layout for file loggers
//
// %d - date
// %p - log level
// %z - pid
// %c - category
// %m - message
//
let plainLayout = log4js.layouts.layout('pattern',
{ pattern: '[%d] [%p] %z %c - %m' }
);
// Layout for console loggers
//
// only difference is `%[`..`%]` - defines highlighted (coloured) part
//
let colouredLayout = log4js.layouts.layout('pattern',
{ pattern: '%[[%d] [%p] %z %c -%] %m' }
);
//
// define system (general) logger
//
N.logger = log4js.getLogger('system');
//
// provide a wrapper to set global log level
//
N.logger.setLevel = function (level) {
level = log4js.levels[level.toUpperCase()];
log4js.setGlobalLogLevel(level);
};
//
// provide shutdown wrapper
//
N.logger.shutdown = function (cb) {
log4js.shutdown(cb);
};
//
// provide getLogger wrapper
//
N.logger.getLogger = function (name) {
if (channels[name]) return channels[name];
let inputInfo = parseLoggerName(name);
if (!inputInfo) {
N.logger.error('Unacceptable logger channel name <%s>. Using <system>.', name);
return N.logger;
}
// Loggers match rules:
//
// Example loggers: `rpc@foo.bar`, `foo.bar`, `rpc@`
//
// 1. `rpc@foo.bar.baz` -> use logger `rpc@foo.bar`
// 2. `rpc@example` -> use logger `rpc@`
// 3. `foo.bar` -> use logger `foo.bar`
// 4. `foo.bar.baz` -> use logger `foo.bar`
// 5. `example` -> use system logger
//
// Note: loggers already sorted from most specific to most
// general (e.g. 'http@forum.index' comes earlier than 'http@forum').
//
let chosenLogger = _.find(loggers, logger => {
let loggerInfo = parseLoggerName(logger.category);
// Transport (responder) name should be equal (even if null)
if (loggerInfo.responderName !== inputInfo.responderName) return false;
// Reached the end (`rpc@`, `http@`) -> suitable
if (!loggerInfo.splittedMethod) return true;
// API path of logger should be equal with start parts of input API path
if (loggerInfo.splittedMethod && inputInfo.splittedMethod &&
loggerInfo.splittedMethod.length <= inputInfo.splittedMethod.length) {
for (let i = 0; i < loggerInfo.splittedMethod.length; i++) {
if (loggerInfo.splittedMethod[i] !== inputInfo.splittedMethod[i]) return false;
}
return true;
}
return false;
});
if (!chosenLogger) {
N.logger.warn('Logger <%s> not found. Using <system>.', name);
chosenLogger = N.logger;
}
channels[name] = chosenLogger; // cache
return chosenLogger;
};
//
// Load supported appenders
//
log4js.loadAppender('file');
log4js.loadAppender('console');
log4js.loadAppender('clustered');
log4js.loadAppender('logLevelFilter');
//
// clear default loggers
//
log4js.clearAppenders();
function clusteredAppender(children, category) {
let clusterAppenderConfig = {
appenders: [], // configs
actualAppenders: [] // functions
};
children.forEach(appender => {
clusterAppenderConfig.appenders.push({ category });
clusterAppenderConfig.actualAppenders.push(appender);
});
return log4js.appenders.clustered(clusterAppenderConfig);
}
//
// configure console logger for non-production environment only
//
if (logToConsole) {
log4js.addAppender(log4js.appenders.console(colouredLayout));
}
//
// leave only loggers (with appenders) configs, removing keywords
//
delete config.options;
//
// configure logger categories and appenders
//
_.forEach(config, (loggerConfig, name) => {
let appendersInGroup = [];
let groupLevel = log4js.levels.FATAL;
_.forEach(loggerConfig, appenderConfig => {
if (!appenders[appenderConfig.file] && cluster.isMaster) {
let filename = path.resolve(mainRoot, appenderConfig.file);
// make sure destination directory for log file exists
mkdirp(path.dirname(filename));
appenders[appenderConfig.file] = log4js.appenders.file(
filename, // filename
plainLayout, // layout
options.file.logSize * 1024 * 1024, // logSize
options.file.backups // numBackups
);
}
let myLevel = baseLevel;
if (appenderConfig.level) {
myLevel = log4js.levels.toLevel(appenderConfig.level, baseLevel);
// get upper threshold
myLevel = myLevel.isGreaterThanOrEqualTo(baseLevel) ? myLevel : baseLevel;
}
// return thresholded appender
let appender = log4js.appenders.logLevelFilter(myLevel, log4js.levels.FATAL, appenders[appenderConfig.file]);
appendersInGroup.push(appender);
groupLevel = groupLevel.isGreaterThanOrEqualTo(myLevel) ? myLevel : groupLevel;
});
if (name !== 'system') {
let resultLogger = log4js.getLogger(name);
resultLogger.getLogger = N.logger.getLogger;
// register logger in the internal cache
loggers.push(resultLogger);
}
if (appendersInGroup.length) {
let clustered = clusteredAppender(appendersInGroup, name);
let loglevel = log4js.appenders.logLevelFilter(groupLevel, log4js.levels.FATAL, clustered);
log4js.addAppender(loglevel, name);
}
});
//
// Ensure loggers are placed in order from most specific to most general.
// e.g. 'http@forum.index' comes earlier than 'http@forum'.
//
loggers.sort(function (a, b) {
a = parseLoggerName(a.category);
b = parseLoggerName(b.category);
if (a.splittedMethod && b.splittedMethod) {
// Both loggers have a specified splittedMethod.
if (a.splittedMethod.length < b.splittedMethod.length) {
return 1;
} else if (a.splittedMethod.length > b.splittedMethod.length) {
return -1;
}
// Both loggers have the same splittedMethod length.
if (a.responderName && b.responderName) {
// Both loggers have a specified responderName.
return 0;
}
// Logger which has a responderName is more specific.
return a.responderName ? -1 : 1;
}
// Logger which has a splittedMethod is more specific.
return a.splittedMethod ? -1 : 1;
});
}
// Just check, that you did not forgot to create config file
// Valid config MUST contain "configured: true" string
//
function checkConfig(N) {
if (!N.config.configured) {
throw new Error('No main configuration file (usually: config/application.yml)');
}
}
// Run `init()` method for all registered apps.
// Usually, hooks loading is placed there
//
function initApps(N) {
N.apps = [ N.mainApp ];
// Try load each enabled application and push to the array of loaded apps
_.forEach(N.config.applications, app => {
N.apps.push(new Application(require(getAppName(app))));
});
// Call init on each application
_.forEach(N.apps, app => app.init(N));
}
////////////////////////////////////////////////////////////////////////////////
module.exports = Promise.coroutine(function* (N) {
initScope(N);
initWire(N);
// Load main app config
let mainConfig = loadConfigs(path.join(N.mainApp.root, '/config')) || {};
if (cluster.isMaster) {
// Ensure all required apps installed before read configs
yield installAppsIfMissed(mainConfig.applications || []);
}
initConfig(N, mainConfig);
initLogger(N);
N.logger.info('Loaded config files', N.__startupTimer.elapsed);
let timer = stopwatch();
checkConfig(N);
initApps(N);
//
// Create `N.version_hash` - unique value, that tracks packages
// and configs change. That helps to rebuild cache.
//
// - main dependencies are:
// - routes
// - environment
// - `package.json` for all apps
// - `bundle.yml` for all apps
// - almost all is located in config. So, track all at once via config change.
//
let hasher = crypto.createHash('md5');
hasher.update(JSON.stringify(_.omit(N.config, [ 'logger' ])));
N.apps.forEach(app => {
hasher.update(fs.readFileSync(path.join(app.root, 'package.json'), 'utf-8'));
// `bundle.yml` is not mandatory
try {
hasher.update(fs.readFileSync(path.join(app.root, 'bundle.yml'), 'utf-8'));
} catch (__) {}
});
N.version_hash = hasher.digest('hex');
N.logger.info('Applications intialized', timer.elapsed);
});
| nguyendev/DVMN | Code/DVMN/DoVuiHaiNao/wwwroot/lib/fontello/lib/system/runner/initialize.js | JavaScript | apache-2.0 | 17,413 |
// Generated on 2015-09-12 using
// generator-webapp 1.0.1
'use strict';
// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'
module.exports = function (grunt) {
// Time how long tasks take. Can help when optimizing build times
require('time-grunt')(grunt);
// Automatically load required grunt tasks
require('jit-grunt')(grunt, {
useminPrepare: 'grunt-usemin'
});
// Configurable paths
var config = {
app: 'app',
dist: 'dist'
};
// Define the configuration for all the tasks
grunt.initConfig({
// Project settings
config: config,
// Watches files for changes and runs tasks based on the changed files
watch: {
bower: {
files: ['bower.json'],
tasks: ['wiredep']
},
babel: {
files: ['<%= config.app %>/scripts/{,*/}*.js'],
tasks: ['babel:dist']
},
babelTest: {
files: ['test/spec/{,*/}*.js'],
tasks: ['babel:test', 'test:watch']
},
gruntfile: {
files: ['Gruntfile.js']
},
sass: {
files: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'],
tasks: ['sass:server', 'postcss']
},
styles: {
files: ['<%= config.app %>/styles/{,*/}*.css'],
tasks: ['newer:copy:styles', 'postcss']
}
},
browserSync: {
dev: {
bsFiles: {
src: [
'<%= config.app %>/{,*/}*.html',
'.tmp/styles/{,*/}*.css',
'<%= config.app %>/images/{,*/}*',
'.tmp/scripts/{,*/}*.js'
]
},
options: {
watchTask: true,
proxy: 'localhost:7070',
open: false,
ghostMode: false,
notify: false
}
},
/*options: {
notify: false,
background: true
},
livereload: {
options: {
files: [*/
//'<%= config.app %>/{,*/}*.html',
//'.tmp/styles/{,*/}*.css',
//'<%= config.app %>/images/{,*/}*',
//'.tmp/scripts/{,*/}*.js'
//],
//port: 9000,
/*server: {
baseDir: ['.tmp', config.app],
routes: {
'/bower_components': './bower_components'
}
}
}
},*/
test: {
options: {
port: 9001,
open: false,
logLevel: 'silent',
host: 'localhost',
server: {
baseDir: ['.tmp', './test', config.app],
routes: {
'/bower_components': './bower_components'
}
}
}
},
dist: {
options: {
background: false,
server: '<%= config.dist %>'
}
}
},
// Empties folders to start fresh
clean: {
dist: {
files: [{
dot: true,
src: [
'.tmp',
'<%= config.dist %>/*',
'!<%= config.dist %>/.git*'
]
}]
},
server: '.tmp'
},
// Make sure code styles are up to par and there are no obvious mistakes
eslint: {
target: [
'Gruntfile.js',
'<%= config.app %>/scripts/{,*/}*.js',
'!<%= config.app %>/scripts/vendor/*',
'test/spec/{,*/}*.js'
]
},
// Mocha testing framework configuration options
mocha: {
all: {
options: {
run: true,
urls: ['http://<%= browserSync.test.options.host %>:<%= browserSync.test.options.port %>/index.html']
}
}
},
// Compiles ES6 with Babel
babel: {
options: {
sourceMap: true
},
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/scripts',
src: '{,*/}*.js',
dest: '.tmp/scripts',
ext: '.js'
}]
},
test: {
files: [{
expand: true,
cwd: 'test/spec',
src: '{,*/}*.js',
dest: '.tmp/spec',
ext: '.js'
}]
}
},
// Compiles Sass to CSS and generates necessary files if requested
sass: {
options: {
sourceMap: true,
sourceMapEmbed: true,
sourceMapContents: true,
includePaths: ['.']
},
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
},
server: {
files: [{
expand: true,
cwd: '<%= config.app %>/styles',
src: ['*.{scss,sass}'],
dest: '.tmp/styles',
ext: '.css'
}]
}
},
postcss: {
options: {
map: true,
processors: [
// Add vendor prefixed styles
require('autoprefixer-core')({
browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
})
]
},
dist: {
files: [{
expand: true,
cwd: '.tmp/styles/',
src: '{,*/}*.css',
dest: '.tmp/styles/'
}]
}
},
// Automatically inject Bower components into the HTML file
wiredep: {
app: {
src: ['<%= config.app %>/index.html'],
exclude: ['bootstrap.js'],
ignorePath: /^(\.\.\/)*\.\./
},
sass: {
src: ['<%= config.app %>/styles/{,*/}*.{scss,sass}'],
ignorePath: /^(\.\.\/)+/
}
},
// Renames files for browser caching purposes
filerev: {
dist: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'<%= config.dist %>/images/{,*/}*.*',
'<%= config.dist %>/styles/fonts/{,*/}*.*',
'<%= config.dist %>/*.{ico,png}'
]
}
},
// Reads HTML for usemin blocks to enable smart builds that automatically
// concat, minify and revision files. Creates configurations in memory so
// additional tasks can operate on them
useminPrepare: {
options: {
dest: '<%= config.dist %>'
},
html: '<%= config.app %>/index.html'
},
// Performs rewrites based on rev and the useminPrepare configuration
usemin: {
options: {
assetsDirs: [
'<%= config.dist %>',
'<%= config.dist %>/images',
'<%= config.dist %>/styles'
]
},
html: ['<%= config.dist %>/{,*/}*.html'],
css: ['<%= config.dist %>/styles/{,*/}*.css']
},
// The following *-min tasks produce minified files in the dist folder
imagemin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.{gif,jpeg,jpg,png}',
dest: '<%= config.dist %>/images'
}]
}
},
svgmin: {
dist: {
files: [{
expand: true,
cwd: '<%= config.app %>/images',
src: '{,*/}*.svg',
dest: '<%= config.dist %>/images'
}]
}
},
htmlmin: {
dist: {
options: {
collapseBooleanAttributes: true,
collapseWhitespace: true,
conservativeCollapse: true,
removeAttributeQuotes: true,
removeCommentsFromCDATA: true,
removeEmptyAttributes: true,
removeOptionalTags: true,
// true would impact styles with attribute selectors
removeRedundantAttributes: false,
useShortDoctype: true
},
files: [{
expand: true,
cwd: '<%= config.dist %>',
src: '{,*/}*.html',
dest: '<%= config.dist %>'
}]
}
},
// By default, your `index.html`'s <!-- Usemin block --> will take care
// of minification. These next options are pre-configured if you do not
// wish to use the Usemin blocks.
// cssmin: {
// dist: {
// files: {
// '<%= config.dist %>/styles/main.css': [
// '.tmp/styles/{,*/}*.css',
// '<%= config.app %>/styles/{,*/}*.css'
// ]
// }
// }
// },
// uglify: {
// dist: {
// files: {
// '<%= config.dist %>/scripts/scripts.js': [
// '<%= config.dist %>/scripts/scripts.js'
// ]
// }
// }
// },
// concat: {
// dist: {}
// },
// Copies remaining files to places other tasks can use
copy: {
dist: {
files: [{
expand: true,
dot: true,
cwd: '<%= config.app %>',
dest: '<%= config.dist %>',
src: [
'*.{ico,png,txt}',
'images/{,*/}*.webp',
'{,*/}*.html',
'styles/fonts/{,*/}*.*'
]
}, {
expand: true,
dot: true,
cwd: '.',
src: 'bower_components/bootstrap-sass/assets/fonts/bootstrap/*',
dest: '<%= config.dist %>'
}]
}
},
// Generates a custom Modernizr build that includes only the tests you
// reference in your app
modernizr: {
dist: {
devFile: 'bower_components/modernizr/modernizr.js',
outputFile: '<%= config.dist %>/scripts/vendor/modernizr.js',
files: {
src: [
'<%= config.dist %>/scripts/{,*/}*.js',
'<%= config.dist %>/styles/{,*/}*.css',
'!<%= config.dist %>/scripts/vendor/*'
]
},
uglify: true
}
},
// Run some tasks in parallel to speed up build process
concurrent: {
server: [
'babel:dist',
'sass:server'
],
test: [
'babel'
],
dist: [
'babel',
'sass',
'imagemin',
'svgmin'
]
}
});
grunt.registerTask('serve', 'start the server and preview your app', function (target) {
if (target === 'dist') {
return grunt.task.run(['build', 'browserSync:dist']);
}
grunt.task.run([
'clean:server',
'wiredep',
'concurrent:server',
'postcss',
'browserSync:dev',
'watch'
]);
});
grunt.registerTask('server', function (target) {
grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
grunt.task.run([target ? ('serve:' + target) : 'serve']);
});
grunt.registerTask('test', function (target) {
if (target !== 'watch') {
grunt.task.run([
'clean:server',
'concurrent:test',
'postcss'
]);
}
grunt.task.run([
'browserSync:test',
'mocha'
]);
});
grunt.registerTask('build', [
'clean:dist',
'wiredep',
'useminPrepare',
'concurrent:dist',
'postcss',
'concat',
'cssmin',
'uglify',
'copy:dist',
'modernizr',
'filerev',
'usemin',
'htmlmin'
]);
grunt.registerTask('default', [
'newer:eslint',
'test',
'build'
]);
};
| fmpwizard/owlcrawler | webapp/Gruntfile.js | JavaScript | apache-2.0 | 11,073 |
/*jslint indent: 2, maxlen: 120, vars: true, white: true, plusplus: true, regexp: true, -W051: true, sloppy: true */
/*global require, exports */
////////////////////////////////////////////////////////////////////////////////
/// @brief node helper module "util"
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2010-2013, triAGENS GmbH, Cologne, Germany
///
/// Parts of the code are based on:
///
/// Copyright Joyent, Inc. and other Node contributors.
///
/// Permission is hereby granted, free of charge, to any person obtaining a
/// copy of this software and associated documentation files (the
/// "Software"), to deal in the Software without restriction, including
/// without limitation the rights to use, copy, modify, merge, publish,
/// distribute, sublicense, and/or sell copies of the Software, and to permit
/// persons to whom the Software is furnished to do so, subject to the
/// following conditions:
///
/// The above copyright notice and this permission notice shall be included
/// in all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
/// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
/// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
/// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
/// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
/// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
/// USE OR OTHER DEALINGS IN THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- Module "util"
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// --SECTION-- public functions
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @brief deprected methods
////////////////////////////////////////////////////////////////////////////////
exports.deprecate = function (fn, msg) {
return fn;
};
////////////////////////////////////////////////////////////////////////////////
/// @brief inherits the prototype methods from one constructor into another.
////////////////////////////////////////////////////////////////////////////////
exports.inherits = function (ctor, superCtor) {
ctor.super_ = superCtor;
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
// End:
| morsdatum/ArangoDB | js/node/util.js | JavaScript | apache-2.0 | 3,998 |
#! /usr/local/bin/node
/*jslint node:true */
// loader.js
// ------------------------------------------------------------------
//
// Load JSON collections into an API BaaS organization + app.
//
// created: Thu Feb 5 19:29:44 2015
// last saved: <2017-April-26 09:03:07>
var fs = require('fs'),
path = require('path'),
q = require('q'),
Getopt = require('node-getopt'),
common = require('./lib/common.js'),
_ = require('lodash'),
startTime,
dataDir = path.join('./', 'data'),
usergrid = require('usergrid'),
re1 = new RegExp('\\s{2,}', 'g'),
batchNum = 0,
batchSize = 25,
count = 0,
getopt = new Getopt([
['c' , 'config=ARG', 'the configuration json file, which contains Usergrid/Baas org, app, and credentials'],
['o' , 'org=ARG', 'the Usergrid/BaaS organization.'],
['a' , 'app=ARG', 'the Usergrid/BaaS application.'],
['u' , 'username=ARG', 'app user with permissions to create collections. (only if not using client creds!)'],
['p' , 'password=ARG', 'password for the app user.'],
['i' , 'clientid=ARG', 'clientid for the Baas app. (only if not using user creds!)'],
['s' , 'clientsecret=ARG', 'clientsecret for the clientid.'],
['e' , 'endpoint=ARG', 'the BaaS endpoint (if not https://apibaas-trial.apigee.net)'],
['A' , 'anonymous', 'connect to BaaS anonymously. In lieu of user+pw or client id+secret.'],
['F' , 'file=ARG', 'upload just THIS .json file'],
['v' , 'verbose'],
['h' , 'help']
]).bindHelp();
// monkeypatch ug client to allow batch create.
// http://stackoverflow.com/a/24334895/48082
usergrid.client.prototype.batchCreate = function (type, entities, callback) {
if (!entities.length) { callback(); }
var data = _.map(entities, function(entity) {
var data = (entity instanceof usergrid.entity) ? entity.get() : entity;
return _.omit(data, 'metadata', 'created', 'modified', 'type', 'activated');
});
var options = {
method: 'POST',
endpoint: type,
body: data
};
var self = this;
this.request(options, function (e, data) {
var entities = [];
if (e) {
if (self.logging) { common.logWrite('could not save entities'); }
if (typeof(callback) === 'function') { callback(e, data); }
return;
}
if (data && data.entities) {
entities = _.map(data.entities, function(data) {
var options = {
type: type,
client: self,
uuid: data.uuid,
data: data || {}
};
var entity = new usergrid.entity(options);
entity._json = JSON.stringify(options.data, null, 2);
return entity;
});
}
else {
e = "No data available";
}
if (typeof(callback) === 'function') {
return callback(e, entities);
}
});
};
function postBatch(batch, ugClient, collection, cb) {
var splitTime = new Date(),
value = splitTime - startTime;
batchNum++;
common.logWrite('batch %d', batchNum);
ugClient.batchCreate(collection, batch, function (e, entities) {
cb(e, entities);
});
}
function arrayToChunks(chunkSize, a) {
var chunks = [];
for (var i=0, L=a.length; i<L; i+=chunkSize) {
chunks.push(a.slice(i,i+chunkSize));
}
return chunks;
}
var toBatches = _.curry(arrayToChunks)(batchSize);
function doUploadWork (ugClient, collectionName, data, cb) {
toBatches(data)
.reduce(function(promise, batch) {
return promise.then(function() {
var d = q.defer();
postBatch(batch, ugClient, collectionName,
function(e, data) {
d.resolve({});
});
return d.promise;
});
}, q({}))
.then(function () {
cb(null);
}, function(e) {
cb(e);
});
}
// data.forEach(function(item){
// count++;
// stack.push(item);
// // if (count % 100 === 0) {
// // process.stdout.write('.');
// // }
// if (count % batchSize === 0) {
// //process.stdout.write('.');
// }
// if ((count != data.length) && (count % (100 * batchSize) === 0)) {
// var splitTime = new Date(),
// value = splitTime - startTime;
// common.logWrite(' %d elapsed %s', count, common.elapsedToHHMMSS(value));
// }
// });
//
// if (stack.length > 0) {
// //process.stdout.write('.');
// postBatch(stack, ugClient, collectionName, function(e, data) {
// stack = [];
// cb(null);
// });
// }
function main(args) {
var collection, baasConn, opt = getopt.parse(args);
try {
baasConn = common.processOptions(opt, getopt);
common.logWrite('start');
startTime = new Date();
common.usergridAuth(baasConn, function (e, ugClient){
if (e) {
common.logWrite(JSON.stringify(e, null, 2) + '\n');
process.exit(1);
}
fs.readdir(dataDir, function (err,files){
files.forEach(function(filename) {
if (filename.endsWith('.json')) {
if ( ! opt.options.file || opt.options.file == filename) {
var shortname = filename.split('.json')[0];
console.log('uploading ' + shortname);
var data = JSON.parse(fs.readFileSync(path.join(dataDir, filename), 'utf8'));
doUploadWork(ugClient, shortname, data, function(e) {
var endTime = new Date(), value = endTime - startTime;
common.logWrite('finis');
common.logWrite('elapsed %d: %s', value, common.elapsedToHHMMSS(value));
});
}
}
});
});
});
}
catch (exc1) {
console.log("Exception:" + exc1);
console.log(exc1.stack);
}
}
main(process.argv.slice(2));
| DinoChiesa/EdgeTools | baasLoadExport/loader.js | JavaScript | apache-2.0 | 5,788 |
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import DateTime from 'grommet/components/DateTime';
import Form from 'grommet/components/Form';
import FormField from 'grommet/components/FormField';
import InteractiveExample from '../../../components/InteractiveExample';
const PROPS_SCHEMA = {
format: {
options: [
'M/D/YYYY h:mm a', 'M/D/YYYY', 'D/M/YYYY', 'H:mm:ss', 'h a', 'M/YYYY'
]
},
step: { options: [1, 5] }
};
export default class HeadlineExamplesDoc extends Component {
constructor () {
super();
this._onChange = this._onChange.bind(this);
this._onPropsChange = this._onPropsChange.bind(this);
this.state = { elementProps: {} };
}
_onPropsChange (nextElementProps) {
const { elementProps, value } = this.state;
let nextValue = value;
if (nextElementProps.format !== elementProps.format) {
nextValue = undefined;
}
this.setState({ elementProps: nextElementProps, value: nextValue });
}
_onChange (value) {
this.setState({ value: value });
}
render () {
const { elementProps, value } = this.state;
const element = (
<Form>
<FormField>
<DateTime id="id" name="name" {...elementProps}
onChange={this._onChange} value={value} />
</FormField>
</Form>
);
return (
<InteractiveExample contextLabel='DateTime' contextPath='/docs/date-time'
preamble={`import DateTime from 'grommet/components/DateTime';`}
propsSchema={PROPS_SCHEMA}
element={element}
onChange={this._onPropsChange} />
);
}
};
| grommet/grommet-docs | src/docs/components/date-time/DateTimeExamplesDoc.js | JavaScript | apache-2.0 | 1,653 |
'use strict';
/* global describe, beforeEach, it */
var _ = require('lodash');
var testUtils = require('../util/testUtils');
var NetSimTestUtils = require('../util/netsimTestUtils');
var utils = require('@cdo/apps/utils');
var DataConverters = require('@cdo/apps/netsim/DataConverters');
var NetSimConstants = require('@cdo/apps/netsim/NetSimConstants');
var NetSimGlobals = require('@cdo/apps/netsim/NetSimGlobals');
var NetSimLocalClientNode = require('@cdo/apps/netsim/NetSimLocalClientNode');
var NetSimLogEntry = require('@cdo/apps/netsim/NetSimLogEntry');
var NetSimLogger = require('@cdo/apps/netsim/NetSimLogger');
var NetSimMessage = require('@cdo/apps/netsim/NetSimMessage');
var NetSimRouterNode = require('@cdo/apps/netsim/NetSimRouterNode');
var NetSimWire = require('@cdo/apps/netsim/NetSimWire');
var Packet = require('@cdo/apps/netsim/Packet');
var asciiToBinary = DataConverters.asciiToBinary;
var assert = testUtils.assert;
var assertOwnProperty = testUtils.assertOwnProperty;
var assertTableSize = NetSimTestUtils.assertTableSize;
var BITS_PER_BYTE = NetSimConstants.BITS_PER_BYTE;
var DnsMode = NetSimConstants.DnsMode;
var fakeShard = NetSimTestUtils.fakeShard;
testUtils.setupLocale('netsim');
describe("NetSimRouterNode", function () {
var testShard, addressFormat, packetCountBitWidth, packetHeaderSpec, encoder;
/**
* Concise router creation for test
* @param {RouterRow} [row]
* @returns {NetSimRouterNode}
*/
var makeLocalRouter = function (row) {
return new NetSimRouterNode(testShard, row);
};
/**
* Synchronous router creation on shard for test
* @returns {NetSimRouterNode}
*/
var makeRemoteRouter = function () {
var newRouter;
NetSimRouterNode.create(testShard, function (e, r) {
newRouter = r;
});
assert.isDefined(newRouter, "Failed to create a remote router.");
return newRouter;
};
/**
* Synchronous client creation on shard for test
* @param {string} displayName
* @returns {NetSimLocalClientNode}
*/
var makeRemoteClient = function (displayName) {
var newClient;
NetSimLocalClientNode.create(testShard, displayName, function (e, n) {
newClient = n;
});
assert.isDefined(newClient, "Failed to create a remote client.");
return newClient;
};
/**
* Synchronous refresh for tests
* @param {string} tableName
* @returns {Array}
*/
var getRows = function (tableName) {
var rows;
testShard[tableName].refresh(function () {
rows = testShard[tableName].readAll();
});
return rows;
};
/**
* Synchronous table size counting for tests
* @param {string} tableName
* @returns {number}
*/
var countRows = function (tableName) {
return getRows(tableName).length;
};
/**
* Get the row most recently added to the specified table.
* @param {string} tableName
* @returns {Object}
*/
var getLatestRow = function (tableName) {
var rows = getRows(tableName);
if (rows.length === 0) {
throw new Error("Now rows in " + tableName + ", unable to retrieve latest row.");
}
return rows[rows.length - 1];
};
/**
* Synchronously inspect a property on the first message in the table.
* @param {string} propertyName
* @returns {*}
*/
var getFirstMessageProperty = function (propertyName) {
var messageRows = getRows('messageTable');
if (messageRows.length === 0) {
throw new Error("No rows in message table, unable to check first message.");
}
return new NetSimMessage(testShard, messageRows[0])[propertyName];
};
/**
* Assert if the given property on the first message does not match
* the expected value.
* @param {string} propertyName
* @param {*} expectedValue
*/
var assertFirstMessageProperty = function (propertyName, expectedValue) {
var realValue = getFirstMessageProperty(propertyName);
assert(_.isEqual(realValue, expectedValue),
"Expected first message." + propertyName + " to be " +
expectedValue + ", but got " + realValue);
};
/**
* Retrieve the value of a certain header on the first message in the table.
* Dependent on current message format & encoder settings.
* @param {string} headerType
* @returns {*}
*/
var getFirstMessageHeader = function (headerType) {
var payload = getFirstMessageProperty('payload');
if (Packet.isAddressField(headerType)) {
return encoder.getHeaderAsAddressString(headerType, payload);
} else {
return encoder.getHeaderAsInt(headerType, payload);
}
};
/**
* Assert if the given header on the first message does not match the
* expected value.
* @param {string} headerType
* @param {*} expectedValue
*/
var assertFirstMessageHeader = function (headerType, expectedValue) {
var headerValue = getFirstMessageHeader(headerType);
assert(_.isEqual(headerValue, expectedValue), "Expected first message " +
headerType + " header to be " + expectedValue + ", but got " +
headerValue);
};
/**
* Retrieve the body of the first message in the table. Dependent on the
* current message format and encoder settings.
* @returns {string}
*/
var getFirstMessageAsciiBody = function () {
var payload = getFirstMessageProperty('payload');
return encoder.getBodyAsAscii(payload, BITS_PER_BYTE);
};
/**
* Assert if the body of the first message does not match the expected value.
* @param {string} expectedValue
*/
var assertFirstMessageAsciiBody = function (expectedValue) {
var bodyAscii = getFirstMessageAsciiBody();
assert(_.isEqual(bodyAscii, expectedValue), "Expected first message " +
"body to be '" + expectedValue + "', but got '" + bodyAscii + "'");
};
/**
* Call tick() with an advanced time parameter on the argument until
* no change is detected in the log table.
* @param {NetSimRouterNode|NetSimLocalClientNode} tickable
* @param {number} [startTime] default 1
* @param {number} [timeStep] default 1
* @returns {number} Next tick time after stabilized
*/
var tickUntilLogsStabilize = function (tickable, startTime, timeStep) {
var t = utils.valueOr(startTime, 1);
timeStep = utils.valueOr(timeStep, 1);
var lastLogCount;
do {
lastLogCount = countRows('logTable');
tickable.tick({time: t});
t += timeStep;
} while (countRows('logTable') !== lastLogCount);
return t;
};
/**
* Build a fake message log that can be passed into
* NetSimLocalClientNode.initializeSimulation as the sent or received log,
* and can be used to sense whether a particular message would be passed
* to the sent/received log UI components.
* @returns {{log: Function, getLatest: Function}}
*/
var makeFakeMessageLog = function () {
var archive = [];
return {
log: function (payload) {
archive.push(payload);
},
getLatest: function () {
if (archive.length === 0) {
throw new Error('Nothing has been logged.');
}
return archive[archive.length - 1];
}
};
};
/**
* Set the test-global address format for routers and auto-DNS
* @param {string} newFormat
*/
var setAddressFormat = function (newFormat) {
addressFormat = newFormat;
NetSimGlobals.getLevelConfig().addressFormat = addressFormat;
encoder = new Packet.Encoder(addressFormat, packetCountBitWidth,
packetHeaderSpec);
};
beforeEach(function () {
NetSimLogger.getSingleton().setVerbosity(NetSimLogger.LogLevel.NONE);
NetSimTestUtils.initializeGlobalsToDefaultValues();
// Create a useful default configuration
addressFormat = '4';
packetCountBitWidth = 4;
packetHeaderSpec = [
Packet.HeaderType.FROM_ADDRESS,
Packet.HeaderType.TO_ADDRESS
];
NetSimGlobals.getLevelConfig().addressFormat = addressFormat;
NetSimGlobals.getLevelConfig().packetCountBitWidth = packetCountBitWidth;
NetSimGlobals.getLevelConfig().routerExpectsPacketHeader = packetHeaderSpec;
NetSimGlobals.getLevelConfig().broadcastMode = false;
encoder = new Packet.Encoder(addressFormat, packetCountBitWidth,
packetHeaderSpec);
testShard = fakeShard();
});
it("has expected row structure and default values", function () {
var router = new NetSimRouterNode(testShard);
var row = router.buildRow();
assertOwnProperty(row, 'routerNumber');
assert.isUndefined(row.routerNumber);
assertOwnProperty(row, 'creationTime');
assert.closeTo(row.creationTime, Date.now(), 10);
assertOwnProperty(row, 'dnsMode');
assert.strictEqual(row.dnsMode, DnsMode.NONE);
assertOwnProperty(row, 'dnsNodeID');
assert.isUndefined(row.dnsNodeID);
assertOwnProperty(row, 'bandwidth');
assert.strictEqual(row.bandwidth, 'Infinity');
assertOwnProperty(row, 'memory');
assert.strictEqual(row.memory, 'Infinity');
assertOwnProperty(row, 'randomDropChance');
assert.strictEqual(row.randomDropChance, 0);
});
describe("constructing from a table row", function () {
var routerFromRow;
it("routerNumber", function () {
routerFromRow = makeLocalRouter({ routerNumber: 42 });
assert.equal(42, routerFromRow.routerNumber);
});
it("creationTime", function () {
routerFromRow = makeLocalRouter({ creationTime: 42 });
assert.closeTo(routerFromRow.creationTime, 42, 10);
});
it("dnsMode", function () {
routerFromRow = makeLocalRouter({ dnsMode: DnsMode.AUTOMATIC });
assert.equal(DnsMode.AUTOMATIC, routerFromRow.dnsMode);
});
it("dnsNodeID", function () {
routerFromRow = makeLocalRouter({ dnsNodeID: 42 });
assert.equal(42, routerFromRow.dnsNodeID);
});
it("bandwidth", function () {
routerFromRow = makeLocalRouter({ bandwidth: 1024 });
assert.equal(1024, routerFromRow.bandwidth);
// Special case: Bandwidth should be able to serialize in Infinity
// from the string 'Infinity' in the database.
routerFromRow = makeLocalRouter({ bandwidth: 'Infinity' });
assert.equal(Infinity, routerFromRow.bandwidth);
});
it("memory", function () {
routerFromRow = makeLocalRouter({ memory: 1024 });
assert.equal(1024, routerFromRow.memory);
// Special case: Memory should be able to serialize in Infinity
// from the string 'Infinity' in the database.
routerFromRow = makeLocalRouter({ memory: 'Infinity' });
assert.equal(Infinity, routerFromRow.memory);
});
it("randomDropChance", function () {
routerFromRow = makeLocalRouter({ randomDropChance: 0.1 });
assert.equal(0.1, routerFromRow.randomDropChance);
});
});
describe("static method get", function () {
var err, result, routerID;
var routerA;
beforeEach(function () {
routerA = makeRemoteRouter();
err = undefined;
result = undefined;
routerID = 0;
});
it("returns an Error object when router cannot be found", function () {
NetSimRouterNode.get(routerID, testShard, function (_err, _result) {
err = _err;
result = _result;
});
assert.equal(null, result);
assert(err instanceof Error, "Returned an error object");
assert.equal('Not Found', err.message);
});
it("returns null for error and a NetSimRouterNode when router is found", function () {
routerID = routerA.entityID;
NetSimRouterNode.get(routerID, testShard, function(_err, _result) {
err = _err;
result = _result;
});
assert.equal(null, err);
assert(result instanceof NetSimRouterNode);
assert.equal(routerID, result.entityID);
});
});
describe("getConnections", function () {
var routerA;
beforeEach(function () {
routerA = makeRemoteRouter();
});
it("returns an empty array when no wires are present", function () {
var wires = routerA.getConnections();
assert.isArray(wires);
assert.strictEqual(wires.length, 0);
});
it("returns wires that have a remote end attached to the router", function () {
NetSimWire.create(testShard, {
localNodeID: 0,
remoteNodeID: routerA.entityID
}, function () {});
assert.equal(1, routerA.getConnections().length);
});
it("returns NetSimWire objects", function () {
NetSimWire.create(testShard, {
localNodeID: 0,
remoteNodeID: routerA.entityID
}, function () {});
assert.instanceOf(routerA.getConnections()[0], NetSimWire, "Got a NetSimWire back");
});
it("skips wires that aren't connected to the router", function () {
NetSimWire.create(testShard, {
localNodeID: 0,
remoteNodeID: routerA.entityID,
localHostname: 'theRightOne'
}, function () {});
NetSimWire.create(testShard, {
localNodeID: 0,
remoteNodeID: routerA.entityID + 1,
localHostname: 'theWrongOne'
}, function () {});
// Only get the one wire back.
assert.equal(1, routerA.getConnections().length);
assert.equal('theRightOne', routerA.getConnections()[0].localHostname);
});
});
/**
* Router maximum connections.
* Hard-coded for now, could be level-driven later.
* @type {number}
* @const
*/
var CONNECTION_LIMIT = 6;
describe("acceptConnection", function () {
var routerA;
beforeEach(function () {
routerA = makeRemoteRouter();
});
it("accepts connection if total connections are at or below limit", function () {
for (var wireID = routerA.entityID + 1;
wireID < routerA.entityID + CONNECTION_LIMIT + 1;
wireID++) {
NetSimWire.create(testShard, {
localNodeID: wireID,
remoteNodeID: routerA.entityID,
localAddress: wireID.toString(10)
}, function () {});
}
assertTableSize(testShard, 'wireTable', CONNECTION_LIMIT);
var accepted;
routerA.acceptConnection(null, function (err, isAccepted) {
accepted = isAccepted;
});
assert.isTrue(accepted);
});
it("rejects connection if total connections are beyond limit", function () {
for (var wireID = routerA.entityID + 1;
wireID < routerA.entityID + CONNECTION_LIMIT + 2;
wireID++) {
NetSimWire.create(testShard, {
localNodeID: wireID,
remoteNodeID: routerA.entityID
}, function () {});
}
assertTableSize(testShard, 'wireTable', CONNECTION_LIMIT + 1);
var error, accepted;
routerA.acceptConnection(null, function (err, isAccepted) {
error = err;
accepted = isAccepted;
});
assert.isFalse(accepted);
assert.instanceOf(error, Error);
assert.equal(error.message, 'Too many connections.');
});
it("rejects connection if an address collision exists", function () {
var address = '14.4';
NetSimWire.create(testShard, {
localNodeID: 10,
remoteNodeID: routerA.entityID,
localAddress: address
}, function () {});
NetSimWire.create(testShard, {
localNodeID: 11,
remoteNodeID: routerA.entityID,
localAddress: address
}, function () {});
var error, accepted;
routerA.acceptConnection(null, function (err, isAccepted) {
error = err;
accepted = isAccepted;
});
assert.isFalse(accepted);
assert.instanceOf(error, Error);
assert.equal(error.message, 'Address collision detected.');
});
});
it("numbers created routers in sequence, starting with 1", function () {
var newRouter;
for (var i = 0; i < 128; i++) {
newRouter = makeRemoteRouter();
assert.equal(i + 1, newRouter.getRouterNumber());
}
});
it("numbers routers in sequence in spite of creating client nodes", function () {
var newRouter, newClient;
// Start with a client, since this is the typical scenario on a new shard.
newClient = makeRemoteClient();
assert.equal(1, newClient.entityID);
// The new client probably adds a router.
// The new router does not get entity ID 1, but it does get router ID 1.
newRouter = makeRemoteRouter();
assert.equal(1, newRouter.getRouterNumber());
assert.equal(2, newRouter.entityID);
// Make another router, make sure it's router #2
newRouter = makeRemoteRouter();
assert.equal(2, newRouter.getRouterNumber());
// Make another client
newClient = makeRemoteClient();
assert.equal(4, newClient.entityID);
// Make another router, make sure it's router #3
newRouter = makeRemoteRouter();
assert.equal(3, newRouter.getRouterNumber());
});
describe("address assignment rules", function () {
var routerA;
function makeWire(nodeIDOffset) {
var newWire;
NetSimWire.create(testShard, {
localNodeID: routerA.entityID + nodeIDOffset,
remoteNodeID: routerA.entityID
}, function (e, w) {
newWire = w;
});
return newWire;
}
beforeEach(function () {
routerA = makeRemoteRouter();
});
describe("getting addresses", function () {
var wire1, wire2, wire3;
beforeEach(function () {
NetSimGlobals.setRandomSeed('address assignment test');
wire1 = makeWire(1);
wire2 = makeWire(2);
wire3 = makeWire(3);
assertTableSize(testShard, 'wireTable', 3);
});
describe("in simple four-bit format", function () {
beforeEach(function () {
setAddressFormat('4');
});
it("creates single-number addresses when using single-number address format", function () {
assert.equal('11', routerA.getRandomAvailableClientAddress());
assert.equal('1', routerA.getRandomAvailableClientAddress());
assert.equal('3', routerA.getRandomAvailableClientAddress());
});
it("sets own address as zero", function () {
assert.equal('0', routerA.getAddress());
});
});
describe("in two-part format", function () {
beforeEach(function () {
setAddressFormat('4.4');
});
it("creates two-part addresses where the first part is the router number", function () {
assert.equal(routerA.entityID + '.11', routerA.getRandomAvailableClientAddress());
assert.equal(routerA.entityID + '.1', routerA.getRandomAvailableClientAddress());
assert.equal(routerA.entityID + '.3', routerA.getRandomAvailableClientAddress());
});
it("sets own address as router#.0", function () {
assert.equal(routerA.entityID + '.0', routerA.getAddress());
});
});
describe("in four-part format", function () {
beforeEach(function () {
setAddressFormat('8.8.8.8');
});
it("uses zeros for all except last two parts", function () {
// You get higher random addresses here, because of the larger
// addressable space.
assert.equal('0.0.' + routerA.entityID + '.200', routerA.getRandomAvailableClientAddress());
assert.equal('0.0.' + routerA.entityID + '.7', routerA.getRandomAvailableClientAddress());
assert.equal('0.0.' + routerA.entityID + '.43', routerA.getRandomAvailableClientAddress());
});
it("sets own address as 0.0.router#.0", function () {
assert.equal('0.0.' + routerA.entityID + '.0', routerA.getAddress());
});
});
});
describe("keeping multipart addresses within addressable space", function () {
var routerB, routerC, routerD, routerE;
beforeEach(function () {
routerB = makeRemoteRouter();
routerC = makeRemoteRouter();
routerD = makeRemoteRouter();
routerE = makeRemoteRouter();
});
it("leaves router number unchanged for one-part addresses", function () {
setAddressFormat('4');
var newRouter;
for (var i = 0; i < 128; i++) {
newRouter = makeRemoteRouter();
assert.equal(newRouter.routerNumber, newRouter.getRouterNumber());
assert.equal("0", newRouter.getAddress());
}
});
it("Constrains router number to addressable space", function () {
// Four possible router addresses
setAddressFormat('2.8');
// Initial node starts at routerNumber 1
assert.equal(1, routerA.routerNumber);
assert.equal(1, routerA.getRouterNumber());
assert.equal(2, routerB.routerNumber);
assert.equal(2, routerB.getRouterNumber());
assert.equal(3, routerC.routerNumber);
assert.equal(3, routerC.getRouterNumber());
// At 4 (our assignable space) router number wraps to zero
assert.equal(4, routerD.routerNumber);
assert.equal(0, routerD.getRouterNumber());
// Collisions are possible
assert.equal(5, routerE.routerNumber);
assert.equal(1, routerE.getRouterNumber());
});
it("Wraps router names/IDs to match the router number", function () {
// Four possible router addresses
setAddressFormat('2.8');
// Initial node starts at routerNumber 1
assert.equal(1, routerA.routerNumber);
assert.equal("Router 1", routerA.getDisplayName());
assert.equal("1.0", routerA.getAddress());
assert.equal(2, routerB.routerNumber);
assert.equal("Router 2", routerB.getDisplayName());
assert.equal("2.0", routerB.getAddress());
assert.equal(3, routerC.routerNumber);
assert.equal("Router 3", routerC.getDisplayName());
assert.equal("3.0", routerC.getAddress());
// At 4 (our assignable space) router number and address wrap to zero
assert.equal(4, routerD.routerNumber);
assert.equal("Router 0", routerD.getDisplayName());
assert.equal("0.0", routerD.getAddress());
// Collisions are possible
assert.equal(5, routerE.routerNumber);
assert.equal("Router 1", routerE.getDisplayName());
assert.equal("1.0", routerE.getAddress());
});
});
describe("random address assignment order", function () {
var router, clients;
beforeEach(function () {
router = makeRemoteRouter();
router.maxClientConnections_ = Infinity;
clients = [];
for (var i = 0; i < 16; i++) {
clients[i] = makeRemoteClient('client' + i);
}
});
it("assigns every address in addressable space", function () {
NetSimGlobals.setRandomSeed('Coverage!');
setAddressFormat('4');
// Addressable space is 0-15
// 0 is reserved for the router
// 15 is reserved for the auto-DNS
for (var i = 0; i < 16; i++) {
clients[i].connectToRouter(router);
}
assert.equal('1', clients[0].getAddress());
assert.equal('2', clients[1].getAddress());
assert.equal('3', clients[2].getAddress());
assert.equal('5', clients[3].getAddress());
assert.equal('12', clients[4].getAddress());
assert.equal('11', clients[5].getAddress());
assert.equal('14', clients[6].getAddress());
assert.equal('13', clients[7].getAddress());
assert.equal('7', clients[8].getAddress());
assert.equal('6', clients[9].getAddress());
assert.equal('4', clients[10].getAddress());
assert.equal('8', clients[11].getAddress());
assert.equal('10', clients[12].getAddress());
assert.equal('9', clients[13].getAddress());
// At this point we've exhausted the address space,
// so the address is left "undefined"
// Might want a different behavior in the future for this,
// but low router capacity limits mean this won't happen in
// production, for now.
assert.equal(undefined, clients[14].getAddress());
});
it("can assign addresses in a different order", function () {
NetSimGlobals.setRandomSeed('Variety');
setAddressFormat('4');
for (var i = 0; i < 16; i++) {
clients[i].connectToRouter(router);
}
assert.equal('4', clients[0].getAddress());
assert.equal('10', clients[1].getAddress());
assert.equal('2', clients[2].getAddress());
assert.equal('1', clients[3].getAddress());
assert.equal('3', clients[4].getAddress());
assert.equal('9', clients[5].getAddress());
assert.equal('11', clients[6].getAddress());
assert.equal('6', clients[7].getAddress());
assert.equal('13', clients[8].getAddress());
assert.equal('14', clients[9].getAddress());
assert.equal('12', clients[10].getAddress());
assert.equal('5', clients[11].getAddress());
assert.equal('8', clients[12].getAddress());
assert.equal('7', clients[13].getAddress());
});
it("shrinks addressable space according to address format", function () {
NetSimGlobals.setRandomSeed('Variety');
setAddressFormat('2');
// Two-bit addresses, so four options, and "00" is used by the router.
for (var i = 0; i < 4; i++) {
clients[i].connectToRouter(router);
}
assert.equal('1', clients[0].getAddress());
assert.equal('3', clients[1].getAddress());
assert.equal('2', clients[2].getAddress());
// No more room!
assert.equal(undefined, clients[3].getAddress());
});
it("grows addressable space according to address format", function () {
NetSimGlobals.setRandomSeed('Variety');
setAddressFormat('8');
// 8-bit addresses, so they go up to 255
// We won't try to show every case.
for (var i = 0; i < 4; i++) {
clients[i].connectToRouter(router);
}
assert.equal('69', clients[0].getAddress());
assert.equal('173', clients[1].getAddress());
assert.equal('29', clients[2].getAddress());
});
});
});
it("still simulates/routes after connect-disconnect-connect cycle", function () {
var routerA = makeRemoteRouter();
var clientA = makeRemoteClient();
NetSimGlobals.getLevelConfig().automaticReceive = true;
var time = 1;
var fakeReceivedLog = makeFakeMessageLog();
clientA.initializeSimulation(null, fakeReceivedLog);
var assertLoopbackWorks = function (forClient) {
// Construct a message with a timestamp payload, to ensure calls to
// this method don't conflict with one another.
var headers = encoder.makeBinaryHeaders({ toAddress: forClient.getAddress()});
var payload = encoder.concatenateBinary(headers, new Date().getTime().toString(2));
forClient.sendMessage(payload, function () {});
time = tickUntilLogsStabilize(forClient, time);
assert.equal(payload, fakeReceivedLog.getLatest());
};
clientA.connectToRouter(routerA);
assertLoopbackWorks(clientA);
clientA.disconnectRemote();
clientA.connectToRouter(routerA);
assertLoopbackWorks(clientA);
clientA.disconnectRemote();
clientA.connectToRouter(routerA);
assertLoopbackWorks(clientA);
});
describe("message routing rules", function () {
var routerA, clientA, clientB;
beforeEach(function () {
routerA = makeRemoteRouter();
clientA = makeRemoteClient();
clientB = makeRemoteClient();
// Manually connect nodes
clientA.initializeSimulation(null, null);
clientA.connectToRouter(routerA);
routerA.stopSimulation();
clientB.initializeSimulation(null, null);
clientB.connectToRouter(routerA);
routerA.stopSimulation();
// Tell router to simulate for local node
routerA.initializeSimulation(clientA.entityID);
var addressTable = routerA.getAddressTable();
assert.equal(addressTable.length, 2);
assert.equal(addressTable[0].isLocal, true);
// Make sure router initial time is zero
routerA.tick({time: 0});
});
it("ignores messages sent to itself from other clients", function () {
clientB.sendMessage('00000', function () {});
routerA.tick({time: 1000});
assertTableSize(testShard, 'logTable', 0);
assertFirstMessageProperty('fromNodeID', clientB.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
});
it("ignores messages sent to others", function () {
var from = clientA.entityID;
var to = clientB.entityID;
NetSimMessage.send(
testShard,
{
fromNodeID: from,
toNodeID: to,
simulatedBy: from,
payload: '00000'
},
function () {});
routerA.tick({time: 1000});
assertTableSize(testShard, 'messageTable', 1);
assertTableSize(testShard, 'logTable', 0);
assertFirstMessageProperty('fromNodeID', from);
assertFirstMessageProperty('toNodeID', to);
});
it("does not forward malformed packets", function () {
// Here, the payload gets 'cleaned' down to empty string, then treated
// as zero when parsing the toAddress.
clientA.sendMessage('00000', function () {});
routerA.tick({time: 1000});
assertTableSize(testShard, 'messageTable', 0);
assertTableSize(testShard, 'logTable', 1);
});
it("does not forward packets with no match in the local network", function () {
var payload = encoder.concatenateBinary({
toAddress: '1111',
fromAddress: '1111'
}, '101010101');
clientA.sendMessage(payload, function () {});
routerA.tick({time: 1000});
assertTableSize(testShard, 'messageTable', 0);
assertTableSize(testShard, 'logTable', 1);
});
it("forwards packets when the toAddress is found in the network", function () {
var fromAddress = clientA.getAddress();
var toAddress = clientB.getAddress();
var headers = encoder.makeBinaryHeaders({
toAddress: toAddress,
fromAddress: fromAddress
});
var payload = encoder.concatenateBinary(headers, '101010101');
clientA.sendMessage(payload, function () {});
routerA.tick({time: 1000});
assertTableSize(testShard, 'messageTable', 1);
assertTableSize(testShard, 'logTable', 1);
// Verify that message from/to node IDs are correct
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', clientB.entityID);
});
describe("broadcast mode", function () {
var clientC;
beforeEach(function () {
clientC = makeRemoteClient();
// Put level in broadcast mode
NetSimGlobals.getLevelConfig().broadcastMode = true;
// Stop simulation from earlier setup, hook up new client, restart
// simulation
routerA.stopSimulation();
clientC.initializeSimulation(null, null);
clientC.connectToRouter(routerA);
routerA.stopSimulation();
routerA.initializeSimulation(clientA.entityID);
});
it("forwards all messages it receives to every connected node", function () {
clientA.sendMessage("00001111", function () {});
routerA.tick({time: 1000});
// Router should log having picked up one message
assertTableSize(testShard, 'logTable', 1);
// Message forwarded in triplicate: Back to local, and out to both remotes
assertTableSize(testShard, 'messageTable', 3);
assertFirstMessageProperty('fromNodeID', routerA.entityID);
});
});
describe("Router bandwidth limits", function () {
var fromNodeID, toNodeID, fromAddress, toAddress;
var sendMessageOfSize = function (messageSizeBits) {
var headers = encoder.makeBinaryHeaders({
toAddress: toAddress,
fromAddress: fromAddress
});
var payload = encoder.concatenateBinary(headers,
'0'.repeat(messageSizeBits - encoder.getHeaderLength()));
clientA.sendMessage(payload, function () {});
};
beforeEach(function () {
fromNodeID = clientA.entityID;
toNodeID = routerA.entityID;
fromAddress = clientA.getAddress();
toAddress = clientB.getAddress();
// Establish time baseline of zero
routerA.tick({time: 0});
assertTableSize(testShard, 'logTable', 0);
});
it("requires variable time to forward packets based on bandwidth", function () {
routerA.bandwidth = 1000; // 1 bit / ms
// Router detects message immediately, but does not send it until
// enough time has passed to send the message based on bandwidth
sendMessageOfSize(1008);
// Message still has not been sent at 1007ms
routerA.tick({time: 1007});
assertTableSize(testShard, 'logTable', 0);
// At 1000bps, it should take 1008ms to send 1008 bits
routerA.tick({time: 1008});
assertTableSize(testShard, 'logTable', 1);
});
it("respects bandwidth setting", function () {
// 0.1 bit / ms, so 10ms / bit
routerA.bandwidth = 100;
// This message should be sent at t=200
sendMessageOfSize(20);
// Message is sent at t=200
routerA.tick({time: 199});
assertTableSize(testShard, 'logTable', 0);
routerA.tick({time: 200});
assertTableSize(testShard, 'logTable', 1);
});
it("routes packet on first tick if bandwidth is infinite", function () {
routerA.bandwidth = Infinity;
// Message is detected immediately, though that's not obvious here.
sendMessageOfSize(1008);
// At infinite bandwidth, router forwards message even though zero
// time has passed.
routerA.tick({time: 0});
assertTableSize(testShard, 'logTable', 1);
});
it("routes 'batches' of packets when multiple packets fit in the bandwidth", function () {
routerA.bandwidth = 1000; // 1 bit / ms
// Router should schedule these all as soon as they show up, for
// 40, 80 and 120 ms respectively (due to the 0.1 bit per ms rate)
sendMessageOfSize(40);
sendMessageOfSize(40);
sendMessageOfSize(40);
// On this tick, two messages should get forwarded because enough
// time has passed for them both to be sent given our current bandwidth.
routerA.tick({time: 80});
assertTableSize(testShard, 'logTable', 2);
// On this final tick, the third message should be sent
routerA.tick({time: 120});
assertTableSize(testShard, 'logTable', 3);
});
// This test and the one below it are an interesting case. It may seem
// silly to test skipping the tick to 80, or having it happen at 40, but
// this is exactly what could happen with a very low framerate and/or a
// very high bandwidth.
//
// We use pessimistic estimates so that when we are batching messages we
// are looking at "the very latest this message would be finished
// sending" and we can grab all the messages we are SURE are done.
// Here, we're modeling an expected error; the second message could be
// done at t=80, but it also might not be, so we don't send it yet.
// We only have enough information to be sure it will be done by t=110.
//
// In the next test case, sending the first message at t=40 introduces
// information that reduces our pessimistic estimate for the second
// message to t=80. You might argue that same information exists in
// this first test case, and it does - but it wouldn't if the first
// message was being simulated by a remote client.
it("is pessimistic when scheduling new packets", function () {
routerA.bandwidth = 1000; // 1 bit / ms
// Router 'starts sending' this message now, expected to finish
// at t=40
sendMessageOfSize(40);
// At t=30, we do schedule another message
// You might think this one is scheduled for t=80, but because
// we can't see partial progress from other clients we assume the
// worst and schedule it for t=110 (30 + 40 + 40)
routerA.tick({time: 30});
sendMessageOfSize(40);
// Jumping to t=80, we see that only one message is sent. If we'd
// been using optimistic scheduling, we would have sent both.})
routerA.tick({time: 80});
assertTableSize(testShard, 'logTable', 1);
// At this point the simulation considers rescheduling the next message.
// Its new pessimistic estimate is t=120 (80{now} + 40{size}) but
// we go with the previous estimate of t=110 since it was better.
// At t=110, the second message is sent
routerA.tick({time: 109});
assertTableSize(testShard, 'logTable', 1);
routerA.tick({time: 110});
assertTableSize(testShard, 'logTable', 2);
});
it("normally corrects pessimistic estimates with rescheduling", function () {
routerA.bandwidth = 1000; // 1 bit / ms
// Router 'starts sending' this message now, expected to finish
// at t=40
sendMessageOfSize(40);
// Again, at t=30, we schedule another message
// We schedule pessimistically, for t=110
routerA.tick({time: 30});
sendMessageOfSize(40);
// Unlike the last test, we tick at exactly t=40 and send the first
// message right on schedule.
routerA.tick({time: 39});
assertTableSize(testShard, 'logTable', 0);
routerA.tick({time: 40});
assertTableSize(testShard, 'logTable', 1);
// This triggers a reschedule for the previous message;
// its new pessimistic estimate says that it can be sent at t=80,
// which is better than the previous t=110 estimate.
// At t=80, the second message is sent
routerA.tick({time: 79});
assertTableSize(testShard, 'logTable', 1);
routerA.tick({time: 80});
assertTableSize(testShard, 'logTable', 2);
});
it("adjusts routing schedule when router bandwidth changes", function () {
routerA.bandwidth = 1000; // 1 bit / ms
// Five 100-bit messages, scheduled for t=100-500 respectively.
sendMessageOfSize(100);
sendMessageOfSize(100);
sendMessageOfSize(100);
sendMessageOfSize(100);
sendMessageOfSize(100);
// First message processed at t=100
routerA.tick({time: 99});
assertTableSize(testShard, 'logTable', 0);
routerA.tick({time: 100});
assertTableSize(testShard, 'logTable', 1);
// Advance halfway through processing the second message
routerA.tick({time: 150});
assertTableSize(testShard, 'logTable', 1);
// Increase the router bandwidth
routerA.setBandwidth(10000); // 10 bits / ms
// This triggers a reschedule; since NOW is 150 and each message now
// takes 10 ms to process, the new schedule is:
// 2: 160
// 3: 170
// 4: 180
// 5: 190
// Message 2 processed at t=160
routerA.tick({time: 159});
assertTableSize(testShard, 'logTable', 1);
routerA.tick({time: 160});
assertTableSize(testShard, 'logTable', 2);
// Message 3 processed at t=170
routerA.tick({time: 169});
assertTableSize(testShard, 'logTable', 2);
routerA.tick({time: 170});
assertTableSize(testShard, 'logTable', 3);
// Increase the bandwidth again
routerA.setBandwidth(100000); // 100 bits / ms
// New schedule (NOW=170, 1ms per message)
// 4: 171
// 5: 172
// Message 4 processed at t=171
routerA.tick({time: 170.9});
assertTableSize(testShard, 'logTable', 3);
routerA.tick({time: 171.0});
assertTableSize(testShard, 'logTable', 4);
// Message 5 processed at t=172
routerA.tick({time: 171.9});
assertTableSize(testShard, 'logTable', 4);
routerA.tick({time: 172.0});
assertTableSize(testShard, 'logTable', 5);
});
it("drops packets after ten minutes in the router queue", function () {
routerA.bandwidth = 1; // 1 bit / second
var tenMinutesInBits = 600;
var tenMinutesInMillis = 600000;
// Send a message that will take ten minutes + 1 second to process.
sendMessageOfSize(tenMinutesInBits + 1);
assertTableSize(testShard, 'messageTable', 1);
assertTableSize(testShard, 'logTable', 0);
// At almost ten minutes, the message should still be present
routerA.tick({time: tenMinutesInMillis - 1});
assertTableSize(testShard, 'messageTable', 1);
assertTableSize(testShard, 'logTable', 0);
// At exactly ten minutes, the message should expire and be removed
// and no related logging occurs
routerA.tick({time: tenMinutesInMillis});
assertTableSize(testShard, 'messageTable', 0);
assertTableSize(testShard, 'logTable', 0);
// Thus, just after ten minutes, no message is routed.
routerA.tick({time: tenMinutesInMillis + 1000});
assertTableSize(testShard, 'messageTable', 0);
assertTableSize(testShard, 'logTable', 0);
});
it("smaller packets can expire if backed up behind large ones", function () {
routerA.bandwidth = 1; // 1 bit / second
var oneMinuteInBits = 60;
var oneMinuteInMillis = 60000;
// This message should take nine minutes to process, so it will be sent.
sendMessageOfSize(9 * oneMinuteInBits);
// This one only takes two minutes to process, but because it's behind
// the nine-minute one it will expire
sendMessageOfSize(2 * oneMinuteInBits);
// This one is tiny and should take sixteen seconds, but it will
// also expire since it's after the first two.
sendMessageOfSize(16);
// Initially, all three messages are in the queue
assertTableSize(testShard, 'messageTable', 3);
assertTableSize(testShard, 'logTable', 0);
// At almost ten minutes the first message has been forwarded, and
// the other two are still enqueued.
routerA.tick({time: 10 * oneMinuteInMillis - 1});
assertTableSize(testShard, 'messageTable', 3);
assertTableSize(testShard, 'logTable', 1);
// At exactly ten minutes, messages two and three are expired and deleted.
routerA.tick({time: 10 * oneMinuteInMillis});
assertTableSize(testShard, 'messageTable', 1);
assertTableSize(testShard, 'logTable', 1);
});
it("removing expired packets allows packets further down the queue to be processed sooner", function () {
routerA.bandwidth = 1; // 1 bit / second
var oneMinuteInBits = 60;
var oneMinuteInMillis = 60000;
// These messages will both expire, since before processing of the
// first one completes they will both be over 10 minutes old.
sendMessageOfSize(12 * oneMinuteInBits);
sendMessageOfSize(3 * oneMinuteInBits);
assertTableSize(testShard, 'messageTable', 2);
assertTableSize(testShard, 'logTable', 0);
// Advance to 9 minutes. Nothing has happened yet.
routerA.tick({time: 9 * oneMinuteInMillis});
assertTableSize(testShard, 'messageTable', 2);
assertTableSize(testShard, 'logTable', 0);
// Here we add a 1-minute message. Since the others still exist,
// and we use pessimistic scheduling, this one is initially scheduled
// to finish at (9 + 12 + 3 + 1) = 25 minutes, meaning it would expire
// as well.
sendMessageOfSize(oneMinuteInBits);
assertTableSize(testShard, 'messageTable', 3);
assertTableSize(testShard, 'logTable', 0);
// At 10 minutes, the first two messages expire.
routerA.tick({time: 10 * oneMinuteInMillis});
assertTableSize(testShard, 'messageTable', 1);
assertTableSize(testShard, 'logTable', 0);
routerA.tick({time: 10 * oneMinuteInMillis + 1});
// This SHOULD allow the third message to complete at 11 minutes
// instead of at 25.
routerA.tick({time: 11 * oneMinuteInMillis - 1});
assertTableSize(testShard, 'messageTable', 1);
assertTableSize(testShard, 'logTable', 0);
routerA.tick({time: 11 * oneMinuteInMillis});
assertTableSize(testShard, 'messageTable', 1);
assertTableSize(testShard, 'logTable', 1);
});
});
describe("Router memory limits", function () {
var sendMessageOfSize = function (messageSizeBits) {
var headers = encoder.makeBinaryHeaders({
toAddress: clientB.getAddress(),
fromAddress: clientA.getAddress()
});
var payload = encoder.concatenateBinary(headers,
'0'.repeat(messageSizeBits - encoder.getHeaderLength()));
clientA.sendMessage(payload, function () {});
};
var assertRouterQueueSize = function (expectedQueueSizeBits) {
var queueSize = getRows('messageTable').filter(function (m) {
return m.toNodeID === routerA.entityID;
}).map(function (m) {
return m.base64Payload.len;
}).reduce(function (p, c) {
return p + c;
}, 0);
assert(expectedQueueSizeBits === queueSize, "Expected router queue to " +
"contain " + expectedQueueSizeBits + " bits, but it contained " +
queueSize + " bits");
};
var assertHowManyDropped = function (expectedDropCount) {
var droppedPackets = getRows('logTable').map(function (l) {
return l.status === NetSimLogEntry.LogStatus.DROPPED ? 1 : 0;
}).reduce(function (p, c) {
return p + c;
}, 0);
assert(droppedPackets === expectedDropCount, "Expected that " +
expectedDropCount + " packets would be dropped, " +
"but logs only report " + droppedPackets + " dropped packets");
};
beforeEach(function () {
// Establish time baseline of zero
routerA.tick({time: 0});
routerA.bandwidth = Infinity;
routerA.memory = 64 * 8; // 64 bytes
assertTableSize(testShard, 'logTable', 0);
});
it("allows messages that fit in router memory", function () {
// Exact fit is okay
// Log table is empty because routing is not complete
sendMessageOfSize(64 * 8);
assertTableSize(testShard, 'messageTable', 1);
assertRouterQueueSize(64 * 8);
assertHowManyDropped(0);
});
it("rejects messages that exceed router memory", function () {
// Over by one bit gets dropped!
// Adds a log entry with a "dropped" status, or some such.
sendMessageOfSize(64 * 8 + 1);
assertTableSize(testShard, 'messageTable', 0);
assertRouterQueueSize(0);
assertHowManyDropped(1);
});
it("rejects messages when they would put queue over its limit", function () {
// Three messages: 62 bytes, 2 bytes, 4 bytes
sendMessageOfSize(62 * 8);
sendMessageOfSize(2 * 8);
sendMessageOfSize(4 * 8);
// The second message should JUST fit, the third message should drop
assertTableSize(testShard, 'messageTable', 2);
assertRouterQueueSize(64 * 8);
assertHowManyDropped(1);
});
it("accepts messages queued beyond memory limit if clearing packets ahead" +
"of them allows them to fit in memory", function () {
// Three messages: 4 bytes, 64 bytes, 2 bytes
sendMessageOfSize(4 * 8);
sendMessageOfSize(62 * 8);
sendMessageOfSize(2 * 8);
// The second message should drop, but the third message should fit
// because the second message was dropped.
assertTableSize(testShard, 'messageTable', 2);
assertRouterQueueSize(6 * 8);
assertHowManyDropped(1);
});
it("can drop multiple packets queued beyond memory limit", function () {
sendMessageOfSize(63 * 8);
sendMessageOfSize(2 * 8);
sendMessageOfSize(4 * 8);
sendMessageOfSize(8 * 8);
sendMessageOfSize(16 * 8);
// Only the first message should stay, all the others should drop
assertTableSize(testShard, 'messageTable', 1);
assertRouterQueueSize(63 * 8);
assertHowManyDropped(4);
});
it("drops packets when memory capacity is reduced below queue size", function () {
sendMessageOfSize(16 * 8);
sendMessageOfSize(16 * 8);
sendMessageOfSize(16 * 8);
// All three should fit in our 64-byte memory
assertTableSize(testShard, 'messageTable', 3);
assertRouterQueueSize(48 * 8);
assertHowManyDropped(0);
// Cut router memory in half, to 32 bytes.
routerA.setMemory(32 * 8);
// This should kick the third message out of memory (but the second
// should just barely fit.
assertTableSize(testShard, 'messageTable', 2);
assertRouterQueueSize(32 * 8);
assertHowManyDropped(1);
});
it("can drop multiple packets when memory capacity is reduced below" +
" queue size", function () {
sendMessageOfSize(20 * 8);
sendMessageOfSize(20 * 8);
sendMessageOfSize(8 * 8);
// All three should fit in our 64-byte memory
assertTableSize(testShard, 'messageTable', 3);
assertRouterQueueSize(48 * 8);
assertHowManyDropped(0);
// Cut router memory to 32 bytes.
routerA.setMemory(16 * 8);
// This should kick the first and second messages out of memory, but
// the third message should fit.
assertTableSize(testShard, 'messageTable', 1);
assertRouterQueueSize(8 * 8);
assertHowManyDropped(2);
});
it("getMemoryInUse() reports correct memory usage", function () {
routerA.setMemory(Infinity);
assertRouterQueueSize(0);
assert.equal(0, routerA.getMemoryInUse());
sendMessageOfSize(64 * 8);
assertRouterQueueSize(64 * 8);
assert.equal(64 * 8, routerA.getMemoryInUse());
sendMessageOfSize(8);
sendMessageOfSize(8);
sendMessageOfSize(8);
sendMessageOfSize(8);
sendMessageOfSize(8);
sendMessageOfSize(8);
assertRouterQueueSize(70 * 8);
assert.equal(70 * 8, routerA.getMemoryInUse());
routerA.setMemory(32 * 8);
assertHowManyDropped(1);
assertRouterQueueSize(6 * 8);
assert.equal(6 * 8, routerA.getMemoryInUse());
});
});
describe("Random drop chance", function () {
var sendMessageOfSize = function (messageSizeBits) {
var headers = encoder.makeBinaryHeaders({
toAddress: clientB.getAddress(),
fromAddress: clientA.getAddress()
});
var payload = encoder.concatenateBinary(headers,
'0'.repeat(messageSizeBits - encoder.getHeaderLength()));
clientA.sendMessage(payload, function () {});
};
var sendXMessagesAndTickUntilStable = function (numToSend) {
for (var i = 0; i < numToSend; i++) {
sendMessageOfSize(8);
}
tickUntilLogsStabilize(routerA);
};
var assertHowManyDropped = function (expectedDropCount) {
var droppedPackets = getRows('logTable').map(function (l) {
return l.status === NetSimLogEntry.LogStatus.DROPPED ? 1 : 0;
}).reduce(function (p, c) {
return p + c;
}, 0);
assert(droppedPackets === expectedDropCount, "Expected that " +
expectedDropCount + " packets would be dropped, " +
"but logs only report " + droppedPackets + " dropped packets");
};
beforeEach(function () {
// Establish time baseline of zero
routerA.tick({time: 0});
assertTableSize(testShard, 'logTable', 0);
assert.equal(Infinity, routerA.bandwidth);
assert.equal(Infinity, routerA.memory);
});
it("zero chance drops nothing", function () {
routerA.randomDropChance = 0;
sendXMessagesAndTickUntilStable(10);
assertTableSize(testShard, 'messageTable', 10);
assertHowManyDropped(0);
});
it("100% chance drops everything", function () {
routerA.randomDropChance = 1;
sendXMessagesAndTickUntilStable(10);
assertTableSize(testShard, 'messageTable', 0);
assertHowManyDropped(10);
});
it("50% drops about half", function () {
NetSimGlobals.setRandomSeed('a');
routerA.randomDropChance = 0.5;
sendXMessagesAndTickUntilStable(20);
assertHowManyDropped(9);
});
it("50% drops about half (example two)", function () {
NetSimGlobals.setRandomSeed('b');
routerA.randomDropChance = 0.5;
sendXMessagesAndTickUntilStable(20);
assertHowManyDropped(11);
});
it("10% drops a few", function () {
NetSimGlobals.setRandomSeed('c');
routerA.randomDropChance = 0.1;
sendXMessagesAndTickUntilStable(30);
assertHowManyDropped(2);
});
it("10% drops a few (example two)", function () {
NetSimGlobals.setRandomSeed('d');
routerA.randomDropChance = 0.1;
sendXMessagesAndTickUntilStable(30);
assertHowManyDropped(1);
});
});
describe("Auto-DNS behavior", function () {
var autoDnsAddress;
var sendToAutoDns = function (fromNode, asciiPayload) {
var headers = encoder.makeBinaryHeaders({
toAddress: autoDnsAddress,
fromAddress: fromNode.getAddress()
});
var payload = encoder.concatenateBinary(headers,
asciiToBinary(asciiPayload, BITS_PER_BYTE));
fromNode.sendMessage(payload, function () {});
};
beforeEach(function () {
routerA.setDnsMode(DnsMode.AUTOMATIC);
autoDnsAddress = routerA.getAutoDnsAddress();
routerA.tick({time: 0});
});
it("can round-trip to auto-DNS service and back",function () {
sendToAutoDns(clientA, '');
// No routing has occurred yet; our original message is still in the table.
assertTableSize(testShard, 'logTable', 0);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', clientA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
assertFirstMessageProperty('simulatedBy', clientA.entityID);
assertFirstMessageHeader(Packet.HeaderType.TO_ADDRESS, autoDnsAddress);
assertFirstMessageHeader(Packet.HeaderType.FROM_ADDRESS, clientA.getAddress());
// On first tick (at infinite bandwidth) message should be routed to
// auto-DNS service.
routerA.tick({time: 1});
// That message should look like this:
// fromNodeID : routerA.entityID
// toNodeID : routerA.entityID
// simulatedBy : clientA.entityID
// TO_ADDRESS : autoDnsAddress
// FROM_ADDRESS : clientA.getAddress()
// But on the same tick, the auto-DNS immediately picks up that message
// and generates a response:
assertTableSize(testShard, 'logTable', 1);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
assertFirstMessageProperty('simulatedBy', clientA.entityID);
assertFirstMessageHeader(Packet.HeaderType.TO_ADDRESS, clientA.getAddress());
assertFirstMessageHeader(Packet.HeaderType.FROM_ADDRESS, autoDnsAddress);
// On second tick, router forwards DNS response back to client
routerA.tick({time: 2});
assertTableSize(testShard, 'logTable', 2);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', clientA.entityID);
assertFirstMessageProperty('simulatedBy', clientA.entityID);
assertFirstMessageHeader(Packet.HeaderType.TO_ADDRESS, clientA.getAddress());
assertFirstMessageHeader(Packet.HeaderType.FROM_ADDRESS, autoDnsAddress);
});
it("ignores auto-DNS messages from remote clients", function () {
sendToAutoDns(clientB, '');
// No routing has occurred yet; our original message is still in the table.
assertTableSize(testShard, 'logTable', 0);
assertTableSize(testShard, 'messageTable', 1);
var originalMessages = getRows('messageTable');
routerA.tick({time: 1});
// Still, no routing has occurred
assertTableSize(testShard, 'logTable', 0);
assertTableSize(testShard, 'messageTable', 1);
assert.deepEqual(originalMessages, getRows('messageTable'));
routerA.tick({time: 2});
// Nothing happens when remote node is not being simulated
assertTableSize(testShard, 'logTable', 0);
assertTableSize(testShard, 'messageTable', 1);
assert.deepEqual(originalMessages, getRows('messageTable'));
});
it("produces a usage message for any badly-formed request", function () {
sendToAutoDns(clientA, 'Would you tea for stay like to?');
tickUntilLogsStabilize(routerA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody("Automatic DNS Node" +
"\nUsage: GET hostname [hostname [hostname ...]]");
});
it("responds with NOT_FOUND when it can't find the requested hostname", function () {
sendToAutoDns(clientA, 'GET wagner14');
tickUntilLogsStabilize(routerA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody("wagner14:NOT_FOUND");
});
it("responds to well-formed requests with a matching number of responses", function () {
sendToAutoDns(clientA, 'GET bert ernie');
tickUntilLogsStabilize(routerA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody("bert:NOT_FOUND ernie:NOT_FOUND");
});
it("knows its own hostname and address", function () {
sendToAutoDns(clientA, 'GET dns');
tickUntilLogsStabilize(routerA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody("dns:15");
});
it("knows the router hostname and address", function () {
sendToAutoDns(clientA, 'GET ' + routerA.getHostname());
tickUntilLogsStabilize(routerA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody(routerA.getHostname() + ':0');
});
it("can look up the client addresses by hostname", function () {
sendToAutoDns(clientA, 'GET ' +
clientA.getHostname() + ' ' +
clientB.getHostname());
tickUntilLogsStabilize(routerA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody(
clientA.getHostname() + ':' + clientA.getAddress() + ' ' +
clientB.getHostname() + ':' + clientB.getAddress());
});
});
});
describe("routing to other routers", function () {
var routerA, routerB;
var clientA, clientB;
beforeEach(function () {
routerA = makeRemoteRouter();
routerB = makeRemoteRouter();
clientA = makeRemoteClient();
clientB = makeRemoteClient();
setAddressFormat('4.4');
NetSimGlobals.getLevelConfig().connectedRouters = true;
clientA.initializeSimulation(null, null);
clientB.initializeSimulation(null, null);
clientA.connectToRouter(routerA);
clientB.connectToRouter(routerB);
// Make sure router initial time is zero
routerA.tick({time: 0});
routerB.tick({time: 0});
});
it("inter-router message is dropped when 'connectedRouters' are disabled",
function () {
NetSimGlobals.getLevelConfig().connectedRouters = false;
var packetBinary = encoder.concatenateBinary(
encoder.makeBinaryHeaders({
toAddress: clientB.getAddress(),
fromAddress: clientA.getAddress()
}),
DataConverters.asciiToBinary('wop'));
clientA.sendMessage(packetBinary, function () {});
// t=0; nothing has happened yet
assertTableSize(testShard, 'logTable', 0);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', clientA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
// t=1; router A picks up message, drops it because it won't route
// out of local subnet
clientA.tick({time: 1000});
assertTableSize(testShard, 'logTable', 1);
var logRow = getLatestRow('logTable');
var log = new NetSimLogEntry(testShard, logRow);
assert.equal(routerA.entityID, logRow.nodeID);
assert.equal(NetSimLogEntry.LogStatus.DROPPED, logRow.status);
assert.equal(packetBinary, log.binary);
assertTableSize(testShard, 'messageTable', 0);
});
it("can send a message to another router", function () {
var logRow, log;
// This test reads better with slower routing.
// It lets you see each step, when with Infinite bandwidth you get
// several things happening on one tick, depending on how simulating
// routers are registered with each client.
routerA.setBandwidth(50); // Requires 1 second for routing
routerB.setBandwidth(25); // Requires 2 seconds for routing, buts starts
// on first tick
var packetBinary = encoder.concatenateBinary(
encoder.makeBinaryHeaders({
toAddress: routerB.getAddress(),
fromAddress: clientA.getAddress()
}),
DataConverters.asciiToBinary('flop'));
clientA.sendMessage(packetBinary, function () {});
// t=0; nothing has happened yet
assertTableSize(testShard, 'logTable', 0);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', clientA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
// t=1; router A picks up message, forwards to router B
clientA.tick({time: 1000});
assertTableSize(testShard, 'logTable', 1);
logRow = getLatestRow('logTable');
log = new NetSimLogEntry(testShard, logRow);
assert.equal(routerA.entityID, logRow.nodeID);
assert.equal(NetSimLogEntry.LogStatus.SUCCESS, logRow.status);
assert.equal(packetBinary, log.binary);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', routerB.entityID);
// t=2; router B picks up message, consumes it
clientA.tick({time: 2000});
assertTableSize(testShard, 'logTable', 2);
logRow = getLatestRow('logTable');
log = new NetSimLogEntry(testShard, logRow);
assert.equal(routerB.entityID, logRow.nodeID);
assert.equal(NetSimLogEntry.LogStatus.SUCCESS, logRow.status);
assert.equal(packetBinary, log.binary);
assertTableSize(testShard, 'messageTable', 0);
});
it("can send a message to client on another router", function () {
var logRow, log;
// This test reads better with slower routing.
// It lets you see each step, when with Infinite bandwidth you get
// several things happening on one tick, depending on how simulating
// routers are registered with each client.
routerA.setBandwidth(50); // Requires 1 second for routing
routerB.setBandwidth(25); // Requires 2 seconds for routing, buts starts
// on first tick
var packetBinary = encoder.concatenateBinary(
encoder.makeBinaryHeaders({
toAddress: clientB.getAddress(),
fromAddress: clientA.getAddress()
}),
DataConverters.asciiToBinary('wop'));
clientA.sendMessage(packetBinary, function () {});
// t=0; nothing has happened yet
assertTableSize(testShard, 'logTable', 0);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', clientA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
// t=1; router A picks up message, forwards to router B
clientA.tick({time: 1000});
assertTableSize(testShard, 'logTable', 1);
logRow = getLatestRow('logTable');
log = new NetSimLogEntry(testShard, logRow);
assert.equal(routerA.entityID, logRow.nodeID);
assert.equal(NetSimLogEntry.LogStatus.SUCCESS, logRow.status);
assert.equal(packetBinary, log.binary);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', routerB.entityID);
// t=2; router B picks up message, forwards to client B
clientA.tick({time: 2000});
assertTableSize(testShard, 'logTable', 2);
logRow = getLatestRow('logTable');
log = new NetSimLogEntry(testShard, logRow);
assert.equal(routerB.entityID, logRow.nodeID);
assert.equal(NetSimLogEntry.LogStatus.SUCCESS, logRow.status);
assert.equal(packetBinary, log.binary);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageProperty('fromNodeID', routerB.entityID);
assertFirstMessageProperty('toNodeID', clientB.entityID);
});
it("can make one extra hop", function () {
var routerC = makeRemoteRouter();
NetSimGlobals.getLevelConfig().minimumExtraHops = 1;
NetSimGlobals.getLevelConfig().maximumExtraHops = 1;
// This test reads better with slower routing.
routerA.setBandwidth(50);
routerB.setBandwidth(50);
routerC.setBandwidth(25);
var packetBinary = encoder.concatenateBinary(
encoder.makeBinaryHeaders({
toAddress: clientB.getAddress(),
fromAddress: clientA.getAddress()
}),
DataConverters.asciiToBinary('wop'));
clientA.sendMessage(packetBinary, function () {});
// t=0; nothing has happened yet
assertTableSize(testShard, 'logTable', 0);
assertFirstMessageProperty('fromNodeID', clientA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
assertFirstMessageProperty('extraHopsRemaining', 1);
assertFirstMessageProperty('visitedNodeIDs', []);
// t=1; router A picks up message, forwards to router B
clientA.tick({time: 1000});
assertTableSize(testShard, 'logTable', 1);
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', routerC.entityID);
assertFirstMessageProperty('extraHopsRemaining', 0);
assertFirstMessageProperty('visitedNodeIDs', [routerA.entityID]);
// t=2; router C picks up message, forwards to router B
clientA.tick({time: 2000});
assertTableSize(testShard, 'logTable', 2);
assertFirstMessageProperty('fromNodeID', routerC.entityID);
assertFirstMessageProperty('toNodeID', routerB.entityID);
assertFirstMessageProperty('extraHopsRemaining', 0);
assertFirstMessageProperty('visitedNodeIDs', [routerA.entityID, routerC.entityID]);
// t=3; router B picks up message, forwards to client B
clientA.tick({time: 3000});
assertTableSize(testShard, 'logTable', 3);
assertFirstMessageProperty('fromNodeID', routerB.entityID);
assertFirstMessageProperty('toNodeID', clientB.entityID);
assertFirstMessageProperty('extraHopsRemaining', 0);
assertFirstMessageProperty('visitedNodeIDs', [routerA.entityID, routerC.entityID, routerB.entityID]);
});
it("can make two extra hops", function () {
NetSimGlobals.getLevelConfig().minimumExtraHops = 2;
NetSimGlobals.getLevelConfig().maximumExtraHops = 2;
NetSimGlobals.setRandomSeed('two-hops');
// Introduce another router so there's space for two extra hops.
var routerC = makeRemoteRouter();
var routerD = makeRemoteRouter();
// This test reads better with slower routing.
routerA.setBandwidth(50);
routerB.setBandwidth(50);
routerC.setBandwidth(25);
routerD.setBandwidth(25);
var packetBinary = encoder.concatenateBinary(
encoder.makeBinaryHeaders({
toAddress: clientB.getAddress(),
fromAddress: clientA.getAddress()
}),
DataConverters.asciiToBinary('wop'));
clientA.sendMessage(packetBinary, function () {});
// t=0; nothing has happened yet
assertTableSize(testShard, 'logTable', 0);
assertFirstMessageProperty('fromNodeID', clientA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
assertFirstMessageProperty('extraHopsRemaining', 2);
assertFirstMessageProperty('visitedNodeIDs', []);
// t=1; router A picks up message, forwards to router B
clientA.tick({time: 1000});
assertTableSize(testShard, 'logTable', 1);
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', routerC.entityID);
assertFirstMessageProperty('extraHopsRemaining', 1);
assertFirstMessageProperty('visitedNodeIDs', [
routerA.entityID]);
// t=2; router C picks up message, forwards to router D
clientA.tick({time: 2000});
assertTableSize(testShard, 'logTable', 2);
assertFirstMessageProperty('fromNodeID', routerC.entityID);
assertFirstMessageProperty('toNodeID', routerD.entityID);
assertFirstMessageProperty('extraHopsRemaining', 0);
assertFirstMessageProperty('visitedNodeIDs', [
routerA.entityID, routerC.entityID]);
// t=3; router D picks up message, forwards to router B
clientA.tick({time: 3000});
assertTableSize(testShard, 'logTable', 3);
assertFirstMessageProperty('fromNodeID', routerD.entityID);
assertFirstMessageProperty('toNodeID', routerB.entityID);
assertFirstMessageProperty('extraHopsRemaining', 0);
assertFirstMessageProperty('visitedNodeIDs', [
routerA.entityID, routerC.entityID, routerD.entityID]);
// t=4; router B picks up message, forwards to client B
clientA.tick({time: 4000});
assertTableSize(testShard, 'logTable', 4);
assertFirstMessageProperty('fromNodeID', routerB.entityID);
assertFirstMessageProperty('toNodeID', clientB.entityID);
assertFirstMessageProperty('extraHopsRemaining', 0);
assertFirstMessageProperty('visitedNodeIDs', [
routerA.entityID, routerC.entityID, routerD.entityID, routerB.entityID]);
});
describe("extra hop randomization", function () {
var routerC, routerD, routerE, routerF;
beforeEach(function () {
routerC = makeRemoteRouter();
routerD = makeRemoteRouter();
routerE = makeRemoteRouter();
routerF = makeRemoteRouter();
});
var sendFromAToB = function () {
var packetBinary = encoder.concatenateBinary(
encoder.makeBinaryHeaders({
toAddress: clientB.getAddress(),
fromAddress: clientA.getAddress()
}),
DataConverters.asciiToBinary('wop'));
clientA.sendMessage(packetBinary, function () {});
tickUntilLogsStabilize(clientA);
};
it("uses one order here", function () {
NetSimGlobals.getLevelConfig().minimumExtraHops = 2;
NetSimGlobals.getLevelConfig().maximumExtraHops = 2;
NetSimGlobals.setRandomSeed('two-hops');
sendFromAToB();
assertFirstMessageProperty('visitedNodeIDs', [
routerA.entityID,
routerC.entityID,
routerF.entityID,
routerB.entityID
]);
});
it("uses a different order here", function () {
NetSimGlobals.getLevelConfig().minimumExtraHops = 2;
NetSimGlobals.getLevelConfig().maximumExtraHops = 2;
NetSimGlobals.setRandomSeed('for something completely different');
sendFromAToB();
assertFirstMessageProperty('visitedNodeIDs', [
routerA.entityID,
routerE.entityID,
routerC.entityID,
routerB.entityID
]);
});
it("uses one number of hops here", function () {
NetSimGlobals.getLevelConfig().minimumExtraHops = 0;
NetSimGlobals.getLevelConfig().maximumExtraHops = 3;
NetSimGlobals.setRandomSeed('some random seed');
sendFromAToB();
assertFirstMessageProperty('visitedNodeIDs', [
routerA.entityID,
routerD.entityID,
routerF.entityID,
routerC.entityID,
routerB.entityID
]);
});
it("uses a different number of hops here", function () {
NetSimGlobals.getLevelConfig().minimumExtraHops = 0;
NetSimGlobals.getLevelConfig().maximumExtraHops = 3;
NetSimGlobals.setRandomSeed('second random seed');
sendFromAToB();
assertFirstMessageProperty('visitedNodeIDs', [
routerA.entityID,
routerD.entityID,
routerB.entityID
]);
});
});
it("only makes one extra hop if two would require backtracking", function () {
NetSimGlobals.getLevelConfig().minimumExtraHops = 2;
NetSimGlobals.getLevelConfig().maximumExtraHops = 2;
var routerC = makeRemoteRouter();
// This test reads better with slower routing.
routerA.setBandwidth(50);
routerB.setBandwidth(50);
routerC.setBandwidth(25);
var packetBinary = encoder.concatenateBinary(
encoder.makeBinaryHeaders({
toAddress: clientB.getAddress(),
fromAddress: clientA.getAddress()
}),
DataConverters.asciiToBinary('wop'));
clientA.sendMessage(packetBinary, function () {});
// t=0; nothing has happened yet
assertTableSize(testShard, 'logTable', 0);
assertFirstMessageProperty('fromNodeID', clientA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
assertFirstMessageProperty('extraHopsRemaining', 2);
assertFirstMessageProperty('visitedNodeIDs', []);
// t=1; router A picks up message, forwards to router B
clientA.tick({time: 1000});
assertTableSize(testShard, 'logTable', 1);
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', routerC.entityID);
assertFirstMessageProperty('extraHopsRemaining', 1);
assertFirstMessageProperty('visitedNodeIDs', [routerA.entityID]);
// t=2; router C picks up message, tries to forward to someone other
// than router B but there are no unvisited options;
// forwards to router B anyway.
clientA.tick({time: 2000});
assertTableSize(testShard, 'logTable', 2);
assertFirstMessageProperty('fromNodeID', routerC.entityID);
assertFirstMessageProperty('toNodeID', routerB.entityID);
assertFirstMessageProperty('extraHopsRemaining', 0);
assertFirstMessageProperty('visitedNodeIDs', [routerA.entityID, routerC.entityID]);
// t=3; router B picks up message, forwards to client B
clientA.tick({time: 3000});
assertTableSize(testShard, 'logTable', 3);
assertFirstMessageProperty('fromNodeID', routerB.entityID);
assertFirstMessageProperty('toNodeID', clientB.entityID);
assertFirstMessageProperty('extraHopsRemaining', 0);
assertFirstMessageProperty('visitedNodeIDs', [routerA.entityID, routerC.entityID, routerB.entityID]);
});
describe("full-shard Auto-DNS", function () {
var sendToAutoDnsA = function (fromNode, asciiPayload) {
var headers = encoder.makeBinaryHeaders({
toAddress: routerA.getAutoDnsAddress(),
fromAddress: fromNode.getAddress()
});
var payload = encoder.concatenateBinary(headers,
asciiToBinary(asciiPayload, BITS_PER_BYTE));
fromNode.sendMessage(payload, function () {});
};
beforeEach(function () {
routerA.setDnsMode(DnsMode.AUTOMATIC);
});
it("cannot get addresses out of subnet when whole-shard routing is disabled", function () {
NetSimGlobals.getLevelConfig().connectedRouters = false;
sendToAutoDnsA(clientA, 'GET ' + routerB.getHostname() + ' ' +
clientB.getHostname());
tickUntilLogsStabilize(clientA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody(
routerB.getHostname() + ':NOT_FOUND ' +
clientB.getHostname() + ':NOT_FOUND');
});
it("can get remote router hostname and address", function () {
sendToAutoDnsA(clientA, 'GET ' + routerB.getHostname());
tickUntilLogsStabilize(clientA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody(
routerB.getHostname() + ':' + routerB.getAddress());
});
it("can look up remote client addresses by hostname", function () {
sendToAutoDnsA(clientA, 'GET ' + clientB.getHostname());
tickUntilLogsStabilize(clientA);
assertTableSize(testShard, 'messageTable', 1);
assertFirstMessageAsciiBody(
clientB.getHostname() + ':' + clientB.getAddress());
});
it("can query another router's Auto-DNS", function () {
// Client B should send a request to router A's auto-dns and
// get a response
sendToAutoDnsA(clientB, 'GET ' + clientA.getHostname());
// Note: With unlimited router bandwidth, these operations sometimes
// collapse into a single tick depending on the order in which
// routers are ticked by the client.
// 1. Initial message from client B to router B
assertFirstMessageProperty('fromNodeID', clientB.entityID);
assertFirstMessageProperty('toNodeID', routerB.entityID);
// 2. Message forwarded from router B to router A
clientB.tick({time: 1});
assertFirstMessageProperty('fromNodeID', routerB.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
// 3. Message forwarded from router A to auto-DNS A
// 4. Auto-DNS A generates response back to router A
clientB.tick({time: 2});
assertFirstMessageProperty('fromNodeID', routerA.entityID);
assertFirstMessageProperty('toNodeID', routerA.entityID);
assertFirstMessageAsciiBody(
clientA.getHostname() + ':' + clientA.getAddress());
// 5. Message forwarded from router A to router B
// 6. And forwarded from router B to client B
clientB.tick({time: 3});
assertFirstMessageProperty('fromNodeID', routerB.entityID);
assertFirstMessageProperty('toNodeID', clientB.entityID);
assertFirstMessageAsciiBody(
clientA.getHostname() + ':' + clientA.getAddress());
});
});
});
});
| dillia23/code-dot-org | apps/test/netsim/NetSimRouterNode.js | JavaScript | apache-2.0 | 79,546 |
/*
* Copyright (C) 2013 Google Inc., authors, and contributors <see AUTHORS file>
* Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
* Created By:
* Maintained By:
*/
//= require can.jquery-all
//= require models/cacheable
(function(ns, can) {
can.Model.Cacheable("CMS.Models.Person", {
root_object : "person"
, root_collection : "people"
, findAll : "GET /people.json"
, create : function(params) {
var _params = {
person : {
name : params.name
, email : params.ldap
, company_id : params.company_id
}
};
return $.ajax({
type : "POST"
, "url" : "/people.json"
, dataType : "json"
, data : _params
});
}
, search : function(request, response) {
return $.ajax({
type : "get"
, url : "/people.json"
, dataType : "json"
, data : {s : request.term}
, success : function(data) {
response($.map( data, function( item ) {
return can.extend({}, item.person, {
label: item.person.email
, value: item.person.id
});
}));
}
});
}
}, {
init : function () {
this._super && this._super();
// this.bind("change", function(ev, attr, how, newVal, oldVal) {
// var obj;
// if(obj = CMS.Models.ObjectPerson.findInCacheById(this.id) && attr !== "id") {
// obj.attr(attr, newVal);
// }
// });
var that = this;
this.each(function(value, name) {
if (value === null)
that.removeAttr(name);
});
}
});
can.Model.Cacheable("CMS.Models.ObjectPerson", {
root_object : "object_person"
, root_collection : "object_people"
, create : function(params) {
var _params = {
object_person : {
personable_id : params.xable_id
, person_id : params.person_id
, role : params.role
, personable_type : params.xable_type
}
};
return $.ajax({
type : "POST"
, "url" : "/object_people.json"
, dataType : "json"
, data : _params
});
}
, update : function(id, object) {
var _params = {
object_person : {
personable_id : object.personable_id
, person_id : object.person_id
, role : object.role
, personable_type : object.personable_type
}
};
return $.ajax({
type : "PUT"
, "url" : "/object_people/" + id + ".json"
, dataType : "json"
, data : _params
});
}
, destroy : "DELETE /object_people/{id}.json"
}, {
init : function() {
var _super = this._super;
function reinit() {
var that = this;
typeof _super === "function" && _super.call(this);
this.attr(
"person"
, CMS.Models.Person.findInCacheById(this.person_id)
|| new CMS.Models.Person(this.person && this.person.serialize ? this.person.serialize() : this.person));
this.each(function(value, name) {
if (value === null)
that.removeAttr(name);
});
}
this.bind("created", can.proxy(reinit, this));
reinit.call(this);
}
});
})(this, can);
| alaeddine10/ggrc-core | src/ggrc/assets/javascripts/pbc/person.js | JavaScript | apache-2.0 | 3,636 |
//Initializes all the global html element objects that are often reused.
function initiateGlobals() {
usernameInput = document.getElementById("usernameInput");
messageTextarea = document.getElementById("messageTextarea");
chatBoxDiv = document.getElementById("chatBoxDiv");
fontSelect = document.getElementById('fontSelect');
colorSelect = document.getElementById('colorSelect');
popupBackgroundDiv = document.getElementById('popupBackgroundDiv');
popupSettingsDiv = document.getElementById('popupSettingsDiv');
defaultRoomInput = document.getElementById('defaultRoomInput');
defaultRoomSelect = document.getElementById('defaultRoomSelect');
roomMembersDiv = document.getElementById('roomMembersDiv');
themeSelect = document.getElementById('themeSelect');
incomingColorsCheck = document.getElementById('incomingColorsCheck');
incomingFontCheck = document.getElementById('incomingFontCheck');
roomSearchInput = document.getElementById('roomSearchInput');
roomsList = document.getElementById('roomsList');
iFrame = document.getElementById('iFrame');
bucketSpan = document.getElementById('bucketSpan');
bucketXSpan = document.getElementById('bucketXSpan');
bucketNextSpan = document.getElementById('bucketNextSpan');
bucketInput = document.getElementById('bucketInput');
bucketInputDiv = document.getElementById('bucketInputDiv');
bucketInputSendSpan = document.getElementById('bucketInputSendSpan');
bucketInputXSpan = document.getElementById('bucketInputXSpan');
persistentUsernameCheck = document.getElementById('persistentUsernameCheck');
popupBackgroundDiv = document.getElementById('popupBackgroundDiv');
popupSettingsDiv = document.getElementById('popupSettingsDiv');
cardElements = document.getElementsByClassName('card');
settingsIcon = document.getElementById('settingsIcon');
iconElements = document.getElementsByClassName('icon');
myBody = document.getElementById('myBody');
notificationSoundSpan = document.getElementById("notificationSoundSpan");
myUsername = usernameInput.value;
myFont = fontSelect.value;
myColor = fontSelect.value;
previousMessage = "";
previousUsername = usernameInput.value;
isNewToRoom = true;
window.onfocus = onFocus;
window.onblur = onBlur;
} | atheiman/chatHub | assets/initialize.js | JavaScript | apache-2.0 | 2,219 |
var caf_comp = require('caf_components');
exports.load = function($, spec, name, modules, cb) {
modules = modules || [];
modules.push(module);
caf_comp.load($, spec, name, modules, cb);
};
| cafjs/caf_session | test/hello/main.js | JavaScript | apache-2.0 | 204 |
// Copyright (c) 2017 Intel Corporation. All rights reserved.
//
// 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.
'use strict';
/**
* @class - Class representing a common object in RCL.
* @ignore
*/
class Entity {
constructor(handle, typeClass, qos) {
this._handle = handle;
this._typeClass = typeClass;
this._qos = qos;
}
get handle() {
return this._handle;
}
get qos() {
return this._qos;
}
get typeClass() {
return this._typeClass;
}
}
module.exports = Entity;
| minggangw/rclnodejs-1 | lib/entity.js | JavaScript | apache-2.0 | 1,020 |
/*!
* Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
* Code licensed under the Apache License v2.0.
* For details, see http://www.apache.org/licenses/LICENSE-2.0.
*/
// jQuery to collapse the navbar on scroll
// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
$(document).ready(function () {
$('html, body').stop().animate({
scrollTop: 0
}, 1500, 'easeInOutExpo');
$('.overlay').delay(1000).fadeOut(1200);
new WOW().init();
}); | kaie-n/kaie-n.github.io | lennylah/js/grayscale.js | JavaScript | apache-2.0 | 788 |
angular.module("notesApp.enseignants.controllers", []).controller("EnseignantController", ["$scope", "$modal", "$log", "Enseignant",
function ($scope, $modal, $log, Enseignant) {
var deps = Enseignant.query(function () {
$scope.enseignants = deps;
$scope.totalItems = $scope.enseignants.length;
});
//debut de la pagination
$scope.itemsPerPage = 15;
$scope.currentPage = 1;
// fin de la pagination
$scope.afficherFenetre = function (cle, item) {
var modelInstance = $modal.open({
templateUrl: 'modules/enseignant/views/nouveau.html',
controller: 'EnseignantFenetreController',
controllerAs: 'enseignant',
keyboard: true,
backdrop: false,
resolve: {
element: function () {
var tt = {};
tt.item = item;
tt.cle = cle;
return tt;
}
}
});
modelInstance.result.then(function (resultat) {
var item = resultat.item;
var cle = resultat.cle;
if ((item.id !== undefined) && (cle !== undefined)) {
item.$update(function () {
$scope.enseignants.splice(cle, 1, item);
});
} else {
Enseignant.save(item, function () {
$scope.enseignants.push(item);
});
}
}, function () {
});
};
$scope.supprimerEnseignant = function (cle, item) {
if (confirm("Voulez vous vraiment supprimer cet enseinant ?")) {
Enseignant.remove({
id: item.id
}, function () {
if (cle !== undefined) {
$scope.enseignants.splice(cle, 1);
}
});
}
};
}]).controller("EnseignantFenetreController", ["$scope", "$modalInstance", "element",
function ($scope, $modalInstance, element) {
$scope.element = element.item;
$scope.cle = element.cle;
$scope.valider = function () {
var resultat = {};
resultat.item = $scope.element;
resultat.cle = $scope.cle;
$modalInstance.close(resultat);
};
$scope.cancel = function () {
$modalInstance.dismiss("Cancel");
};
}]);
| infotel-iss/notesBackend | src/main/webapp/modules/enseignant/js/controllers.js | JavaScript | apache-2.0 | 2,613 |
//>>built
define("dojox/editor/plugins/nls/zh/Breadcrumb",{nodeActions:"${nodeName} \u64cd\u4f5c",selectContents:"\u9009\u62e9\u5185\u5bb9",selectElement:"\u9009\u62e9\u5143\u7d20",deleteElement:"\u5220\u9664\u5143\u7d20",deleteContents:"\u5220\u9664\u5185\u5bb9",moveStart:"\u5c06\u5149\u6807\u79fb\u81f3\u5f00\u5934",moveEnd:"\u5c06\u5149\u6807\u79fb\u81f3\u7ed3\u5c3e"});
//# sourceMappingURL=Breadcrumb.js.map | Caspar12/zh.sw | zh.web.site.admin/src/main/resources/static/js/dojo/dojox/editor/plugins/nls/zh/Breadcrumb.js | JavaScript | apache-2.0 | 413 |
'use strict';
var mongoose = require('mongoose');
var Book = new mongoose.Schema({
bookname: {
type: String,
require: true
},
isbn : {
type: String,
require : true
}
createdAt: {
type: Date,
'default': Date.now
}
}, {strict: true});
module.exports = mongoose.model('Book', Book);
| giboow/bibliworld | API/models/book.js | JavaScript | apache-2.0 | 320 |
/*
* Copyright 2012 Amadeus s.a.s.
* 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.
*/
/**
* Script for highlight display
* @class aria.tools.inspector.InspectorDisplayScript
*/
Aria.tplScriptDefinition({
$classpath : 'aria.tools.inspector.InspectorDisplayScript',
$prototype : {
/**
* Highlight a template in the application on mouseover
* @param {Object} event
* @param {Object} template description
*/
tplMouseOver : function (event, template) {
this.moduleCtrl.displayHighlight(template.templateCtxt.getContainerDiv());
this.data.overModuleCtrl = template.moduleCtrl;
this.mouseOver(event);
this._refreshModulesDisplay();
// prevent propagation
event.stopPropagation();
},
/**
* Remove highlight from a template link on mouseout
* @param {Object} event
*/
tplMouseOut : function (event, template) {
// this.moduleCtrl.clearHighlight();
this.data.overModuleCtrl = null;
this.mouseOut(event);
this._refreshModulesDisplay();
// prevent propagation
event.stopPropagation();
},
/**
* Highlight the template associated with a module
* @param {Object} event
* @param {Object} module description
*/
moduleMouseOver : function (event, module) {
this.data.overTemplates = module.outerTemplateCtxts;
this.mouseOver(event);
this._refreshTemplatesDisplay();
// prevent propagation
event.stopPropagation();
},
/**
* Remove for highlights for a module
* @param {Object} event
*/
moduleMouseOut : function (event) {
// this.moduleCtrl.clearHighlight();
this.data.overTemplates = null;
this.mouseOut(event);
this._refreshTemplatesDisplay();
// prevent propagation
event.stopPropagation();
},
/**
* Highlight an element on mouseover
* @param {Object} event
*/
mouseOver : function (event) {
event.target.setStyle("background:#DDDDDD;");
},
/**
* Remove highlight of element on mouseout
* @param {Object} event
*/
mouseOut : function (event) {
event.target.setStyle("");
},
/**
* Display details regarding a given template
* @param {Object} event
* @param {Object} template
*/
selectTemplate : function (event, template) {
this.data.selectedTemplate = template;
this.$refresh();
},
/**
* Display details regarding a given module
* @param {Object} event
* @param {Object} template
*/
selectModule : function (event, module) {
this.data.selectedModule = module;
this.$refresh();
},
/**
* Call the module controller to reload a given template instance
* @param {Object} event
* @param {Object} template
*/
reloadTemplate : function (event, template) {
this.moduleCtrl.reloadTemplate(template.templateCtxt);
},
/**
* Call the module controller to refresh a given template
* @param {Object} event
* @param {Object} template
*/
refreshTemplate : function (event, template) {
this.moduleCtrl.refreshTemplate(template.templateCtxt);
},
/**
* Act on module event
* @param {Object} event
*/
onModuleEvent : function (event) {
if (event.name == "contentChanged") {
this.$refresh();
}
},
/**
* Refresh the list of modules only.
*/
_refreshModulesDisplay : function () {
this.$refresh({
section : "modules"
});
},
/**
* Refresh the list of templates only.
*/
_refreshTemplatesDisplay : function () {
this.$refresh({
section : "templates"
});
}
}
}); | flongo/ariatemplates | src/aria/tools/inspector/InspectorDisplayScript.js | JavaScript | apache-2.0 | 4,847 |
/*!
* Copyright 2014 Apereo Foundation (AF) Licensed under the
* Educational Community 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://opensource.org/licenses/ECL-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.
*/
define(['jquery', 'oae.core', 'jquery.history'], function($, oae) {
return function(uid) {
// The widget container
var $rootel = $('#' + uid);
// Variable that will be used to keep track of the provided page structure
var lhNavigationPages = null;
// Variable that will be used to keep track of the first part of the browser title
// that needs to be set for each page
var baseBrowserTitle = null;
/**
* Render a newly selected page. We first deselect the previously selected page, and then put an active
* marker on the newly selected page in the navigation. Next, the page content associated to that is shown
* (if it has been rendered previously) or rendered.
*/
var renderPage = function() {
// Remove the active indicator on the previously selected page
$('.oae-lhnavigation ul li', $rootel).removeClass('active');
// Get the current page from the History.js state and select it.
var selectedPage = getPage(History.getState().data.page);
// Mark the selected page as active in the left hand navigation
$('.oae-lhnavigation ul li[data-id="' + selectedPage.id + '"]', $rootel).addClass('active');
// Set the browser title
var browserTitle = baseBrowserTitle ? [baseBrowserTitle] : [];
browserTitle.push(selectedPage.title);
oae.api.util.setBrowserTitle(browserTitle);
// Hide the current open page
$('.oae-page > div:not(#lhnavigation-toggle-container)', $rootel).hide();
// Render the page's content. We first check if the page has been rendered before. If that's
// the case, we just show it again. Otherwise, we render the page structure first and render
// all of the widgets
var $pageContainer = $('.oae-page', $rootel);
var $cachedPage = $('div[data-page="' + selectedPage.id + '"]', $pageContainer);
if ($cachedPage.length > 0) {
$cachedPage.show();
} else {
// TODO: We are temporarily allowing the navigation toggle to be displayed in lhnav on some
// pages here because the secondary clip items collapse into it on narrow screens. In the future
// those secondary clips will collapse into the main clip instead. In this case the lhnavigation
// toggle can be completely removed from the lhnavigation.html template because in all other
// views, the lhnavigation toggle is provided by the `listHeader` macro in list.html
$pageContainer.append(oae.api.util.template().render($('#lhnavigation-page-template'), {
'selectedPage': selectedPage
}));
// Collect the widget data into a format that is understood by the widget loader
var widgetData = {};
$.each(selectedPage.layout, function(columnIndex, column) {
$.each(column.widgets, function(widgetIndex, widget) {
if (widget.settings) {
widgetData['lhnavigation-widget-' + (widget.id || widget.name)] = widget.settings;
}
});
});
// Render the widgets and pass in the widget data
oae.api.widget.loadWidgets($pageContainer, false, widgetData);
}
};
/**
* Get the page with a given page id from the provided page structure.
*
* @param {String} pageId Id of the page we want to retrieve from the provided pagestructure
* @return {Object} Object representing the page with the provided page id. If no page with the provided page id can be found, the first page will be returned
*/
var getPage = function(pageId) {
for (var i = 0; i < lhNavigationPages.length; i++) {
if (lhNavigationPages[i].id === pageId) {
return lhNavigationPages[i];
}
}
// Return the first page if no page with the provided id can be found
return lhNavigationPages[0];
};
/**
* Render the left hand navigation based on the structure that has been passed in
* and start listening to click events for the different elements in there.
*
* @param {Object[]} lhNavPages The page navigation structure
* @param {Object[]} [lhNavActions] The action buttons structure
* @param {String} [baseUrl] The current page's base URL. The different page ids will be appended to this to generate the full URL of each page
* @param {Boolean} [showLhNavigationToggle] Whether or not the left hand navigation toggle button should be shown
*/
var setUpNavigation = function(lhNavPages, lhNavActions, baseUrl, showLhNavigationToggle) {
// Render the navigation
var renderedNavigation = oae.api.util.template().render($('#lhnavigation-navigation-template', $rootel), {
'lhNavPages': lhNavPages,
'lhNavActions': lhNavActions,
'baseUrl': baseUrl
});
$('.oae-lhnavigation > ul.nav', $rootel).html(renderedNavigation);
// Render clip actions first
if (lhNavActions && lhNavActions.length) {
setUpNavigationActions();
}
// Show the left hand navigation toggle when required
if (showLhNavigationToggle) {
$('#lhnavigation-toggle-container', $rootel).show();
}
// Extract the currently selected page from the URL by parsing the URL fragment that's
// inside of the current History.js hash. The expected URL structure is `/me/<pageId>[?q=foo]`.
// This will only be executed when the page is loaded.
var loadedUrl = $.url(History.getState().hash);
var pageId = loadedUrl.segment().pop();
var selectedPage = getPage(pageId);
var query = loadedUrl.param().q;
// When the page loads, the History.js state data object will either be empty (when having
// followed a link or entering the URL directly) or will contain the previous state data when
// refreshing the page. This is why we use the URL to determine the initial state. We want
// to replace the initial state with all of the required state data for the requested URL so
// we have the correct state data in all circumstances. Calling the `replaceState` function
// will automatically trigger the statechange event, which will take care of the page rendering.
// for the requested module. However, as the page can already have the History.js state data
// when only doing a page refresh, we need to add a random number to make sure that History.js
// recognizes this as a new state and triggers the `statechange` event.
var data = {
'page': pageId,
'_': Math.random()
};
// Although the `title` and `url` field are optional, we need to enter them as IE9 simply doesn't
// handle their absense very well. We cannot lose any parameters such as the `q` query string
// parameter as IE9 is not able to recover it from its state.
var title = selectedPage.title;
var url = $.url(History.getState().hash).attr('path');
if (query) {
data.query = query;
url += '?q=' + query;
}
// Replace the old state.
History.replaceState(data, title, url);
// Bind the click event
$rootel.on('click', '.oae-lhnavigation ul li[data-id]', function(ev) {
// Only push state when a link other than the active one has been clicked
if (!$(this).hasClass('active')) {
var page = getPage($(this).attr('data-id'));
var data = {'page': page.id};
var title = page.title;
var url = $('a', $(this)).attr('href');
// Push the state and render the selected page
History.pushState(data, title, url);
}
ev.preventDefault();
});
};
/**
* Bind the navigation actions
*/
var setUpNavigationActions = function() {
// Set up the collapsable menu items
$rootel.on('click', '.oae-lhnavigation > ul > li > button', function(ev) {
$(this).next('.lhnavigation-collapsed').toggle({
'duration': 250,
'easing': 'linear'
});
$(this).find('.lhnavigation-caret-container i').toggle();
});
};
/**
* The statechange event will be triggered every time the browser back or forward button
* is pressed or state is pushed/replaced using History.js.
*/
$(window).on('statechange', renderPage);
/**
* Initialise a new left hand navigation structure by triggering event that define the pages
* and actions that need to be rendered in the navigation. In case this widget isn't ready at
* the time when the supplying page sends out its request, we also send out a ready event,
* which allows for the supplying widget to resend its data.
*
* A left hand navigation contains 2 different sections. The first section is a list of action
* buttons that can replace the page clips when the viewport width is too small to render them.
* These actions can also be grouped into collapsible sections. An example array required to
* initiate these action buttons is the following:
*
* [
* {
* 'icon': 'icon-cloud-upload',
* 'title': oae.api.i18n.translate('__MSG__UPLOAD__'),
* 'class': 'oae-trigger-upload'
* },
* {
* 'icon': 'icon-plus-sign',
* 'title': oae.api.i18n.translate('__MSG__CREATE__'),
* 'children': [
* {
* 'icon': 'icon-group',
* 'title': oae.api.i18n.translate('__MSG__GROUP__'),
* 'class': 'oae-trigger-creategroup'
* }
* ]
* }
* ]
*
* Notes:
*
* - `title` is the title of the action button.
* - `icon` is the FontAwesome icon class that preceeds the title of the action button.
* @see http://fontawesome.io/3.2.1/
* - `class` can be used to add one or more CSS classes to the action button. Multiple classes can be
* added by separating them with a space. This can for example be used to add widget triggers to
* an action button.
* - `closeNav` determines whether or not the left hand navigation should be closed when the current
* item is seelcted.
* - `children` is an optional array of action buttons that will be rendered as children of the list item
* it belongs to. Each child item has the same properties as top level items.
*
* The second section is a list of pages. Each of these pages will render one or more widgets when clicked.
* An example array required to initiate these pages is the following:
*
* [
* {
* 'id': 'dashboard',
* 'title': oae.api.i18n.translate('__MSG__RECENT_ACTIVITY__'),
* 'closeNav': true,
* 'icon': 'icon-dashboard',
* 'layout': [
* {
* 'id': 'activity',
* 'width': 'col-md-12',
* 'widgets': [
* 'name': 'activity',
* 'settings': {
* 'context': oae.data.me,
* 'canManage': true
* }
* }
* ]
* }
* ]
* }
* ]
*
* Notes:
*
* - `id` is the page alias that will be used in the url (e.g. /baseUrl/<pageId>).
* - `title` is the title of the navigation item.
* - `icon` is the FontAwesome icon class that preceeds the title of the navigation item.
* @see http://fontawesome.io/3.2.1/
* - `layout` defines the structure of the page that is associated to the navigation item.
* It contains the following properties:
* - `width` defines the page width, leveraging Bootstrap's grid system
* @see http://getbootstrap.com/css/#grid
* - `widgets` defines an array of widgets to be loaded on the page containing the following properties:
* - `id` is the unique id that should be applied to the widget container. If no `id` is provided,
* the widget name will be used instead
* - `name` is the name of the widget to be loaded
* - `settings` is a widget settings object that will be passed into the widget as widget data
*/
$(window).on('oae.trigger.lhnavigation', function(ev, _lhNavigationPages, _lhNavigationActions, _baseUrl, _baseBrowserTitle, _showLhNavigationToggle) {
lhNavigationPages = _lhNavigationPages;
baseBrowserTitle = _baseBrowserTitle;
setUpNavigation(_lhNavigationPages, _lhNavigationActions, _baseUrl, _showLhNavigationToggle);
});
$(window).trigger('oae.ready.lhnavigation');
};
});
| Coenego/avocet-ui | node_modules/oae-core/lhnavigation/js/lhnavigation.js | JavaScript | apache-2.0 | 14,879 |
Polymer({
is: 'pie-chart',
properties: {
title: '',
inputs: {
notify: true,
type: Array,
value: () => {
return [{
input: 'slice',
txt: 'Pick a dimension',
selectedValue: null,
selectedObjs: [],
selectedName: 'label',
uitype: 'single-value',
displayName: 'Diamension',
maxSelectableValues: 1
}, {
input: 'sliceSize',
txt: 'Pick a mesaure',
selectedValue: null,
selectedObjs: [],
selectedName: 'count',
uitype: 'single-value',
displayName: 'Value',
maxSelectableValues: 1
}, {
input: 'sliceSize',
txt: 'Group By',
selectedValue: null,
selectedObjs: [],
selectedName: 'count',
uitype: 'single-value',
displayName: 'Group By',
maxSelectableValues: 1
}];
}
},
area: {
type: Array,
value: () => {
return [{
input: 'height',
txt: 'Height of the chart',
uitype: 'Number',
selectedValue: 500,
callBack: 'chartHeightCb'
}, {
input: 'width',
txt: 'Width of the chart',
uitype: 'Number',
selectedValue: 960
}, {
input: 'marginTop',
txt: 'Top margin',
uitype: 'Number',
selectedValue: 40
}, {
input: 'marginRight',
txt: 'Right margin',
uitype: 'Number',
selectedValue: 10
}, {
input: 'marginBottom',
txt: 'Bottom margin',
uitype: 'Number',
selectedValue: 20
}, {
input: 'marginLeft',
txt: 'Left margin',
uitype: 'Number',
selectedValue: 50
}, {
input: 'innerRadius',
txt: 'Inner Radius',
uitype: 'Number',
selectedValue: 0,
callBack: 'innerRadiusCb'
}];
}
}
},
behaviors: [
PolymerD3.chartBehavior
],
innerRadiusCb: function() {
this.parentG.innerHTML = '';
this.draw();
},
draw: function() {
this.debounce('pieChartDrawDeounce', () => {
let slice = this.inputs[0].selectedValue;
let sliceSize = this.inputs[1].selectedValue;
// if slice exists, it would be an array
if (!slice || !sliceSize) {
return false;
}
let groupBy = this.inputs[2].selectedValue;
slice = slice[0];
sliceSize = sliceSize[0];
let width = this.chartWidth,
height = this.chartHeight,
radius = Math.min(width, height) / 2;
let innerRadius = this.area[6].selectedValue;
let color = d3.scale.category20c();
let arc = d3.svg.arc()
.outerRadius(radius - 10)
.innerRadius(innerRadius);
let labelArc = d3.svg.arc()
.outerRadius(radius - 40)
.innerRadius(radius - 40);
let groupedData;
if (!groupBy) {
groupedData = d3.nest().key(d => d).entries(this.source);
} else {
groupedData = d3.nest().key(d => d[groupBy]).entries(this.source);
}
let pie = d3.layout.pie()
.sort(null)
.value(function(d) {
return d[sliceSize];
});
this.parentG.attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');
let me = this;
if (this.parentG) {
this.parentG.html('');
}
let g = this.parentG.selectAll('.arc')
.data(pie(me.source))
.enter().append('g')
.attr('class', 'arc');
let segments = g.append('path')
.attr('d', arc)
.style('fill', function(d) {
return color(d.data[slice]);
})
.attr('class', 'pie-slice');
// g.append('text')
// .attr('transform', function(d) {
// return 'translate(' + labelArc.centroid(d) + ')';
// })
// .attr('dy', '.35em')
// .text(function(d) {
// return d.data[slice];
// });
let htmlCallback = d => {
// temp. setup to check if grouping works
let gpName = d.data.groupName || d.data[this.inputs[1].selectedValue[0]];
let str = '<table class="pie-tooltip">' +
'<tr>' +
'<td>' + d.data[this.inputs[0].selectedValue] + ',</td>' +
'<td>' + gpName + '</td>' +
'</tr>' +
'</table>';
return str;
};
// attachToolTip: (parentG, elem, customClass, htmlCallback) => {
this.attachToolTip(this.parentG, segments, 'pie-slice', htmlCallback);
}, 400);
//me.makeChartWrap();
}
}); | arunsoman/polymer-d3 | pie-chart/pie-chart.js | JavaScript | apache-2.0 | 4,691 |
/* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
ABOUT THIS NODE.JS EXAMPLE: This example works with the AWS SDK for JavaScript version 3 (v3),
which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at
https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/ses-examples-receipt-rules.html.
Purpose:
ses_createreceiptruleset.js demonstrates how to create an empty Amazon SES rule set.
Inputs (replace in code):
- RULE_SET_NAME
Running the code:
node ses_createreceiptruleset.js
*/
// snippet-start:[ses.JavaScript.rules.createReceiptRuleSetV3]
// Import required AWS SDK clients and commands for Node.js
import {
CreateReceiptRuleSetCommand
} from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";
// Set the parameters
const params = { RuleSetName: "RULE_SET_NAME" }; //RULE_SET_NAME
const run = async () => {
try {
const data = await sesClient.send(new CreateReceiptRuleSetCommand(params));
console.log(
"Success",
data
);
return data; // For unit tests.
} catch (err) {
console.log("Error", err.stack);
}
};
run();
// snippet-end:[ses.JavaScript.rules.createReceiptRuleSetV3]
// For unit tests only.
// module.exports ={run, params};
| awsdocs/aws-doc-sdk-examples | javascriptv3/example_code/ses/src/ses_createreceiptruleset.js | JavaScript | apache-2.0 | 1,343 |
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function GMAP_GET_ADDRESS_OBJECT(address,name,description,img)
{
var obj = new Object();
obj.address=address;
obj.name=name;
obj.description=description;
obj.img=img;
obj.point=null;
obj.found=false;
obj.direction_required=false;
var direction_hint='DIRECTION:';
if(obj.address.toUpperCase().indexOf(direction_hint)==0)
{
obj.address=obj.address.substring(direction_hint.length);
obj.direction_required=true;
}
return obj;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function GMAP_INIT()
{
GMAP_LOAD_MAP_VIEW();
if(!gmap_do_not_load_onload)
GMAP_SET_MAP_ADDRESS(null);
if(GMAP_IS_IE_BROWSER())
document.body.onunload=GUnload;
else
this.onunload=GUnload;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function GMAP_INIT_TRIGGER_SET_ON_LOAD()
{
if(GMAP_IS_IE_BROWSER())
document.body.onload=GMAP_INIT;
else
this.onload=GMAP_INIT;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function gmap_set_address(address)
{
GMAP_SET_MAP_ADDRESS(address);
}
var GMAP_SET_MAP_ADDRESS_timer=null;
var GMAP_SET_MAP_ADDRESS_address=null;
function GMAP_SET_MAP_ADDRESS(address,private)
{
if(typeof private == 'undefined')private=false;
if(GMAP_SET_MAP_ADDRESS_timer!=null)
{
try{if(!private)clearTimeout(GMAP_SET_MAP_ADDRESS_timer);}catch(e){alert(1)}
GMAP_SET_MAP_ADDRESS_timer=null;
}
if((gmap_geocoder==null) || (gmap==null) || GMAP_FETCH_MAP_ADDRESS_POINT_onprocess)
{
GMAP_SET_MAP_ADDRESS_address=address;
GMAP_SET_MAP_ADDRESS_timer=setTimeout("GMAP_SET_MAP_ADDRESS(GMAP_SET_MAP_ADDRESS_address,true)",100);
return;
}
if(address!=null)
{
map_address = new Array();
for(var i=0;i<address.length;i++)
{
map_address[map_address.length]=GMAP_GET_ADDRESS_OBJECT(address[i][0],address[i][1],address[i][2],[i][3]);
}
}
var time_stamp=GMAP_GET_TIME_STAMP();
for(var i=0;i<map_address.length;i++)
{
map_address[i].time_stamp=time_stamp;
}
document.getElementById(gmap_id).style.visibility='hidden';
GMAP_FETCH_MAP_ADDRESS_POINT();
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function GMAP_LOAD_MAP_VIEW()
{
if (GBrowserIsCompatible())
{
gmap = new GMap2(document.getElementById(gmap_id));
if(gmap){}
else return;
GEvent.addListener ( gmap,
'click',
function(overlay, latlng)
{
if((overlay!=null) && (typeof overlay == 'object')) return;
if(typeof gmap_click_event == 'function')
{
var ret = gmap_click_event(latlng.lat(),latlng.lng());
if(ret)
{
var LatLngStr = "Lat = " + latlng.lat() + ", Long = " + latlng.lng();
gmap.openInfoWindow(latlng, LatLngStr);
}
}
}
);
gmap.enableScrollWheelZoom();
//gmap.addControl(new GLargeMapControl()); // a large pan/zoom control used on Google Maps. Appears in the top left corner of the gmap.
//gmap.addControl(new GSmallMapControl()); // a smaller pan/zoom control used on Google Maps. Appears in the top left corner of the gmap.
//gmap.addControl(new GSmallZoomControl()); // a small zoom control (no panning controls) used in the small gmap blowup windows used to display driving directions steps on Google Maps.
//gmap.addControl(new GScaleControl()); // a gmap scale
//gmap.addControl(new GMapTypeControl()); // buttons that let the user toggle between gmap types (such as Map and Satellite)
//gmap.addControl(new GOverviewMapControl()); // a collapsible overview gmap in the corner of the screen
for(var i=0;i<gmap_controls.length;i++)
{
eval('gmap.addControl(new '+gmap_controls[i]+'());');
}
GMAP_DISPLAY_POINT_NOTHING_FOUND();
gmap_geocoder = new GClientGeocoder();
document.getElementById(gmap_id).style.background="";
document.getElementById(gmap_id).style.backgroundColor="#ffffff";
//document.getElementById(gmap_id).style.visibility='hidden';
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function GMAP_DISPLAY_POINT_NOTHING_FOUND()
{
gmap.setCenter(new GLatLng(37.4419, -122.1419), 1);
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| mrinsss/Full-Repo | urbanzing/system/application/libraries/libgmap/codebase/google_map_main.js | JavaScript | apache-2.0 | 5,137 |
/**
* @license
* Copyright 2015 The Lovefield Project Authors. All Rights Reserved.
*
* 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.
*/
goog.setTestOnly();
goog.provide('lf.testing.SmokeTester');
goog.require('goog.Promise');
goog.require('goog.testing.jsunit');
goog.require('lf.TransactionType');
goog.require('lf.backstore.TableType');
goog.require('lf.service');
/**
* Smoke test for the most basic DB operations, Create, Read, Update, Delete.
* @constructor @struct
*
* @param {!lf.Global} global
* @param {!lf.Database} db Must compatible with HR schema's Region table.
*/
lf.testing.SmokeTester = function(global, db) {
/** @private {!lf.Database} */
this.db_ = db;
/** @private {!lf.BackStore} */
this.backStore_ = global.getService(lf.service.BACK_STORE);
/** @private {!lf.schema.Table} */
this.r_ = /** @type {!lf.schema.Table} */ (db.getSchema().table('Region'));
};
/**
* Clears all tables in given DB.
* @return {!IThenable}
*/
lf.testing.SmokeTester.prototype.clearDb = function() {
var tables = this.db_.getSchema().tables();
var deletePromises = tables.map(function(table) {
return this.db_.delete().from(table).exec();
}, this);
return goog.Promise.all(deletePromises);
};
/**
* @typedef {{
* id: !lf.schema.BaseColumn.<string>,
* name: !lf.schema.BaseColumn.<string>
* }}
* @private
*/
var RegionTableType_;
/**
* Smoke test for the most basic DB operations, Create, Read, Update, Delete.
* @return {!IThenable}
*/
lf.testing.SmokeTester.prototype.testCRUD = function() {
var regionRows = this.generateSampleRows_();
var db = this.db_;
// Workaround Closure compiler type checking for dynamic schema creation.
// Closure compiler does not know that "id" and "name" were added at runtime,
// therefore use a typedef to make it think so.
var r = /** @type {!RegionTableType_} */ (this.r_);
/**
* Inserts 5 records to the database.
* @return {!IThenable}
*/
var insertFn = goog.bind(function() {
return db.insert().into(this.r_).values(regionRows).exec();
}, this);
/**
* Selects all records from the database.
* @return {!IThenable}
*/
var selectAllFn = goog.bind(function() {
return db.select().from(this.r_).exec();
}, this);
/**
* Selects some records from the databse.
* @param {!Array<string>} ids
* @return {!IThenable}
*/
var selectFn = goog.bind(function(ids) {
return db.select().from(this.r_).where(r.id.in(ids)).exec();
}, this);
/**
* Upadates the 'name' field of two specific rows.
* @return {!IThenable}
*/
var updateFn = goog.bind(function() {
return db.update(this.r_).
where(r.id.in(['1', '2'])).
set(r.name, 'Mars').exec();
}, this);
/**
* Updates two specific records by replacing the entire row.
* @return {!IThenable}
*/
var replaceFn = goog.bind(function() {
var regionRow0 = this.r_.createRow({id: '1', name: 'Venus' });
var regionRow1 = this.r_.createRow({id: '2', name: 'Zeus' });
return db.insertOrReplace().
into(this.r_).
values([regionRow0, regionRow1]).exec();
}, this);
/**
* Deletes two specific records from the database.
* @return {!IThenable}
*/
var deleteFn = goog.bind(function() {
return db.delete().from(this.r_).where(r.id.in(['4', '5'])).exec();
}, this);
return insertFn().then(function() {
return selectFn(['1', '5']);
}).then(function(results) {
assertEquals(2, results.length);
assertObjectEquals({id: '1', name: 'North America'}, results[0]);
assertObjectEquals({id: '5', name: 'Southern Europe'}, results[1]);
return selectAllFn();
}).then(function(results) {
assertEquals(regionRows.length, results.length);
return updateFn();
}).then(function() {
return selectFn(['1', '2']);
}).then(function(results) {
assertObjectEquals({id: '1', name: 'Mars'}, results[0]);
assertObjectEquals({id: '2', name: 'Mars'}, results[1]);
return replaceFn();
}).then(function() {
return selectFn(['1', '2']);
}).then(function(results) {
assertObjectEquals({id: '1', name: 'Venus'}, results[0]);
assertObjectEquals({id: '2', name: 'Zeus'}, results[1]);
}).then(function() {
return deleteFn();
}).then(function() {
return selectAllFn();
}).then(function(result) {
assertEquals(regionRows.length - 2, result.length);
});
};
/**
* Tests that queries that have overlapping scope are processed in a serialized
* manner.
* @return {!IThenable}
*/
lf.testing.SmokeTester.prototype.testOverlappingScope_MultipleInserts =
function() {
// TODO(arthurhsu): add a new test case to test failure case.
var rowCount = 3;
var rows = this.generateSampleRowsWithSamePrimaryKey_(3);
var db = this.db_;
var r = this.r_;
// Issuing multiple queries back to back (no waiting on the previous query to
// finish). All rows to be inserted have the same primary key.
var promises = rows.map(
function(row) {
return db.insertOrReplace().into(r).values([row]).exec();
});
return goog.Promise.all(promises).then(goog.bind(function() {
// The fact that this success callback executes is already a signal that
// no exception was thrown during update of primary key index, which
// proves that all insertOrReplace queries where not executed
// simultaneously, instead the first query inserted the row, and
// subsequent queries updated it.
return this.selectAll_();
}, this)).then(function(results) {
// Assert that only one record exists in the DB.
assertEquals(1, results.length);
var retrievedRow = results[0];
// Assert the retrieved row matches the value ordered by the last query.
assertEquals(
'Region' + String(rowCount - 1),
retrievedRow.payload()['name']);
});
};
/**
* Smoke test for transactions.
* @return {!IThenable}
*/
lf.testing.SmokeTester.prototype.testTransaction = function() {
var rows = this.generateSampleRows_();
var r = this.r_;
var db = this.db_;
var tx = db.createTransaction(lf.TransactionType.READ_WRITE);
var insert1 = db.insert().into(r).values(rows.slice(1));
var insert2 = db.insert().into(r).values([rows[0]]);
var resolver = goog.Promise.withResolver();
tx.exec([insert1, insert2]).then(goog.bind(function() {
return this.selectAll_();
}, this)).then(function(results) {
assertEquals(5, results.length);
// Transaction shall not be able to be executed again after committed.
var select = db.select().from(r);
var thrown = false;
try {
tx.exec([select]);
} catch (e) {
thrown = true;
assertEquals(e.code, 107); // 107: Invalid transaction state transition.
}
assertTrue(thrown);
// Invalid query shall be caught in transaction, too.
var select2 = db.select().from(r).from(r);
var tx2 = db.createTransaction(lf.TransactionType.READ_ONLY);
return tx2.exec([select2]);
}).then(function() {
resolver.reject('transaction shall fail');
}, function(e) {
assertEquals(e.code, 515); // 515: from() has already been called.
resolver.resolve();
});
return resolver.promise;
};
/**
* Generates sample records to be used for testing.
* @return {!Array<!lf.Row>}
* @private
*/
lf.testing.SmokeTester.prototype.generateSampleRows_ = function() {
var r = this.r_;
return [
r.createRow({id: '1', name: 'North America' }),
r.createRow({id: '2', name: 'Central America' }),
r.createRow({id: '3', name: 'South America' }),
r.createRow({id: '4', name: 'Western Europe' }),
r.createRow({id: '5', name: 'Southern Europe' })
];
};
/**
* Generates sample records such that all generated rows have the same primary
* key.
* @param {number} count The number of rows to be generated.
* @return {!Array<!lf.Row>}
* @private
*/
lf.testing.SmokeTester.prototype.generateSampleRowsWithSamePrimaryKey_ =
function(count) {
var r = this.r_;
var sampleRows = new Array(count);
for (var i = 0; i < count; i++) {
sampleRows[i] = r.createRow(
//{id: i.toString(), name: 'Region' + i.toString() });
{id: 1, name: 'Region' + i.toString() });
}
return sampleRows;
};
/**
* Selects all entries from the database (skips the cache).
* @return {!IThenable}
* @private
*/
lf.testing.SmokeTester.prototype.selectAll_ = function() {
var r = this.r_;
var tx = this.backStore_.createTx(lf.TransactionType.READ_ONLY, [r]);
return tx.getTable(
r.getName(), goog.bind(r.deserializeRow, r), lf.backstore.TableType.DATA).
get([]);
};
| digital-synapse/lovefield | testing/smoke_tester.js | JavaScript | apache-2.0 | 9,103 |
requirejs(['jquery', 'bootstrap', 'app/spreadsheet_utility', 'app/spreadsheet_equations', 'app/spreadsheet_calculator', 'app/spreadsheet_table'], function($, bootstrap, SpreadsheetUtility, SpreadsheetEquations, SpreadsheetCalculator, SpreadsheetTable) {
// The entire application is namespaced behind this App variable (Singleton)
var App = new function() {
/*
=================================================================
APP VARIABLES
=================================================================
*/
var $spreadsheet = $('#spreadsheet');
var spreadsheet = document.getElementById('spreadsheet');
// Helper class for equation calculator
var spreadsheetEquations = new SpreadsheetEquations();
var equationCalculator = new SpreadsheetCalculator(spreadsheetEquations);
var spreadsheetTable = new SpreadsheetTable();
// Used for formatting cells
var $selectedCell = null;
/*
=================================================================
BUSINESS LOGIC
=================================================================
*/
var setUpSpreadSheetTable = function() {
var size = 50;
spreadsheetTable.createTable(spreadsheet, size, size);
};
/* Listeners */
var onFocusInputListener = function($inputCells) {
// On selection of cell
$inputCells.focus(function() {
$selectedCell = $(this);
// Show equation
var equationAttr = spreadsheetTable.ATTRS.EQUATION;
if (SpreadsheetUtility.hasAttr($selectedCell.attr(equationAttr))) {
$selectedCell.val($selectedCell.attr(equationAttr));
}
});
};
var onEnterKeyListener = function($inputCells) {
$inputCells.keyup(function(e) {
// Enter key
if (e.which == 13) {
$(this).blur();
}
});
};
var onBlurInputListener = function($inputCells) {
// On leaving the cell
$inputCells.blur(function() {
// Save
spreadsheetTable.storeCellData($(this));
// Update equation cells
equationCalculator.calculateAllEquations(spreadsheetTable);
});
};
/* Button Setups */
var setUpReloadButton = function() {
var loadData;
$('#reload-button').click(function() {
// clear data
loadData = $('#spreadsheet tr').detach();
setTimeout(function() {
// Reload the HTML elements
loadData.appendTo($spreadsheet);
}, 50);
});
};
var toggleClassOnButtonClick = function(buttonId, className) {
$(buttonId).click(function() {
if ($selectedCell === null) {
return;
} else if ($selectedCell.hasClass(className)) {
$selectedCell.removeClass(className);
} else {
$selectedCell.addClass(className);
}
});
};
var removeAlignmentClasses = function() {
// alignment classes
var alignClasses = ['align-left','align-center','align-right'];
if ($selectedCell !== null) {
for (var i = 0; i < alignClasses.length; i++) {
$selectedCell.removeClass(alignClasses[i]);
}
}
};
var toggleAlignmentOnButtonClick = function(buttonId, className) {
$(buttonId).click(function() {
if ($selectedCell === null) {
return;
} else {
removeAlignmentClasses();
$selectedCell.addClass(className);
}
});
};
var setUpFormatterButtons = function() {
toggleClassOnButtonClick('#bold-button', 'bold');
toggleClassOnButtonClick('#italics-button', 'italics');
toggleClassOnButtonClick('#underline-button', 'under-line');
};
var setUpAlignmentButtons = function() {
toggleAlignmentOnButtonClick('#align-left-button', 'align-left');
toggleAlignmentOnButtonClick('#align-center-button', 'align-center');
toggleAlignmentOnButtonClick('#align-right-button', 'align-right');
};
/*
=================================================================
APP BUSINESS LOGIC INITIALISATION
=================================================================
*/
var buttonsInit = function() {
setUpReloadButton();
setUpFormatterButtons();
setUpAlignmentButtons();
};
var spreadsheetInit = function() {
setUpSpreadSheetTable();
};
var listenersInit = function() {
var $inputCells = $('.inputCell');
onBlurInputListener($inputCells);
onFocusInputListener($inputCells);
onEnterKeyListener($inputCells);
};
return {
init: function() {
buttonsInit(); // Initialise Buttons
spreadsheetInit(); // Initialise App code
listenersInit(); // Initialise all listeners
}
};
};
/* Initialise app when page loads */
$(function() {
App.init();
});
return App;
}); | haiquangtran/SpreadsheetApp | js/app/spreadsheet_main.js | JavaScript | apache-2.0 | 5,755 |
function boss() {
return {h: 104, d: 8, a: 1};
}
function parse(block) {
var lines = block.split('\n');
return lines.slice(1).map(l=>l.match(/([a-z0-9+]+)[ ]+([0-9]+)[ ]+([0-9]+)[ ]+([0-9]+)/i));
}
var weapons = parse(`Weapons: Cost Damage Armor
Dagger 8 4 0
Shortsword 10 5 0
Warhammer 25 6 0
Longsword 40 7 0
Greataxe 74 8 0`);
var armor = parse(`Armor: Cost Damage Armor
Leather 13 0 1
Chainmail 31 0 2
Splintmail 53 0 3
Bandedmail 75 0 4
Platemail 102 0 5`).concat(null);
var rings = parse(`Rings: Cost Damage Armor
Damage1 25 1 0
Damage2 50 2 0
Damage3 100 3 0
Defens1 20 0 1
Defense2 40 0 2
Defense3 80 0 3`).concat(null).concat(null);
function fight(player, boss) {
var hp = Math.max(1,player.d-boss.a);
var bp = Math.max(1,boss.d-player.a);
while(player.h>0&&boss.h>0) {
boss.h -= Math.max(1,player.d-boss.a);
player.h -= Math.max(1,boss.d-player.a);
}
if (boss.h<=0) {
return true;
} return false;
}
function sum(items) {
var player = {h:100, d:0, a:0, c:0}
items.forEach(it=>{
if (it!=null) {
player.d+=Number(it[3]);
player.a+=Number(it[4]);
player.c+=Number(it[2]);
}
});
return player;
}
function solve() {
var cost = Infinity;
var pack = null;
weapons.forEach(w=>{
armor.forEach(a=>{
rings.forEach(r1=>{
rings.forEach(r2=>{
if (r1!=r2||r1==null) {
var xp = [w,a,r1,r2];
var pl = sum(xp);
if (fight(pl,boss())) {
cost = Math.min(cost,pl.c);
if (cost==pl.c) {
console.log(sum(xp));
pack = (xp.map(x=>x!=null?x[1]:" ").join(' '));
console.log(pack);
}
}
}
});
});
});
});
return cost;
}
function solve2() {
var cost = 0;
var pack = null;
weapons.forEach(w=>{
armor.forEach(a=>{
rings.forEach(r1=>{
rings.forEach(r2=>{
if (r1!=r2||r1==null) {
var xp = [w,a,r1,r2];
var pl = sum(xp);
if (!fight(pl,boss())) {
cost = Math.max(cost,pl.c);
if (cost==pl.c) {
console.log(sum(xp));
pack = (xp.map(x=>x!=null?x[1]:" ").join(' '));
console.log(pack);
}
}
}
});
});
});
});
return cost;
}
//console.log(fight({h:100, d: 0, a:0}, {h: 104, d: 8, a: 1}));
console.log(solve());
console.log(solve2());
| farafonoff/Advent2016 | 2015/Puzzle21/01.js | JavaScript | apache-2.0 | 2,769 |
var allTestFiles = [];
// var TEST_REGEXP = /test.*\.js$/;
var TEST_REGEXP = /.*Spec\.js$/;
Object.keys(window.__karma__.files).forEach(function(file) {
if (TEST_REGEXP.test(file)) {
allTestFiles.push(file);
}
});
var dojoConfig = {
packages: [
{
name:"spec",
location:"/base/test/spec"
}, {
name:"weighted-overlay-modeler",
location:"/base/src/lib/weighted-overlay-modeler"
}, {
name: 'esri',
location: 'http://js.arcgis.com/3.10/js/esri'
}, {
name: 'dojo',
location: 'http://js.arcgis.com/3.10/js/dojo/dojo'
}, {
name: 'dojox',
location: 'http://js.arcgis.com/3.10/js/dojo/dojox'
}, {
name: 'dijit',
location: 'http://js.arcgis.com/3.10/js/dojo/dijit'
}
],
async: true
};
/**
* This function must be defined and is called back by the dojo adapter
* @returns {string} a list of dojo spec/test modules to register with your testing framework
*/
window.__karma__.dojoStart = function(){
return allTestFiles;
} | Esri/landscape-modeler-js | test/spec/main.js | JavaScript | apache-2.0 | 1,148 |
export default class CreateReferendum {
constructor(referendumId, name, proposal, options) {
this.referendumId = referendumId;
this.name = name; // mandatory
this.proposal = proposal; // mandatory
this.options = options; // mandatory
}
}; | kmalakoff/nota | src/commands/CreateReferendum.js | JavaScript | apache-2.0 | 259 |
const path = require('path');
const fs = require('fs');
const request = require('request');
const cachedRequest = require('cached-request')(request)
function resolveUrls(urls, callback) {
// console.log('resolveUrls', urls);
Promise.all(urls.map((url, idx) => {
return new Promise((resolve, reject) => {
const options = {
url: url,
ttl: 3600000 //3 seconds
};
cachedRequest(options, (error, response, body) => {
if (error) {
reject(error);
} else {
// console.log(options.url);
resolve(`// loaded from ${url}\nmodule.exports = ${JSON.stringify({
url: url,
body: body.toString()
})};`);
}
});
})
}))
.then((bodies) => callback(null, bodies))
.catch((error) => callback(error, null));
}
function loader(content) {
// console.log(path.resolve(__dirname, 'dist'));
cachedRequest.setCacheDirectory(
path.join(path.resolve(__dirname), '.dice-req-cache')
);
const callback = this.async();
if (!callback) {
throw 'there is no sync resolver';
}
const urls = content.
split(/[\n\r]+/).
map(i => i.replace(/^\s+|\s+$/g, '')).
filter(i => i.length)
resolveUrls(urls, (err, resolved) => {
callback(err, resolved.join('\n'))
});
}
loader.testLoader = function(stopWebPack) {
return new Promise((rs, rj) => {
loader.apply({
async: () => { return function(_err, js) {
eval(js);
rs(module.exports);
}; },
}, [fs.readFileSync(require.resolve(stopWebPack)).toString()]);
});
}
module.exports = loader;
// module.exports.raw = true;
// module.exports.pitch = function(remainingRequest, precedingRequest, data) {
// console.log('>>>>>>>>>>>>pitch:', remainingRequest, precedingRequest, data);
// data.value = 42;
// };
| mabels/clavator | src/server/dispatcher/dice-ware-loader.js | JavaScript | apache-2.0 | 1,840 |
/*jshint strict: false */
/*global chrome */
var merge = require('./merge');
exports.extend = require('pouchdb-extend');
exports.ajax = require('./deps/ajax');
exports.createBlob = require('./deps/binary/blob'); // TODO: don't export this
exports.uuid = require('./deps/uuid');
exports.getArguments = require('argsarray');
var EventEmitter = require('events').EventEmitter;
var collections = require('pouchdb-collections');
exports.Map = collections.Map;
exports.Set = collections.Set;
var parseDoc = require('./deps/docs/parseDoc');
var Promise = require('./deps/promise');
exports.Promise = Promise;
var base64 = require('./deps/binary/base64');
// TODO: don't export these
exports.atob = base64.atob;
exports.btoa = base64.btoa;
var binStringToBlobOrBuffer =
require('./deps/binary/binaryStringToBlobOrBuffer');
// TODO: only used by the integration tests
exports.binaryStringToBlobOrBuffer = binStringToBlobOrBuffer;
exports.lastIndexOf = function (str, char) {
for (var i = str.length - 1; i >= 0; i--) {
if (str.charAt(i) === char) {
return i;
}
}
return -1;
};
exports.clone = function (obj) {
return exports.extend(true, {}, obj);
};
// like underscore/lodash _.pick()
function pick(obj, arr) {
var res = {};
for (var i = 0, len = arr.length; i < len; i++) {
var prop = arr[i];
if (prop in obj) {
res[prop] = obj[prop];
}
}
return res;
}
exports.pick = pick;
exports.inherits = require('inherits');
function isChromeApp() {
return (typeof chrome !== "undefined" &&
typeof chrome.storage !== "undefined" &&
typeof chrome.storage.local !== "undefined");
}
// Pretty dumb name for a function, just wraps callback calls so we dont
// to if (callback) callback() everywhere
exports.call = exports.getArguments(function (args) {
if (!args.length) {
return;
}
var fun = args.shift();
if (typeof fun === 'function') {
fun.apply(this, args);
}
});
exports.filterChange = function filterChange(opts) {
var req = {};
var hasFilter = opts.filter && typeof opts.filter === 'function';
req.query = opts.query_params;
return function filter(change) {
if (!change.doc) {
// CSG sends events on the changes feed that don't have documents,
// this hack makes a whole lot of existing code robust.
change.doc = {};
}
if (opts.filter && hasFilter && !opts.filter.call(this, change.doc, req)) {
return false;
}
if (!opts.include_docs) {
delete change.doc;
} else if (!opts.attachments) {
for (var att in change.doc._attachments) {
if (change.doc._attachments.hasOwnProperty(att)) {
change.doc._attachments[att].stub = true;
}
}
}
return true;
};
};
exports.parseDoc = parseDoc.parseDoc;
exports.invalidIdError = parseDoc.invalidIdError;
exports.isCordova = function () {
return (typeof cordova !== "undefined" ||
typeof PhoneGap !== "undefined" ||
typeof phonegap !== "undefined");
};
exports.hasLocalStorage = function () {
if (isChromeApp()) {
return false;
}
try {
return localStorage;
} catch (e) {
return false;
}
};
exports.Changes = Changes;
exports.inherits(Changes, EventEmitter);
function Changes() {
if (!(this instanceof Changes)) {
return new Changes();
}
var self = this;
EventEmitter.call(this);
this.isChrome = isChromeApp();
this._listeners = {};
this.hasLocal = false;
if (!this.isChrome) {
this.hasLocal = exports.hasLocalStorage();
}
if (this.isChrome) {
chrome.storage.onChanged.addListener(function (e) {
// make sure it's event addressed to us
if (e.db_name != null) {
//object only has oldValue, newValue members
self.emit(e.dbName.newValue);
}
});
} else if (this.hasLocal) {
if (typeof addEventListener !== 'undefined') {
addEventListener("storage", function (e) {
self.emit(e.key);
});
} else { // old IE
window.attachEvent("storage", function (e) {
self.emit(e.key);
});
}
}
}
Changes.prototype.addListener = function (dbName, id, db, opts) {
if (this._listeners[id]) {
return;
}
var self = this;
var inprogress = false;
function eventFunction() {
if (!self._listeners[id]) {
return;
}
if (inprogress) {
inprogress = 'waiting';
return;
}
inprogress = true;
var changesOpts = pick(opts, [
'style', 'include_docs', 'attachments', 'conflicts', 'filter',
'doc_ids', 'view', 'since', 'query_params', 'binary'
]);
db.changes(changesOpts).on('change', function (c) {
if (c.seq > opts.since && !opts.cancelled) {
opts.since = c.seq;
exports.call(opts.onChange, c);
}
}).on('complete', function () {
if (inprogress === 'waiting') {
process.nextTick(function () {
self.notify(dbName);
});
}
inprogress = false;
}).on('error', function () {
inprogress = false;
});
}
this._listeners[id] = eventFunction;
this.on(dbName, eventFunction);
};
Changes.prototype.removeListener = function (dbName, id) {
if (!(id in this._listeners)) {
return;
}
EventEmitter.prototype.removeListener.call(this, dbName,
this._listeners[id]);
};
Changes.prototype.notifyLocalWindows = function (dbName) {
//do a useless change on a storage thing
//in order to get other windows's listeners to activate
if (this.isChrome) {
chrome.storage.local.set({dbName: dbName});
} else if (this.hasLocal) {
localStorage[dbName] = (localStorage[dbName] === "a") ? "b" : "a";
}
};
Changes.prototype.notify = function (dbName) {
this.emit(dbName);
this.notifyLocalWindows(dbName);
};
exports.once = require('./deps/once');
exports.toPromise = require('./deps/toPromise');
exports.adapterFun = function (name, callback) {
var log = require('debug')('pouchdb:api');
function logApiCall(self, name, args) {
if (!log.enabled) {
return;
}
var logArgs = [self._db_name, name];
for (var i = 0; i < args.length - 1; i++) {
logArgs.push(args[i]);
}
log.apply(null, logArgs);
// override the callback itself to log the response
var origCallback = args[args.length - 1];
args[args.length - 1] = function (err, res) {
var responseArgs = [self._db_name, name];
responseArgs = responseArgs.concat(
err ? ['error', err] : ['success', res]
);
log.apply(null, responseArgs);
origCallback(err, res);
};
}
return exports.toPromise(exports.getArguments(function (args) {
if (this._closed) {
return Promise.reject(new Error('database is closed'));
}
var self = this;
logApiCall(self, name, args);
if (!this.taskqueue.isReady) {
return new Promise(function (fulfill, reject) {
self.taskqueue.addTask(function (failed) {
if (failed) {
reject(failed);
} else {
fulfill(self[name].apply(self, args));
}
});
});
}
return callback.apply(this, args);
}));
};
exports.cancellableFun = function (fun, self, opts) {
opts = opts ? exports.clone(true, {}, opts) : {};
var emitter = new EventEmitter();
var oldComplete = opts.complete || function () { };
var complete = opts.complete = exports.once(function (err, resp) {
if (err) {
oldComplete(err);
} else {
emitter.emit('end', resp);
oldComplete(null, resp);
}
emitter.removeAllListeners();
});
var oldOnChange = opts.onChange || function () {};
var lastChange = 0;
self.on('destroyed', function () {
emitter.removeAllListeners();
});
opts.onChange = function (change) {
oldOnChange(change);
if (change.seq <= lastChange) {
return;
}
lastChange = change.seq;
emitter.emit('change', change);
if (change.deleted) {
emitter.emit('delete', change);
} else if (change.changes.length === 1 &&
change.changes[0].rev.slice(0, 1) === '1-') {
emitter.emit('create', change);
} else {
emitter.emit('update', change);
}
};
var promise = new Promise(function (fulfill, reject) {
opts.complete = function (err, res) {
if (err) {
reject(err);
} else {
fulfill(res);
}
};
});
promise.then(function (result) {
complete(null, result);
}, complete);
// this needs to be overwridden by caller, dont fire complete until
// the task is ready
promise.cancel = function () {
promise.isCancelled = true;
if (self.taskqueue.isReady) {
opts.complete(null, {status: 'cancelled'});
}
};
if (!self.taskqueue.isReady) {
self.taskqueue.addTask(function () {
if (promise.isCancelled) {
opts.complete(null, {status: 'cancelled'});
} else {
fun(self, opts, promise);
}
});
} else {
fun(self, opts, promise);
}
promise.on = emitter.on.bind(emitter);
promise.once = emitter.once.bind(emitter);
promise.addListener = emitter.addListener.bind(emitter);
promise.removeListener = emitter.removeListener.bind(emitter);
promise.removeAllListeners = emitter.removeAllListeners.bind(emitter);
promise.setMaxListeners = emitter.setMaxListeners.bind(emitter);
promise.listeners = emitter.listeners.bind(emitter);
promise.emit = emitter.emit.bind(emitter);
return promise;
};
exports.explain404 = require('./deps/explain404');
exports.info = function (str) {
if (typeof console !== 'undefined' && 'info' in console) {
console.info(str);
}
};
exports.parseUri = require('./deps/parseUri');
exports.compare = function (left, right) {
return left < right ? -1 : left > right ? 1 : 0;
};
// compact a tree by marking its non-leafs as missing,
// and return a list of revs to delete
exports.compactTree = function compactTree(metadata) {
var revs = [];
merge.traverseRevTree(metadata.rev_tree, function (isLeaf, pos,
revHash, ctx, opts) {
if (opts.status === 'available' && !isLeaf) {
revs.push(pos + '-' + revHash);
opts.status = 'missing';
}
});
return revs;
};
var vuvuzela = require('vuvuzela');
exports.safeJsonParse = function safeJsonParse(str) {
try {
return JSON.parse(str);
} catch (e) {
return vuvuzela.parse(str);
}
};
exports.safeJsonStringify = function safeJsonStringify(json) {
try {
return JSON.stringify(json);
} catch (e) {
return vuvuzela.stringify(json);
}
};
exports.parseDesignDocFunctionName = function (s) {
if (!s) {
return null;
}
var parts = s.split('/');
if (parts.length === 2) {
return parts;
} else if (parts.length === 1) {
return [s, s];
} else {
return null;
}
};
exports.normalizeDesignDocFunctionName = function (s) {
var normalized = this.parseDesignDocFunctionName(s);
return normalized ? normalized.join('/') : null;
};
| KlausTrainer/pouchdb | lib/utils.js | JavaScript | apache-2.0 | 10,959 |
var __UserInfo = null;
function GetUserInfo() {
if (__UserInfo == null) {
alert("您尚未登录,请重新登陆!");
location = "Login.html";
return;
}
return __UserInfo;
}
var dhMb = "<li>" +
" <a href='[URL]' target='mainpage' onclick='aSelect(this,2);'>" +
" <i class='[img]'></i>" +
" [name]" +
" </a>" +
"</li>";
var dhFMb = "<a href='#' class='dropdown-toggle'>" +
" <i class='[img]'></i>" +
" <span class='menu-text'> [name] </span>" +
" <b class='arrow icon-angle-down'></b>" +
"</a>";
function aSelect(a, num) {
var lilist = null;
if (num == 1)
lilist = a.parentNode.parentNode.getElementsByTagName("li");
else
lilist = a.parentNode.parentNode.parentNode.parentNode.getElementsByTagName("li");
for (var i = 0; i < lilist.length; i++) {
if (a.parentNode != lilist[i])
lilist[i].className = "";
}
a.parentNode.className = "active";
}
var nowDialog = {
nDialog: null,
nWin: null,
retFun: null
};
//填出框
function OpenDialog(title, url, win, retFun, height) {
var h = (height ? height : "400");
if (!url) { alert("请录入URL"); return; }
var strFrame = "<iframe style='width:100%;height:[height]px;' src='[url]' frameborder='0'></iframe>";
nowDialog.nDialog = bootbox.dialog((strFrame.replace("[height]", h).replace("[url]", url)));
nowDialog.nWin = win;
nowDialog.retFun = retFun;
}
function CloseDialog() {
bootbox.hideAll();
if (nowDialog.nWin && nowDialog.retFun) {
var fun = nowDialog.nWin.eval(nowDialog.retFun);
new fun();
}
}
//格式化
function jsonDateFormat(jsonDate) {//json日期格式转换为正常格式
try {//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
var date = new Date(parseInt(jsonDate.replace("/Date(", "").replace(")/", ""), 10));
var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
var milliseconds = date.getMilliseconds();
return date.getFullYear() + "-" + month + "-" + day;
} catch (ex) {//出自http://www.cnblogs.com/ahjesus 尊重作者辛苦劳动成果,转载请注明出处,谢谢!
return "";
}
}
function Load() {
var request = new DBRequest("SystemBLL.SysUser", "GetUser", "SystemBLL");
request.send(function (ret) {
__UserInfo = ret.d;
var user = GetUserInfo();
if (user) {
var strHTML = "";
if (user.CaiDans.length != 0) {
strHTML = getNextItem(0, user.CaiDans);
}
document.getElementById("ulnav").innerHTML = strHTML;
}
document.getElementById("userName").innerHTML = user.UserName;
});
}
function getNextItem(pid, caidans) {
var retStr = "";
for (var i = 0; i < caidans.length; i++) {
if (caidans[i].cdPID == pid) {
var x = getNextItem(caidans[i].cdID, caidans);
if (x != "") {
retStr = retStr + "<li>" + (dhFMb.replace("[img]", caidans[i].cdImg).replace("[name]", caidans[i].cdName) + "<ul class='submenu'>" + x + "</ul>") + "</li>";
} else {
retStr = retStr + (dhMb.replace("[img]", caidans[i].cdImg).replace("[name]", caidans[i].cdName).replace("[URL]", caidans[i].cdURL));
}
}
}
return retStr;
}
function UpdatePassword() {
window.top.OpenDialog("修改密码", "View/System/UpdateUserPass.html", window, null);
}
function Logout() {
if (confirm("是否确定注销?")) {
var request = new DBRequest("SystemBLL.SysUser", "Logout", "SystemBLL");
request.send(function (ret) {
location = "login.html";
});
}
} | yiaslu/qbpDemo | WebUI/Controllers/index.js | JavaScript | apache-2.0 | 4,203 |