text
stringlengths 2
6.14k
|
|---|
/*
* Copyright (C) 2013, 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.ApplicationCacheFrameTreeElement = class ApplicationCacheFrameTreeElement extends WebInspector.GeneralTreeElement
{
constructor(representedObject)
{
console.assert(representedObject instanceof WebInspector.ApplicationCacheFrame);
super("application-cache-frame", "", "", representedObject, false);
this.updateTitles();
}
updateTitles()
{
var url = this.representedObject.frame.url;
var parsedURL = parseURL(url);
this.mainTitle = WebInspector.displayNameForURL(url, parsedURL);
// Show the host as the subtitle only if it doesn't match the subtitle of the manifest tree element,
// and it doesn't match the mainTitle.
var subtitle = WebInspector.displayNameForHost(parsedURL.host);
var manifestTreeElement = null;
var currentAncestor = this.parent;
while (currentAncestor && !currentAncestor.root) {
if (currentAncestor instanceof WebInspector.ApplicationCacheManifestTreeElement) {
manifestTreeElement = currentAncestor;
break;
}
currentAncestor = currentAncestor.parent;
}
var subtitleIsDuplicate = subtitle === this._mainTitle || manifestTreeElement ? subtitle === manifestTreeElement.subtitle : false;
this.subtitle = subtitleIsDuplicate ? null : subtitle;
}
};
|
// Imports
const electron = require('electron');
const winston = require('winston');
const path = require('path');
const program = require('yargs').parse(process.argv);
const {app} = electron;
const loglevel = getLogLevel();
const logfile = path.join(app.getPath('userData'), 'logfile.log')
const logger = new (winston.Logger)({
level: loglevel,
transports: [
new (winston.transports.File)({ filename: logfile })
]
});
function getLogLevel() {
if (program.debug){
return 'debug'
} else if (program.verbose) {
return 'verbose'
} else {
return 'info'
}
}
module.exports = logger;
|
/* eslint-disable camelcase */
import {
selectAPIResponse,
selectAPIByKey,
} from 'foremanReact/redux/API/APISelectors';
import { selectDoesIntervalExist } from 'foremanReact/redux/middlewares/IntervalMiddleware/IntervalSelectors';
import { STATUS } from 'foremanReact/constants';
import { selectForemanTasks } from '../../ForemanTasksSelectors';
import { FOREMAN_TASK_DETAILS } from './TaskDetailsConstants';
export const selectTaskDetails = state =>
selectForemanTasks(state).taskDetails || {};
export const selectTaskDetailsResponse = state =>
selectAPIResponse(state, FOREMAN_TASK_DETAILS);
export const selectStartAt = state =>
selectTaskDetailsResponse(state)?.start_at;
export const selectStartBefore = state =>
selectTaskDetailsResponse(state)?.start_before;
export const selectStartedAt = state =>
selectTaskDetailsResponse(state)?.started_at;
export const selectEndedAt = state =>
selectTaskDetailsResponse(state)?.ended_at;
export const selectInput = state =>
selectTaskDetailsResponse(state).input || [];
export const selectOutput = state =>
selectTaskDetailsResponse(state).output || {};
export const selectResumable = state =>
selectTaskDetailsResponse(state).resumable || false;
export const selectCancellable = state =>
selectTaskDetailsResponse(state).cancellable || false;
export const selectErrors = state => {
const { humanized } = selectTaskDetailsResponse(state);
return humanized ? humanized.errors : [];
};
export const selectProgress = state =>
selectTaskDetailsResponse(state).progress
? Math.trunc(selectTaskDetailsResponse(state).progress * 100)
: 0;
export const selectUsername = state =>
selectTaskDetailsResponse(state)?.username;
export const selectLabel = state => selectTaskDetailsResponse(state)?.label;
export const selectExecutionPlan = state =>
selectTaskDetailsResponse(state).execution_plan || {};
export const selectFailedSteps = state =>
selectTaskDetailsResponse(state).failed_steps || [];
export const selectRunningSteps = state =>
selectTaskDetailsResponse(state).running_steps || [];
export const selectHelp = state => selectTaskDetailsResponse(state)?.help;
export const selectHasSubTasks = state =>
selectTaskDetailsResponse(state).has_sub_tasks || false;
export const selectLocks = state =>
selectTaskDetailsResponse(state).locks || [];
export const selectLinks = state =>
selectTaskDetailsResponse(state).links || [];
export const selectUsernamePath = state =>
selectTaskDetailsResponse(state)?.username_path;
export const selectAction = state =>
selectTaskDetailsResponse(state).action || '';
export const selectState = state => selectTaskDetailsResponse(state)?.state;
export const selectResult = state => selectTaskDetailsResponse(state)?.result;
export const selectTimeoutId = state =>
selectTaskDetailsResponse(state)?.timeoutId;
export const selectTaskReload = state =>
!!selectDoesIntervalExist(state, FOREMAN_TASK_DETAILS);
export const selectParentTask = state =>
selectTaskDetailsResponse(state).parent_task_id || '';
export const selectExternalId = state =>
selectTaskDetailsResponse(state)?.external_id;
export const selectDynflowEnableConsole = state =>
selectTaskDetailsResponse(state).dynflow_enable_console || false;
export const selectCanEdit = state =>
selectTaskDetailsResponse(state).can_edit || false;
export const selectStatus = state => selectTaskDetailsResponse(state).status;
export const selectAPIError = state =>
selectTaskDetailsResponse(state)?.APIerror;
export const selectIsLoading = state =>
!!selectAPIByKey(state, FOREMAN_TASK_DETAILS).response &&
selectStatus(state) === STATUS.PENDING;
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch10/10.4/10.4.3/10.4.3-1-50gs.js
* @description Strict - checking 'this' from a global scope (Anonymous FunctionExpression with a strict directive prologue defined within a FunctionExpression)
* @noStrict
*/
var f1 = function () {
return ((function () {
"use strict";
return typeof this;
})()==="undefined") && (this===fnGlobalObject());
}
if (! f1()) {
throw "'this' had incorrect value!";
}
|
import React from 'react';
import TableHistory from '../../../../../src/screens/history/widgets/table-history/table-history';
import { mount, configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
configure({ adapter: new Adapter() });
const rows = [
{
pk: 69,
exposure: {
dateobs: '2019-01-01T22:00:00Z',
exposure_id: 3,
tile: 6,
telra: 333.22,
teldec: 14.84,
exptime: 1000,
airmass: null,
flavor: 'science',
},
datemjd: 58484.916666666664,
runtime: '110.648429',
qa_tests: [
{
r0: {
fiberfl: { steps_status: ['NORMAL', 'NORMAL', 'NORMAL', 'NORMAL'] },
preproc: { steps_status: ['NORMAL', 'NORMAL', 'NORMAL', 'NORMAL'] },
extract: { steps_status: ['NORMAL'] },
skysubs: { steps_status: ['NORMAL'] },
},
},
],
},
{
pk: 70,
exposure: {
dateobs: '2019-01-01T22:00:00Z',
exposure_id: 4,
tile: 7,
telra: 332.35,
teldec: 12.32,
exptime: 1000,
airmass: null,
flavor: 'science',
},
datemjd: 58484.916666666664,
runtime: '96.254038',
qa_tests: [
{
r0: {
fiberfl: { steps_status: ['NORMAL', 'NORMAL', 'NORMAL', 'NORMAL'] },
preproc: { steps_status: ['NORMAL', 'NORMAL', 'NORMAL', 'NORMAL'] },
extract: { steps_status: ['NORMAL'] },
skysubs: { steps_status: ['None'] },
},
},
],
},
];
describe('TableHistory Controls', () => {
const getHistory = jest.fn(),
getHistoryOrdered = jest.fn(() => rows),
navigateToQA = jest.fn();
let wrapper;
beforeEach(() => {
window.getSelection = () => {
return {
removeAllRanges: () => {},
};
};
const tableHistory = (
<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
<TableHistory
rows={rows}
getHistory={getHistory}
navigateToQA={navigateToQA}
getHistoryOrdered={getHistoryOrdered}
limit={10}
type={'process'}
/>
</MuiThemeProvider>
);
wrapper = mount(tableHistory);
});
it('Render processing history header', () => {
expect(
wrapper
.find('span')
.at(0)
.text()
).toBe('Status');
expect(
wrapper
.find('span')
.at(1)
.text()
).toBe('Program');
expect(
wrapper
.find('span')
.at(2)
.text()
).toBe('Process ID');
expect(
wrapper
.find('span')
.at(3)
.text()
).toBe('Exp ID');
expect(
wrapper
.find('span')
.at(4)
.text()
).toBe('Flavor');
expect(
wrapper
.find('span')
.at(5)
.text()
).toBe('Tile ID');
expect(
wrapper
.find('span')
.at(6)
.text()
).toBe('Process Date');
expect(
wrapper
.find('span')
.at(7)
.text()
).toBe('Process Time');
expect(
wrapper
.find('span')
.at(8)
.text()
).toBe('OBS Date');
expect(
wrapper
.find('span')
.at(9)
.text()
).toBe('MJD');
expect(
wrapper
.find('span')
.at(10)
.text()
).toBe('RA (deg)');
expect(
wrapper
.find('span')
.at(11)
.text()
).toBe('Dec (deg)');
expect(
wrapper
.find('span')
.at(12)
.text()
).toBe('Exp Time(s)');
expect(
wrapper
.find('span')
.at(13)
.text()
).toBe('Airmass');
expect(
wrapper
.find('span')
.at(14)
.text()
).toBe('FWHM (arcsec)');
expect(
wrapper
.find('span')
.at(15)
.text()
).toBe('QA');
expect(
wrapper
.find('span')
.at(16)
.text()
).toBe('View');
expect(
wrapper
.find('span')
.at(17)
.text()
).toBe('COM');
expect(
wrapper
.find('span')
.at(18)
.text()
).toBe('Logs');
});
// it('mounts rendering table', () => {
// expect(getHistory).toBeCalled();
// expect(
// wrapper
// .find('TableHeaderColumn')
// .at(1)
// .text()
// ).toBe('Process ID');
// expect(
// wrapper
// .find('TableRowColumn')
// .at(1)
// .text()
// ).toBe('69');
// });
// it('orders table', () => {
// wrapper
// .find('span')
// .at(1)
// .simulate('click');
// expect(getHistoryOrdered).toBeCalledWith('-pk');
// wrapper
// .find('span')
// .at(0)
// .simulate('click');
// expect(getHistoryOrdered).toBeCalledWith('-pk');
// });
it('calls navigateToQA error', async () => {
await wrapper
.find('TableCell')
.at(53)
.find('span')
.at(0)
.simulate('click');
expect(
wrapper
.find('TableCell')
.at(53)
.find('span')
.at(0)
.text()
).toBe('✖︎');
expect(navigateToQA).toBeCalledWith('70');
});
it('calls navigateToQA ok', async () => {
await wrapper
.find('TableCell')
.at(34)
.find('span')
.at(0)
.simulate('click');
expect(
wrapper
.find('TableCell')
.at(34)
.find('span')
.at(0)
.text()
).toBe('✓');
expect(navigateToQA).toBeCalledWith('69');
});
});
|
var test = require("test");
test.setup();
var os = require('os');
var coroutine = require('coroutine');
var n;
describe('coroutine', function() {
function t_fiber(v1, v2) {
n = v1 + v2;
}
it('start', function() {
n = 123;
var f = t_fiber.start(100, 200);
assert.equal(n, 123);
coroutine.sleep();
assert.equal(n, 300);
});
it('join', function() {
n = 300;
var f = coroutine.start(t_fiber, 123, 200);
assert.equal(n, 300);
f.join();
assert.equal(n, 323);
});
it("Memory Leak detect", function() {
GC();
var no1 = os.memoryUsage().nativeObjects;
var f = (function(v) {}).start(new Buffer());
GC();
assert.equal(no1 + 2, os.memoryUsage().nativeObjects);
f.join();
GC();
assert.equal(no1, os.memoryUsage().nativeObjects);
});
it('Fiber-local storage', function() {
function t_fiber1(v1, v2) {
n = v1 + v2 + this.v;
}
n = 323;
var f = t_fiber1.start(100, 200);
assert.equal(n, 323);
f.v = 1000;
f.join();
assert.equal(n, 1300);
});
it('current', function() {
function t_fiber2(v1, v2) {
n = v1 + v2 + coroutine.current().v;
}
n = 1300;
var f = t_fiber2.start(100, 200);
assert.equal(n, 1300);
f.v = 2000;
f.join();
assert.equal(n, 2300);
f = t_fiber2.start(100, 200);
assert.equal(n, 2300);
f.v = 1000;
coroutine.sleep(100);
f.join();
assert.equal(n, 1300);
});
it('caller', function() {
function t_fiber3(v1, v2) {
n = v1 + v2 + this.caller.v;
}
n = 1300;
var f = t_fiber3.start(100, 200);
assert.equal(n, 1300);
coroutine.current().v = 1234;
f.join();
assert.equal(n, 1534);
});
it('inherit local storage', function() {
function t_fiber4() {
n = coroutine.current().v;
}
n = 0;
coroutine.current().v = 1000;
var f = t_fiber4.start();
assert.equal(n, 0);
coroutine.current().v = 2000;
f.join();
assert.equal(n, 1000);
});
it('parallel', function() {
var funs = [
function() {
coroutine.sleep(100);
return 1;
},
function() {
coroutine.sleep(100);
return 2;
},
function() {
coroutine.sleep(100);
return 3;
},
function() {
coroutine.sleep(100);
},
function() {
coroutine.sleep(100);
}
];
var rs = coroutine
.parallel(funs[0], funs[1], funs[2], funs[3], funs[4]);
assert.equal(rs[0], 1);
assert.equal(rs[1], 2);
assert.equal(rs[2], 3);
rs = coroutine.parallel(funs);
assert.equal(rs[0], 1);
assert.equal(rs[1], 2);
assert.equal(rs[2], 3);
assert.throws(function() {
coroutine.parallel(funs[0], funs[1], funs[2], funs[3], funs[4],
function() {
console.log(notExistsValue);
});
});
assert.throws(function() {
coroutine.parallel(function() {
console.log(notExistsValue);
}, funs[0], funs[1], funs[2], funs[3], funs[4]);
});
assert.deepEqual(coroutine.parallel([1, 2, 3, 4, 5], function(v) {
return v + 1;
}), [2, 3, 4, 5, 6]);
});
it('stack overflow', function() {
function stack_size() {
function t() {
t();
}
assert.throws(function() {
t();
});
}
stack_size.start();
coroutine.sleep();
});
describe('BlockQueue', function() {
it("add", function() {
var q = new coroutine.BlockQueue(3);
assert.equal(q.add(100), true);
assert.equal(q.add(200), true);
assert.equal(q.add(300), true);
assert.deepEqual(q.toArray(), [100, 200, 300]);
assert.throws(function() {
q.add(400);
});
assert.deepEqual(q.toArray(), [100, 200, 300]);
});
it("offer", function() {
var q = new coroutine.BlockQueue(3);
assert.equal(q.offer(100), true);
assert.equal(q.offer(200), true);
assert.equal(q.offer(300), true);
assert.deepEqual(q.toArray(), [100, 200, 300]);
assert.equal(q.offer(400), false);
assert.deepEqual(q.toArray(), [100, 200, 300]);
});
it("remove", function() {
var q = new coroutine.BlockQueue(3);
q.add(100);
q.add(200);
assert.equal(q.remove(), 100);
assert.deepEqual(q.toArray(), [200]);
assert.equal(q.remove(), 200);
assert.deepEqual(q.toArray(), []);
assert.throws(function() {
q.remove();
});
assert.deepEqual(q.toArray(), []);
});
it("poll", function() {
var q = new coroutine.BlockQueue(3);
q.add(100);
q.add(200);
assert.equal(q.poll(), 100);
assert.deepEqual(q.toArray(), [200]);
assert.equal(q.poll(), 200);
assert.deepEqual(q.toArray(), []);
assert.isNull(q.poll());
assert.deepEqual(q.toArray(), []);
});
it("clear/length", function() {
var q = new coroutine.BlockQueue(3);
q.add(100);
q.add(200);
assert.deepEqual(q.toArray(), [100, 200]);
q.clear();
assert.deepEqual(q.toArray(), []);
assert.equal(q.length, 0);
});
it("element", function() {
var q = new coroutine.BlockQueue(3);
q.add(100);
q.add(200);
assert.equal(q.element(), 100);
assert.deepEqual(q.toArray(), [100, 200]);
q.clear();
assert.throws(function() {
q.element();
});
});
it("peek", function() {
var q = new coroutine.BlockQueue(3);
q.add(100);
q.add(200);
assert.equal(q.element(), 100);
assert.deepEqual(q.toArray(), [100, 200]);
q.clear();
assert.isNull(q.peek());
});
it("put", function() {
var q = new coroutine.BlockQueue(3);
q.add(100);
q.add(200);
assert.equal(q.element(), 100);
assert.deepEqual(q.toArray(), [100, 200]);
q.put(300);
assert.deepEqual(q.toArray(), [100, 200, 300]);
(function() {
q.put(400);
}).start();
coroutine.sleep(10);
assert.deepEqual(q.toArray(), [100, 200, 300]);
q.remove();
assert.deepEqual(q.toArray(), [200, 300]);
coroutine.sleep(10);
assert.deepEqual(q.toArray(), [200, 300, 400]);
});
it("take", function() {
var q = new coroutine.BlockQueue(3);
var e;
(function() {
e = q.take();
}).start();
coroutine.sleep(10);
q.add(100);
q.add(200);
assert.deepEqual(q.toArray(), [100, 200]);
coroutine.sleep(10);
assert.equal(e, 100);
assert.deepEqual(q.toArray(), [200]);
});
});
});
// test.run(console.DEBUG);
|
//-------------------------------------------------
// Add two complex numbers
//-------------------------------------------------
var complexAdd = function (a, b)
{
return [a[0] + b[0], a[1] + b[1]];
};
//-------------------------------------------------
// Subtract two complex numbers
//-------------------------------------------------
var complexSubtract = function (a, b)
{
return [a[0] - b[0], a[1] - b[1]];
};
//-------------------------------------------------
// Multiply two complex numbers
//
// (a + bi) * (c + di) = (ac - bd) + (ad + bc)i
//-------------------------------------------------
var complexMultiply = function (a, b)
{
return [(a[0] * b[0] - a[1] * b[1]),
(a[0] * b[1] + a[1] * b[0])];
};
//-------------------------------------------------
// Calculate |a + bi|
//
// sqrt(a*a + b*b)
//-------------------------------------------------
var complexMagnitude = function (c)
{
return Math.sqrt(c[0]*c[0] + c[1]*c[1]);
};
//-------------------------------------------------
// Exports
//-------------------------------------------------
module.exports = {
add: complexAdd,
subtract: complexSubtract,
multiply: complexMultiply,
magnitude: complexMagnitude
};
|
module.exports = Marionette.CompositeView.extend( {
id: 'elementor-panel-revisions',
template: '#tmpl-elementor-panel-revisions',
childView: require( './view' ),
childViewContainer: '#elementor-revisions-list',
ui: {
discard: '.elementor-panel-scheme-discard .elementor-button',
apply: '.elementor-panel-scheme-save .elementor-button'
},
events: {
'click @ui.discard': 'onDiscardClick',
'click @ui.apply': 'onApplyClick'
},
isRevisionApplied: false,
jqueryXhr: null,
currentPreviewId: null,
currentPreviewItem: null,
initialize: function() {
this.listenTo( elementor.channels.editor, 'saved', this.onEditorSaved );
},
getRevisionViewData: function( revisionView ) {
var self = this,
revisionID = revisionView.model.get( 'id' );
self.jqueryXhr = elementor.ajax.send( 'get_revision_data', {
data: {
id: revisionID
},
success: function( data ) {
self.setEditorData( data );
self.setRevisionsButtonsActive( true );
self.jqueryXhr = null;
revisionView.$el.removeClass( 'elementor-revision-item-loading' );
self.enterReviewMode();
},
error: function( data ) {
revisionView.$el.removeClass( 'elementor-revision-item-loading' );
if ( 'abort' === self.jqueryXhr.statusText ) {
return;
}
self.currentPreviewItem = null;
self.currentPreviewId = null;
alert( 'An error occurred' );
}
} );
},
setRevisionsButtonsActive: function( active ) {
this.ui.apply.add( this.ui.discard ).prop( 'disabled', ! active );
},
setEditorData: function( data ) {
var collection = elementor.getRegion( 'sections' ).currentView.collection;
collection.reset( data );
},
deleteRevision: function( revisionView ) {
var self = this;
revisionView.$el.addClass( 'elementor-revision-item-loading' );
elementor.revisions.deleteRevision( revisionView.model, {
success: function() {
if ( revisionView.model.get( 'id' ) === self.currentPreviewId ) {
self.onDiscardClick();
}
self.currentPreviewId = null;
},
error: function( data ) {
revisionView.$el.removeClass( 'elementor-revision-item-loading' );
alert( 'An error occurred' );
}
} );
},
enterReviewMode: function() {
elementor.changeEditMode( 'review' );
},
exitReviewMode: function() {
elementor.changeEditMode( 'edit' );
},
navigate: function( reverse ) {
var currentPreviewItemIndex = this.collection.indexOf( this.currentPreviewItem.model ),
requiredIndex = reverse ? currentPreviewItemIndex - 1 : currentPreviewItemIndex + 1;
if ( requiredIndex < 0 ) {
requiredIndex = this.collection.length - 1;
}
if ( requiredIndex >= this.collection.length ) {
requiredIndex = 0;
}
this.children.findByIndex( requiredIndex ).ui.detailsArea.trigger( 'click' );
},
onEditorSaved: function() {
this.exitReviewMode();
this.setRevisionsButtonsActive( false );
},
onApplyClick: function() {
elementor.getPanelView().getChildView( 'footer' )._publishBuilder();
this.isRevisionApplied = true;
this.currentPreviewId = null;
},
onDiscardClick: function() {
this.setEditorData( elementor.config.data );
elementor.setFlagEditorChange( this.isRevisionApplied );
this.isRevisionApplied = false;
this.setRevisionsButtonsActive( false );
this.currentPreviewId = null;
this.exitReviewMode();
if ( this.currentPreviewItem ) {
this.currentPreviewItem.$el.removeClass( 'elementor-revision-current-preview' );
}
},
onDestroy: function() {
if ( this.currentPreviewId ) {
this.onDiscardClick();
}
},
onRenderCollection: function() {
if ( ! this.currentPreviewId ) {
return;
}
var currentPreviewModel = this.collection.findWhere({ id: this.currentPreviewId });
this.currentPreviewItem = this.children.findByModelCid( currentPreviewModel.cid );
this.currentPreviewItem.$el.addClass( 'elementor-revision-current-preview' );
},
onChildviewDetailsAreaClick: function( childView ) {
var self = this,
revisionID = childView.model.get( 'id' );
if ( revisionID === self.currentPreviewId ) {
return;
}
if ( this.jqueryXhr ) {
this.jqueryXhr.abort();
}
if ( self.currentPreviewItem ) {
self.currentPreviewItem.$el.removeClass( 'elementor-revision-current-preview' );
}
childView.$el.addClass( 'elementor-revision-current-preview elementor-revision-item-loading' );
if ( elementor.isEditorChanged() && null === self.currentPreviewId ) {
elementor.saveEditor( {
status: 'autosave',
onSuccess: function() {
self.getRevisionViewData( childView );
}
} );
} else {
self.getRevisionViewData( childView );
}
self.currentPreviewItem = childView;
self.currentPreviewId = revisionID;
},
onChildviewDeleteClick: function( childView ) {
var self = this,
type = childView.model.get( 'type' ),
id = childView.model.get( 'id' );
var removeDialog = elementor.dialogsManager.createWidget( 'confirm', {
message: elementor.translate( 'dialog_confirm_delete', [ type ] ),
headerMessage: elementor.translate( 'delete_element', [ type ] ),
strings: {
confirm: elementor.translate( 'delete' ),
cancel: elementor.translate( 'cancel' )
},
defaultOption: 'confirm',
onConfirm: function() {
self.deleteRevision( childView );
}
} );
removeDialog.show();
}
} );
|
$(document).ready(function () {
var URL = '/flooding/scenario/share/action/';
var click_handler = function (event) {
var that = $(this);
var handle_response = function(data) {
var parsed;
if (JSON !== undefined) {
parsed = JSON.parse(data);
} else {
parsed = eval(data); // IE7
}
that.attr('data-action', parsed.action);
if (parsed.is_url) {
that.html('<a href="#">'+parsed.message+'</a>');
} else {
that.html(parsed.message);
}
};
var action = that.attr("data-action");
var scenario_id = that.attr("data-scenario-id");
var project_id = that.attr("data-project-id");
if (action !== undefined && action !== "") {
$.post(URL, {
'action': action,
'scenario_id': scenario_id,
'project_id': project_id
}, handle_response);
}
};
var prevent_action_handler = function (event) {
event.preventDefault();
};
// Add the click handler to all elements with class "shareaction"
$(".shareaction").click(click_handler);
// Add the prevent action handler to any a's inside it
$(".shareaction a").click(prevent_action_handler);
});
|
/**
* @license Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* A lightweight representation of an HTML comment.
*
* @class
* @constructor Creates a comment class instance.
* @param {String} value The comment text value.
*/
CKEDITOR.htmlParser.comment = function( value ) {
/**
* The comment text.
*
* @property {String}
*/
this.value = value;
/** @private */
this._ = {
isBlockLike: false
};
};
CKEDITOR.htmlParser.comment.prototype = {
/**
* The node type. This is a constant value set to {@link CKEDITOR#NODE_COMMENT}.
*
* @readonly
* @property {Number} [=CKEDITOR.NODE_COMMENT]
*/
type: CKEDITOR.NODE_COMMENT,
/**
* Writes the HTML representation of this comment to a CKEDITOR.htmlWriter.
*
* @param {CKEDITOR.htmlParser.basicWriter} writer The writer to which write the HTML.
*/
writeHtml: function( writer, filter ) {
var comment = this.value;
if ( filter ) {
if ( !( comment = filter.onComment( comment, this ) ) )
return;
if ( typeof comment != 'string' ) {
comment.parent = this.parent;
comment.writeHtml( writer, filter );
return;
}
}
writer.comment( comment );
}
};
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/**
* @fileoverview 'settings-device-page' is the settings page for device and
* peripheral settings.
*/
Polymer({
is: 'settings-device-page',
behaviors: [
I18nBehavior,
WebUIListenerBehavior,
settings.RouteObserverBehavior,
],
properties: {
/** Preferences state. */
prefs: {
type: Object,
notify: true,
},
/** @private */
hasMouse_: {
type: Boolean,
value: false,
},
/** @private */
hasTouchpad_: {
type: Boolean,
value: false,
},
/** @private */
stylusAllowed_: {
type: Boolean,
value: function() {
return loadTimeData.getBoolean('stylusAllowed');
},
readOnly: true,
},
/** @private */
showStorageManager_: {
type: Boolean,
value: function() {
return loadTimeData.getBoolean('showStorageManager');
},
readOnly: true,
},
},
observers: [
'pointersChanged_(hasMouse_, hasTouchpad_)',
],
ready: function() {
cr.addWebUIListener('has-mouse-changed', this.set.bind(this, 'hasMouse_'));
cr.addWebUIListener(
'has-touchpad-changed', this.set.bind(this, 'hasTouchpad_'));
settings.DevicePageBrowserProxyImpl.getInstance().initializePointers();
},
/**
* @return {string}
* @private
*/
getPointersTitle_: function() {
if (this.hasMouse_ && this.hasTouchpad_)
return this.i18n('mouseAndTouchpadTitle');
if (this.hasMouse_)
return this.i18n('mouseTitle');
if (this.hasTouchpad_)
return this.i18n('touchpadTitle');
return '';
},
/**
* @return {string}
* @private
*/
getPointersIcon_: function() {
if (this.hasMouse_)
return 'settings:mouse';
if (this.hasTouchpad_)
return 'settings:touch-app';
return '';
},
/**
* Handler for tapping the mouse and touchpad settings menu item.
* @private
*/
onPointersTap_: function() {
settings.navigateTo(settings.Route.POINTERS);
},
/**
* Handler for tapping the Keyboard settings menu item.
* @private
*/
onKeyboardTap_: function() {
settings.navigateTo(settings.Route.KEYBOARD);
},
/**
* Handler for tapping the Keyboard settings menu item.
* @private
*/
onStylusTap_: function() {
settings.navigateTo(settings.Route.STYLUS);
},
/**
* Handler for tapping the Display settings menu item.
* @private
*/
onDisplayTap_: function() {
settings.navigateTo(settings.Route.DISPLAY);
},
/**
* Handler for tapping the Storage settings menu item.
* @private
*/
onStorageTap_: function() {
settings.navigateTo(settings.Route.STORAGE);
},
/** @protected */
currentRouteChanged: function() {
this.checkPointerSubpage_();
},
/**
* @param {boolean} hasMouse
* @param {boolean} hasTouchpad
* @private
*/
pointersChanged_: function(hasMouse, hasTouchpad) {
this.$.pointersRow.hidden = !hasMouse && !hasTouchpad;
this.checkPointerSubpage_();
},
/**
* Leaves the pointer subpage if all pointing devices are detached.
* @private
*/
checkPointerSubpage_: function() {
if (!this.hasMouse_ && !this.hasTouchpad_ &&
settings.getCurrentRoute() == settings.Route.POINTERS) {
settings.navigateTo(settings.Route.DEVICE);
}
},
});
|
/*
---
description: specific class for parsing subtitles file in SubViewer format (.sub)
license: GNU GPL
authors:
- Clément Hallet
requires:
- MooPlay
- MooPlay.Utils
- MooPlay.Subtitle.Parser.Base
- MooPlay.Subtitle.Item
provides:
- MooPlay.Subtitle.Parser.SubViewer
...
*/
MooPlay.Subtitle.Parser.SubViewer = new Class({
Implements: MooPlay.Subtitle.Parser.Base,
regexps: {
time: /^(\d{2}):(\d{2}):(\d{2}).(\d{3}),(\d{2}):(\d{2}):(\d{2}).(\d{3})$/,
text: /^(.+)$/
},
options: {
srt_end_of_line: '\n',
onComplete: $empty
},
parse: function(data) {
var subs = [];
var current_sub = null;
var current_text = null;
var index = null
var lines = data.split(this.options.srt_end_of_line);
// in case file doesn't end with an empty line
lines.push('');
do {
var line = lines.shift();
if(line != null && this.regexps.time.test(line)) {
current_text = [];
current_sub = {};
var times = this.regexps.time.exec(line);
current_sub.start = MooPlay.Utils.sexagesimalToTimestamp({ h: times[1].toInt(), m: times[2].toInt(), s: times[3].toInt(), ms: times[4].toInt() });
current_sub.end = MooPlay.Utils.sexagesimalToTimestamp({ h: times[5].toInt(), m: times[6].toInt(), s: times[7].toInt(), ms: times[8].toInt() });
var times = null;
} else if(line != null && this.regexps.text.test(line)) {
current_text = this.regexps.text.exec(line)[0].split('[BR]');
} else if(current_sub != null) {
subs.push(new MooPlay.Subtitle.Item(current_sub.start, current_sub.end, current_text));
current_sub = null;
current_text = null;
}
} while(line != null);
return subs;
},
});
|
//= require jquery-ui/effects/effect-blind
//= require jquery-ui/effects/effect-bounce
//= require jquery-ui/effects/effect-clip
//= require jquery-ui/effects/effect-drop
//= require jquery-ui/effects/effect-explode
//= require jquery-ui/effects/effect-fade
//= require jquery-ui/effects/effect-fold
//= require jquery-ui/effects/effect-highlight
//= require jquery-ui/effects/effect-puff
//= require jquery-ui/effects/effect-pulsate
//= require jquery-ui/effects/effect-scale
//= require jquery-ui/effects/effect-shake
//= require jquery-ui/effects/effect-size
//= require jquery-ui/effects/effect-slide
//= require jquery-ui/effects/effect-transfer
|
/*!
* VisualEditor ContentEditable DatetimeAnnotation class.
*
* @copyright 2011-2016 VisualEditor Team and others; see http://ve.mit-license.org
*/
/**
* ContentEditable datetime annotation.
*
* @class
* @extends ve.ce.TextStyleAnnotation
* @constructor
* @param {ve.dm.DatetimeAnnotation} model Model to observe
* @param {ve.ce.ContentBranchNode} [parentNode] Node rendering this annotation
* @param {Object} [config] Configuration options
*/
ve.ce.DatetimeAnnotation = function VeCeDatetimeAnnotation() {
// Parent constructor
ve.ce.DatetimeAnnotation.super.apply( this, arguments );
// DOM changes
this.$element.addClass( 've-ce-datetimeAnnotation' );
};
/* Inheritance */
OO.inheritClass( ve.ce.DatetimeAnnotation, ve.ce.TextStyleAnnotation );
/* Static Properties */
ve.ce.DatetimeAnnotation.static.name = 'textStyle/datetime';
ve.ce.DatetimeAnnotation.static.tagName = 'time';
/* Registration */
ve.ce.annotationFactory.register( ve.ce.DatetimeAnnotation );
|
/* @flow */
'use strict';
import React from 'react';
import {View} from 'react-native';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import Icon from './Icon';
import Button from './Button';
import computeProps from '../../Utils/computeProps';
import Input from './Input';
import _ from 'lodash';
export default class InputGroup extends NativeBaseComponent {
propTypes: {
borderType : React.PropTypes.string,
toolbar : React.PropTypes.bool,
atoolbar : React.PropTypes.bool,
iconRight : React.PropTypes.bool,
success : React.PropTypes.bool,
disabled : React.PropTypes.bool,
error : React.PropTypes.bool,
style : React.PropTypes.object
}
getInitialStyle() {
return {
textInput: {
backgroundColor: 'transparent',
flexDirection: 'row',
borderColor: (this.props.error) ? this.getTheme().inputErrorBorderColor : (this.props.success) ? this.getTheme().inputSuccessBorderColor : this.getTheme().inputBorderColor,
paddingRight: 5,
alignItems: 'center'
},
outerBorder: {
position:'relative',
borderColor: 'white',
borderWidth: this.getTheme().borderWidth,
borderTopWidth: 0,
borderRightWidth: 0,
borderLeftWidth: 0
},
darkborder: {
borderColor: '#000'
},
lightborder: {
borderColor: '#fff'
},
underline: {
position:'relative',
borderWidth: this.getTheme().borderWidth,
borderTopWidth: 0,
borderRightWidth: 0,
borderLeftWidth: 0
},
bordered: {
position:'relative',
borderWidth: this.getTheme().borderWidth
},
rounded: {
position:'relative',
borderWidth: this.getTheme().borderWidth,
borderRadius: 30
}
}
}
prepareRootProps() {
var type = {
paddingLeft: (this.props.borderType === 'rounded' && !this.props.children.type == Icon) ? 15 :
(this.props.children.type == Icon ) ? this.getTheme().inputPaddingLeftIcon : 5
}
var defaultStyle = (this.props.borderType === 'regular') ? this.getInitialStyle().bordered : (this.props.borderType === 'rounded') ? this.getInitialStyle().rounded : this.getInitialStyle().underline;
type = _.merge(type, defaultStyle);
var addedProps = _.merge(this.getInitialStyle().textInput, type);
var defaultProps = {
style: addedProps,
key: 'inpGroup'
}
return computeProps(this.props, defaultProps);
}
getIconProps(icon) {
var defaultStyle = {
fontSize: (this.props.toolbar || this.props.atoolbar) ? this.getTheme().toolbarIconSize : 27,
alignSelf: 'center',
lineHeight: (this.props.toolbar || this.props.atoolbar) ? 24 : undefined,
paddingRight: 5,
marginLeft: (this.props.toolbar || this.props.atoolbar) ? 5 : undefined
}
var defaultProps = {
style: defaultStyle,
key: 'icon'
}
return computeProps(icon.props, defaultProps);
}
getButtonProps(button) {
var defaultStyle = {
alignSelf: 'center',
paddingRight: 5,
marginLeft: (this.props.toolbar || this.props.atoolbar) ? 5 : undefined,
height: this.props.toolbar ? 30 : undefined,
fontSize: this.props.toolbar ? 15 : undefined
}
var defaultProps = {
style: defaultStyle,
key: 'button',
inputButton: true
}
return computeProps(button.props, defaultProps);
}
renderChildren() {
var inputProps = {};
var newChildren = [];
var childrenArray = React.Children.toArray(this.props.children);
var iconElement = [];
iconElement = _.remove(childrenArray, function(item) {
if(item.type == Icon) {
return true;
}
});
var buttonElement = [];
buttonElement = _.remove(childrenArray, function(item) {
if(item.type == Button) {
return true;
}
});
var inp = _.find(childrenArray, function(item) {
if(item && item.type == Input) {
return true;
}
});
if(inp) {
inputProps = inp.props;
var clonedInp = React.cloneElement(
inp,
{
...this.inputProps,
key: 'inp',
editable: this.props.disabled ? false : undefined
}
)
}
if(Array.isArray(this.props.children)) {
if(this.props.iconRight) {
if(clonedInp) {
newChildren.push(clonedInp);
}
newChildren.push(React.cloneElement(iconElement[0],this.getIconProps(iconElement[0])));
}
else if(buttonElement.length>0) {
newChildren.push(React.cloneElement(
iconElement[0],
{
...this.getIconProps(iconElement[0]),
key: 'icon0'
}
));
if(clonedInp) {
newChildren.push(clonedInp);
}
newChildren.push(React.cloneElement(
buttonElement[0],
{
...this.getButtonProps(buttonElement[0]),
key: 'button1'
}
));
}
else {
if (iconElement.length > 1) {
newChildren.push(React.cloneElement(
iconElement[0],
{
...this.getIconProps(iconElement[0]),
key: 'icon0'
}
));
if(clonedInp) {
newChildren.push(clonedInp);
}
newChildren.push(React.cloneElement(
iconElement[1],
{
...this.getIconProps(iconElement[1]),
key: 'icon1'
}
));
} else {
newChildren.push(React.cloneElement(iconElement[0], this.getIconProps(iconElement[0])));
if(clonedInp) {
newChildren.push(clonedInp);
}
}
}
}
else {
if(clonedInp) {
newChildren.push(clonedInp);
}
}
return newChildren;
}
render() {
return (
<View {...this.prepareRootProps()} >
{this.renderChildren()}
</View>
);
}
}
|
/**
* Created by pinballwizard on 06.12.15.
*/
$(document).ready(function(){
$('.button-collapse').sideNav();
$('.modal-trigger').leanModal();
$('select').material_select();
$('.dropdown-button').dropdown({
belowOrigin: true
});
$('.switch').change(function(){
$(this).parents("form").submit();
});
// Настройка выбора даты
$('.datepicker').pickadate({
monthsFull: ['Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'],
monthsShort: ['Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек'],
weekdaysFull: ['Воскресенье', 'Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота'],
weekdaysShort: ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'],
format: 'dd.mm.yyyy',
// First day of the week
firstDay: 'monday',
// Date limits
max: 'today',
// Buttons
today: 'Сегодня',
clear: 'Очистить',
close: 'Закрыть',
// Accessibility labels
labelMonthNext: 'Следующий',
labelMonthPrev: 'Предыдущий',
labelMonthSelect: 'Выбрать месяц',
labelYearSelect: 'Выбрать год',
selectMonths: true, // Creates a dropdown to control month
selectYears: 200 // Creates a dropdown of number years to control year
});
});
|
"use strict";
/*global ajaxify, templates*/
(function(ajaxify) {
ajaxify.widgets = {};
ajaxify.widgets.reposition = function(location) {
$('body [no-widget-class]').each(function() {
var $this = $(this);
if ($this.attr('no-widget-target') === location) {
$this.removeClass();
$this.addClass($this.attr('no-widget-class'));
}
});
};
ajaxify.widgets.render = function(template, url, callback) {
var widgetLocations = ['sidebar', 'footer', 'header'], numLocations;
$('#content [widget-area]').each(function() {
var location = $(this).attr('widget-area');
if ($.inArray(location, widgetLocations) === -1) {
widgetLocations.push(location);
}
});
numLocations = widgetLocations.length;
if (!numLocations) {
ajaxify.widgets.reposition();
}
function renderWidgets(location) {
var area = $('#content [widget-area="' + location + '"]'),
areaData = {
location: location,
template: template + '.tpl',
url: url
};
$.get(RELATIVE_PATH + '/api/widgets/render', areaData, function(renderedWidgets) {
var html = '';
for (var i=0; i<renderedWidgets.length; ++i) {
html += templates.parse(renderedWidgets[i].html, {});
}
if (!area.length && window.location.pathname.indexOf('/admin') === -1 && renderedWidgets.length) {
if (location === 'footer' && !$('#content [widget-area="footer"]').length) {
$('#content').append($('<div class="col-xs-12"><div widget-area="footer"></div></div>'));
} else if (location === 'sidebar' && !$('#content [widget-area="sidebar"]').length) {
$('#content > *').wrapAll($('<div class="col-lg-9 col-xs-12"></div>'));
$('#content').append($('<div class="col-lg-3 col-xs-12"><div widget-area="sidebar"></div></div>'));
} else if (location === 'header' && !$('#content [widget-area="header"]').length) {
$('#content').prepend($('<div class="col-xs-12"><div widget-area="header"></div></div>'));
}
area = $('#content [widget-area="' + location + '"]');
}
area.html(html);
if (!renderedWidgets.length) {
area.addClass('hidden');
ajaxify.widgets.reposition(location);
}
$('#content [widget-area] img:not(.user-img)').addClass('img-responsive');
checkCallback();
});
}
function checkCallback() {
numLocations--;
if (numLocations < 0) {
$(window).trigger('action:widgets.loaded', {});
if (typeof callback === 'function') {
callback();
}
}
}
for (var i=0; i<widgetLocations.length; ++i) {
renderWidgets(widgetLocations[i]);
}
checkCallback();
};
}(ajaxify || {}));
|
import Vuex, { Store } from 'vuex';
import VueRouter from 'vue-router';
import { createLocalVue, mount } from '@vue/test-utils';
import { SelectList } from '../../src/components';
import fixtures from '../__fixtures__/common';
describe('SelectList.test.js', () => {
let localVue;
let store;
beforeEach(() => {
localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(VueRouter);
const { state } = fixtures;
store = new Store({ state });
});
it('renders', () => {
const wrapper = mount(SelectList, {
localVue,
store,
propsData: {
listItems: []
}
});
expect(wrapper.element).toMatchSnapshot();
});
it('renders with values', async () => {
const expectedItems = [
'abc',
'bcd',
'test'
];
const wrapper = mount(SelectList, {
localVue,
store,
propsData: {
listItems: expectedItems
}
});
expectedItems.forEach(item => {
wrapper.setData({ newItem: item });
wrapper.vm.addNewItem();
});
await wrapper.vm.$nextTick();
expect(wrapper.element).toMatchSnapshot();
const inputWrapperArray = wrapper.findAll('li input[type="text"]');
expect(inputWrapperArray.length).toEqual(expectedItems.length);
wrapper.vm.editItems.forEach((item, index) => {
expect(item.value).toEqual(expectedItems[index]);
});
});
});
|
'use strict';
define(['lodash'], function(_) {
var dependencies = ['$stateParams', '$q', 'ModelService',
'PataviService', 'ResultsPlotService',
'CacheService'
];
var RankProbabilitiesPlotDirective = function($stateParams, $q, ModelService,
PataviService, ResultsPlotService, CacheService) {
return {
restrict: 'E',
scope: {
analysisId: '=',
modelId: '=',
baselineTreatmentId: '=',
regressionLevel: '='
},
templateUrl: './rankProbabilitiesPlotTemplate.html',
link: function(scope) {
scope.resultsMessage = {};
function getResults(model) {
return PataviService.listen(model.taskUrl);
}
var problemPromise = CacheService.getProblem($stateParams.projectId, scope.analysisId);
var modelPromise = CacheService.getModel($stateParams.projectId, scope.analysisId, scope.modelId);
$q.all([problemPromise, modelPromise]).then(function(values) {
var problem = values[0];
var model = values[1];
getResults(model).then(function(results) {
var rankProbabilitiesByLevel = ModelService.addLevelandProcessData(results.rankProbabilities,
problem.treatments, ModelService.nameRankProbabilities);
if (scope.regressionLevel !== undefined) {
scope.rankProbabilities = _.find(rankProbabilitiesByLevel, ['level', scope.regressionLevel.toString()]);
} else {
var rankProbabilities = ModelService.selectLevel(model.regressor, problem, rankProbabilitiesByLevel,
results.regressor);
scope.rankProbabilities = rankProbabilities.selected;
}
});
});
}
};
};
return dependencies.concat(RankProbabilitiesPlotDirective);
});
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* Refer 13.1;
* It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs within a FormalParameterList
* of a strict mode FunctionDeclaration or FunctionExpression.
*
* @path ch13/13.1/13.1-18-s.js
* @description StrictMode - SyntaxError is thrown if the identifier 'eval' appears within a FormalParameterList of a strict mode FunctionExpression when FuctionBody is strict code
* @onlyStrict
*/
function testcase() {
try {
eval("var _13_1_18_fun = function (eval) { 'use strict'; }");
return false;
} catch (e) {
return e instanceof SyntaxError;
}
}
runTestCase(testcase);
|
/*global define*/
define([
'../Core/defaultValue',
'../Core/defined',
'../Core/DeveloperError',
'../Core/getImagePixels',
'../Core/loadImageViaBlob',
'../ThirdParty/when'
], function(
defaultValue,
defined,
DeveloperError,
getImagePixels,
loadImageViaBlob,
when) {
"use strict";
/**
* A policy for discarding tile images that match a known image containing a
* "missing" image.
*
* @alias DiscardMissingTileImagePolicy
* @constructor
*
* @param {Object} options Object with the following properties:
* @param {String} options.missingImageUrl The URL of the known missing image.
* @param {Cartesian2[]} options.pixelsToCheck An array of {@link Cartesian2} pixel positions to
* compare against the missing image.
* @param {Boolean} [options.disableCheckIfAllPixelsAreTransparent=false] If true, the discard check will be disabled
* if all of the pixelsToCheck in the missingImageUrl have an alpha value of 0. If false, the
* discard check will proceed no matter the values of the pixelsToCheck.
*/
var DiscardMissingTileImagePolicy = function(options) {
options = defaultValue(options, defaultValue.EMPTY_OBJECT);
if (!defined(options.missingImageUrl)) {
throw new DeveloperError('options.missingImageUrl is required.');
}
if (!defined(options.pixelsToCheck)) {
throw new DeveloperError('options.pixelsToCheck is required.');
}
this._pixelsToCheck = options.pixelsToCheck;
this._missingImagePixels = undefined;
this._missingImageByteLength = undefined;
this._isReady = false;
var that = this;
function success(image) {
if (defined(image.blob)) {
that._missingImageByteLength = image.blob.size;
}
var pixels = getImagePixels(image);
if (options.disableCheckIfAllPixelsAreTransparent) {
var allAreTransparent = true;
var width = image.width;
var pixelsToCheck = options.pixelsToCheck;
for (var i = 0, len = pixelsToCheck.length; allAreTransparent && i < len; ++i) {
var pos = pixelsToCheck[i];
var index = pos.x * 4 + pos.y * width;
var alpha = pixels[index + 3];
if (alpha > 0) {
allAreTransparent = false;
}
}
if (allAreTransparent) {
pixels = undefined;
}
}
that._missingImagePixels = pixels;
that._isReady = true;
}
function failure() {
// Failed to download "missing" image, so assume that any truly missing tiles
// will also fail to download and disable the discard check.
that._missingImagePixels = undefined;
that._isReady = true;
}
when(loadImageViaBlob(options.missingImageUrl), success, failure);
};
/**
* Determines if the discard policy is ready to process images.
* @returns True if the discard policy is ready to process images; otherwise, false.
*/
DiscardMissingTileImagePolicy.prototype.isReady = function() {
return this._isReady;
};
/**
* Given a tile image, decide whether to discard that image.
*
* @param {Image} image An image to test.
* @returns True if the image should be discarded; otherwise, false.
*
* @exception {DeveloperError} <code>shouldDiscardImage</code> must not be called before the discard policy is ready.
*/
DiscardMissingTileImagePolicy.prototype.shouldDiscardImage = function(image) {
if (!this._isReady) {
throw new DeveloperError('shouldDiscardImage must not be called before the discard policy is ready.');
}
var pixelsToCheck = this._pixelsToCheck;
var missingImagePixels = this._missingImagePixels;
// If missingImagePixels is undefined, it indicates that the discard check has been disabled.
if (!defined(missingImagePixels)) {
return false;
}
if (defined(image.blob) && image.blob.size !== this._missingImageByteLength) {
return false;
}
var pixels = getImagePixels(image);
var width = image.width;
for (var i = 0, len = pixelsToCheck.length; i < len; ++i) {
var pos = pixelsToCheck[i];
var index = pos.x * 4 + pos.y * width;
for (var offset = 0; offset < 4; ++offset) {
var pixel = index + offset;
if (pixels[pixel] !== missingImagePixels[pixel]) {
return false;
}
}
}
return true;
};
return DiscardMissingTileImagePolicy;
});
|
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2015 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko
* Website: http://www.espocrm.com
*
* EspoCRM is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
************************************************************************/
Espo.define('Crm:Views.Record.Panels.Tasks', 'Views.Record.Panels.Relationship', function (Dep) {
return Dep.extend({
name: 'tasks',
template: 'crm:record.panels.tasks',
tabList: ['actual', 'completed'],
defaultTab: 'actual',
sortBy: 'createdAt',
asc: false,
buttonList: [
{
action: 'createTask',
title: 'Create Task',
acl: 'edit',
aclScope: 'Task',
html: '<span class="glyphicon glyphicon-plus"></span>',
}
],
listLayout: {
rows: [
[
{
name: 'name',
link: true,
},
{
name: 'isOverdue'
}
],
[
{name: 'assignedUser'},
{name: 'status'},
{name: 'dateEnd'},
]
]
},
events: _.extend({
'click button.tab-switcher': function (e) {
var $target = $(e.currentTarget);
this.$el.find('button.tab-switcher').removeClass('active');
$target.addClass('active');
this.currentTab = $target.data('tab');
this.collection.where = this.where = [
{
type: 'primary',
value: this.currentTab
}
];
this.listenToOnce(this.collection, 'sync', function () {
this.notify(false);
}.bind(this));
this.notify('Loading...');
this.collection.fetch();
this.getStorage().set('state', this.getStorageKey(), this.currentTab);
}
}, Dep.prototype.events),
data: function () {
return {
currentTab: this.currentTab,
tabList: this.tabList
};
},
getStorageKey: function () {
return 'tasks-' + this.model.name + '-' + this.name;
},
setup: function () {
this.scope = this.model.name;
this.currentTab = this.getStorage().get('state', this.getStorageKey()) || this.defaultTab;
this.where = [
{
type: 'primary',
value: this.currentTab
}
];
},
afterRender: function () {
var link = 'tasks';
if (this.scope == 'Account') {
link = 'tasksPrimary';
}
var url = this.model.name + '/' + this.model.id + '/' + link;
if (!this.getAcl().check('Task', 'read')) {
this.$el.find('.list-container').html(this.translate('No Access'));
this.$el.find('.button-container').remove();
return;
};
this.getCollectionFactory().create('Task', function (collection) {
this.collection = collection;
collection.seeds = this.seeds;
collection.url = url;
collection.where = this.where;
collection.sortBy = this.sortBy;
collection.asc = this.asc;
collection.maxSize = this.getConfig().get('recordsPerPageSmall') || 5;
this.listenToOnce(this.collection, 'sync', function () {
this.createView('list', 'Record.ListExpanded', {
el: this.$el.selector + ' > .list-container',
pagination: false,
type: 'listRelationship',
rowActionsView: 'Record.RowActions.RelationshipNoUnlink',
checkboxes: false,
collection: collection,
listLayout: this.listLayout,
}, function (view) {
view.render();
});
}.bind(this));
this.collection.fetch();
}, this);
},
actionCreateTask: function (data) {
var self = this;
var link = 'tasks';
var scope = 'Task';
var foreignLink = this.model.defs['links'][link].foreign;
this.notify('Loading...');
this.createView('quickCreate', 'Modals.Edit', {
scope: scope,
relate: {
model: this.model,
link: foreignLink,
}
}, function (view) {
view.render();
view.notify(false);
view.once('after:save', function () {
self.collection.fetch();
});
});
},
actionRefresh: function () {
this.collection.fetch();
}
});
});
|
/*
* commonjs/prefs.js - preferences defaults and helper functions
*
* This class is used to make the prefs handling between the different versions
* more uniform. The functions here are completely framework agnostic.
*/
/* FeedReader - A RSS Feed Aggregator for Firefox OS
* Copyright (C) 2009-2013 Timo Tegtmeier
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
function DefaultPrefs() {
}
DefaultPrefs.prototype = {
updateInterval: 30,
storyKeepTime: 24 * 3,
updateOnStart: true,
notificationEnabled: true,
notifyWithSound: false,
blinkingEnabled: true,
notifyWhileRunning: true,
unobtrusiveNotifications: true,
wakingEnabled: false,
titleColor: "black",
summaryLength: 120,
largeFont: false,
showNewCount: true,
showUnreadCount: true,
showChanges: false,
leftHanded: true,
enableRotation: true,
rilUser: "", // Read it Later
rilPassword: "",
gReaderUser: "", // Google Reader
gReaderPassword: ""
};
function _copyPrefs(source, target) {
var defaults = new DefaultPrefs();
for(key in defaults) {
var sourceSetting = source[key];
target[key] = sourceSetting !== undefined ? sourceSetting : defaults[key];
}
}
function PrefsLoader(source) {
this.source = source;
}
PrefsLoader.prototype.loadInto = function(target, currentVersion) {
_copyPrefs(this.source, target);
if(this.source.version < currentVersion) {
target.showChanges = true;
target.save(false);
}
};
function PrefsSaver(source) {
this.source = source;
}
PrefsSaver.prototype.saveInto = function(target, currentVersion) {
_copyPrefs(this.source, target);
target["version"] = currentVersion;
};
|
import Ember from "ember";
import UserSession from "hospitalrun/mixins/user-session";
export default Ember.ObjectController.extend(UserSession, {
canAdmitPatient: function() {
var admitted = this.get('admitted');
if (!admitted) {
return this.currentUserCan('admit_patient');
}
}.property('admitted'),
canDischargePatient: function() {
var admitted = this.get('admitted');
if (admitted) {
return this.currentUserCan('discharge_patient');
}
}.property('admitted'),
canDelete: function() {
return this.parentController.get('canDelete');
}.property(),
canAdd: function() {
return this.parentController.get('canAdd');
}.property(),
showActions: function() {
return this.parentController.get('showActions');
}.property()
});
|
var _ = require('lodash'),
config = require('../../config'),
getConfig;
getConfig = function getConfig(name) {
var defaults = {
// custom ---v [@aguestuser -- 1.16.16]
blog: {
name: 'blog',
route: '/blog'
},
index: {
name: 'index',
route: '/',
frontPageTemplate: 'home'
},
// ^--- end custom
tag: {
name: 'tag',
route: '/' + config.routeKeywords.tag + '/:slug/',
postOptions: {
filter: 'tags:\'%s\''
},
data: {
tag: {
type: 'read',
resource: 'tags',
options: {slug: '%s'}
}
},
slugTemplate: true
},
author: {
name: 'author',
route: '/' + config.routeKeywords.author + '/:slug/',
postOptions: {
filter: 'author:\'%s\''
},
data: {
author: {
type: 'read',
resource: 'users',
options: {slug: '%s'}
}
},
slugTemplate: true
}
};
return _.cloneDeep(defaults[name]);
};
module.exports = getConfig;
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'fakeobjects', 'sr-latn', {
anchor: 'Unesi/izmeni sidro',
flash: 'Flash Animation', // MISSING
hiddenfield: 'Skriveno polje',
iframe: 'IFrame', // MISSING
unknown: 'Unknown Object' // MISSING
} );
|
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'table', 'pt', {
border: 'Tamanho da Margem',
caption: 'Título',
cell: {
menu: 'Célula',
insertBefore: 'Inserir Célula Antes',
insertAfter: 'Inserir Célula Depois',
deleteCell: 'Apagar Células',
merge: 'Unir Células',
mergeRight: 'Unir à Direita',
mergeDown: 'Unir Abaixo',
splitHorizontal: 'Dividir Célula Horizontalmente',
splitVertical: 'Dividir Célula Verticalmente',
title: 'Propriedades da Célula',
cellType: 'Tipo de Célula',
rowSpan: 'Filas na Célula',
colSpan: 'Colunas na Célula',
wordWrap: 'Continuar',
hAlign: 'Alinhamento Horizontal',
vAlign: 'Alinhamento Vertical',
alignBaseline: 'Base',
bgColor: 'Cor de Fundo',
borderColor: 'Cor da Margem',
data: 'Dados',
header: 'Cabeçalho',
yes: 'Sim',
no: 'Não',
invalidWidth: 'A largura da célula deve ser um número.',
invalidHeight: 'A altura da célula deve ser um número.',
invalidRowSpan: 'As filas da célula deve ter um número inteiro.',
invalidColSpan: 'As colunas da célula deve ter um número inteiro.',
chooseColor: 'Escolher'
},
cellPad: 'Criação de Espaço',
cellSpace: 'Espaçamento Célula',
column: {
menu: 'Coluna',
insertBefore: 'Inserir Coluna Antes',
insertAfter: 'Inserir Coluna Depois',
deleteColumn: 'Apagar Colunas'
},
columns: 'Colunas',
deleteTable: 'Apagar Tabela',
headers: 'Cabeçalhos',
headersBoth: 'Ambos',
headersColumn: 'Primeira coluna',
headersNone: 'Nenhum',
headersRow: 'Primeira Linha',
invalidBorder: 'O tamanho da margem tem de ser um número.',
invalidCellPadding: 'A criação do espaço na célula deve ser um número positivo.',
invalidCellSpacing: 'O espaçamento da célula deve ser um número positivo.',
invalidCols: 'O número de colunas tem de ser um número maior que 0.',
invalidHeight: 'A altura da tabela tem de ser um número.',
invalidRows: 'O número das linhas tem de ser um número maior que 0.',
invalidWidth: 'A largura da tabela tem de ser um número.',
menu: 'Propriedades da Tabela',
row: {
menu: 'Linha',
insertBefore: 'Inserir Linha Antes',
insertAfter: 'Inserir Linha Depois',
deleteRow: 'Apagar Linhas'
},
rows: 'Linhas',
summary: 'Sumário',
title: 'Propriedades da Tabela',
toolbar: 'Tabela',
widthPc: 'percentagem',
widthPx: 'pontos',
widthUnit: 'unidade da largura'
} );
|
// -*- indent-tabs-mode: nil; js-indent-level: 2 -*-
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
Components.utils.import("resource://gre/modules/Services.jsm");
Components.utils.import("resource://gre/modules/FormHistory.jsm");
var dialog; // Quick access to document/form elements.
var gFindInst; // nsIWebBrowserFind that we're going to use
var gFindInstData; // use this to update the find inst data
function initDialogObject()
{
// Create dialog object and initialize.
dialog = new Object;
dialog.findKey = document.getElementById("dialog.findKey");
dialog.caseSensitive = document.getElementById("dialog.caseSensitive");
dialog.wrap = document.getElementById("dialog.wrap");
dialog.find = document.getElementById("btnFind");
dialog.up = document.getElementById("radioUp");
dialog.down = document.getElementById("radioDown");
dialog.rg = dialog.up.radioGroup;
dialog.bundle = null;
// Move dialog to center, if it not been shown before
var windowElement = document.getElementById("findDialog");
if (!windowElement.hasAttribute("screenX") || !windowElement.hasAttribute("screenY"))
{
sizeToContent();
moveToAlertPosition();
}
}
function fillDialog()
{
// get the find service, which stores global find state
var findService = Components.classes["@mozilla.org/find/find_service;1"]
.getService(Components.interfaces.nsIFindService);
// Set initial dialog field contents. Use the gFindInst attributes first,
// this is necessary for window.find()
dialog.findKey.value = gFindInst.searchString ? gFindInst.searchString : findService.searchString;
dialog.caseSensitive.checked = gFindInst.matchCase ? gFindInst.matchCase : findService.matchCase;
dialog.wrap.checked = gFindInst.wrapFind ? gFindInst.wrapFind : findService.wrapFind;
var findBackwards = gFindInst.findBackwards ? gFindInst.findBackwards : findService.findBackwards;
if (findBackwards)
dialog.rg.selectedItem = dialog.up;
else
dialog.rg.selectedItem = dialog.down;
}
function saveFindData()
{
// get the find service, which stores global find state
var findService = Components.classes["@mozilla.org/find/find_service;1"]
.getService(Components.interfaces.nsIFindService);
// Set data attributes per user input.
findService.searchString = dialog.findKey.value;
findService.matchCase = dialog.caseSensitive.checked;
findService.wrapFind = dialog.wrap.checked;
findService.findBackwards = dialog.up.selected;
}
function onLoad()
{
initDialogObject();
// get the find instance
var arg0 = window.arguments[0];
// If the dialog was opened from window.find(),
// arg0 will be an instance of nsIWebBrowserFind
if (arg0 instanceof Components.interfaces.nsIWebBrowserFind) {
gFindInst = arg0;
} else {
gFindInstData = arg0;
gFindInst = gFindInstData.webBrowserFind;
}
fillDialog();
doEnabling();
if (dialog.findKey.value)
dialog.findKey.select();
dialog.findKey.focus();
}
function onUnload()
{
window.opener.findDialog = 0;
}
function onAccept()
{
if (gFindInstData && gFindInst != gFindInstData.webBrowserFind) {
gFindInstData.init();
gFindInst = gFindInstData.webBrowserFind;
}
// Transfer dialog contents to the find service.
saveFindData();
updateFormHistory();
// set up the find instance
gFindInst.searchString = dialog.findKey.value;
gFindInst.matchCase = dialog.caseSensitive.checked;
gFindInst.wrapFind = dialog.wrap.checked;
gFindInst.findBackwards = dialog.up.selected;
// Search.
var result = gFindInst.findNext();
if (!result)
{
if (!dialog.bundle)
dialog.bundle = document.getElementById("findBundle");
Services.prompt.alert(window, dialog.bundle.getString("notFoundTitle"),
dialog.bundle.getString("notFoundWarning"));
dialog.findKey.select();
dialog.findKey.focus();
}
return false;
}
function doEnabling()
{
dialog.find.disabled = !dialog.findKey.value;
}
function updateFormHistory()
{
if (window.opener.PrivateBrowsingUtils &&
window.opener.PrivateBrowsingUtils.isWindowPrivate(window.opener) ||
!dialog.findKey.value)
return;
FormHistory.update({
op: "bump",
fieldname: "find-dialog",
value: dialog.findKey.value
}, {
handleError: function(aError) {
Components.utils.reportError("Saving find to form history failed: " +
aError.message);
}
});
}
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at <http://mozilla.org/MPL/2.0/>. */
// @flow
import type { Command } from "../../reducers/types";
import type { Expression, LoadedObject, Frame, Scope, Why } from "../../types";
import type { PromiseAction } from "../utils/middleware/promise";
export type PauseAction =
| {|
+type: "BREAK_ON_NEXT",
+value: boolean
|}
| {|
+type: "RESUME",
+value: void
|}
| {|
+type: "PAUSED",
+why: Why,
+scopes: Scope,
+frames: Frame[],
+selectedFrameId: string,
+loadedObjects: LoadedObject[]
|}
| {|
+type: "PAUSE_ON_EXCEPTIONS",
+shouldPauseOnExceptions: boolean,
+shouldPauseOnCaughtExceptions: boolean
|}
| PromiseAction<{|
+type: "COMMAND",
+command: Command
|}>
| {|
+type: "SELECT_FRAME",
+frame: Frame
|}
| {|
+type: "SELECT_COMPONENT",
+componentIndex: number
|}
| {|
+type: "SET_POPUP_OBJECT_PROPERTIES",
+objectId: string,
+properties: Object
|}
| {|
+type: "ADD_EXPRESSION",
+id: number,
+input: string,
+value: string,
+expressionError: ?string
|}
| PromiseAction<
{|
+type: "EVALUATE_EXPRESSION",
+input: string
|},
Object
>
| PromiseAction<{|
+type: "EVALUATE_EXPRESSIONS",
+results: Expression[],
+inputs: string[]
|}>
| {|
+type: "UPDATE_EXPRESSION",
+expression: Expression,
+input: string,
+expressionError: ?string
|}
| {|
+type: "DELETE_EXPRESSION",
+input: string
|}
| {|
+type: "CLEAR_AUTOCOMPLETE"
|}
| {|
+type: "CLEAR_EXPRESSION_ERROR"
|}
| {|
+type: "AUTOCOMPLETE",
+input: string,
+result: Object
|}
| PromiseAction<
{|
+type: "MAP_SCOPES",
+frame: Frame
|},
{
scope: Scope,
mappings: {
[string]: string | null
}
}
>
| {|
+type: "MAP_FRAMES",
+frames: Frame[]
|}
| {|
+type: "ADD_EXTRA",
+extra: any
|}
| PromiseAction<
{|
+type: "ADD_SCOPES",
+frame: Frame
|},
Scope
>
| {|
+type: "TOGGLE_SKIP_PAUSING",
skipPausing: boolean
|};
|
var data = require('../../fixtures/data'),
heads = JSON.parse(data.event.json),
macros = require('../../fixtures/macros'),
Parser = require('../../../lib/esl/Parser'),
parser, socket;
describe('esl.Parser', function() {
before(function(done) {
macros.getEchoServerSocket(function(err, client, server) {
if(err) return done(err);
socket = client;
parser = new Parser(client);
done();
});
});
it('should have the correct exports', function() {
expect(Parser).to.be.a('function');
});
describe('normal events', describeEvents(data.stream.normal));
describe('plain events', describeEvents(data.stream.plain));
describe('json events', describeEvents(data.stream.json));
describe('xml events', describeEvents(data.stream.xml));
describe('normal events doubled', describeEvents(data.stream.normal + data.stream.normal));
describe('plain events doubled', describeEvents(data.stream.plain + data.stream.plain));
describe('json events doubled', describeEvents(data.stream.json + data.stream.json));
describe('xml events doubled', describeEvents(data.stream.xml + data.stream.xml));
after(function() {
socket.end();
});
});
function describeEvents(streamData) {
return function() {
it('should parse an event given all at once', function(done) {
parser.once('esl::event', testParserEvent.bind(null, done));
socket.write(streamData);
});
it('should parse an event given one line at a time', function(done) {
parser.once('esl::event', testParserEvent.bind(null, done));
//make socket get only 1 line at a time, to test the parser
//gleaning only parts at a time
(function writeSocketLinesAsync(socket, lns, i) {
if(i === lns.length) return;
socket.write(lns[i] + '\n');
process.nextTick(function() {
writeSocketLinesAsync(socket, lns, ++i);
});
})(socket, streamData.split('\n'), 0);
});
};
}
function testParserEvent(done, evt) {
//event name
expect(evt.getType()).to.equal(heads['Event-Name']);
expect(evt.type).to.equal(heads['Event-Name']);
expect(evt.getHeader('Event-Name')).to.equal(heads['Event-Name']);
//subclass
expect(evt.getHeader('Event-Subclass')).to.equal(heads['Event-Subclass']);
//body
expect(evt.getBody()).to.equal(heads._body);
//content type
if(!heads['Content-Type'])
expect(evt.getHeader('Content-Type')).to.be.null;
else
expect(evt.getHeader('Content-Type')).to.equal(heads['Content-Type']);
done();
}
|
const { FileModel } = require('./model');
class ThumbnailService {
patch(id, data) {
return FileModel.updateOne(
{ thumbnailRequestToken: id },
{
$set: {
thumbnailRequestToken: null,
thumbnail: data.thumbnail,
},
}
).exec();
}
setup(app) {
this.app = app;
}
}
module.exports = function service() {
const app = this;
// Initialize our service with any options it requires
app.use('/fileStorage/thumbnail', new ThumbnailService());
};
|
import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import SPELLS from 'common/SPELLS';
import { formatThousands } from 'common/format';
import TraitStatisticBox from 'interface/others/TraitStatisticBox';
import ItemDamageDone from 'interface/others/ItemDamageDone';
/*
Umbral Blaze:
Your Hand of Guldan has a 15% chance to burn its target for X additional Shadowflame damage every 2 sec for 6 sec.
*/
class UmbralBlaze extends Analyzer {
damage = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTrait(SPELLS.UMBRAL_BLAZE.id);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.UMBRAL_BLAZE_DEBUFF), this.onUmbralBlazeDamage);
}
onUmbralBlazeDamage(event) {
this.damage += event.amount + (event.absorbed || 0);
}
statistic() {
return (
<TraitStatisticBox
trait={SPELLS.UMBRAL_BLAZE.id}
value={<ItemDamageDone amount={this.damage} />}
tooltip={`${formatThousands(this.damage)} damage`}
/>
);
}
}
export default UmbralBlaze;
|
const { Configuration } = require('@hpi-schul-cloud/commons');
/**
* Converts consentStatus to a filter condition for consent
* @param {...string} status
*/
const createConsentFilterQuery = (...status) => {
const currentDate = new Date();
const secondConsentSwitchDate = new Date();
secondConsentSwitchDate.setFullYear(currentDate.getFullYear() - Configuration.get('CONSENT_AGE_SECOND'));
const firstConsentSwitchDate = new Date();
firstConsentSwitchDate.setFullYear(currentDate.getFullYear() - Configuration.get('CONSENT_AGE_FIRST'));
const createRequiredConsents = (...persons) =>
persons.reduce((person, current) => {
current[`consent.${person}.privacyConsent`] = true;
current[`consent.${person}.termsOfUseConsent`] = true;
return current;
}, {});
const createMissingConsents = (...persons) =>
persons.reduce(
(person, current) => {
current.$or.push({ [`consent.${person}.privacyConsent`]: true });
current.$or.push({ [`consent.${person}.termsOfUseConsent`]: true });
return current;
},
{ $or: [] }
);
const orConditions = status.reduce((query, stat) => {
if (stat === 'missing') {
query.push({
...createMissingConsents('userConsent'),
birthday: {
$gte: secondConsentSwitchDate,
},
});
query.push({
...createMissingConsents('parentConsents'),
birthday: {
$gt: firstConsentSwitchDate,
$lte: secondConsentSwitchDate,
},
});
query.push({
...createMissingConsents('parentConsents'),
birthday: {
$lt: firstConsentSwitchDate,
},
});
} else if (stat === 'parentAgree') {
query.push({
...createRequiredConsents('parentConsents'),
...createMissingConsents('userConsent'),
birthday: {
$gt: firstConsentSwitchDate,
$lte: secondConsentSwitchDate,
},
});
} else if (stat === 'ok') {
query.push({
...createRequiredConsents('userConsent'),
birthday: {
$gte: secondConsentSwitchDate,
},
});
query.push({
...createRequiredConsents('userConsent', 'parentConsents'),
birthday: {
$gt: firstConsentSwitchDate,
$lte: secondConsentSwitchDate,
},
});
query.push({
...createRequiredConsents('parentConsents'),
birthday: {
$lt: firstConsentSwitchDate,
},
});
}
return query;
}, []);
return {
$or: orConditions,
};
};
const checkParentConsent = (parentConsents) => {
if (!parentConsents) return false;
const agrements = parentConsents.filter((consent) => consent.privacyConsent && consent.termsOfUseConsent);
if (parentConsents.length !== 0 && agrements.length === parentConsents.length) {
return true;
}
return false;
};
const checkUserConsent = (userConsent) => userConsent && userConsent.privacyConsent && userConsent.termsOfUseConsent;
/**
* Calculate the consent status
* @param {Date} birthday
* @param {Object} consent
*/
const defineConsentStatus = (birthday, consent) => {
if (!consent) {
return 'missing';
}
if (!birthday) {
if (checkUserConsent(consent.userConsent) === true) {
return 'ok';
}
return 'unknown';
}
const currentDate = new Date();
const secondConsentSwitchDate = new Date();
secondConsentSwitchDate.setFullYear(currentDate.getFullYear() - Configuration.get('CONSENT_AGE_SECOND'));
const firstConsentSwitchDate = new Date();
firstConsentSwitchDate.setFullYear(currentDate.getFullYear() - Configuration.get('CONSENT_AGE_FIRST'));
const { parentConsents, userConsent } = consent;
if (birthday.getTime() > firstConsentSwitchDate.getTime()) {
// only parents have to agree
if (checkParentConsent(parentConsents) === true) {
return 'ok';
}
} else if (birthday.getTime() <= secondConsentSwitchDate.getTime()) {
// only user has to agree
if (checkUserConsent(userConsent) === true) {
return 'ok';
}
} else if (checkParentConsent(parentConsents)) {
if (checkUserConsent(userConsent) === true) {
return 'ok';
}
return 'parentsAgreed';
}
return 'missing';
};
/**
* Calclulate if parent Consent is required
* @param {Date} birthday
* @returns {boolean}
*/
const isParentConsentRequired = (birthday) => {
if (!(birthday instanceof Date)) return undefined;
const currentDate = new Date();
const secondConsentSwitchDate = new Date();
secondConsentSwitchDate.setFullYear(currentDate.getFullYear() - Configuration.get('CONSENT_AGE_SECOND'));
if (birthday.getTime() <= secondConsentSwitchDate.getTime()) {
return false;
}
return true;
};
/**
* Creates a consent object, how it looked before it moved to users model
* @param {*} user
*/
const userToConsent = (user) => ({
_id: user._id,
userId: user._id,
requiresParentConsent: isParentConsentRequired(user.birthday),
consentStatus: defineConsentStatus(user.birthday, user.consent),
...user.consent,
});
/**
* data will be moved to the attribute consent
* @param {Object} data
*/
// eslint-disable-next-line no-unused-vars
const modifyDataForUserSchema = ({ _id, userId, ...data }) => ({
consent: {
...data,
},
});
module.exports = {
defineConsentStatus,
isParentConsentRequired,
createConsentFilterQuery,
userToConsent,
modifyDataForUserSchema,
};
|
/**
* @author Anakeen
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
*/
// --------------------------------------------------
// $Id: Lib.General.js,v 1.1 2002/01/08 12:41:34 eric Exp $
// --------------------------------------------------
// $Log: Lib.General.js,v $
// Revision 1.1 2002/01/08 12:41:34 eric
// first
//
// Revision 1.1 2000/11/06 20:19:39 marc
// Creation de Generals (checkint)
// Ajout des scrollbars dans les fenetres complementaires
//
//
// --------------------------------------------------
// Check date and time format
//
// Check for an unsigned integer.
// ------------------------------
function checkint(val, min, max) {
var reint = /^[\s]*[\d]+[\s]*$/;
if (val == "" ) return false;
if (reint.test(val)) {
if (min != -1 && val<min) return false;
if (max != -1 && val>max) return false;
} else {
return false;
}
return true;
}
|
OC.L10N.register(
"federatedfilesharing",
{
"Federated sharing" : "Compartilhamento federado",
"Add to your ownCloud" : "Adiconar ao seu ownCloud",
"Invalid Federated Cloud ID" : "Inválida Associação de Nuvem ID",
"Sharing %s failed, because this item is already shared with %s" : "Compartilhamento %s falhou, porque este ítem já está compartilhado com %s",
"Not allowed to create a federated share with the same user" : "Não é permitido criar um compartilhamento associado com o mesmo usuário",
"File is already shared with %s" : "O arquivo já é compartilhado com %s",
"Sharing %s failed, could not find %s, maybe the server is currently unreachable." : "O compartilhamento %s falhou, porque não foi possível encontrar %s, talvez o servidor esteja inacessível.",
"You received \"/%3$s\" as a remote share from %1$s (on behalf of %2$s)" : "Você recebeu \"/%3$s\" como um compartilhamento remoto de %1$s (em nome de %2$s)",
"You received \"/%3$s\" as a remote share from %1$s" : "Você recebeu \"/%3$s\" como um compertilhamento remoto de %1$s",
"Accept" : "Aceitar",
"Decline" : "Rejeitar",
"Share with me through my #ownCloud Federated Cloud ID, see %s" : "Compartilhe comigo através do meu #ownCloud Nuvem ID Federada, veja %s",
"Share with me through my #ownCloud Federated Cloud ID" : "Compartilhe comigo através do meu #ownCloud Nuvem ID Federada",
"Federated Cloud Sharing" : "Nuvem Associada Federada",
"Open documentation" : "Abrir documentação",
"Allow users on this server to send shares to other servers" : "Permitir que os usuários deste servidor enviem compartilhamentos para outros servidores",
"Allow users on this server to receive shares from other servers" : "Permitir que os usuários nesse servidor recebam compartilhamentos de outros servidores",
"Federated Cloud" : "Nuvem Federada",
"Your Federated Cloud ID:" : "Sua ID na Nuvem Federada:",
"Share it:" : "Compartilhe:",
"Add to your website" : "Adicione ao seu website",
"Share with me via ownCloud" : "Compartilhe comigo via ownCloud",
"HTML Code:" : "Código HTML:"
},
"nplurals=2; plural=(n > 1);");
|
//
// Component displaying date filter inputs
//
import React from 'react';
import moment from 'moment';
import DatePicker from 'components/DatePicker';
import RadioGroup from 'components/RadioGroup';
import {
FormGroup,
ControlLabel,
HelpBlock,
Label,
Collapse,
} from 'react-bootstrap';
import styles from './styles.css';
/* eslint-disable react/prefer-stateless-function */
export default class DateRange extends React.Component {
constructor(props) {
super(props);
this.state = {
specific: true,
dateOne: moment().utcOffset(moment().toISOString()).startOf('date').toISOString(),
dateTwo: moment().utcOffset(moment().toISOString()).startOf('date').toISOString(),
};
}
setStateAndNotify(state) {
this.setState(state, () => this.props.onChange({
specific: this.state.specific,
dateOne: this.state.dateOne,
dateTwo: this.state.dateTwo,
}));
}
setStatusStyle() {
if (this.state.specific) {
return undefined;
}
if (this.state.dateOne !== null && this.state.dateTwo !== null) {
if (moment(new Date(this.state.dateOne)) > moment(new Date(this.state.dateTwo))) {
return 'error';
}
}
return undefined;
}
setMessageStatus() {
if (this.state.specific) {
return undefined;
}
if (this.state.dateOne !== null && this.state.dateTwo !== null) {
if (moment(new Date(this.state.dateOne)) > moment(new Date(this.state.dateTwo))) {
return 'First date must be before second date';
}
}
return '';
}
handleChange(name) {
return (event) => {
switch (name) {
case 'mode':
this.setStateAndNotify({ specific: event === 'Specific' });
break;
case 'rangeMin':
this.setStateAndNotify({ dateOne: event });
break;
case 'rangeMax':
this.setStateAndNotify({ dateTwo: event });
break;
default:
}
};
}
render() {
return (
<div>
<FormGroup className={styles.dateRangeLog}>
<ControlLabel>
<h4><Label bsStyle="primary">Date</Label></h4>
</ControlLabel>
<RadioGroup
className={styles.radioLogs}
inline
values={['Specific', 'Range']}
placeholder="Specific"
onChange={this.handleChange('mode')}
/>
</FormGroup>
<FormGroup validationState={this.setStatusStyle()}>
<DatePicker
value={this.state.dateOne}
onChange={this.handleChange('rangeMin')}
/>
<Collapse className={styles.rangeMaxLogs} in={!this.state.specific} timeout={500}>
<div>
<DatePicker
value={this.state.dateTwo}
onChange={this.handleChange('rangeMax')}
/>
</div>
</Collapse>
<HelpBlock>{this.setMessageStatus()}</HelpBlock>
</FormGroup>
</div>
);
}
}
DateRange.propTypes = {
onChange: React.PropTypes.func,
};
|
function validateEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return !re.test(email);
}
module.exports = function(obj, reqkeys) {
var keys = Object.keys(reqkeys);
var errs = [];
for (i = 0, len = keys.length; i < len; ++i) {
if (Object.keys(obj).indexOf(keys[i]) > -1) {
var thiskey = keys[i];
switch (reqkeys[keys[i]]) {
case 'string':
if (typeof obj[thiskey] !== 'string') errs.push(keys[i]);
break;
case 'date':
if (!(new Date(obj[thiskey]) !== "Invalid Date" && !isNaN(new Date(obj[thiskey])))) {
errs.push(keys[i])
};
break;
case 'email':
if(validateEmail(obj[thiskey])) {
errs.push(keys[i]);
}
}
} else {
errs.push(keys[i]);
}
}
if (errs.length == 0) {
return true;
} else {
return errs;
}
}
|
#!/usr/bin/env node
var program = require('commander');
var wcag = require('./lib/wcag');
program
.version('1.0.0')
.usage('<color1> <color2> [fontsize]');
program.on('--help', function(){
console.log(' Examples:');
console.log('');
console.log(' $ wcag-contrast-verifier ffffff 010101 18');
console.log(' $ wcag-contrast-verifier 1188ff 12ff21');
console.log('');
});
program.parse(process.argv);
var colorA,
colorB,
fontSize,
result;
if (program.args.length < 2) {
program.help();
} else {
colorA = program.args[0];
colorB = program.args[1];
fontSize = program.args[2] || null;
result = wcag.verifyContrastRatio(colorA, colorB, fontSize);
console.log(result);
parseResult(result);
}
function parseResult(result) {
var key,
val;
for (key in result) {
if (result.hasOwnProperty(key)) {
val = result[key];
if (val === false) {
process.exit(1);
}
}
}
process.exit(0);
};
|
import { StatusUpdate } from 'models/statusUpdate';
export default class {
constructor( option ) {
this.statusUpdateId = option.statusUpdateId;
this.statusUpdate = null;
}
execute() {
return getStatusUpdate.call( this )
.bind( this )
.then( returnStatusUpdate );
}
}
////////////////////
///// private
function getStatusUpdate() {
return StatusUpdate
.forge( {
id: this.statusUpdateId
} )
.fetch( {
require: true,
withRelated: [
'images',
{
user: qb => {
qb.select( 'id', 'name', 'image_url' );
}
}
]
} );
}
function returnStatusUpdate( statusUpdate ) {
return statusUpdate;
}
|
/**
* Created by niels on 11/26/14.
*
* The main controller module which all other controllers are based on.
* Also, the controller "mainCtrl" used by the frontpage is defined here.
*/
var ctrls = angular.module('nourControllers', ['userServices', "nourConfig", "nourUpload"]); //injection 'userServices' into our controllers, so we can use the "user" object everywhere
ctrls.controller("mainCtrl", ['$scope', function ($scope) {
// Application state
$scope.name = "World";
}]);
|
// Copyright 2021 Google LLC
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
// Search the bookmarks when entering the search keyword.
$('#search').change(function () {
$('#bookmarks').empty();
dumpBookmarks($('#search').val());
});
// Traverse the bookmark tree, and print the folder and nodes.
function dumpBookmarks(query) {
var bookmarkTreeNodes = chrome.bookmarks.getTree(function (bookmarkTreeNodes) {
$('#bookmarks').append(dumpTreeNodes(bookmarkTreeNodes, query));
});
}
function dumpTreeNodes(bookmarkNodes, query) {
var list = $('<ul>');
for (var i = 0; i < bookmarkNodes.length; i++) {
list.append(dumpNode(bookmarkNodes[i], query));
}
return list;
}
function dumpNode(bookmarkNode, query) {
if (bookmarkNode.title) {
if (query && !bookmarkNode.children) {
if (String(bookmarkNode.title.toLowerCase()).indexOf(query.toLowerCase()) == -1) {
return $('<span></span>');
}
}
var anchor = $('<a>');
anchor.attr('href', bookmarkNode.url);
anchor.text(bookmarkNode.title);
/*
* When clicking on a bookmark in the extension, a new tab is fired with
* the bookmark url.
*/
anchor.click(function () {
chrome.tabs.create({ url: bookmarkNode.url });
});
var span = $('<span>');
var options = bookmarkNode.children ?
$('<span>[<a href="#" id="addlink">Add</a>]</span>') :
$('<span>[<a id="editlink" href="#">Edit</a> <a id="deletelink" ' +
'href="#">Delete</a>]</span>');
var edit = bookmarkNode.children ? $('<table><tr><td>Name</td><td>' +
'<input id="title"></td></tr><tr><td>URL</td><td><input id="url">' +
'</td></tr></table>') : $('<input>');
// Show add and edit links when hover over.
span.hover(function () {
span.append(options);
$('#deletelink').click(function (event) {
console.log(event)
$('#deletedialog').empty().dialog({
autoOpen: false,
closeOnEscape: true,
title: 'Confirm Deletion',
modal: true,
show: 'slide',
position: {
my: "left",
at: "center",
of: event.target.parentElement.parentElement
},
buttons: {
'Yes, Delete It!': function () {
chrome.bookmarks.remove(String(bookmarkNode.id));
span.parent().remove();
$(this).dialog('destroy');
},
Cancel: function () {
$(this).dialog('destroy');
}
}
}).dialog('open');
});
$('#addlink').click(function (event) {
edit.show();
$('#adddialog').empty().append(edit).dialog({
autoOpen: false,
closeOnEscape: true,
title: 'Add New Bookmark',
modal: true,
show: 'slide',
position: {
my: "left",
at: "center",
of: event.target.parentElement.parentElement
},
buttons: {
'Add': function () {
edit.hide();
chrome.bookmarks.create({
parentId: bookmarkNode.id,
title: $('#title').val(), url: $('#url').val()
});
$('#bookmarks').empty();
$(this).dialog('destroy');
window.dumpBookmarks();
},
'Cancel': function () {
edit.hide();
$(this).dialog('destroy');
}
}
}).dialog('open');
});
$('#editlink').click(function (event) {
edit.show();
edit.val(anchor.text());
$('#editdialog').empty().append(edit).dialog({
autoOpen: false,
closeOnEscape: true,
title: 'Edit Title',
modal: true,
show: 'fade',
position: {
my: "left",
at: "center",
of: event.target.parentElement.parentElement
},
buttons: {
'Save': function () {
edit.hide();
chrome.bookmarks.update(String(bookmarkNode.id), {
title: edit.val()
});
anchor.text(edit.val());
options.show();
$(this).dialog('destroy');
},
'Cancel': function () {
edit.hide();
$(this).dialog('destroy');
}
}
}).dialog('open');
});
options.fadeIn();
},
// unhover
function () {
options.remove();
}).append(anchor);
}
var li = $(bookmarkNode.title ? '<li>' : '<div>').append(span);
if (bookmarkNode.children && bookmarkNode.children.length > 0) {
li.append(dumpTreeNodes(bookmarkNode.children, query));
}
return li;
}
document.addEventListener('DOMContentLoaded', function () {
dumpBookmarks();
});
|
import React from 'react'
import classNames from 'classnames'
import { Link } from 'react-router'
import { FlatButton } from 'material-ui'
import { NavigationClose } from 'material-ui/svg-icons'
import { fullWhite } from 'material-ui/styles/colors'
import { getAdoptedDateString } from '../helpers/date'
const renderSkipassBalance = skipass => {
if (skipass.isUnUsed) {
return (
<section className='skipass-card__balance-container'>
<h5 className='skipass-card__balance-title'>Unused</h5>
</section>
)
}
return (
<section className='skipass-card__balance-container'>
<h5 className='skipass-card__balance-title'>Balance</h5>
<span className='skipass-card__balance'>{skipass.balance}</span>
</section>
)
}
const SkipassCard = ({ skipass, onRemoveSkipass }) => {
const skipassUrl = `/skipasses/${skipass.cardNumber}`
const className = classNames('skipass-card', 'md-shadow--2dp', 'md-shadow--animated', 'md-shadow--2dp-interactive', {
'skipass-card--zero-balance': skipass.balance === 0
})
return (
<article className={className}>
<header className='skipass-card__header'>
<h5 className='skipass-card__title'>
<Link to={skipassUrl} className='skipass-card__link'>{skipass.name}</Link>
</h5>
<FlatButton className='skipass-card__close-button'
onTouchTap={onRemoveSkipass.bind(null, skipass)}
icon={<NavigationClose color={fullWhite} />} />
</header>
<Link to={skipassUrl} className='skipass-card__link skipass-card__main-container'>
<h5 className='skipass-card__card-number'>{skipass.cardNumber}</h5>
<section className='skipass-card__info-container'>
<time className='skipass-card__purchase-date' dateTime={skipass.purchaseDate}>{ getAdoptedDateString(skipass.purchaseDate) }</time>
</section>
{ renderSkipassBalance(skipass) }
</Link>
</article>
)
}
export default SkipassCard
|
var vows = require('vows-batch-retry'),
fs = require('fs'),
net = require('net'),
assert = require('assert'),
helper = require('./integration_helper.js');
vows.describe('Integration tls appendpeercert:').addBatchRetry({
'tls info': {
topic: function() {
var callback = this.callback;
helper.createAgent([
'input://tcp://localhost:17874?ssl=true&ssl_key=test/ssl/server.key&ssl_cert=test/ssl/server.crt&ssl_requestCert=true&ssl_ca=test/ssl/root-ca.crt&ssl_rejectUnauthorized=true',
'output://file://output.txt?serializer=json_logstash',
], function(agent) {
helper.createAgent([
'input://tcp://localhost:17873',
'output://tcp://localhost:17874?serializer=raw&ssl=true&ssl_ca=test/ssl/root-ca.crt&ssl_key=test/ssl/client.key&ssl_cert=test/ssl/client.crt',
], function(agent2) {
var c = net.createConnection({
port: 17873
}, function() {
c.write('toto');
c.end();
});
c.on('end', function() {
setTimeout(function() {
agent2.close(function() {
agent.close(function() {
callback(null);
});
});
}, 100);
});
});
});
},
check: function(err) {
assert.ifError(err);
var c1 = fs.readFileSync('output.txt').toString();
fs.unlinkSync('output.txt');
var splitted = c1.split('\n');
assert.equal(splitted.length, 2);
assert.equal('', splitted[splitted.length - 1]);
var client_tls_info = {
authorized: true,
peer_cert: {
subject: {
C: 'FR',
ST: 'Node-Logstash',
O: 'Node-Logstash',
CN: 'client_name'
},
issuer: {
C: 'FR',
ST: 'Node-Logstash',
O: 'Node-Logstash',
CN: 'ca.node-logstash.testing'
},
valid_from: 'Nov 15 10:02:44 2013 GMT',
valid_to: 'Nov 13 10:02:44 2023 GMT',
fingerprint: '9D:39:A4:D8:B3:02:0E:4E:F5:42:1B:63:D9:86:E3:45:3E:51:A1:84'
},
};
helper.checkResult(splitted[0], {
'@version': '1',
'host': '127.0.0.1',
'tcp_port': 17874,
'message': 'toto',
'tls': client_tls_info
});
}
},
}, 5, 20000).addBatchRetry({
'no appendpeercert': {
topic: function() {
var callback = this.callback;
helper.createAgent([
'input://tcp://localhost:17874?ssl=true&ssl_key=test/ssl/server.key&ssl_cert=test/ssl/server.crt&ssl_requestCert=true&ssl_ca=test/ssl/root-ca.crt&ssl_rejectUnauthorized=true&appendPeerCert=false',
'output://file://output.txt?serializer=json_logstash',
], function(agent) {
helper.createAgent([
'input://tcp://localhost:17873',
'output://tcp://localhost:17874?serializer=raw&ssl=true&ssl_ca=test/ssl/root-ca.crt&ssl_key=test/ssl/client.key&ssl_cert=test/ssl/client.crt',
], function(agent2) {
var c = net.createConnection({
port: 17873
}, function() {
c.write('toto');
c.end();
});
c.on('end', function() {
setTimeout(function() {
agent2.close(function() {
agent.close(function() {
callback(null);
});
});
}, 100);
});
});
});
},
check: function(err) {
assert.ifError(err);
var c1 = fs.readFileSync('output.txt').toString();
fs.unlinkSync('output.txt');
var splitted = c1.split('\n');
assert.equal(splitted.length, 2);
assert.equal('', splitted[splitted.length - 1]);
helper.checkResult(splitted[0], {
'@version': '1',
'host': '127.0.0.1',
'tcp_port': 17874,
'message': 'toto'
});
}
},
}, 5, 20000).export(module);
|
//8.31.2013 - Ryan Whitley
//Starting a Plug and Play GP Workflow
//names is an array of operation names. Used to list possible operations
//Use the name as a key to look up the full operation module from the operations object.
//Example: GP.operations["Buffer"]
var GP = { operations: {}, names: [] };
//Dynamically load Query or Geoprocessing Options from the plugin folder.
require("fs").readdirSync(__dirname).forEach(function (file) {
if (file != "index.js" && file != "GeoOperation.js.example" && file != ".DS_Store") {
try {
var operation = require(__dirname + "/" + file);
var name = operation.name.toLowerCase(); //Lower name
GP.names.push(name);
GP.operations[name] = operation;
}
catch(e){
console.log("Error loading geoprocessing operation: " + e)
}
}
});
module.exports = GP;
|
import { table } from 'env';
function asmFunc(env) {
var FUNCTION_TABLE = env.table;
var Math_imul = Math.imul;
var Math_fround = Math.fround;
var Math_abs = Math.abs;
var Math_clz32 = Math.clz32;
var Math_min = Math.min;
var Math_max = Math.max;
var Math_floor = Math.floor;
var Math_ceil = Math.ceil;
var Math_trunc = Math.trunc;
var Math_sqrt = Math.sqrt;
var abort = env.abort;
var nan = NaN;
var infinity = Infinity;
function main() {
var wasm2js_i32$0 = 0, wasm2js_i32$1 = 0, wasm2js_i32$2 = 0;
FUNCTION_TABLE[foo(2 | 0) | 0 | 0](1) | 0;
FUNCTION_TABLE[4 | 0](foo(3 | 0) | 0) | 0;
(wasm2js_i32$1 = foo(5 | 0) | 0, wasm2js_i32$0 = bar(6 | 0) | 0 | 0), FUNCTION_TABLE[wasm2js_i32$0](wasm2js_i32$1 | 0) | 0;
FUNCTION_TABLE[8 | 0](7) | 0;
baz((11 ? 9 : 10) | 0) | 0;
baz((wasm2js_i32$0 = foo(12 | 0) | 0, wasm2js_i32$1 = 13, wasm2js_i32$2 = 14, wasm2js_i32$2 ? wasm2js_i32$0 : wasm2js_i32$1) | 0) | 0;
baz((wasm2js_i32$0 = 15, wasm2js_i32$1 = foo(16 | 0) | 0, wasm2js_i32$2 = 17, wasm2js_i32$2 ? wasm2js_i32$0 : wasm2js_i32$1) | 0) | 0;
baz((foo(20 | 0) | 0 ? 18 : 19) | 0) | 0;
baz((wasm2js_i32$0 = foo(21 | 0) | 0, wasm2js_i32$1 = 22, wasm2js_i32$2 = foo(23 | 0) | 0, wasm2js_i32$2 ? wasm2js_i32$0 : wasm2js_i32$1) | 0) | 0;
baz((wasm2js_i32$0 = 24, wasm2js_i32$1 = foo(25 | 0) | 0, wasm2js_i32$2 = foo(26 | 0) | 0, wasm2js_i32$2 ? wasm2js_i32$0 : wasm2js_i32$1) | 0) | 0;
baz((wasm2js_i32$0 = foo(27 | 0) | 0, wasm2js_i32$1 = foo(28 | 0) | 0, wasm2js_i32$2 = 29, wasm2js_i32$2 ? wasm2js_i32$0 : wasm2js_i32$1) | 0) | 0;
baz((wasm2js_i32$0 = foo(30 | 0) | 0, wasm2js_i32$1 = foo(31 | 0) | 0, wasm2js_i32$2 = foo(32 | 0) | 0, wasm2js_i32$2 ? wasm2js_i32$0 : wasm2js_i32$1) | 0) | 0;
}
function foo($0) {
$0 = $0 | 0;
return 1 | 0;
}
function bar($0) {
$0 = $0 | 0;
return 2 | 0;
}
function baz($0) {
$0 = $0 | 0;
return 3 | 0;
}
FUNCTION_TABLE[1] = foo;
FUNCTION_TABLE[2] = bar;
FUNCTION_TABLE[3] = baz;
return {
"main": main
};
}
var retasmFunc = asmFunc( { abort: function() { throw new Error('abort'); },
table
});
export var main = retasmFunc.main;
|
/** Init APIS **/
var API = new platAPI();
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import RadioButton from '../RadioButton';
import warning from 'warning';
import { settings } from 'carbon-components';
const { prefix } = settings;
export default class RadioButtonGroup extends React.Component {
state = { selected: this.props.valueSelected || this.props.defaultSelected };
static propTypes = {
/**
* Provide a collection of <RadioButton> components to render in the group
*/
children: PropTypes.node,
/**
* Provide an optional className to be applied to the container node
*/
className: PropTypes.string,
/**
* Specify the <RadioButton> to be selected by default
*/
defaultSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* Specify the name of the underlying <input> nodes
*/
name: PropTypes.string.isRequired,
/**
* Specify whether the group is disabled
*/
disabled: PropTypes.bool,
/**
* Provide an optional `onChange` hook that is called whenever the value of
* the group changes
*/
onChange: PropTypes.func,
/**
* Specify the value that is currently selected in the group
*/
valueSelected: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
static defaultProps = {
onChange: /* istanbul ignore next */ () => {},
};
static getDerivedStateFromProps({ valueSelected, defaultSelected }, state) {
const { prevValueSelected } = state;
return prevValueSelected === valueSelected
? null
: {
selected: valueSelected || defaultSelected,
prevValueSelected: valueSelected,
};
}
getRadioButtons = () => {
const children = React.Children.map(this.props.children, radioButton => {
const { value, ...other } = radioButton.props;
/* istanbul ignore if */
if (radioButton.props.hasOwnProperty('checked')) {
warning(
false,
`Instead of using the checked property on the RadioButton, set
the defaultSelected property or valueSelected property on the RadioButtonGroup.`
);
}
return (
<RadioButton
{...other}
name={this.props.name}
key={value}
value={value}
onChange={this.handleChange}
checked={value === this.state.selected}
/>
);
});
return children;
};
handleChange = (newSelection, value, evt) => {
if (newSelection !== this.state.selected) {
this.setState({ selected: newSelection });
this.props.onChange(newSelection, this.props.name, evt);
}
};
render() {
const { disabled, className } = this.props;
const wrapperClasses = classNames(
`${prefix}--radio-button-group`,
className
);
return (
<div className={`${prefix}--form-item`}>
<div className={wrapperClasses} disabled={disabled}>
{this.getRadioButtons()}
</div>
</div>
);
}
}
|
//// [declarationEmit_readonly.ts]
class C {
constructor(readonly x: number) {}
}
//// [declarationEmit_readonly.js]
var C = (function () {
function C(x) {
this.x = x;
}
return C;
}());
//// [declarationEmit_readonly.d.ts]
declare class C {
readonly x: number;
constructor(x: number);
}
|
/**
* Created by hooxin on 14-5-22.
*/
Ext.define('Techsupport.view.sysadmin.department.Add', {
extend: 'Techsupport.view.base.BaseDetail',
title: '机构新增',
alias: 'widget.departmentadd',
initComponent: function () {
this.callParent(arguments);
this.down('form panel').add({fieldLabel: '机构代码', name: 'departcode', allowBlank: false,
blankText: '机构代码不能为空', vtype: 'alphanum',
validator: function (value) {
return this.textValid;
},
textValid: false
},
{fieldLabel: '机构名称', name: 'departname', allowBlank: false, blankText: '机构名称不能为空'},
{fieldLabel: '机构级别', name: 'departlevel', allowBlank: false, blankText: '机构级别不能为空', vtype: 'number'},
{fieldLabel: '机构全码', name: 'departfullcode', allowBlank: false, blankText: '机构全码不能为空', readOnly: true, vtype: 'alphanum'},
{fieldLabel: '上级机构id', name: 'parentDepartid', allowBlank: false, blankText: '上级机构id不能为空', hidden: true, readOnly: true, vtype: 'number'},
{fieldLabel: '上级机构名称', name: 'parentDepartname', allowBlank: false, blankText: '上级机构名称不能为空', readOnly: true},
{fieldLabel: '序号', name: 'nodeOrder', allowBlank: false, blankText: '序号不能为空', vtype: 'number'},
{fieldLabel: '是否为下级', name: 'isLeaf', allowBlank: false, blankText: '不能为空', hidden: true, xtype: 'combobox', readOnly: true,
store: 'YN',
queryMode: 'local',
displayField: 'text',
valueField: 'value',
value: 'Y'});
}
});
|
/**
* Copyright 2012-2016, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
// more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
module.exports = function isPlainObject(obj) {
return (
Object.prototype.toString.call(obj) === '[object Object]' &&
Object.getPrototypeOf(obj) === Object.prototype
);
};
|
var ngHttp = require('./http');
window.ngHttp = ngHttp;
//# sourceMappingURL=http_sfx.js.map
|
Toobs.UI.Debug = Class.create();
Toobs.UI.Debug.prototype = {
initialize: function() {
Toobs.debug('Debug - init()');
Toobs.Comp['Debug'] = this;
this._debugButton = this.debugButton.bindAsEventListener(this);
this._clearButton = this.clearButton.bindAsEventListener(this);
try {
if (Toobs.isDebugEnabled) {
this.debugContainer = $('debugContainer');
Event.observe($('debugIcon'), 'click', this._debugButton, false);
Event.observe($('clearIcon'), 'click', this._clearButton, false);
}
} catch (x) {
Toobs.error(x);
}
},
debugButton: function(evt) {
var icon = Event.element(evt);
Toobs.debug('debugButton - click - ' + icon);
if (icon.hasClassName('debugOpen')) {
icon.addClassName('debugClosed');
icon.removeClassName('debugOpen');
icon.src = context + 'img/disclose-closed_12.gif';
$('toobsDebug').style.display = 'none';
$('clearIcon').style.display = 'none';
this.debugContainer.removeClassName('conOpen');
} else {
icon.addClassName('debugOpen');
icon.removeClassName('debugClosed');
icon.src = context + 'img/disclose-open_12.gif';
$('toobsDebug').style.display = 'block';
$('clearIcon').style.display = 'block';
this.debugContainer.addClassName('conOpen');
}
},
clearButton: function(evt) {
var icon = Event.element(evt);
Toobs.debug('clearButton - click - ' + icon);
$('toobsDebug').innerHTML = '';
}
}
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
if (typeof window.CustomEvent !== 'function') {
exports.CustomEvent = function(type, eventInitDict) {
var newEvent = document.createEvent('CustomEvent');
newEvent.initCustomEvent(type,
!!(eventInitDict && eventInitDict.bubbles),
!!(eventInitDict && eventInitDict.cancelable),
(eventInitDict ? initargs.details : null));
return newEvent;
};
}
|
// Use local reference to collection, attached to this controller. Notice that
// when changes are made to this local collection reference, they are not
// automatically reflected in the runtime state of other references to this
// collection. The back-end persistence state is identical among all references,
// but the current runtime state is dependent on the reference instance.
var myModels = $.myModelId;
var common = require('common');
function addItem(e) {
common.addItem(myModels);
}
function removeItem(e) {
common.removeItem(myModels, e.index);
}
if (OS_IOS || OS_MOBILEWEB) {
common.prepNavBar($.window, addItem);
}
myModels.comparator = common.comparator;
myModels.fetch();
|
'use strict';
const d3Selection = require('d3-selection');
const PubSub = require('pubsub-js');
const bar = require('./../../src/charts/bar');
const miniTooltip = require('./../../src/charts/mini-tooltip');
const colors = require('./../../src/charts/helpers/color');
const dataBuilder = require('./../../test/fixtures/barChartDataBuilder');
const aTestDataSet = () => new dataBuilder.BarDataBuilder();
require('./helpers/resizeHelper');
function createSimpleBarChart() {
let barChart = bar(),
barContainer = d3Selection.select('.js-bar-chart-container'),
containerWidth = barContainer.node() ? barContainer.node().getBoundingClientRect().width : false,
dataset;
if (containerWidth) {
dataset = aTestDataSet().withLettersFrequency().build();
barChart
.width(containerWidth)
.hasPercentage(true)
.enableLabels(true)
.labelsNumberFormat('.0%')
.height(300);
barContainer.datum(dataset).call(barChart);
}
}
function createHorizontalBarChart() {
let barChart = bar(),
tooltip = miniTooltip(),
barContainer = d3Selection.select('.js-horizontal-bar-chart-container'),
containerWidth = barContainer.node() ? barContainer.node().getBoundingClientRect().width : false,
tooltipContainer,
dataset;
if (containerWidth) {
dataset = aTestDataSet().withColors().build();
barChart
.isHorizontal(true)
.isAnimated(true)
.margin({
left: 120,
right: 20,
top: 20,
bottom: 30
})
.colorSchema(colors.colorSchemas.britecharts)
.width(containerWidth)
.yAxisPaddingBetweenChart(30)
.height(300)
.percentageAxisToMaxRatio(1.3)
.on('customMouseOver', tooltip.show)
.on('customMouseMove', tooltip.update)
.on('customMouseOut', tooltip.hide);
barContainer.datum(dataset).call(barChart);
tooltipContainer = d3Selection.select('.js-horizontal-bar-chart-container .bar-chart .metadata-group');
tooltipContainer.datum([]).call(tooltip);
}
}
function createBarChartWithTooltip() {
let barChart = bar(),
tooltip = miniTooltip(),
barContainer = d3Selection.select('.js-bar-chart-tooltip-container'),
containerWidth = barContainer.node() ? barContainer.node().getBoundingClientRect().width : false,
tooltipContainer,
dataset;
if (containerWidth) {
d3Selection.select('.js-download-button').on('click', function() {
barChart.exportChart('barchart.png', 'Britecharts Bar Chart');
});
dataset = aTestDataSet().withLettersFrequency().build();
barChart
.width(containerWidth)
.height(300)
.isAnimated(true)
.on('customMouseOver', tooltip.show)
.on('customMouseMove', tooltip.update)
.on('customMouseOut', tooltip.hide);
barContainer.datum(dataset).call(barChart);
tooltip
.numberFormat('.2%')
tooltipContainer = d3Selection.select('.bar-chart .metadata-group');
tooltipContainer.datum([]).call(tooltip);
}
}
function createLoadingState() {
let barChart = bar(),
barContainer = d3Selection.select('.js-loading-container'),
containerWidth = barContainer.node() ? barContainer.node().getBoundingClientRect().width : false,
dataset = null;
if (containerWidth) {
barContainer.html(barChart.loadingState());
}
}
// Show charts if container available
if (d3Selection.select('.js-bar-chart-tooltip-container').node()){
createBarChartWithTooltip();
createHorizontalBarChart();
createSimpleBarChart();
createLoadingState();
let redrawCharts = function(){
d3Selection.selectAll('.bar-chart').remove();
createBarChartWithTooltip();
createHorizontalBarChart();
createSimpleBarChart();
createLoadingState();
};
// Redraw charts on window resize
PubSub.subscribe('resize', redrawCharts);
}
|
define([
"classes/Extension",
"yaml-js",
], function(Extension, YAML) {
var yamlFrontMatterParser = new Extension("yamlFrontMatterParser", "YAML front matter");
var eventMgr;
yamlFrontMatterParser.onEventMgrCreated = function(eventMgrParameter) {
eventMgr = eventMgrParameter;
};
var fileDesc;
yamlFrontMatterParser.onFileSelected = function(fileDescParam) {
fileDesc = fileDescParam;
};
var regex = /^(\s*-{3}\s*\n([\w\W]+?)\n\s*-{3}\s*\n)?([\w\W]*)$/;
yamlFrontMatterParser.onPagedownConfigure = function(editor) {
var converter = editor.getConverter();
converter.hooks.chain("preConversion", function(text) {
var results = regex.exec(text);
var yaml = results[2];
if (yaml && (!fileDesc.frontMatter || fileDesc.frontMatter._yaml != yaml)) {
fileDesc.frontMatter = undefined;
try {
fileDesc.frontMatter = YAML.parse(yaml);
fileDesc.frontMatter._yaml = yaml;
fileDesc.frontMatter._frontMatter = results[1];
}
catch (e) {}
}
eventMgr.onMarkdownTrim((results[1] || '').length);
return results[3];
});
};
return yamlFrontMatterParser;
});
|
/* Any copyright is dedicated to the Public Domain.
http://creativecommons.org/publicdomain/zero/1.0/ */
// This file tests that dbs of various page sizes are using the right cache
// size (bug 703113).
/**
* In order to change the cache size, we must open a DB, change the page
* size, create a table, close the DB, then re-open the DB. We then check
* the cache size after reopening.
*
* @param dbOpener
* function that opens the DB specified in file
* @param file
* file holding the database
* @param pageSize
* the DB's page size
* @param expectedCacheSize
* the expected cache size for the given page size
*/
function check_size(dbOpener, file, pageSize, expectedCacheSize)
{
// Open the DB, immediately change its page size.
let db = dbOpener(file);
db.executeSimpleSQL("PRAGMA page_size = " + pageSize);
// Check the page size change worked.
let stmt = db.createStatement("PRAGMA page_size");
do_check_true(stmt.executeStep());
do_check_eq(stmt.row.page_size, pageSize);
stmt.finalize();
// Create a simple table.
db.executeSimpleSQL("CREATE TABLE test ( id INTEGER PRIMARY KEY )");
// Close and re-open the DB.
db.close();
db = dbOpener(file);
// Check cache size is as expected.
let stmt = db.createStatement("PRAGMA cache_size");
do_check_true(stmt.executeStep());
do_check_eq(stmt.row.cache_size, expectedCacheSize);
stmt.finalize();
}
function new_file(name)
{
let file = dirSvc.get("ProfD", Ci.nsIFile);
file.append(name + ".sqlite");
do_check_false(file.exists());
return file;
}
function run_test()
{
// This is copied from the logic in Connection::initialize().
function cacheSize(pageSize) {
const DEFAULT_CACHE_SIZE_PAGES = 2000;
const MAX_CACHE_SIZE_BYTES = 4 * 1024 * 1024;
return Math.min(DEFAULT_CACHE_SIZE_PAGES, MAX_CACHE_SIZE_BYTES / pageSize);
}
let pageSizes = [
1024,
4096,
32768,
];
for (let i = 0; i < pageSizes.length; i++) {
let pageSize = pageSizes[i];
let expectedCacheSize = cacheSize(pageSize);
check_size(getDatabase,
new_file("shared" + pageSize), pageSize, expectedCacheSize);
check_size(getService().openUnsharedDatabase,
new_file("unshared" + pageSize), pageSize, expectedCacheSize);
}
}
|
/**
* @license Copyright 2019 The Lighthouse 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.
*/
'use strict';
const makeComputedArtifact = require('../computed-artifact.js');
const ComputedMetric = require('./metric.js');
const LHError = require('../../lib/lh-error.js');
const TracingProcessor = require('../../lib/tracehouse/trace-processor.js');
const LanternTotalBlockingTime = require('./lantern-total-blocking-time.js');
const TimetoInteractive = require('./interactive.js');
/**
* @fileoverview This audit determines Total Blocking Time.
* We define Blocking Time as any time interval in the loading timeline where task length exceeds
* 50ms. For example, if there is a 110ms main thread task, the last 60ms of it is blocking time.
* Total Blocking Time is the sum of all Blocking Time between First Contentful Paint and
* Interactive Time (TTI).
*
* This is a new metric designed to accompany Time to Interactive. TTI is strict and does not
* reflect incremental improvements to the site performance unless the improvement concerns the last
* long task. Total Blocking Time on the other hand is designed to be much more responsive
* to smaller improvements to main thread responsiveness.
*/
class TotalBlockingTime extends ComputedMetric {
/**
* @return {number}
*/
static get BLOCKING_TIME_THRESHOLD() {
return 50;
}
/**
* @param {Array<{start: number, end: number, duration: number}>} topLevelEvents
* @param {number} fcpTimeInMs
* @param {number} interactiveTimeMs
* @return {number}
*/
static calculateSumOfBlockingTime(topLevelEvents, fcpTimeInMs, interactiveTimeMs) {
if (interactiveTimeMs <= fcpTimeInMs) return 0;
const threshold = TotalBlockingTime.BLOCKING_TIME_THRESHOLD;
let sumBlockingTime = 0;
for (const event of topLevelEvents) {
// Early exit for small tasks, which should far outnumber long tasks.
if (event.duration < threshold) continue;
// We only want to consider tasks that fall between FCP and TTI.
// FCP is picked as the lower bound because there is little risk of user input happening
// before FCP so Long Queuing Qelay regions do not harm user experience. Developers should be
// optimizing to reach FCP as fast as possible without having to worry about task lengths.
if (event.end < fcpTimeInMs) continue;
// TTI is picked as the upper bound because we want a well defined end point so that the
// metric does not rely on how long we trace.
if (event.start > interactiveTimeMs) continue;
// We first perform the clipping, and then calculate Blocking Region. So if we have a 150ms
// task [0, 150] and FCP happens midway at 50ms, we first clip the task to [50, 150], and then
// calculate the Blocking Region to be [100, 150]. The rational here is that tasks before FCP
// are unimportant, so we care whether the main thread is busy more than 50ms at a time only
// after FCP.
const clippedStart = Math.max(event.start, fcpTimeInMs);
const clippedEnd = Math.min(event.end, interactiveTimeMs);
const clippedDuration = clippedEnd - clippedStart;
if (clippedDuration < threshold) continue;
// The duration of the task beyond 50ms at the beginning is considered the Blocking Region.
// Example:
// [ 250ms Task ]
// | First 50ms | Blocking Region (200ms) |
sumBlockingTime += (clippedDuration - threshold);
}
return sumBlockingTime;
}
/**
* @param {LH.Artifacts.MetricComputationData} data
* @param {LH.Audit.Context} context
* @return {Promise<LH.Artifacts.LanternMetric>}
*/
static computeSimulatedMetric(data, context) {
return LanternTotalBlockingTime.request(data, context);
}
/**
* @param {LH.Artifacts.MetricComputationData} data
* @param {LH.Audit.Context} context
* @return {Promise<LH.Artifacts.Metric>}
*/
static async computeObservedMetric(data, context) {
const {firstContentfulPaint} = data.traceOfTab.timings;
if (!firstContentfulPaint) {
throw new LHError(LHError.errors.NO_FCP);
}
const interactiveTimeMs = (await TimetoInteractive.request(data, context)).timing;
const events = TracingProcessor.getMainThreadTopLevelEvents(data.traceOfTab);
return {
timing: TotalBlockingTime.calculateSumOfBlockingTime(
events,
firstContentfulPaint,
interactiveTimeMs
),
};
}
}
module.exports = makeComputedArtifact(TotalBlockingTime);
|
/*-------------------------------------------------------------------------------------------------------------------*\
| Copyright (C) 2017 PayPal |
| |
| 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';
exports.server = require('./lib/server');
exports.client = require('./lib/client');
exports.expressView = require('./lib/expressView');
exports.reactRouterServerErrors = require('./lib/reactRouterServerErrors');
|
//@module
/*
Copyright 2011-2016 Marvell Semiconductor, 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.
*/
exports.pins = {
audio: {type: "Audio", sampleRate: 8000, channels: 1, direction: "input"}
};
exports.configure = function() {
this.audio.init();
this.audio.start();
}
exports.read = function() {
var buffer = this.audio.read();
var samples = new Int16Array(buffer)
var count = samples.length;
var total = 0, peak = 0, rms = 0.1;
for (var i = 0; i < count; i += 1) {
var sample = samples[i];
if (sample & 0x8000)
sample |= 0xFFFF0000;
if (sample < 0)
sample = -sample;
total += sample;
rms += sample * sample;
if (peak < sample)
peak = sample;
}
return { /*samples: samples,*/ count: count, peak: peak, average: Math.round(total / count), rms: Math.round(Math.sqrt(rms / count))};
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import MultiTableController from '../multi-table';
import ColumnDefinition from '../../utils/column-definition';
export default MultiTableController.extend({
breadcrumbs: [{
text: "All Tasks",
routeName: "dag.tasks",
}],
columns: ColumnDefinition.make([{
id: 'index',
headerTitle: 'Task Index',
contentPath: 'index',
cellComponentName: 'em-table-linked-cell',
getCellContent: function (row) {
return {
routeName: "task",
model: row.get("entityID"),
text: row.get("index")
};
}
},{
id: 'vertexName',
headerTitle: 'Vertex Name',
contentPath: 'vertexName',
cellComponentName: 'em-table-linked-cell',
getCellContent: function (row) {
return {
routeName: "vertex",
model: row.get("vertexID"),
text: row.get("vertexName")
};
}
},{
id: 'status',
headerTitle: 'Status',
contentPath: 'status',
cellComponentName: 'em-table-status-cell',
observePath: true
},{
id: 'progress',
headerTitle: 'Progress',
contentPath: 'progress',
cellComponentName: 'em-table-progress-cell',
observePath: true
},{
id: 'startTime',
headerTitle: 'Start Time',
contentPath: 'startTime',
cellComponentName: 'date-formatter',
},{
id: 'endTime',
headerTitle: 'End Time',
contentPath: 'endTime',
cellComponentName: 'date-formatter',
},{
id: 'duration',
headerTitle: 'Duration',
contentPath: 'duration',
cellDefinition: {
type: 'duration'
}
},{
id: 'log',
headerTitle: 'Successful/Last Attempt Log',
cellComponentName: 'em-table-tasks-log-link-cell',
enableSearch: false,
contentPath: 'logs',
getCellContent: function (row) {
var attemptID = row.get("successfulAttemptID");
if(!attemptID) {
let allAttemptIDs = row.get("attemptIDs") || [];
attemptID = allAttemptIDs[allAttemptIDs.length - 1];
}
return attemptID;
}
}])
});
|
/**
* Copyright 2017 Google Inc. 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';
var assert = require('assert');
var common = require('./common');
var semver = require('semver');
describe('generic-pool2', function() {
var ROOT_SPAN = 'root-span';
var CHILD_SPAN_1 = 'child-span-1';
var CHILD_SPAN_2 = 'child-span-2';
var api;
var genericPool;
before(function() {
api = require('../..').start({
projectId: '0',
samplingRate: 0
});
genericPool = require('./fixtures/generic-pool2');
});
after(function() {
common.stopAgent(api);
common.cleanTraces(api);
});
it('perserves context', function(done) {
var config = {
name: 'generic-pool2 test',
create: function(callback) {
callback(function() {
var childSpan = api.createChildSpan({ name: CHILD_SPAN_2 });
assert.ok(childSpan);
childSpan.endSpan();
});
},
destroy: function(fn) {
}
};
var pool = new genericPool.Pool(config);
api.runInRootSpan({ name: ROOT_SPAN }, function(span) {
pool.acquire(function(err, fn) {
assert.ifError(err);
var childSpan = api.createChildSpan({ name: CHILD_SPAN_1 });
assert.ok(childSpan);
fn();
childSpan.endSpan();
span.endSpan();
var spans = common.getTraces(api)[0].spans;
assert.ok(spans);
assert.strictEqual(spans.length, 3);
assert.strictEqual(spans[0].name, ROOT_SPAN);
assert.strictEqual(spans[1].name, CHILD_SPAN_1);
assert.strictEqual(spans[2].name, CHILD_SPAN_2);
done();
});
});
});
});
describe('generic-pool3', function() {
var agent;
var genericPool;
if (semver.satisfies(process.version, '<4')) {
console.log('Skipping testing generic-pool@3 on Node.js version ' +
process.version + ' that predates version 4.');
return;
}
before(function() {
agent = require('../..').start({
projectId: '0',
samplingRate: 0
});
genericPool = require('./fixtures/generic-pool3');
});
after(function() {
common.stopAgent(agent);
common.cleanTraces(agent);
});
it ('preserves context', function() {
var ROOT_SPAN = 'root-span';
var CHILD_SPAN_1 = 'child-span-1';
var CHILD_SPAN_2 = 'child-span-2';
var CHILD_SPAN_3 = 'child-span-3';
var factory = {
create: function() {
return new Promise(function(resolve, reject) {
resolve(function(input) {
assert.strictEqual(input, 'SomeInput');
var childSpan = agent.createChildSpan({ name: CHILD_SPAN_2 });
assert.ok(childSpan);
childSpan.endSpan();
});
});
},
destroy: function(fn) {
return new Promise(function(resolve) {
resolve();
});
}
};
var opts = {
max: 1,
min: 1
};
var pool = genericPool.createPool(factory, opts);
var promise;
agent.runInRootSpan({ name: ROOT_SPAN }, function(rootSpan) {
promise = pool.acquire().then(function(fn) {
var childSpan = agent.createChildSpan({ name: CHILD_SPAN_1 });
assert.ok(childSpan);
fn('SomeInput');
childSpan.endSpan();
}).then(function() {
var childSpan = agent.createChildSpan({ name: CHILD_SPAN_3 });
assert.ok(childSpan);
childSpan.endSpan();
rootSpan.endSpan();
var spans = common.getTraces(agent)[0].spans;
assert.ok(spans);
assert.strictEqual(spans.length, 4);
assert.strictEqual(spans[0].name, ROOT_SPAN);
assert.strictEqual(spans[1].name, CHILD_SPAN_1);
assert.strictEqual(spans[2].name, CHILD_SPAN_2);
assert.strictEqual(spans[3].name, CHILD_SPAN_3);
});
});
return promise;
});
});
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
import templateUrl from './group.jade';
export default ['igniteFormGroup', [() => {
const controller = [function() { }];
const link = (scope, el, attrs, [ngModelCtrl, ownFormCtrl, parentFormCtrl]) => {
if (!ownFormCtrl)
return;
const name = attrs.ngForm;
ngModelCtrl.$name = name;
parentFormCtrl.$addControl(ngModelCtrl);
parentFormCtrl.$removeControl(ownFormCtrl);
scope.ngModel = scope.ngModel || [];
parentFormCtrl.$defaults = parentFormCtrl.$defaults || {};
if (parentFormCtrl.$pristine) {
if (!(_.isNull(parentFormCtrl.$defaults[name]) || _.isUndefined(parentFormCtrl.$defaults[name])))
scope.ngModel = parentFormCtrl.$defaults[name];
else
parentFormCtrl.$defaults[name] = _.cloneDeep(scope.ngModel);
}
const setAsDefault = () => {
if (!parentFormCtrl.$pristine)
return;
scope.ngModel = scope.ngModel || [];
parentFormCtrl.$defaults = parentFormCtrl.$defaults || {};
parentFormCtrl.$defaults[name] = _.cloneDeep(scope.ngModel);
};
const setAsDirty = () => {
if (_.isEqual(scope.ngModel, parentFormCtrl.$defaults[name]))
ngModelCtrl.$setPristine();
else
ngModelCtrl.$setDirty();
};
scope.$watch(() => parentFormCtrl.$pristine, setAsDefault);
scope.$watch('ngModel', setAsDefault);
scope.$watch('ngModel', setAsDirty, true);
};
return {
restrict: 'E',
scope: {
ngModel: '=ngModel'
},
bindToController: {
label: '@'
},
link,
templateUrl,
controller,
controllerAs: 'group',
replace: true,
transclude: true,
require: ['?ngModel', '?form', '^^form']
};
}]];
|
var common = require('./common');
var sinon = common.sinon;
var should = common.should;
var moment = common.moment;
var CacheEntry = require('../lib/cache/CacheEntry');
function createVoidCacheEntry(){
var entry = {};
var createdAt = new Date();
var lastAccessedAt = new Date();
var cacheEntry =
new CacheEntry(entry, createdAt.valueOf(), lastAccessedAt.valueOf());
return cacheEntry;
}
describe('Cache module',function(){
describe('Cache Entry class', function(){
describe('default arguments values ',function(){
var sandbox;
var testTime;
before(function(){
testTime = 100500;
sandbox = sinon.sandbox.create();
sandbox.useFakeTimers(testTime, 'Date');
});
after(function(){
sandbox.restore();
});
it('for createdAt an lastAccessedAt should be current utc time tick',
function(){
var cacheEntry = new CacheEntry();
should.not.exist(cacheEntry.value);
cacheEntry.createdAt.should.be.equal(testTime);
cacheEntry.lastAccessedAt.should.be.equal(testTime);
});
});
describe('constructor expecting', function(){
var entry;
var createdAt;
var lastAccessedAt;
var cacheEntry;
before(function () {
entry = {};
createdAt = new Date();
lastAccessedAt = new Date();
cacheEntry = new CacheEntry(entry, createdAt.valueOf(), lastAccessedAt.valueOf());
});
it('should store entry in it initial state', function(){
cacheEntry.value.should.be.equal(entry);
});
it('createdAt in number format', function(){
cacheEntry.createdAt.should.be.equal(createdAt.valueOf());
});
it('lastAccessedAt in number format', function(){
cacheEntry.lastAccessedAt.should.be.equal(lastAccessedAt.valueOf());
});
});
describe('constructor params validation', function(){
function createCacheEntry(createdAt, lastAccessedAt){
return function(){
return new CacheEntry({},createdAt, lastAccessedAt);
};
}
it('should throw "expecting date in timestamp format"', function(){
createCacheEntry('boom!')
.should.throw(/expecting date in timestamp format/i);
createCacheEntry(1, 'boom!')
.should.throw(/expecting date in timestamp format/i);
});
});
describe('call to touch method', function(){
var cacheEntry;
before(function () {
cacheEntry = createVoidCacheEntry();
});
it('should change lastAccessedTime to current for cache entry', function(done){
var was = cacheEntry.lastAccessedAt;
setTimeout(function () {
cacheEntry.touch();
cacheEntry.lastAccessedAt.should.be.gt(was);
done();
}, 20);
});
});
describe('call to isExpired', function(){
describe('if entry is fresh', function(){
var cacheEntry;
before(function () {
cacheEntry = createVoidCacheEntry();
});
it('should not be expired', function(){
var notExpired = cacheEntry.isExpired(300,300);
/* jshint -W030 */
notExpired.should.not.be.true;
});
});
describe('if entry is idle for to long', function(){
var cacheEntry;
before(function () {
cacheEntry = createVoidCacheEntry();
cacheEntry.lastAccessedAt -= 500 * 1000;
});
it('should be expired', function(){
var expired = cacheEntry.isExpired(300,300);
/* jshint -W030 */
expired.should.be.true;
});
});
describe('if entry is created a long time ago', function(){
var cacheEntry;
before(function () {
cacheEntry = createVoidCacheEntry();
cacheEntry.createdAt -= 500 * 1000;
});
it('should be expired', function(){
var expired = cacheEntry.isExpired(300,300);
/* jshint -W030 */
expired.should.be.true;
});
});
});
describe('call to toObject', function(){
var cacheEntry;
var expectCreatedAt;
var expectLastAccessedAt;
var object;
before(function () {
cacheEntry = createVoidCacheEntry();
expectCreatedAt = moment.utc(cacheEntry.createdAt).format('YYYY-MM-DD HH:mm:ss.SSS');
expectLastAccessedAt = moment.utc(cacheEntry.lastAccessedAt).format('YYYY-MM-DD HH:mm:ss.SSS');
object = cacheEntry.toObject();
});
it('should return current entry state with formatted dates', function(){
object.createdAt.should.be.equal(expectCreatedAt);
object.lastAccessedAt.should.be.equal(expectLastAccessedAt);
});
});
describe('call to type method parse', function(){
var cacheEntry;
var expectCreatedAt;
var expectLastAccessedAt;
var parsedCacheEntry;
before(function () {
cacheEntry = createVoidCacheEntry();
expectCreatedAt = moment.utc(cacheEntry.createdAt).format('YYYY-MM-DD HH:mm:ss.SSS');
expectLastAccessedAt = moment.utc(cacheEntry.lastAccessedAt).format('YYYY-MM-DD HH:mm:ss.SSS');
parsedCacheEntry = CacheEntry.parse({
createdAt: expectCreatedAt,
lastAccessedAt: expectLastAccessedAt
});
});
it('should return instance of CacheEntry with utc time', function(){
parsedCacheEntry.createdAt.should.be.equal(cacheEntry.createdAt);
parsedCacheEntry.lastAccessedAt.should.be.equal(cacheEntry.lastAccessedAt);
});
});
});
});
|
import $ from "jquery";
import "./search.scss";
import algoliasearch from "algoliasearch/lite";
import instantsearch from "instantsearch.js/es";
import {configure, searchBox, infiniteHits} from "instantsearch.js/es/widgets";
import resultTemplate from "./search-result.mustache"
import emptyResultsTemplate from "./empty-result.mustache"
import UrlUtils from "query-string"
import debounce from 'debounce';
const searchDelay = 300;
const KEYS = {
UP: 38,
DOWN: 40,
ENTER: 13,
ESC: 27
};
let isInited = false;
let search;
let $searchPopup;
export function openPopup() {
if (!isInited) {
search.start();
isInited = true;
}
$searchPopup.one('transitionend', () => $('.ais-SearchBox-input').focus());
$searchPopup.addClass('_visible');
$('body').addClass('_no-scroll');
}
export function initSearch() {
$searchPopup = $('.search-popup');
const $closeButton = $('.search-popup__close');
search = instantsearch({
indexName: indexName,
searchClient: algoliasearch('7961PKYRXV', '604fa45d89af86bdf9eed4cc862b2d0b'),
searchFunction: debounce((helper) => {
const searchResults = $('.search-popup__results');
helper.search();
if (helper.state.query === '') {
searchResults.hide();
} else {
searchResults.show();
}
}, searchDelay),
routing: {
stateMapping: {
stateToRoute(uiState) {
const indexUiState = uiState[indexName];
return {
q: indexUiState.query,
p: indexUiState.page
};
},
routeToState(routeState) {
return {
[indexName]: {
query: routeState.q,
page: routeState.p
}
}
}
}
}
});
search.addWidgets([
configure({
attributesToSnippet: ['content:90'],
snippetEllipsisText: '...',
typoTolerance: true
}),
searchBox({
container: '.search-popup__input',
placeholder: 'Search',
showReset: false,
showSubmit: false,
showLoadingIndicator: false
}),
infiniteHits({
container: '.search-popup__results',
templates: {
empty: emptyResultsTemplate,
item: resultTemplate
}
})
]
);
search.on('render', function () {
$('.ais-InfiniteHits-item._active').removeClass('_active');
$('.ais-InfiniteHits-item:first').addClass('_active')
});
function closePopup() {
const $input = $('.ais-SearchBox-input');
$input.val('');
$input[0].dispatchEvent(new Event('input'));
$input.blur();
$('body').removeClass('_no-scroll');
$searchPopup.removeClass('_visible');
}
$searchPopup.keyup(function (e) {
handlerKeysEvent();
if (e.keyCode === KEYS.ESC) { // escape key
closePopup()
} else if (e.keyCode === KEYS.ENTER) { //enter
const searchRef = $('.ais-InfiniteHits-item._active a').attr('href');
if (searchRef !== undefined) {
window.location.href = searchRef;
}
} else if (e.keyCode === KEYS.DOWN) { //arrow down
const $activeElement = $('.ais-InfiniteHits-item._active');
const $nextElement = $activeElement.next();
if ($nextElement.length > 0) {
$activeElement.removeClass('_active');
$nextElement.addClass('_active');
const popupTop = $nextElement.position().top + $nextElement.outerHeight() - $(window).height();
if (popupTop > 0) {
$searchPopup.scrollTop($searchPopup.scrollTop() + popupTop);
}
}
} else if (e.keyCode === 38) { //arrow up
const $activeElement = $('.ais-InfiniteHits-item._active');
const $prevElement = $activeElement.prev();
if ($prevElement.length > 0) {
$prevElement.addClass('_active');
$activeElement.removeClass('_active');
const popupTop = $prevElement.position().top;
if (popupTop < 0) {
$searchPopup.scrollTop($searchPopup.scrollTop() + popupTop);
}
}
}
});
$closeButton.on('click', event => {
event.stopPropagation();
closePopup();
});
$(".search-popup").click(function () {
$(".ais-SearchBox-input").select();
});
const urlParameters = UrlUtils.parse(UrlUtils.extract(window.location.href));
if ('q' in urlParameters && urlParameters.q !== '') {
openPopup();
}
}
function handlerKeysEvent() {
$(".ais-SearchBox-input").keydown(function (e) {
if (e.keyCode === KEYS.DOWN || e.keyCode === KEYS.UP) {
e.preventDefault()
}
})
}
|
/**
* @author caspar - chengzhihang
* @contact 279397942@qq.com
* @date 2016/12/29
* @file admin/view-partial/main/order/widget/dialog/SetDeliverPrintWaybillTemplateDialog
*/
define([
'admin/widget/dialog/ConfirmDialog',
'admin/view-partial/main/order/widget/form/value-widget/edit/DeliverPrintWaybillTemplateIdSelect2',
'admin/api/orderHttpService',
'admin/api/apiConfig',
'zh/core',
'admin/util/request',
'dojo/_base/array',
"dojo/_base/declare"
], function (ConfirmDialog, DeliverPrintWaybillTemplateIdSelect2, orderHttpService, apiConfig, zh, request, array, declare) {
return declare('admin/view-partial/main/order/widget/dialog/SetDeliverPrintWaybillTemplateDialog', [ConfirmDialog], {
/**
* 是否在隐藏之后,自动销毁窗体
*/
isAutoDestroyOnHideAfter: true,
action: apiConfig.admin.order.setDeliverPrintWaybillTemplate,
request: request,
title: '选择快递单类型',
postCreate: function () {
this.inherited(arguments);
this.addItem(new DeliverPrintWaybillTemplateIdSelect2({
width: 'style',
style: {width: '200px'},
labelStyle: {width: '100px'},
}));
},
});
});
|
/*
Copyright [2016] [Relevance Lab]
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.
*/
// The file contains all the end points for Tracks
var logger = require('_pr/logger')(module);
var Track = require('_pr/model/track/trackType');
var errorResponses = require('./error_responses');
module.exports.setRoutes = function(app, sessionVerificationFunc) {
app.all('/trackType/*', sessionVerificationFunc);
// Get all track
app.get('/trackType', function(req, res) {
Track.getTrackType(function(err, trackType) {
if (err) {
res.status(500).send(errorResponses.db.error);
return;
}
if (trackType) {
res.send(200, trackType);
return;
}
});
});
// Create track
app.post('/trackType', function(req, res) {
logger.debug(JSON.stringify(req.body));
logger.debug("Got Track data: ", JSON.stringify(req.body.trackTypeData));
Track.createNew(req.body.trackTypeData, function(err, trackType) {
if (err) {
logger.debug("error ", errorResponses.db.error);
res.status(500).send(errorResponses.db.error);
return;
}
if (trackType) {
logger.debug("post trackType");
res.send(200, trackType);
return;
}
});
});
// Update Track
app.post('/trackType/:trackTypeId/update', function(req, res) {
logger.debug("Got track Type data: ", JSON.stringify(req.body.trackTypeData), req.params.trackTypeId);
Track.getTrackTypeById(req.params.trackTypeId, function(err, trackType) {
if (err) {
res.status(500).send(errorResponses.db.error);
return;
}
if (!trackType) {
res.send(404, "Tracks not found!");
return;
}
Track.updateTrack(req.params.trackTypeId, req.body.trackTypeData, function(err, updateCount) {
if (err) {
res.status(500).send(errorResponses.db.error);
return;
}
res.send(200, {
updateCount: updateCount
});
});
});
});
// Get Track w.r.t. Id
app.get('/trackType/:trackTypeId', function(req, res) {
Track.getTrackTypeById(req.params.trackTypeId, function(err, trackType) {
if (err) {
res.status(500).send(errorResponses.db.error);
return;
}
if (trackType) {
res.send(200, trackType);
return;
} else {
res.send(404, "Track not found!");
return;
}
});
});
// Delete Track w.r.t. Id
app.delete('/trackType/:trackTypeId', function(req, res) {
Track.getTrackTypeById(req.params.trackTypeId, function(err, trackType) {
if (err) {
res.status(500).send(errorResponses.db.error);
return;
}
if (trackType) {
Track.removeTracks(req.params.trackTypeId, function(err, trackType) {
if (err) {
logger.debug("Error while removing trackType: ", JSON.stringify(trackType));
res(500, "Error while removing trackType:");
return;
}
if (trackType) {
logger.debug("Successfully Removed trackType.");
res.send(200, "Successfully Removed trackType.");
return;
}
});
} else {
res.send(404, "Tracks not found!");
return;
}
});
});
};
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Subscriber_1 = require("../Subscriber");
var Subscription_1 = require("../Subscription");
function finalize(callback) {
return function (source) { return source.lift(new FinallyOperator(callback)); };
}
exports.finalize = finalize;
var FinallyOperator = (function () {
function FinallyOperator(callback) {
this.callback = callback;
}
FinallyOperator.prototype.call = function (subscriber, source) {
return source.subscribe(new FinallySubscriber(subscriber, this.callback));
};
return FinallyOperator;
}());
var FinallySubscriber = (function (_super) {
__extends(FinallySubscriber, _super);
function FinallySubscriber(destination, callback) {
var _this = _super.call(this, destination) || this;
_this.add(new Subscription_1.Subscription(callback));
return _this;
}
return FinallySubscriber;
}(Subscriber_1.Subscriber));
//# sourceMappingURL=finalize.js.map
|
import { module, test } from 'qunit';
import { getFormatedDuration } from 'thirdeye-frontend/utils/anomaly';
module('Unit | Utility | anomaly', function() {
test('it returns a formated duration time correctly', function(assert) {
assert.equal(getFormatedDuration(1491804013000, 1491890413000), '1 day', 'it returns correct duration ok');
});
test('it returns a non-zero duration time correctly', function(assert) {
//We want to display only non-zero duration values in our table
assert.equal(getFormatedDuration(1491804013000, 1491804013000), '', 'it filters out non-zero duration ok');
});
});
|
/**
* A track which shows a scale proportional to slice of the genome being
* shown by the reference track. This track tries to show a scale in kbp,
* mbp or gbp depending on the size of the view and also tries to round the
* scale size (e.g. prefers "1,000 bp", "1,000 kbp" over "1 kbp" and "1 mbp")
*
* <---------- 30 bp ---------->
*
* @flow
*/
'use strict';
import type {VizProps} from '../VisualizationWrapper';
import type {Scale} from './d3utils';
import type {State} from '../types';
import React from 'react';
import EmptySource from '../sources/EmptySource';
import canvasUtils from './canvas-utils';
import dataCanvas from 'data-canvas';
import style from '../style';
import d3utils from './d3utils';
class ScaleTrack extends React.Component<VizProps<void>, State> {
props: VizProps<void>;
state: State; // no state, used to make flow happy
ref: Object;
static defaultSource: Object;
constructor(props: VizProps<void>) {
super(props);
this.ref = React.createRef();
}
getScale(): Scale {
return d3utils.getTrackScale(this.props.range, this.props.width);
}
render(): any {
return <canvas ref={this.ref} />;
}
componentDidMount() {
this.updateVisualization();
}
componentDidUpdate(prevProps: any, prevState: any) {
this.updateVisualization();
}
updateVisualization() {
const canvas = this.ref.current;
var {range, width, height} = this.props;
d3utils.sizeCanvas(canvas, width, height);
var ctx = dataCanvas.getDataContext(canvasUtils.getContext(canvas));
ctx.save();
ctx.reset();
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
var viewSize = range.stop - range.start + 1,
midX = Math.round(width / 2),
midY = Math.round(height / 2);
// Mid label
var {prefix, unit} = d3utils.formatRange(viewSize);
ctx.lineWidth = 1;
ctx.fillStyle = style.SCALE_FONT_COLOR;
ctx.font = style.SCALE_FONT_STYLE;
ctx.textAlign = "center";
ctx.fillText(prefix + " " + unit,
midX,
midY + style.SCALE_TEXT_Y_OFFSET);
// Left line
canvasUtils.drawLine(ctx, 0.5, midY - 0.5, midX - style.SCALE_LINE_PADDING - 0.5, midY - 0.5);
// Left arrow
ctx.beginPath();
ctx.moveTo(0.5 + style.SCALE_ARROW_SIZE, midY - style.SCALE_ARROW_SIZE - 0.5);
ctx.lineTo(0.5, midY - 0.5);
ctx.lineTo(0.5 + style.SCALE_ARROW_SIZE, midY + style.SCALE_ARROW_SIZE - 0.5);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Right line
canvasUtils.drawLine(ctx, midX + style.SCALE_LINE_PADDING - 0.5, midY - 0.5, width - 0.5, midY - 0.5);
// Right arrow
ctx.beginPath();
ctx.moveTo(width - style.SCALE_ARROW_SIZE - 0.5, midY - style.SCALE_ARROW_SIZE - 0.5);
ctx.lineTo(width - 0.5, midY - 0.5);
ctx.lineTo(width - style.SCALE_ARROW_SIZE - 0.5, midY + style.SCALE_ARROW_SIZE - 0.5);
ctx.closePath();
ctx.fill();
ctx.stroke();
// Clean up afterwards
ctx.restore();
}
}
ScaleTrack.displayName = 'scale';
ScaleTrack.defaultSource = EmptySource.create();
module.exports = ScaleTrack;
|
/**
* Include mixin for ./model.js
*/
var AbstractClass = require('./model.js');
/**
* Allows you to load relations of several objects and optimize numbers of requests.
*
* @param {Array} objects - array of instances
* @param {String}, {Object} or {Array} include - which relations you want to load.
* @param {Function} cb - Callback called when relations are loaded
*
* Examples:
*
* - User.include(users, 'posts', function() {}); will load all users posts with only one additional request.
* - User.include(users, ['posts'], function() {}); // same
* - User.include(users, ['posts', 'passports'], function() {}); // will load all users posts and passports with two
* additional requests.
* - Passport.include(passports, {owner: 'posts'}, function() {}); // will load all passports owner (users), and all
* posts of each owner loaded
* - Passport.include(passports, {owner: ['posts', 'passports']}); // ...
* - Passport.include(passports, {owner: [{posts: 'images'}, 'passports']}); // ...
*
*/
AbstractClass.include = function (objects, include, cb) {
var self = this;
if (
(include.constructor.name == 'Array' && include.length == 0) ||
(include.constructor.name == 'Object' && Object.keys(include).length == 0)
) {
cb(null, objects);
return;
}
include = processIncludeJoin(include);
var keyVals = {};
var objsByKeys = {};
var nbCallbacks = 0;
for (var i = 0; i < include.length; i++) {
var callback = processIncludeItem(objects, include[i], keyVals, objsByKeys);
if (callback !== null) {
nbCallbacks++;
callback(function() {
nbCallbacks--;
if (nbCallbacks == 0) {
cb(null, objects);
}
});
} else {
cb(null, objects);
}
}
function processIncludeJoin(ij) {
if (typeof ij === 'string') {
ij = [ij];
}
if (ij.constructor.name === 'Object') {
var newIj = [];
for (var key in ij) {
var obj = {};
obj[key] = ij[key];
newIj.push(obj);
}
return newIj;
}
return ij;
}
function processIncludeItem(objs, include, keyVals, objsByKeys) {
var relations = self.relations;
if (include.constructor.name === 'Object') {
var relationName = Object.keys(include)[0];
var subInclude = include[relationName];
} else {
var relationName = include;
var subInclude = [];
}
var relation = relations[relationName];
if (!relation) {
return function() {
cb(new Error('Relation "' + relationName + '" is not defined for ' + self.modelName + ' model'));
}
}
var req = {'where': {}};
if (!keyVals[relation.keyFrom]) {
objsByKeys[relation.keyFrom] = {};
objs.filter(Boolean).forEach(function(obj) {
if (!objsByKeys[relation.keyFrom][obj[relation.keyFrom]]) {
objsByKeys[relation.keyFrom][obj[relation.keyFrom]] = [];
}
objsByKeys[relation.keyFrom][obj[relation.keyFrom]].push(obj);
});
keyVals[relation.keyFrom] = Object.keys(objsByKeys[relation.keyFrom]);
}
if (keyVals[relation.keyFrom].length > 0) {
// deep clone is necessary since inq seems to change the processed array
var keysToBeProcessed = {};
var inValues = [];
for (var j = 0; j < keyVals[relation.keyFrom].length; j++) {
keysToBeProcessed[keyVals[relation.keyFrom][j]] = true;
if (keyVals[relation.keyFrom][j] !== 'null' && keyVals[relation.keyFrom][j] !== 'undefined') {
inValues.push(keyVals[relation.keyFrom][j]);
}
}
req['where'][relation.keyTo] = {inq: inValues};
req['include'] = subInclude;
return function(cb) {
relation.modelTo.all(req, function(err, objsIncluded) {
for (var i = 0; i < objsIncluded.length; i++) {
delete keysToBeProcessed[objsIncluded[i][relation.keyTo]];
var objectsFrom = objsByKeys[relation.keyFrom][objsIncluded[i][relation.keyTo]];
for (var j = 0; j < objectsFrom.length; j++) {
if (!objectsFrom[j].__cachedRelations) {
objectsFrom[j].__cachedRelations = {};
}
if (relation.multiple) {
if (!objectsFrom[j].__cachedRelations[relationName]) {
objectsFrom[j].__cachedRelations[relationName] = [];
}
objectsFrom[j].__cachedRelations[relationName].push(objsIncluded[i]);
} else {
objectsFrom[j].__cachedRelations[relationName] = objsIncluded[i];
}
}
}
// No relation have been found for these keys
for (var key in keysToBeProcessed) {
var objectsFrom = objsByKeys[relation.keyFrom][key];
for (var j = 0; j < objectsFrom.length; j++) {
if (!objectsFrom[j].__cachedRelations) {
objectsFrom[j].__cachedRelations = {};
}
objectsFrom[j].__cachedRelations[relationName] = relation.multiple ? [] : null;
}
}
cb(err, objsIncluded);
});
};
}
return null;
}
}
|
/*
* Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
*/
var mnPageLoader = new MonitorNetworkingLoader();
function MonitorNetworkingLoader() {
this.load = function (paramObject) {
var self = this, currMenuObj = globalObj.currMenuObj,
hashParams = paramObject['hashParams'],
rootDir = currMenuObj['resources']['resource'][0]['rootDir'],
pathMNView = rootDir + '/js/views/MonitorNetworkingView.js',
renderFn = paramObject['function'];
check4CTInit(function () {
if (self.mnView == null) {
requirejs([pathMNView], function (MonitorNetworkingView) {
self.mnView = new MonitorNetworkingView();
self.renderView(renderFn, hashParams);
});
} else {
self.renderView(renderFn, hashParams);
}
});
};
this.renderView = function (renderFn, hashParams, view) {
$(contentContainer).html("");
switch (renderFn) {
case 'renderProjects':
if (hashParams.type == "project") {
if (hashParams.view == "details") {
this.mnView.renderProject({hashParams: hashParams});
} else {
this.mnView.renderProjectList({hashParams: hashParams});
}
} else if (hashParams.type == "flow"){
if (hashParams.view == "list") {
this.mnView.renderFlowList({hashParams: hashParams});
} else if (hashParams.view == "details") {
this.mnView.renderFlow({hashParams: hashParams});
}
}
break;
case 'renderNetworks':
if (hashParams.type == "network") {
if (hashParams.view == "details") {
this.mnView.renderNetwork({hashParams: hashParams});
} else {
if(view != undefined) {
view.renderNetworkList({hashParams: hashParams});
} else {
this.mnView.renderNetworkList({hashParams: hashParams});
}
}
} else if (hashParams.type == "flow"){
if (hashParams.view == "list") {
this.mnView.renderFlowList({hashParams: hashParams});
} else if (hashParams.view == "details") {
this.mnView.renderFlow({hashParams: hashParams});
}
}
break;
case 'renderInstances':
if (hashParams.view == "details") {
this.mnView.renderInstance({hashParams: hashParams});
} else {
this.mnView.renderInstanceList({hashParams: hashParams});
}
break;
case 'renderFlows':
if (hashParams.view == "list") {
this.mnView.renderFlowList({hashParams: hashParams});
} else if (hashParams.view == "details") {
this.mnView.renderFlow({hashParams: hashParams});
}
break;
}
},
this.updateViewByHash = function (hashObj, lastHashObj) {
var renderFn;
if(hashObj.type == "network"){
renderFn = "renderNetworks";
} else if (hashObj.type == "project"){
renderFn = "renderProjects"
} else if (hashObj.type == "instance"){
renderFn = "renderInstances"
} else if (hashObj.type == "flow"){
renderFn = "renderFlows"
}
this.load({hashParams: hashObj, 'function': renderFn});
};
this.destroy = function () {
};
};
|
// A document.ready shim
// https://github.com/whatwg/html/issues/127
export function documentReady() {
const rs = document.readyState;
if (rs === 'interactive' || rs === 'completed') {
return Promise.resolve();
}
return new Promise(
resolve => document.addEventListener(
'readystatechange', resolve, { once: true }
)
);
}
export function getResourceLinks(elem) {
return Array.prototype.map.call(
elem.querySelectorAll('link[rel="localization"]'),
el => [el.getAttribute('href'), el.getAttribute('name') || 'main']
).reduce(
(seq, [href, name]) => seq.set(name, (seq.get(name) || []).concat(href)),
new Map()
);
}
export function getMeta(head) {
let availableLangs = [];
let defaultLang = null;
let appVersion = null;
// XXX take last found instead of first?
const metas = Array.from(head.querySelectorAll(
'meta[name="availableLanguages"],' +
'meta[name="defaultLanguage"],' +
'meta[name="appVersion"]')
);
for (const meta of metas) {
const name = meta.getAttribute('name');
const content = meta.getAttribute('content').trim();
switch (name) {
case 'availableLanguages':
availableLangs = content.split(',').map(lang => lang.trim());
break;
case 'defaultLanguage':
defaultLang = content;
break;
case 'appVersion':
appVersion = content;
}
}
return {
defaultLang,
availableLangs,
appVersion
};
}
|
var Foo = (function () {
function Foo(x) {
// WScript.Echo("Constructor function has executed");
}
Foo.prototype.bar1 = function (a) {
};
return Foo;
})();
//class Foo(s: String);
var f1 = new Foo("hey");
f1.bar1("a");
Foo();
Foo("s");
|
/*!
* classie - class helper functions
* from bonzo https://github.com/ded/bonzo
*
* classie.has( elem, 'my-class' ) -> true/false
* classie.add( elem, 'my-new-class' )
* classie.remove( elem, 'my-unwanted-class' )
* classie.toggle( elem, 'my-class' )
*/
/*jshint browser: true, strict: true, undef: true */
/*global define: false */
( function( window ) {
'use strict';
// class helper functions from bonzo https://github.com/ded/bonzo
function classReg( className ) {
return new RegExp("(^|\\s+)" + className + "(\\s+|$)");
}
// classList support for class management
// altho to be fair, the api sucks because it won't accept multiple classes at once
var hasClass, addClass, removeClass;
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
function toggleClass( elem, c ) {
var fn = hasClass( elem, c ) ? removeClass : addClass;
fn( elem, c );
}
var classie = {
// full names
hasClass: hasClass,
addClass: addClass,
removeClass: removeClass,
toggleClass: toggleClass,
// short names
has: hasClass,
add: addClass,
remove: removeClass,
toggle: toggleClass
};
// transport
if ( typeof define === 'function' && define.amd ) {
// AMD
define( classie );
} else {
// browser global
window.classie = classie;
}
})( window );
|
function externalLinks()
{ for(var c = document.getElementsByTagName("a"), a = 0;a < c.length;a++)
{ var b = c[a]; b.getAttribute("href")
&& b.hostname !== location.hostname
&& (b.target = "_blank") } } ; externalLinks();
function toggleCurrent (elem) {
var parent_li = elem.closest('li');
parent_li.siblings('li.current').removeClass('current');
parent_li.siblings().find('li.current').removeClass('current');
parent_li.find('> ul li.current').removeClass('current');
parent_li.toggleClass('current');
}
$(document).ready(function() {
// Shift nav in mobile when clicking the menu.
$(document).on('click', "[data-toggle='wy-nav-top']", function() {
$("[data-toggle='wy-nav-shift']").toggleClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
});
// Nav menu link click operations
$(document).on('click', ".wy-menu-vertical .current ul li a", function() {
var target = $(this);
// Close menu when you click a link.
$("[data-toggle='wy-nav-shift']").removeClass("shift");
$("[data-toggle='rst-versions']").toggleClass("shift");
// Handle dynamic display of l3 and l4 nav lists
toggleCurrent(target);
if (typeof(window.SphinxRtdTheme) != 'undefined') {
window.SphinxRtdTheme.StickyNav.hashChange();
}
});
$(document).on('click', "[data-toggle='rst-current-version']", function() {
$("[data-toggle='rst-versions']").toggleClass("shift-up");
});
// Make tables responsive
$("table.docutils:not(.field-list)").wrap("<div class='wy-table-responsive'></div>");
// Add expand links to all parents of nested ul
$('.wy-menu-vertical ul').not('.simple').siblings('a').each(function () {
var link = $(this);
expand = $('<span class="toctree-expand"></span>');
expand.on('click', function (ev) {
toggleCurrent(link);
ev.stopPropagation();
return false;
});
link.prepend(expand);
});
});
// Sphinx theme state
window.SphinxRtdTheme = (function (jquery) {
var stickyNav = (function () {
var navBar,
win,
winScroll = false,
winResize = false,
linkScroll = false,
winPosition = 0,
winHeight,
docHeight,
enable = function () {
init();
reset();
win.on('hashchange', reset);
// Set scroll monitor
win.on('scroll', function () {
if (!linkScroll) {
winScroll = true;
}
});
setInterval(function () { if (winScroll) scroll(); }, 25);
// Set resize monitor
win.on('resize', function () {
winResize = true;
});
setInterval(function () { if (winResize) resize(); }, 25);
resize();
},
init = function () {
navBar = jquery('nav.wy-nav-side:first');
win = jquery(window);
},
reset = function () {
// Get anchor from URL and open up nested nav
var anchor = encodeURI(window.location.hash);
if (anchor) {
try {
var link = $('.wy-menu-vertical')
.find('[href="' + anchor + '"]');
$('.wy-menu-vertical li.toctree-l1 li.current')
.removeClass('current');
link.closest('li.toctree-l2').addClass('current');
link.closest('li.toctree-l3').addClass('current');
link.closest('li.toctree-l4').addClass('current');
}
catch (err) {
console.log("Error expanding nav for anchor", err);
}
}
},
scroll = function () {
winScroll = false;
var newWinPosition = win.scrollTop(),
winBottom = newWinPosition + winHeight,
navPosition = navBar.scrollTop(),
newNavPosition = navPosition + (newWinPosition - winPosition);
if (newWinPosition < 0 || winBottom > docHeight) {
return;
}
navBar.scrollTop(newNavPosition);
winPosition = newWinPosition;
},
resize = function () {
winResize = false;
winHeight = win.height();
docHeight = $(document).height();
},
hashChange = function () {
linkScroll = true;
win.one('hashchange', function () {
linkScroll = false;
});
};
jquery(init);
return {
enable: enable,
hashChange: hashChange
};
}());
return {
StickyNav: stickyNav
};
}($));
|
'use strict';
angular.module('ontimeApp')
.controller('EmployeeDetailController', function ($scope, $rootScope, $stateParams, entity, Employee, Employment) {
$scope.employee = entity;
$scope.load = function (id) {
Employee.get({id: id}, function(result) {
$scope.employee = result;
});
};
var unsubscribe = $rootScope.$on('ontimeApp:employeeUpdate', function(event, result) {
$scope.employee = result;
});
$scope.$on('$destroy', unsubscribe);
});
|
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'image2', 'pt-br', {
alt: 'Texto Alternativo',
btnUpload: 'Enviar para o Servidor',
captioned: 'Legenda da Imagem',
captionPlaceholder: 'Legenda',
infoTab: 'Informações da Imagem',
lockRatio: 'Travar Proporções',
menu: 'Formatar Imagem',
pathName: 'Imagem',
pathNameCaption: 'Legenda',
resetSize: 'Redefinir para o Tamanho Original',
resizer: 'Click e arraste para redimensionar',
title: 'Formatar Imagem',
uploadTab: 'Enviar ao Servidor',
urlMissing: 'URL da imagem está faltando.',
altMissing: 'Texto alternativo não informado.'
} );
|
/*
Language: HTTP
Description: HTTP request and response headers with automatic body highlighting
Author: Ivan Sagalaev <maniac@softwaremaniacs.org>
Category: protocols, web
Website: https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview
*/
export default function(hljs) {
const regex = hljs.regex;
const VERSION = 'HTTP/(2|1\\.[01])';
const HEADER_NAME = /[A-Za-z][A-Za-z0-9-]*/;
const HEADER = {
className: 'attribute',
begin: regex.concat('^', HEADER_NAME, '(?=\\:\\s)'),
starts: {
contains: [
{
className: "punctuation",
begin: /: /,
relevance: 0,
starts: {
end: '$',
relevance: 0
}
}
]
}
};
const HEADERS_AND_BODY = [
HEADER,
{
begin: '\\n\\n',
starts: { subLanguage: [], endsWithParent: true }
}
];
return {
name: 'HTTP',
aliases: ['https'],
illegal: /\S/,
contains: [
// response
{
begin: '^(?=' + VERSION + " \\d{3})",
end: /$/,
contains: [
{
className: "meta",
begin: VERSION
},
{
className: 'number', begin: '\\b\\d{3}\\b'
}
],
starts: {
end: /\b\B/,
illegal: /\S/,
contains: HEADERS_AND_BODY
}
},
// request
{
begin: '(?=^[A-Z]+ (.*?) ' + VERSION + '$)',
end: /$/,
contains: [
{
className: 'string',
begin: ' ',
end: ' ',
excludeBegin: true,
excludeEnd: true
},
{
className: "meta",
begin: VERSION
},
{
className: 'keyword',
begin: '[A-Z]+'
}
],
starts: {
end: /\b\B/,
illegal: /\S/,
contains: HEADERS_AND_BODY
}
},
// to allow headers to work even without a preamble
hljs.inherit(HEADER, {
relevance: 0
})
]
};
}
|
// Generated by IcedCoffeeScript 1.8.0-d
(function() {
var Base, b2u, u2b;
exports.b2u = b2u = function(b) {
return new Uint8Array(b);
};
exports.u2b = u2b = function(u) {
return new Buffer(u);
};
exports.Base = Base = (function() {
function Base(_arg) {
this.publicKey = _arg.publicKey, this.secretKey = _arg.secretKey, this.lib = _arg.lib;
}
Base.prototype.genFromSeed = function(_arg) {
var seed, tmp;
seed = _arg.seed;
tmp = this.lib.js.sign.keyPair.fromSeed(b2u(seed));
this.secretKey = u2b(tmp.secretKey);
this.publicKey = u2b(tmp.publicKey);
return {
secretKey: this.secretKey,
publicKey: this.publicKey
};
};
Base.prototype.get_secret_key = function() {
return this.secretKey;
};
Base.prototype.get_public_key = function() {
return this.publicKey;
};
return Base;
})();
}).call(this);
|
import React from "react";
import Header from "../components/Header";
import Footer from "../components/Footer";
export default class App extends React.Component {
displayName = "App"
render() {
return (
<section className="blue-grey lighten-5">
<Header />
<main className="container">
{this.props.children}
</main>
<Footer />
</section>
);
}
}
|
{
"label": "Label",
"alias": "Alias",
"addFieldset": "Tilføj et element",
"hideFieldsetControls": "Skjul fieldsets?",
"hideFieldsetControlsDescription": "Skjuler kontrollerne tilføj/fjern/sortér.",
"toggleAdvanced": "Slå avancerede muligheder til/fra",
"toggleAdvancedDescription": "Vis avancerede muligheder.",
"hidePropertyLabels": "Skjul labels på egenskaber?",
"hidePropertyLabelsDescription": "Skjuler labels på egenskaber.",
"maxFieldsets": "Maks antal fieldsets",
"maxFieldsetsDescription": "Hvor mange fieldsets er tilladt? Hvis der skrives '1' vil deaktivere kontrollerne. Som standard er det ubegrænset.",
"enableMultipleFieldsets": "Aktivér flere Fieldsets?",
"enableMultipleFieldsetsDescription": "Tillader flere typer af fieldsets i denne archetype.",
"hideFieldsetToolbar": "Skjul Fieldset værktøjslinie?",
"hideFieldsetToolbarDescription": "Skjuler den fieldset værktøjslinie der fremkommer når der findes mere end ét fieldset.",
"customWrapperClass": "Egen Wrapper Class",
"customWrapperClassDescription": "(Mulighed) Angiv din egen CSS class som tilføjes på wrapper div'en.",
"cssFile": "CSS fil",
"cssFileDescription": "(Mulighed) Tilføj en sti til din egen CSS fil der skal inkluderes på siden.",
"jsFile": "JavaScript fil",
"jsFileDescription": "(Mulighed) Tilføj en sti til din egen JavaScript fil der skal inkluderes på siden.",
"toggleDeveloperMode": "Slå udvikler muligheder til/fra.",
"toggleDeveloperModeDescription": "Aktivér på udvikler muligheder.",
"configModel": "Konfigurationsmodel",
"configModelDescription": "Vær forsigt med at redigere teksten for neden, den kontrollerer skemaet for denne archetype.",
"helpText": "Hjælpe tekst",
"defaultValue": "Standard værdi",
"dataType": "Datatype",
"required": "Påkrævet",
"regEx": "RegEx validering",
"properties": "Egenskaber",
"labelTemplate": "Label skabelon",
"select": "Vælg",
"icon": "Ikon",
"enableDisabling": "Aktivér fieldset-deaktivering?",
"enableDisablingDescription": "Tillad brugere at aktivere/deaktivere individuelle fieldsets.",
"deepDatatypeRequest":"Enable Deep Datatype Requests?",
"deepDatatypeRequestDescription":"Allows for easier datatype interception at the cost of caching performance.",
"overrideDefaultConverterDescription":"Check this if you wish to use your own custom property value converter.",
"overrideDefaultConverter":"Override Default Property Value Converter?",
"enableCloning":"Enable Cloning?",
"enableCloningDescription":"Enable Fieldset Cloning.",
"fieldsetGroups":"Fieldset-grupper",
"fieldsetGroupsDescription":"Hvis du har mange fieldsets, skal du måske overveje at gruppere dem i fieldset-vælgeren. Når du først har defineret dine grupper her, vil en gruppe-vælger dukke op i fieldset-editoren, og du kan derefter vælge grupper for alle dine fieldsets.",
"fieldsetGroupName":"Navn",
"addFieldsetGroup":"Tilføj gruppe"
}
|
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
|
'use strict'
var test = require('tap').test
var pino = require('../')
var sink = require('./helper').sink
test('inserts timestamp by default', function (t) {
var instance = pino(sink(function (chunk, enc, cb) {
t.equal(chunk.hasOwnProperty('time'), true)
t.ok(new Date(chunk.time) <= new Date(), 'time is greater than timestamp')
t.equal(chunk.msg, 'foobar')
cb()
t.end()
}))
instance.info('foobar')
})
test('omits timestamp with option', function (t) {
var instance = pino({timestamp: false}, sink(function (chunk, enc, cb) {
t.equal(chunk.hasOwnProperty('time'), false)
t.equal(chunk.msg, 'foobar')
cb()
t.end()
}))
instance.info('foobar')
})
test('child inserts timestamp by default', function (t) {
var logger = pino(sink(function (chunk, enc, cb) {
t.equal(chunk.hasOwnProperty('time'), true)
t.ok(new Date(chunk.time) <= new Date(), 'time is greater than timestamp')
t.equal(chunk.msg, 'foobar')
cb()
t.end()
}))
var instance = logger.child({component: 'child'})
instance.info('foobar')
})
test('child omits timestamp with option', function (t) {
var logger = pino({timestamp: false}, sink(function (chunk, enc, cb) {
t.equal(chunk.hasOwnProperty('time'), false)
t.equal(chunk.msg, 'foobar')
cb()
t.end()
}))
var instance = logger.child({component: 'child'})
instance.info('foobar')
})
|
define({
"left": "Rata kiri",
"right": "Rata kanan",
"arrangement": "Penataan",
"autoUpdate": "Pembaruan otomatis",
"respectCurrentMapScale": "Skala peta yang tepat saat ini",
"layerSelectorTitle": "Pilih layer mana yang akan menampilkan legenda: ",
"showLegendsForLayers": "Perlihatkan legenda untuk layer:",
"showBasemapLegends": "Tampilkan legenda peta dasar",
"honorTheWebMapSetting": "Ikuti pengaturan peta web",
"reset": "Atur ulang",
"resetTip": "Atur ulang ke pengaturan asli peta web"
});
|
var config = require('../config').config;
var convert = require('data2xml')();
var markdown = require('node-markdown').Markdown;
var Topic = require('../proxy').Topic;
var mcache = require('memory-cache');
exports.index = function (req, res, next) {
if (!config.rss) {
res.statusCode = 404;
return res.send('Please set `rss` in config.js');
}
res.contentType('application/xml');
if (!config.debug && mcache.get('rss')) {
res.send(mcache.get('rss'));
} else {
var opt = { limit: config.rss.max_rss_items, sort: [ [ 'create_at', 'desc' ] ] };
Topic.getTopicsByQuery({}, opt, function (err, topics) {
if (err) {
return next(err);
}
var rss_obj = {
_attr: { version: '2.0' },
channel: {
title: config.rss.title,
link: config.rss.link,
language: config.rss.language,
description: config.rss.description,
item: []
},
};
topics.forEach(function (topic) {
rss_obj.channel.item.push({
title: topic.title,
link: config.rss.link + '/topic/' + topic._id,
guid: config.rss.link + '/topic/' + topic._id,
description: markdown(topic.content, true),
author: topic.author.name,
pubDate: topic.create_at.toUTCString()
});
});
var rssContent = convert('rss', rss_obj);
mcache.put('rss', rssContent, 1000 * 60 * 5); // 五分钟
res.send(rssContent);
});
}
};
|
var TX = A0;
//var CODE = 0b10100000111111101110;
var CODE = 0b10000100101011100101;
function sendCommand(command) {
var bits = (CODE & ~0b11111) | command;
for (var i=24;i>=0;i--) {
if ((bits>>i)&1) {
digitalPulse(TX,1,0.9);
digitalPulse(TX,0,0.3);
} else {
digitalPulse(TX,1,0.3);
digitalPulse(TX,0,0.9);
}
}
digitalPulse(TX,1,0.001);
}
function sendMultiple(command) {
print("send "+command);
var n = 10;
var interval = setInterval(function() {
sendCommand(command);
if (n-- < 0) clearInterval(interval);
}, 50);
console.log('mains socket command sent !');
}
function pageHandler(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var u = url.parse(req.url, true);
res.write('<html><body>Sockets: <a href="/?s0=off">all off</a> 1<a href="/?s1=on">on</a> or <a href="/?s1=off">off</a> 2<a href="/?s2=on">on</a> or <a href="/?s2=off">off</a> 3<a href="/?s3=on">on</a> or <a href="/?s3=off">off</a> 4<a href="/?s4=on">on</a> or <a href="/?s4=off">off</a> </body></html>');
if (u.query !== null) {
//if (u.query["s1"]=="on") sendMultiple(0b11110);
//if (u.query["s1"]=="off") sendMultiple(0b01110);
if (u.query["s0"]=="off") sendMultiple(0b10000); // all off
if (u.query["s1"]=="on") sendMultiple(0b11110); // 1 on
if (u.query["s1"]=="off") sendMultiple(0b01110); // 1 off
if (u.query["s2"]=="on") sendMultiple(0b10110); // 2 on
if (u.query["s2"]=="off") sendMultiple(0b00110); // 2 off
if (u.query["s3"]=="on") sendMultiple(0b11010); // 3 on
if (u.query["s3"]=="off") sendMultiple(0b01010); // 3 off
if (u.query["s4"]=="on") sendMultiple(0b11100); // 4 on
if (u.query["s4"]=="off") sendMultiple(0b01100); // 4 off
}
res.end();
}
var wlan = require("CC3000").connect();
//wlan.connect( "AccessPointName", "WPA2key", function (s) {
wlan.connect( "Seedsdesign", "jaimelesfraisesdesbois666", function (s) {
if (s=="dhcp") {
console.log("Connect to http://"+wlan.getIP().ip);
require("http").createServer(pageHandler).listen(80);
}
});
|
/// <amd-dependency path="angular">
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
define(["require", "exports", "angular", "./Directive", "./urlHelper", "angular"], function (require, exports, angular, Directive, urlHelper) {
var parse;
var syncUrl = (function (_super) {
__extends(syncUrl, _super);
function syncUrl() {
_super.apply(this, arguments);
//These should all be constant
this.varName = "=";
this.urlName = "=";
this.kind = "=?"; //"number"
}
syncUrl.prototype.construct = function (element) {
var unsub;
switch (this.kind) {
default:
urlHelper.bindObjToUrl(this.$parent, this.varName, this.urlName, JSON.parse, JSON.stringify, parse);
break;
case "number":
urlHelper.bindNumberToUrl(this.$parent, this.varName, this.urlName, parse);
break;
}
this.$on("$destroy", function () {
unsub();
});
};
return syncUrl;
})(Directive);
var mod = angular.module("syncUrl", []);
mod.directive("syncUrl", function ($parse) {
parse = $parse;
return (new syncUrl().createScope());
});
});
|
// /*jshint expr: true*/
// 'use strict';
// describe('measureCommitteeOpposingDirective', function() {
// var scope, measureCommitteeListEl;
// beforeEach(angular.mock.module('measureCommitteeList'));
// beforeEach(function() {
// //TODO factory.js
// var committees = [
// {
// name: 'American Test Committee',
// contributions: 10
// },
// {
// name: 'American Test Commission',
// contributions: 10
// },
// {
// name: 'Committee for American Tests',
// contributions: 10
// }
// ];
// angular.mock.inject(function($compile, $rootScope) {
// scope = $rootScope.$new();
// scope.committees = committees;
// measureCommitteeListEl = angular.element('<measure-committee-list committees="committees"></measure-committee-list>');
// $compile(measureCommitteeListEl)(scope);
// $rootScope.$digest();
// });
// });
// afterEach(function() {
// measureCommitteeListEl.remove();
// });
// it('should have two committees', function() {
// expect(measureCommitteeListEl.find('li')).to.have.length(3);
// });
// });
|
require('ts-node/register');
require('./src/main');
|
'use strict';
module.exports = function(app) {
var users = require('../../app/controllers/users.server.controller');
var teachers = require('../../app/controllers/teachers.server.controller');
// Teachers Routes
app.route('/teachers')
.get(teachers.list)
.post(users.requiresLogin, teachers.create);
app.route('/teachers/:teacherId')
.get(teachers.read)
.put(users.requiresLogin, teachers.hasAuthorization, teachers.update)
.delete(users.requiresLogin, teachers.hasAuthorization, teachers.delete);
// Finish by binding the Teacher middleware
app.param('teacherId', teachers.teacherByID);
};
|
/**
* Hunter-lab space.
*
* @module color-space/labh
*/
var xyz = require('./xyz');
module.exports = {
name: 'labh',
//mins/maxes are taken from colormine
//FIXME: check whether mins/maxes correct
min: [0,-128,-128],
max: [100,128,128],
channel: ['lightness', 'a', 'b'],
alias: ['hunter-lab', 'hlab'],
//maths are taken from EasyRGB
xyz: function(lab) {
var l = lab[0], a = lab[1], b = lab[2];
var _y = l / 10;
var _x = a / 17.5 * l / 10;
var _z = b / 7 * l / 10;
var y = _y * _y;
var x = ( _x + y ) / 1.02;
var z = -( _z - y ) / 0.847;
return [x,y,z];
}
};
//extend xyz
xyz.labh = function(xyz){
var x = xyz[0], y = xyz[1], z = xyz[2];
var l = 10 * Math.sqrt( y );
var a = y === 0 ? 0 : 17.5 * ((( 1.02 * x ) - y ) / Math.sqrt( y ) );
var b = y === 0 ? 0 : 7 * ( ( y - ( 0.847 * z ) ) / Math.sqrt( y ) );
return [l, a, b];
};
|
var model = require('./model')
var inspect = require('util').inspect
module.exports = api
function isFunction (f) {
return 'function' === typeof f
}
function isObject (o) {
return 'object' === typeof o
}
var timer = null
//gonna
var RADIUS = 50
function left(r, radius) {
r = model.get(r)
return r.get('x') - (radius || RADIUS) / 2
}
function right(r, radius) {
r = model.get(r)
return r.get('x') + (radius || RADIUS) / 2
}
function dist (a, b) {
a = a.get ? a : model.get(a)
b = b.get ? b : model.get(b)
var x = a.get('x') - b.get('x')
var y = a.get('y') - b.get('y')
var l = Math.sqrt(x*x+y*y)
// console.log("x", x, "y", y, a.state, b.state)
return {x: x, y: y, length: l}
}
model.on('row_update', function detect () {
if(timer)
return
//detect collisions.
var rows = model.rows
//sort by x
var sorted = Object.keys(rows).sort(function (a, b) {
left(a) - left(b)
})
//iterate over sorted..
sorted.forEach(function (e, i) {
//check things that maybe intersect.
var j = i + 1
//sort the elements by their left bound,
//so it is easy to check whether there has been a collision.
while(sorted[j] && left(sorted[j]) < right(sorted[i])) {
if(dist(sorted[i], sorted[j]).length < RADIUS*2) {
model.emit('touch', sorted[i], sorted[j])
}
j ++
}
})
// setTimeout(detect, 50)
})
function api (row) {
function safe (fun) {
return function () {
console.log(JSON.stringify([ 'start', row.id ]))
var f
try {
f = fun.apply(this, arguments)
} catch (err) {
console.log(JSON.stringify([ 'error', row.id ]))
//TODO: present this back to the user somehow...
//or, make the entity die.
row.set('message', {text: err.toString().toUpperCase(), stroke: 'red', fill: 'black'})
console.error('user-error', err.toString().toUpperCase())
return
}
console.log(JSON.stringify([ 'end', row.id ]))
return f
}
}
var thinker = null, hearer = null
function createListener (event, wrapper) {
wrapper = wrapper || function (l) {
return l
}
var _listener
return function (listener) {
model.removeListener(event, listener)
if(isFunction(listener)) {
var wrapped =
model.on(event, _listener = safe(wrapper(listener)))
}
return self
}
}
var self = {
id: function () {
return row.id
},
whatDist: function (other) {
other = model.rows[other]
if(!other) return
var coord = dist(other, row)
// console.log("c", coord)
return coord
},
set: function () {
return row.set.apply(row, arguments)
},
get: function () {
return row.get.apply(row, arguments)
},
say: function (text, opts) {
if(!opts) opts = {}
if(typeof text === 'object') {
opts = text
}
else opts.text = text
if(opts.text) {
if(String(opts.text).length > 140)
opts.text = String(text).substring(0, 140)
row.set('message', opts)
model.emit('say', text, self.id())
}
return self
},
move: function (x, y) {
if(isObject(x))
y = x.y, x=x.x
//check for max X,Y
var _x = row.get('x') + x
, _y = row.get('y') + y;
// console.log('['+_x+', '+_y+']--'+row.get('id'))
row.set('x', _x)
row.set('y', _y)
return self
},
think: function (think) {
clearInterval(thinker)
//console.log('THINK')
//depending on how 'smart' the entity is,
//CURRENTLY, just hard code to 500 ms
if(isFunction(think))
thinker = setInterval(safe(think), 500)
return self
},
hear: createListener('say', function (f) {
return function (message, id) {
if(self.whatDist(id).length < 1000 && id !== self.id()) {
f(message, id)
}
}
}),
touch: createListener('touch', function (fun) {
return function (a, b) {
if (row.id == a) fun(b)
else
if (row.id == b) fun(a)
}
}),
bless: function (id, atm) {
//transfer energy to another ID
amt = amt || 1
var other = model.rows[id], back
if(!other) return
//transfer energy to the other...
//other.set('energy', other.get('energy') + amt)
if(isFunction(other._cursed))
back = other._cursed(self.id(), amt) || 0
else
//just give in if you don't refuse.
back = amt * -1
amt = amt * Math.random()
back = back * Math.random()
//okay, you can attack + or -
//what if the user gives in?
//
var diff
if(amt > 0 && back > 0) {
//the winner gains the diff,
//the looser looses the diff
diff = amt - back
} else {
diff = (amt - back) / 2
}
row.set('energy', row.get('energy') + diff)
energy.set('energy', energy.get('energy') + diff)
},
//a curse is just a negative blessing.
curse: function (id, amt) {
return self.bless(id, (amt || 1) * -1)
},
cursed: function (func) {
//when you are cursed, curse them back.
//or bless them back... whatever...
row._cursed = safe(func)
}
}
//prevent context reassign
for (var k in self) {
self[k] = self[k].bind(self)
}
return self
}
|
import Ember from 'ember';
import filterComponents from 'diesel/utils/filter-risk-components';
import ColumnConfigMixin from 'diesel/mixins/components/column-config';
const COLUMN_PRESETS = {
'title': 'Predisposing Conditions',
'description': 'Description',
'pervasiveness': 'Pervasiveness',
'actions': ''
};
export default Ember.Component.extend(ColumnConfigMixin, {
filters: { search: '', sort: null, pervasiveness: null },
tagName: 'table',
classNames: ['base-table'],
columns: ['title', 'description', 'pervasiveness', 'actions'],
columnPresets: COLUMN_PRESETS,
filteredPredisposingConditions: Ember.computed('filters.pervasiveness', 'filters.sort', 'filters.search', 'predisposingConditions.[]', function() {
let predisposingConditions = this.get('predisposingConditions');
let filters = this.get('filters');
return filterComponents(predisposingConditions, filters);
})
});
|
/**
* @fileoverview A rule to warn against using arrow functions when they could be
* confused with comparisions
* @author Jxck <https://github.com/Jxck>
*/
"use strict";
const astUtils = require("../ast-utils.js");
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
/**
* Checks whether or not a node is a conditional expression.
* @param {ASTNode} node - node to test
* @returns {boolean} `true` if the node is a conditional expression.
*/
function isConditional(node) {
return node && node.type === "ConditionalExpression";
}
//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow arrow functions where they could be confused with comparisons",
category: "ECMAScript 6",
recommended: false
},
schema: [{
type: "object",
properties: {
allowParens: {type: "boolean"}
},
additionalProperties: false
}]
},
create: function(context) {
const config = context.options[0] || {};
const sourceCode = context.getSourceCode();
/**
* Reports if an arrow function contains an ambiguous conditional.
* @param {ASTNode} node - A node to check and report.
* @returns {void}
*/
function checkArrowFunc(node) {
const body = node.body;
if (isConditional(body) && !(config.allowParens && astUtils.isParenthesised(sourceCode, body))) {
context.report(node, "Arrow function used ambiguously with a conditional expression.");
}
}
return {
ArrowFunctionExpression: checkArrowFunc
};
}
};
|
'use strict'
const Buffer = require('safe-buffer').Buffer
const crypto = require('crypto')
const npm = require('../npm')
const log = require('npmlog')
let pack
const path = require('path')
let effectiveOwner
const npmSession = crypto.randomBytes(8).toString('hex')
log.verbose('npm-session', npmSession)
module.exports = pacoteOpts
function pacoteOpts (moreOpts) {
if (!pack) {
pack = require('../pack.js')
}
const ownerStats = calculateOwner()
const opts = {
cache: path.join(npm.config.get('cache'), '_cacache'),
ca: npm.config.get('ca'),
cert: npm.config.get('cert'),
defaultTag: npm.config.get('tag'),
dirPacker: pack.packGitDep,
hashAlgorithm: 'sha1',
includeDeprecated: false,
key: npm.config.get('key'),
localAddress: npm.config.get('local-address'),
log: log,
maxAge: npm.config.get('cache-min'),
maxSockets: npm.config.get('maxsockets'),
npmSession: npmSession,
offline: npm.config.get('offline'),
preferOffline: npm.config.get('prefer-offline') || npm.config.get('cache-min') > 9999,
preferOnline: npm.config.get('prefer-online') || npm.config.get('cache-max') <= 0,
projectScope: npm.projectScope,
proxy: npm.config.get('https-proxy') || npm.config.get('proxy'),
noProxy: npm.config.get('noproxy'),
refer: npm.registry.refer,
registry: npm.config.get('registry'),
retry: {
retries: npm.config.get('fetch-retries'),
factor: npm.config.get('fetch-retry-factor'),
minTimeout: npm.config.get('fetch-retry-mintimeout'),
maxTimeout: npm.config.get('fetch-retry-maxtimeout')
},
scope: npm.config.get('scope'),
strictSSL: npm.config.get('strict-ssl'),
userAgent: npm.config.get('user-agent'),
dmode: npm.modes.exec,
fmode: npm.modes.file,
umask: npm.modes.umask
}
if (ownerStats.uid != null || ownerStats.gid != null) {
Object.assign(opts, ownerStats)
}
npm.config.keys.forEach(function (k) {
const authMatchGlobal = k.match(
/^(_authToken|username|_password|password|email|always-auth|_auth)$/
)
const authMatchScoped = k[0] === '/' && k.match(
/(.*):(_authToken|username|_password|password|email|always-auth|_auth)$/
)
// if it matches scoped it will also match global
if (authMatchGlobal || authMatchScoped) {
let nerfDart = null
let key = null
let val = null
if (!opts.auth) { opts.auth = {} }
if (authMatchScoped) {
nerfDart = authMatchScoped[1]
key = authMatchScoped[2]
val = npm.config.get(k)
if (!opts.auth[nerfDart]) {
opts.auth[nerfDart] = {
alwaysAuth: !!npm.config.get('always-auth')
}
}
} else {
key = authMatchGlobal[1]
val = npm.config.get(k)
opts.auth.alwaysAuth = !!npm.config.get('always-auth')
}
const auth = authMatchScoped ? opts.auth[nerfDart] : opts.auth
if (key === '_authToken') {
auth.token = val
} else if (key.match(/password$/i)) {
auth.password =
// the config file stores password auth already-encoded. pacote expects
// the actual username/password pair.
Buffer.from(val, 'base64').toString('utf8')
} else if (key === 'always-auth') {
auth.alwaysAuth = val === 'false' ? false : !!val
} else {
auth[key] = val
}
}
if (k[0] === '@') {
if (!opts.scopeTargets) { opts.scopeTargets = {} }
opts.scopeTargets[k.replace(/:registry$/, '')] = npm.config.get(k)
}
})
Object.keys(moreOpts || {}).forEach((k) => {
opts[k] = moreOpts[k]
})
return opts
}
function calculateOwner () {
if (!effectiveOwner) {
effectiveOwner = { uid: 0, gid: 0 }
// Pretty much only on windows
if (!process.getuid) {
return effectiveOwner
}
effectiveOwner.uid = +process.getuid()
effectiveOwner.gid = +process.getgid()
if (effectiveOwner.uid === 0) {
if (process.env.SUDO_UID) effectiveOwner.uid = +process.env.SUDO_UID
if (process.env.SUDO_GID) effectiveOwner.gid = +process.env.SUDO_GID
}
}
return effectiveOwner
}
|
var _ = require( "lodash" );
var when = require( "when" );
var util = require( "util" );
var log = require( "./log" )( "seriate.transaction" );
var sql = require( "mssql" );
function errorHandler( err ) {
this.err = err;
this.transition( "error" );
}
module.exports = function( SqlContext ) {
var TransactionContext = SqlContext.extend( {
states: {
connecting: {
success: "startingTransaction"
},
startingTransaction: {
_onEnter: function() {
var args = [ function( err ) {
if ( err ) {
this.handle( "error", err );
} else {
this.handle( "success" );
}
}.bind( this ) ];
if ( this.isolationLevel ) {
var isolationLevel = this.isolationLevel;
if ( _.isString( this.isolationLevel ) ) {
isolationLevel = sql.ISOLATION_LEVEL[ this.isolationLevel.toUpperCase() ];
if ( isolationLevel === undefined ) {
var err = new Error( "Unknown isolation level: \"" + this.isolationLevel + "\"" );
this.handle( "error", err );
}
}
args.unshift( isolationLevel );
}
this.transaction = this.transaction || new sql.Transaction( this.connection );
this.transaction.begin.apply( this.transaction, args );
},
success: function() {
this.nextState();
},
error: errorHandler
},
done: {
_onEnter: function() {
var self = this;
self.emit( "end", {
sets: self.results,
transaction: {
commit: function() {
return when.promise( function( resolve, reject ) {
self.transaction.commit( function( commitError ) {
if ( commitError ) {
self.transaction.rollback( function( rollbackErr ) {
if ( rollbackErr ) {
var message = util.format( "Error occurred during automatic roll back after a commit error.\n\tCommit error: %s\n\tRollback error: %s\n",
commitError,
rollbackErr );
log.error( message );
reject( new Error( message ) );
} else {
reject( commitError );
}
} );
} else {
resolve();
}
} );
} );
},
rollback: function() {
return when.promise( function( resolve, reject ) {
self.transaction.rollback( function( err ) {
if ( err ) {
log.error( "Error occurred while rolling back: %s", err.message );
reject( err );
} else {
resolve();
}
} );
} );
}
}
} );
}
},
error: {
_onEnter: function() {
var precedingErrorMessage = _.map( this.err && this.err.precedingErrors, function( error ) {
return "\n\tPreceding error: " + error.message;
} ).join( "" );
var message = util.format( "TransactionContext Error. Failed on step \"%s\" with: \"%s\"%s", this.priorState, this.err.message, precedingErrorMessage );
this.err.message = message;
this.err.step = this.priorState;
if ( this.transaction ) {
this.transaction.rollback( function( rollbackErr ) {
if ( rollbackErr ) {
message = util.format( "Error occurred during automatic roll back after error on transaction on step %s.\n\tTransaction error: %s\n\tRollback error: %s\n",
this.priorState,
this.err.message,
rollbackErr );
this.err.message = message;
}
log.error( message );
this.emit( "error", this.err );
}.bind( this ) );
} else {
log.error( message );
this.emit( "error", this.err );
}
}
}
}
} );
return TransactionContext;
};
|
var AbstractIterator = require('abstract-leveldown').AbstractIterator
var inherits = require('inherits')
function DeferredIterator (db, options) {
AbstractIterator.call(this, db)
this._options = options
this._iterator = null
this._operations = []
}
inherits(DeferredIterator, AbstractIterator)
DeferredIterator.prototype.setDb = function (db) {
var it = this._iterator = db.iterator(this._options)
this._operations.forEach(function (op) {
it[op.method].apply(it, op.args)
})
}
DeferredIterator.prototype._operation = function (method, args) {
if (this._iterator) return this._iterator[method].apply(this._iterator, args)
this._operations.push({ method: method, args: args })
}
'next end'.split(' ').forEach(function (m) {
DeferredIterator.prototype['_' + m] = function () {
this._operation(m, arguments)
}
})
// Must defer seek() rather than _seek() because it requires db._serializeKey to be available
DeferredIterator.prototype.seek = function () {
this._operation('seek', arguments)
}
module.exports = DeferredIterator
|
import moment from 'moment'
/**
* This function will be used to convert a date to a moment.
*
* It accepts input as sring, date or moment
*
* @param {String/Date/Moment} value
*
* @param {String} [dateFormat] if value is string, it will be parsed to a moment
* using this format.
* You can skip this argument and only specify the config instead,
* where you can have a dateFormat property
*
* @param {Object} [config]
* @param {String} [config.dateFormat] a dateFormat string
* @param {String} [config.locale] a locale
* @param {Boolean} [config.strict] whether to perform strict parsing on strings
*
* @return {Moment}
*/
export default (value, dateFormat, config) => {
if (typeof dateFormat === 'object') {
config = dateFormat
dateFormat = null
}
const strict = !!(config && config.strict)
const locale = config && config.locale
dateFormat = dateFormat || (config && config.dateFormat) || 'YYYY-MM-DD'
if (typeof value == 'string') {
return moment(value, dateFormat, locale, strict)
}
value = value == null ?
new Date() :
value
return moment(value, undefined, locale, strict)
}
|
'use strict';
var test = require('tape');
var errors = require('../../../src/errors');
test('We get custom errors with stacks', function(t) {
t.plan(3);
var fauxJax = require('faux-jax');
var createFixture = require('../../utils/create-fixture');
var fixture = createFixture();
var index = fixture.index;
fauxJax.install();
fauxJax.once('request', function(req) {
req.respond(400, {}, '{"message": "GOAWAY!", "status": 400}');
fauxJax.restore();
});
index.search('something', function(err) {
t.ok(err instanceof Error, 'Its an instance of Error');
t.ok(err instanceof errors.AlgoliaSearchError, 'Its an instance of AlgoliaSearchError');
t.ok(err.stack, 'We have a stacktrace');
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.