text
stringlengths 2
6.14k
|
|---|
angular.module('app.services', [
'app.services.actions',
'app.services.connection',
'app.services.coverart',
'app.services.locale',
'app.services.logging',
'app.services.mopidy',
'app.services.paging',
'app.services.platform',
'app.services.router',
'app.services.servers',
'app.services.settings'
]);
|
// SERVER-4516 and SERVER-6913: test that update and findAndModify tolerate
// an _id in the update document, as long as the _id will not be modified
var t = db.jstests_server4516;
var startingDoc = {_id: 1, a: 1};
function prepare() {
t.drop();
t.save(startingDoc);
}
function update_succeeds(updateDoc, qid, resultDoc) {
prepare();
t.update({_id: qid}, updateDoc, true);
assert.eq(t.findOne({_id: qid}), resultDoc);
prepare();
t.findAndModify({query: {_id: qid}, update: updateDoc, upsert: true});
assert.eq(t.findOne({_id: qid}), resultDoc);
}
update_succeeds({_id: 1, a: 2}, 1, {_id: 1, a: 2});
update_succeeds({$set: {_id: 1}}, 1, {_id: 1, a: 1});
update_succeeds({_id: 1, b: "a"}, 1, {_id: 1, b: "a"});
update_succeeds({_id: 2, a: 3}, 2, {_id: 2, a: 3});
function update_fails(updateDoc, qid) {
prepare();
var res = t.update({_id: qid}, updateDoc, true);
assert.writeError(res);
assert.eq(t.count(), 1);
assert.eq(t.findOne(), startingDoc);
prepare();
assert.throws(function() {
t.findAndModify({query: {_id: qid}, update: updateDoc, upsert: true});
});
assert.eq(t.count(), 1);
assert.eq(t.findOne(), startingDoc);
}
update_fails({$set: {_id: 2}}, 1);
update_fails({_id: 2, a: 3}, 1);
update_fails({_id: 2, a: 3}, 3);
|
/**
* @fileoverview Defines compressors utility methods.
*
* @see https://google.github.io/styleguide/javascriptguide.xml
* @see https://developers.google.com/closure/compiler/docs/js-for-compiler
* @module glize/compressors
*/
import * as lzw from 'lzw-compressor';
/**
* Enumeration of available compression types.
* @enum {string}
*/
export const TYPE = {
LZW: 'lzw'
};
/**
* Compress data string using specified compression type.
* @param {string} data Data to compress.
* @param {string=} [opt_type=TYPE.LZW] Optional compression type.
* @return {string} Returns compressed data.
* @method
* @example
* const result = compress(
* 'Any string of any length. Any string of any length. Any string of any length.');
* console.log(result);
* //> Any string of aā leĈth. ĀĂĄĆĈĊČĎĂđēĕėďĚćĉċčďġgĔ.
*/
export const compress = (data, opt_type = TYPE.LZW) => {
let result = '';
if (TYPE.LZW === opt_type) {
result = lzw.compress(data);
}
return result;
};
/**
* Decompress data string using specified compression type.
* @param {string} data Data to compress.
* @param {string=} [opt_type=TYPE.LZW] Optional compression type.
* @return {string} Returns compressed data.
* @method
* @example
* const result = decompress('Any string of aā leĈth. ĀĂĄĆĈĊČĎĂđēĕėďĚćĉċčďġgĔ.');
* console.log(result);
* //> Any string of any length. Any string of any length. Any string of any length.
*/
export const decompress = (data, opt_type = TYPE.LZW) => {
let result = '';
if (TYPE.LZW === opt_type) {
result = lzw.decompress(data);
}
return result;
};
|
// ----------------------------------------------------------------------------
// Module initialization
var Config = require("config").config;
var utils = require("utils");
var validators = require("validators");
// ----------------------------------------------------------------------------
// Setting class.
function Setting() {
$.title_label.text_id = this.args.title_id;
$.title_label.text = Alloy.Globals.L(this.args.title_id);
// This will trigger UI update. Ugly solution I know.
$.setting.top = this.args.top || 0;
if (typeof this.args.width !== 'undefined') {
$.setting.width = this.args.width;
}
// Listen to the "SettingChanges" event. It simply updates the string
// representation of the property that the view shows.
this.addSettingsChangedHandler(this.updateValue);
}
// Inherits from Controller...
Setting.prototype = new (require("controller"))(
arguments[0], [$.title_label]
);
// Read the actual value of the property that this setting is responsible for
Setting.prototype.updateValue = function() {
$.setting_value.text =
Alloy.Globals.L(Config.getProperty(this.args.propertyName).stringValue());
};
Setting.prototype.handleClick = function (initial, use, validator) {
var self = this;
var arg = {
useValue: function(value) {
if (eval("validators." + validator + "(value)")) {
use(self.args.propertyName, value);
self.updateValue();
} else {
alert(Alloy.Globals.L("illegal_value"));
}
},
value: initial,
validator: validator
};
utils.openWindowWithBottomClicksDisabled(this.args.controllerName, arg);
};
Setting.prototype.clickHandler = function() {
var initial = Config.getProperty(this.args.propertyName).get();
var validator = typeof this.args.validator !== 'undefined' ?
this.args.validator : "ok";
function use(n, v) {
Config.getProperty(n).set(v);
}
this.handleClick(initial, use, validator);
};
// ----------------------------------------------------------------------------
// Create the object representing this particular setting
var setting = new Setting();
// Handling button click event
function onClick(e) {
setting.clickHandler();
}
|
(function() {
'use strict';
angular
.module('fitappApp')
.controller('RequestResetController', RequestResetController);
RequestResetController.$inject = ['$timeout', 'Auth'];
function RequestResetController ($timeout, Auth) {
var vm = this;
vm.error = null;
vm.errorEmailNotExists = null;
vm.requestReset = requestReset;
vm.resetAccount = {};
vm.success = null;
$timeout(function (){angular.element('#email').focus();});
function requestReset () {
vm.error = null;
vm.errorEmailNotExists = null;
Auth.resetPasswordInit(vm.resetAccount.email).then(function () {
vm.success = 'OK';
}).catch(function (response) {
vm.success = null;
if (response.status === 400 && response.data === 'e-mail address not registered') {
vm.errorEmailNotExists = 'ERROR';
} else {
vm.error = 'ERROR';
}
});
}
}
})();
|
'use strict';
const { extend } = require('underscore');
const dbclient = require('abacus-dbclient');
const { testCollectedUsageID, testResourceID, testOrganizationID, testSpaceID, testConsumerID, testPlanID,
testResourceType, testAccountID, testMeteringPlanID, testRatingPlanID,
testPricingPlanID } = require('./fixtures/usageDocumentFieldsConstants');
const _commonBlueprint = {
collected_usage_id: testCollectedUsageID,
resource_id: testResourceID,
organization_id: testOrganizationID,
space_id: testSpaceID,
consumer_id: testConsumerID,
plan_id: testPlanID,
resource_type: testResourceType,
account_id: testAccountID,
metering_plan_id: testMeteringPlanID,
rating_plan_id: testRatingPlanID,
pricing_plan_id: testPricingPlanID
};
const buildUsage = (...builders) => {
const usage = {};
for(let builder of builders)
builder(usage);
return extend(usage, {
id: dbclient.kturi(usage.resource_instance_id, usage.processed)
});
};
const withEndTimestamp = (timestamp) => (usage) => usage.end = timestamp;
const withStartTimestamp = (timestamp) => (usage) => usage.start = timestamp;
const withProcessedTimestamp = (timestamp) => (usage) => usage.processed = timestamp;
const withBlueprint = (blueprint) => (usage) => extend(usage, blueprint);
const withDefaultBlueprint = () => (usage) => extend(usage, _commonBlueprint);
const withResourceInstanceId = (resourceInstanceId) => (usage) => usage.resource_instance_id = resourceInstanceId;
const withAccumulatedUsage = (accumulatedUsage) => (usage) => usage.accumulated_usage = accumulatedUsage;
const buildAccumulatedUsage = (...builders) => {
const accumulatedUsage = { windows: [[null], [null], [null], [null, null, null, null, null, null], [null, null]] };
for(let builder of builders)
builder(accumulatedUsage);
return accumulatedUsage;
};
const withMetricName = (metricName) => (accumulatedUsage) => accumulatedUsage.metric = metricName;
const withCurrentDayQuantity = (quantity) => (accumulatedUsage) =>
accumulatedUsage.windows[3][0] = { quantity: quantity };
const withPreviousDayQuantity = (quantity) => (accumulatedUsage) =>
accumulatedUsage.windows[3][1] = { quantity: quantity };
const withCurrentMonthQuantity = (quantity) => (accumulatedUsage) =>
accumulatedUsage.windows[4][0] = { quantity: quantity };
module.exports = {
buildUsage, withEndTimestamp, withStartTimestamp, withProcessedTimestamp, withBlueprint, withDefaultBlueprint,
withResourceInstanceId, withAccumulatedUsage, buildAccumulatedUsage, withMetricName, withCurrentDayQuantity,
withCurrentMonthQuantity, withPreviousDayQuantity
};
|
"use strict";
import chai from "chai";
import chaiAsPromised from "chai-as-promised";
import sinon from "sinon";
import BusinessElementsClient from "../src";
import uuid from "uuid";
import * as requests from "../src/requests";
chai.use(chaiAsPromised);
chai.should();
chai.config.includeStack = true;
const FAKE_SERVER_URL = "http://api.fake-server";
/** @test {Attribute} */
describe("Attribute", () => {
let sandbox, client, attributeId, attribute;
beforeEach(() => {
sandbox = sinon.sandbox.create();
client = new BusinessElementsClient(FAKE_SERVER_URL);
attributeId = uuid.v4();
attribute = client.tenant("example.com").attributes().attribute(attributeId);
});
afterEach(() => {
sandbox.restore();
});
/** @test {Attribute#get} */
describe("#get()", () => {
const data = {id: attributeId};
beforeEach(() => {
sandbox.stub(client, "execute").returns(Promise.resolve(data));
});
it("should get capture", () => {
attribute.get();
sinon.assert.calledWithMatch(client.execute, {
path: `/attributes/${attributeId}`
});
});
it("should return attribute data", () => {
return attribute.get().should.become(data);
});
});
/** @test {Attribute#edit} */
describe("#edit()", () => {
const response = {status: "Ok"};
const schema = {
"type": "object",
"properties": {
"type": {
"title": "type",
"type": "string"
}
}
};
beforeEach(() => {
sandbox.stub(client, "execute").returns(Promise.resolve(response));
sandbox.spy(requests, "updateAttribute");
});
it("should edit the attribute", () => {
attribute.edit(schema, {});
sinon.assert.calledWithMatch(requests.updateAttribute, attributeId, schema);
});
it("should return success", () => {
return attribute.edit(schema, {}).should.eventually.become(response);
});
});
/** @test {Attribute#remove} */
describe("#remove()", () => {
const response = {status: "Ok"};
beforeEach(() => {
sandbox.stub(client, "execute").returns(Promise.resolve(response));
sandbox.spy(requests, "deleteAttribute");
});
it("should delete the attribute", () => {
attribute.remove({});
sinon.assert.calledWithMatch(requests.deleteAttribute, attributeId);
});
it("should return success", () => {
return attribute.remove({}).should.eventually.become(response);
});
});
});
|
'use strict';
angular.module('playgroundApp', [
'playgroundApp.filters',
'playgroundApp.services',
'playgroundApp.directives',
'ngRoute',
'ui.bootstrap',
'ui',
])
.config(function($locationProvider, $routeProvider, $httpProvider,
$dialogProvider) {
$locationProvider.html5Mode(true);
// TODO: add list of promises to be resolved for injection
// TODO: resolved promises are injected into controller
// TODO: see http://www.youtube.com/watch?v=P6KITGRQujQ
$routeProvider
.when('/playground/', {
templateUrl: '/playground/main.html',
controller: MainController,
})
.when('/playground/p/:project_id/', {
templateUrl: '/playground/project.html',
controller: ProjectController,
reloadOnSearch: false,
});
$httpProvider.interceptors.push('pgHttpInterceptor');
// TODO: test these defaults?
$dialogProvider.options({
backdropFade: true,
modalFade: true,
});
})
.value('ui.config', {
codemirror: {
lineNumbers: true,
matchBrackets: true,
autofocus: true,
undoDepth: 440, // default = 40
}
});
|
define([
'jquery',
'underscore',
'backbone',
'app'
],
function (
$, _, Backbone, app
) {
var Models = {},
Collections = {},
Views = {};
Models.Project = Backbone.Model.extend();
Collections.Projects = Backbone.Model.extend({
model: Models.Project,
url: function() {
return app.api('projects/' + this.get('platform') +
(this.get('uri') ? '/' + this.get('uri') : ''));
},
parse: function(res) {
return { projects: res };
}
});
Models.Project = Backbone.Model.extend({
url: function() {
return app.api('projects?' + this.get('params'));
}
});
return {
Models: Models,
Collections: Collections,
Views: Views
};
});
|
import App from '../containers/App';
import { PageNotFound } from '../components';
import homeRoute from '../features/home/route';
import taggrRoute from '../features/taggr/route';
const routes = [{
path: '/',
component: App,
childRoutes: [
homeRoute,
taggrRoute,
{ path: '*', name: 'Page not found', component: PageNotFound },
],
}];
// Handle isIndex property of route config:
// 1. remove the first child with isIndex=true from childRoutes
// 2. assign it to the indexRoute property of the parent.
function handleIndexRoute(route) {
if (!route.childRoutes || !route.childRoutes.length) {
return;
}
route.childRoutes = route.childRoutes.filter(child => { // eslint-disable-line
if (child.isIndex) {
/* istanbul ignore next */
if (process.env.NODE_ENV === 'dev' && route.indexRoute) {
console.error('More than one index route: ', route);
}
/* istanbul ignore else */
if (!route.indexRoute) {
delete child.path; // eslint-disable-line
route.indexRoute = child; // eslint-disable-line
return false;
}
}
return true;
});
route.childRoutes.forEach(handleIndexRoute);
}
routes.forEach(handleIndexRoute);
export default routes;
|
'use strict';
const Task = require('co-task');
const sql = require('../api/helpers/sql');
module.exports = {
up: function (queryInterface, Sequelize) {
return Task.spawn(function* () {
yield queryInterface.addColumn('ClassicSalads', 'ClassicSaladCatagoryId', Sequelize.INTEGER);
yield sql.foreignKeyUp(queryInterface, 'ClassicSalads', 'ClassicSaladCatagoryId', 'ClassicSaladCatagories', 'id');
});
},
down: function (queryInterface, Sequelize) {
return Task.spawn(function* () {
yield sql.foreignKeyDown(queryInterface, 'ClassicSalads', 'ClassicSaladCatagoryId', 'ClassicSaladCatagories', 'id');
yield queryInterface.removeColumn('ClassicSalads', 'ClassicSaladCatagoryId');
});
}
};
|
/*global describe, beforeEach, it*/
'use strict';
var assert = require('yeoman-generator').assert;
var helper = require('./helper');
describe('mcap:connections', function () {
beforeEach(function (done) {
var answers = {
name: 'MyApp'
};
// Creates a generateor with the default options / arguments
helper.createAppGenerator({
answers: answers
}, done);
});
it('creates expected files', function (done) {
var expectedFiles = [
'connections/sap.json'
];
var expectedContent = {
name: 'SAP',
description: 'SAP API',
type: 'rest',
properties: {
descriptorUrl: 'http://sap.mway.io',
username: 'admin',
password: 'root'
}
};
var answers = {
name: 'SAP',
description: 'SAP API',
descriptorUrl: 'http://sap.mway.io',
username: 'admin',
password: 'root'
};
helper.createSubGenerator('connection', {answers: answers}, function () {
assert.file(expectedFiles);
helper.deepEqual('connections/sap.json', expectedContent);
done();
});
});
});
|
const browserSync = require('../../../');
const utils = require('../utils');
const register = require('../../../dist/plugins/clients').ClientEvents.register;
const assert = require('chai').assert;
describe('Client connection stream', function () {
it('does not have duplicates', function (done) {
browserSync.create({}).subscribe(function (bs) {
const client = utils.getClientSocket(bs);
client.emit(register, utils.getClient('123456'));
client.emit(register, utils.getClient('123456'));
bs.clients$.skip(1)
.take(2)
.toArray()
.subscribe(function (clients) {
assert.equal(clients[0].size, 1);
assert.equal(clients[1].size, 1);
const jsClients1 = clients[0].toList().toJS();
const jsClients2 = clients[1].toList().toJS();
assert.equal(jsClients1[0].id, '123456');
assert.equal(jsClients2[0].id, '123456');
bs.cleanup();
done();
}, function (err) {done(err)});
});
});
it('allows unique clients', function (done) {
browserSync.create({}).subscribe(function (bs) {
const client = utils.getClientSocket(bs);
client.emit(register, utils.getClient('xyz'));
client.emit(register, utils.getClient('zxy'));
bs.clients$.skip(1)
.take(2)
.toArray()
.subscribe(function (clients) {
assert.equal(clients[0].size, 1);
assert.equal(clients[1].size, 2);
const jsClients1 = clients[0].toList().toJS();
const jsClients2 = clients[1].toList().toJS();
assert.equal(jsClients1[0].id, 'xyz');
assert.equal(jsClients2[0].id, 'xyz');
assert.equal(jsClients2[1].id, 'zxy');
bs.cleanup();
done();
}, function(err) { done(err) });
});
});
it('allows unique clients (stress)', function (done) {
browserSync.create({}).subscribe(function (bs) {
for (var i = 1, n = 51; i < n; i += 1) {
utils.getClientSocket(bs).emit(register, utils.getClient('id-' + i));
}
bs.clients$.skip(1)
.take(50)
.toArray()
.subscribe(function (clients) {
assert.equal(clients[49].size, 50);
assert.ok(clients[49].get('id-40'));
assert.equal(clients[49].get('id-40').get('id'), 'id-40');
bs.cleanup();
done();
}, function(err) { done(err) });
});
});
});
|
'use strict';
// https://github.com/tc39/proposal-iterator-helpers
var aCallable = require('../internals/a-callable');
var anObject = require('../internals/an-object');
var getBuiltIn = require('../internals/get-built-in');
var getMethod = require('../internals/get-method');
var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF;
var createMethod = function (TYPE) {
var IS_TO_ARRAY = TYPE == 0;
var IS_FOR_EACH = TYPE == 1;
var IS_EVERY = TYPE == 2;
var IS_SOME = TYPE == 3;
return function (iterator, fn, target) {
anObject(iterator);
var Promise = getBuiltIn('Promise');
var next = aCallable(iterator.next);
var index = 0;
var MAPPING = fn !== undefined;
if (MAPPING || !IS_TO_ARRAY) aCallable(fn);
return new Promise(function (resolve, reject) {
var closeIteration = function (method, argument) {
try {
var returnMethod = getMethod(iterator, 'return');
if (returnMethod) {
return Promise.resolve(returnMethod.call(iterator)).then(function () {
method(argument);
}, function (error) {
reject(error);
});
}
} catch (error2) {
return reject(error2);
} method(argument);
};
var onError = function (error) {
closeIteration(reject, error);
};
var loop = function () {
try {
if (IS_TO_ARRAY && (index > MAX_SAFE_INTEGER) && MAPPING) {
throw TypeError('The allowed number of iterations has been exceeded');
}
Promise.resolve(anObject(next.call(iterator))).then(function (step) {
try {
if (anObject(step).done) {
if (IS_TO_ARRAY) {
target.length = index;
resolve(target);
} else resolve(IS_SOME ? false : IS_EVERY || undefined);
} else {
var value = step.value;
if (MAPPING) {
Promise.resolve(IS_TO_ARRAY ? fn(value, index) : fn(value)).then(function (result) {
if (IS_FOR_EACH) {
loop();
} else if (IS_EVERY) {
result ? loop() : closeIteration(resolve, false);
} else if (IS_TO_ARRAY) {
target[index++] = result;
loop();
} else {
result ? closeIteration(resolve, IS_SOME || value) : loop();
}
}, onError);
} else {
target[index++] = value;
loop();
}
}
} catch (error) { onError(error); }
}, onError);
} catch (error2) { onError(error2); }
};
loop();
});
};
};
module.exports = {
toArray: createMethod(0),
forEach: createMethod(1),
every: createMethod(2),
some: createMethod(3),
find: createMethod(4)
};
|
export const removeWeight = (element) => {
try {
element.removeAttribute('data-weight');
} catch (e) {
// We are now in IE11 territory
if (!!element) {
element.setAttribute('data-weight', null);
}
}
};
|
'use strict';
module.exports = function (grunt) {
grunt.config(
'a11y', {
live: {
options: {
urls: ['www.google.com']
}
}
});
};
|
var config = require('./lib/config');
var FaceRec = require('./lib/facerec').FaceRec;
var hfr = new FaceRec(config);
// constant
var threshold = 20;
var prevX;
var prevY;
setInterval(function() {
var result = hfr.detect();
console.log('result:' + JSON.stringify(result));
if (result && result.pos_x && result.pos_y) {
var newX = result.pos_x;
var newY = result.pos_y;
var deltaX = newX - prevX;
var deltaY = newY - prevY;
if (Math.abs(deltaX) > threshold) {
var direction = deltaX > 0 ? "right" : "left";
console.log("moving head to " + direction + " , distance" + Math.abs(deltaX));
}
if (Math.abs(deltaY) > threshold) {
var direction = deltaY > 0 ? "down" : "up";
console.log("moving head to " + direction + " , distance" + Math.abs(deltaY));
}
console.log('updating x and y');
prevX = newX;
prevY = newY;
}
}, 5000);
|
var structCO__config__t =
[
[ "CNT_NMT", "structCO__config__t.html#aeef814580eb5ece5156e63bfc1b490c9", null ],
[ "ENTRY_H1017", "structCO__config__t.html#ad17f77b55de3d90ec983fcac49eeab6d", null ],
[ "CNT_HB_CONS", "structCO__config__t.html#a0031fc8f80e95f8480c918dbf8289671", null ],
[ "ENTRY_H1016", "structCO__config__t.html#a0af4cf7d0355861e7f60206d794d6a91", null ],
[ "CNT_EM", "structCO__config__t.html#a515e08f68835f71a6f145be8f27b510a", null ],
[ "ENTRY_H1001", "structCO__config__t.html#a6a6c19e816fb76882e85b2c07c0d8f42", null ],
[ "ENTRY_H1014", "structCO__config__t.html#a4827d94f6152cc12d86bd21312ae86e4", null ],
[ "ENTRY_H1015", "structCO__config__t.html#a141f21b4d1730206d1af823fd6b13a01", null ],
[ "ENTRY_H1003", "structCO__config__t.html#a7e320b309714b7f623c2006d45fee929", null ],
[ "CNT_SDO_SRV", "structCO__config__t.html#aac83faf556924515cc2aa8003753ab58", null ],
[ "ENTRY_H1200", "structCO__config__t.html#a05ab8adad4517850e31e5542895f7cc5", null ],
[ "CNT_SDO_CLI", "structCO__config__t.html#a2fc9606643a7fb4d4237f01812d3a6d2", null ],
[ "ENTRY_H1280", "structCO__config__t.html#a9f871c4ec753e8414cdb47eb78c3e09d", null ],
[ "CNT_TIME", "structCO__config__t.html#ada2a43384a544fa2f235de24a874b1e6", null ],
[ "ENTRY_H1012", "structCO__config__t.html#abac6be7122af1a8a4f9ae3ff5912d490", null ],
[ "CNT_SYNC", "structCO__config__t.html#af6dbc7d9f31b4cb050e23af8cff3df33", null ],
[ "ENTRY_H1005", "structCO__config__t.html#a02a4992f47db72816753ff2aa1964318", null ],
[ "ENTRY_H1006", "structCO__config__t.html#aa9befdebbaaa22f309b9a1b115612071", null ],
[ "ENTRY_H1007", "structCO__config__t.html#ad51ab63ca8b5836bf0dd8543f02db544", null ],
[ "ENTRY_H1019", "structCO__config__t.html#a468c82f6a0afd757a6b78ce33532c0d2", null ],
[ "CNT_RPDO", "structCO__config__t.html#a7a75302ac077462b67d767b0a11c9f56", null ],
[ "ENTRY_H1400", "structCO__config__t.html#a5e0984d93183493d587523888465eaa7", null ],
[ "ENTRY_H1600", "structCO__config__t.html#ab2ddc9943fd8c89f3b852d7ac9508d21", null ],
[ "CNT_TPDO", "structCO__config__t.html#a1d830617f50e3235de35a403a1513693", null ],
[ "ENTRY_H1800", "structCO__config__t.html#a29b98c08edfe0fba2e46c7af7a9edf6f", null ],
[ "ENTRY_H1A00", "structCO__config__t.html#a43fd6a448c91910c603f2c7756610432", null ],
[ "CNT_LEDS", "structCO__config__t.html#a642809cc681792bca855906241d891cc", null ],
[ "CNT_GFC", "structCO__config__t.html#ae282bab830810b61c0b0c3223654d674", null ],
[ "ENTRY_H1300", "structCO__config__t.html#a91c9f3ddb67231854af39224a9597e20", null ],
[ "CNT_SRDO", "structCO__config__t.html#ae58a44be57069709af3f6acbd10953e1", null ],
[ "ENTRY_H1301", "structCO__config__t.html#a87076cb1f9282d9720c21d395ff4e541", null ],
[ "ENTRY_H1381", "structCO__config__t.html#a7b3172b29ce8751adcab9e4351dcc31e", null ],
[ "ENTRY_H13FE", "structCO__config__t.html#a03fcaca5a8e0e71b86086908cae75f3d", null ],
[ "ENTRY_H13FF", "structCO__config__t.html#aa4cb9674209b83e7f0e48b01feaa04ef", null ],
[ "CNT_LSS_SLV", "structCO__config__t.html#a00a7a598b946ed13e3af7696e9f92dcc", null ],
[ "CNT_LSS_MST", "structCO__config__t.html#ac253cae7039090a6c04bc1e385f3ec21", null ],
[ "CNT_GTWA", "structCO__config__t.html#a64725014ecce342843f14ffc4b57e2a2", null ],
[ "CNT_TRACE", "structCO__config__t.html#aaafb8ffff236b51cd6d4ab16426d460f", null ]
];
|
'use strict';
var path = require('path');
var util = require('util');
module.exports = function(grunt) {
grunt.registerMultiTask('vjslanguages', 'A Grunt plugin for compiling VideoJS language assets.', function() {
var createLanguageFile = function(languageName, languageData, jsFilePath) {
var jsTemplate = 'videojs.addLanguage("' + languageName + '",' + JSON.stringify(languageData,null,' ') + ');';
grunt.file.write(jsFilePath, jsTemplate);
grunt.log.writeln('- [' + languageName +'] Language Built. File "' + jsFilePath + '" created.');
};
this.files.forEach(function(f) {
var languageName, languageData, jsFilePath;
// Multiple Files Case
if(util.isArray(f.src)){
for(var i =0; i < f.src.length; i++) {
languageName = path.basename(f.src[i], '.json');
languageData = grunt.file.readJSON(f.src[i]);
jsFilePath = path.join(f.dest, languageName + '.js');
createLanguageFile(languageName, languageData, jsFilePath);
}
}
// Singular File Case
else {
languageName = path.basename(f.src, '.json');
languageData = grunt.file.readJSON(f.src);
jsFilePath = path.join(f.dest, languageName + '.js');
createLanguageFile(languageName, languageData, jsFilePath);
}
});
});
};
|
$(document).ready(function(){
$("#inc_tab #tb1").removeClass();
$("#inc_tab #tb4").addClass("active");
$("#user_name").blur(function(){
var user_name = $.trim($(this).val());
$(this).val(user_name);
if (user_name.length==0){
$(this).parent().find("#user_name_null_warn").show();
$(this).parent().find("#user_name_exist_warn").hide();
return;
}
$(this).parent().find("#user_name_null_warn").hide();
var user_id = $(this).parent().find("#user_id").val();
var obj = $(this).parent().find("#user_name_exist_warn");
$.post(app.global.variable.base_path +"user/name/verify", {user_id:user_id, user_name:user_name}, function(data) {
if(data.toString().length > 0){
obj.show();
}else{
obj.hide();
}
})
})
$('#user_save_cancel').click(function(){
window.location.href=app.global.variable.base_path +'user/list';
})
selectRoleChange();
})
function selectRoleChange(){
var obj = $("#select_role_id");
var role_id_obj = obj.parent().find("#role_id");
$("#role_authority_"+role_id_obj.val()).hide();
$("#role_authority_"+obj.val()).show();
role_id_obj.val(obj.val());
}
function user_sava_check(){
var obj = $("#user_editor_form");
var valid = true;
obj.find(".functionWarn").each(function(){
if($(this).is(":visible")){
valid = false;
}
})
// 用户名
var user_name = obj.find("#user_name").val();
if(isSpace(user_name)){
obj.find("#user_name_null_warn").show();
valid = false;
}else{
obj.find("#user_name_null_warn").hide();
}
return valid;
}
|
define(
['app/models/proto_model'],
function(ProtoModel) {
var Model = ProtoModel.extend({
// matches first part of method name in @remote.method
urlRoot: '/cru_api.order_',
must_be_floats: ['sub_total', 'actual_total'],
});
return Model;
}
);
|
/*
* ! ${copyright}
*/
sap.ui.define([
"delegates/odata/v4/TableDelegate",
"sap/ui/core/Core"
], function(
TableDelegate,
Core
) {
"use strict";
/**
* Test delegate for OData V4.
*/
var ODataTableDelegate = Object.assign({}, TableDelegate);
/**
* Updates the binding info with the relevant path and model from the metadata.
*
* @param {Object} oTable The MDC table instance
* @param {Object} oBindingInfo The bindingInfo of the table
*/
ODataTableDelegate.updateBindingInfo = function(oTable, oBindingInfo) {
TableDelegate.updateBindingInfo.apply(this, arguments);
var oFilterBar = Core.byId(oTable.getFilter());
if (oFilterBar) {
// get the basic search
var sSearchText = oFilterBar.getSearch instanceof Function ? oFilterBar.getSearch() : "";
if (sSearchText && sSearchText.indexOf(" ") === -1) { // to allow search for "(".....
sSearchText = '"' + sSearchText + '"'; // TODO: escape " in string
} // if it contains spaces allow opeartors like OR...
oBindingInfo.parameters.$search = sSearchText || undefined;
}
};
return ODataTableDelegate;
});
|
var logger = require('../logging').getLogger(__LOGGER__);
var {PAGE_CSS_NODE_ID} = require('../constants');
var Q = require('q');
var PageUtil = require('./PageUtil')
var loadedCss = {};
module.exports = {
registerPageLoad: function registerPageLoad() {
if (SERVER_SIDE) {
throw new Error("ClientCssHelper.registerPageLoad can't be called server-side");
}
// for each css node in the head that the react-server server wrote to the response, note it down in the cache, so that
// we can remove it on a page to page transition.
var serverWrittenLinkNodes = document.head.querySelectorAll(`link[${PAGE_CSS_NODE_ID}],style[${PAGE_CSS_NODE_ID}]`);
for (var i = 0; i < serverWrittenLinkNodes.length; i++) {
var key, styleNode = serverWrittenLinkNodes[i];
if (styleNode.href) {
key = normalizeLocalUrl(styleNode.href);
} else {
key = styleNode.innerHTML;
}
loadedCss[key] = styleNode;
}
},
ensureCss: function ensureCss(routeName, pageObject) {
if (SERVER_SIDE) {
throw new Error("ClientCssHelper.registerPageLoad can't be called server-side");
}
return Q.all(PageUtil.standardizeStyles(pageObject.getHeadStylesheets())).then(newCss => {
var newCssByKey = {};
newCss
.filter(style => !!style)
.forEach(style => {newCssByKey[this._keyFromStyleSheet(style)] = style});
// first, remove the unneeded CSS link elements.
Object.keys(loadedCss).forEach(loadedCssKey => {
if (!newCssByKey[loadedCssKey]) {
// remove the corresponding node from the DOM.
logger.debug("Removing stylesheet: " + loadedCssKey);
var node = loadedCss[loadedCssKey];
node.parentNode.removeChild(node);
delete loadedCss[loadedCssKey];
}
});
// next add the style URLs that weren't already loaded.
return Q.all(Object.keys(newCssByKey).map(newCssKey => {
var retval;
if (!loadedCss[newCssKey]) {
// this means that the CSS is not currently present in the
// document, so we need to add it.
logger.debug("Adding stylesheet: " + newCssKey);
var style = newCssByKey[newCssKey];
var styleTag;
if (style.href) {
styleTag = document.createElement('link');
styleTag.rel = 'stylesheet';
styleTag.href = style.href;
// If we _can_ wait for the CSS to be loaded before
// proceeding, let's do so.
if ('onload' in styleTag) {
var dfd = Q.defer();
styleTag.onload = dfd.resolve;
retval = dfd.promise;
}
} else {
styleTag = document.createElement('style');
styleTag.innerHTML = style.text;
}
styleTag.type = style.type;
styleTag.media = style.media;
loadedCss[newCssKey] = styleTag;
document.head.appendChild(styleTag);
} else {
logger.debug(`Stylesheet already loaded (no-op): ${newCssKey}`);
}
return retval;
}));
});
},
_keyFromStyleSheet: function(style) {
return normalizeLocalUrl(style.href) || style.text;
},
}
function normalizeLocalUrl(url) {
// Step 1: make the url protocol less first. This helps recognizing http://0.0.0.0:3001/common.css
// and //0.0.0.0:3001/common.css as the same file.
// Step 2: The browser will give us a full URL even if we only put a
// path in on the server. So, if we're comparing against just
// a path here we need to strip the base off to avoid a flash
// of unstyled content.
if (typeof url === 'string') {
url = url
.replace(/^http[s]?:/, '')
.replace(new RegExp("^//" + location.host), '');
}
return url;
}
|
var activeElements = [];
var sleepElements = [];
var promises = [];
$.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/assetdatabases/D0EgxEhIf8KUieOFdFcX1IWQZ8qIGYDdE0m5aJCwNb4x_gSlVQSVRFUjAwMVxQSUZJVE5FU1M/elements", {
type : 'GET',
headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
success: function(results){
for (var i = 0; i < results.Items.length; i++) {
var item = results.Items[i];
getSubElements(item);
}
}
}).done(function(){
$.when.apply($,promises).done(function(){
spinner.stop(target);
var blackout = document.getElementById('blackout');
$('#blackout').css('opacity', '0');
$('#blackout').css('width', '0%');
$('#blackout').css('height', '0%');
});
});
var getSubElements = function(personElement){
promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + personElement.WebId + "/elements", {
type : 'GET',
headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
success: function(results){
for (var i = 0; i < results.Items.length; i++) {
var innerItem = results.Items[i];
if (innerItem.TemplateName == "Fitbit Activity Template") {
getFitbitActivityAttributes({
Person : personElement.Name,
Child : "Fitbit Activity",
ChildWebId : innerItem.WebId
});
} else if (innerItem.TemplateName == "Fitbit Sleep Template") {
getFitbitSleepAttributes({
Person : personElement.Name,
Child : "Fitbit Sleep",
ChildWebId : innerItem.WebId
});
}
}}}));
}
var getFitbitActivityAttributes = function(object) {
promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + object.ChildWebId + "/attributes",{
type : 'GET',
headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
success: function(results){
object.Attributes = [];
activeElements.push(object);
for (var i = 0; i < results.Items.length; i++) {
var attribute = results.Items[i];
object.Attributes.push({
Attribute : attribute.Name,
AttributeWebId : attribute.WebId
});
};
}
}));
}
var getFitbitSleepAttributes = function(object) {
promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + object.ChildWebId + "/attributes",{
type : 'GET',
headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")},
success: function(results){
object.Attributes = [];
sleepElements.push(object);
for (var i = 0; i < results.Items.length; i++) {
var attribute = results.Items[i];
object.Attributes.push({
Attribute : attribute.Name,
AttributeWebId : attribute.WebId
});
};
}
}));
}
|
(function(jQuery) {
"use strict";
var control = Echo.Control.manifest("Echo.Tests.Controls.TestControl");
if (Echo.Control.isDefined(control)) return;
control.init = function() {
if (!Echo.Variables) {
Echo.Variables = {};
}
Echo.Variables.TestControl = "production";
this.ready();
};
control.config = {};
control.templates.main = "";
Echo.Control.create(control);
})(Echo.jQuery);
|
exports.view = function() {
this.render();
};
exports.async = function() {
this.render();
};
|
module.exports = {
readFiles: readFiles
};
var filewalker = require('filewalker');
var _ = require('kling/kling.js');
var fs = require('fs');
function readFiles(directory, fileSuffix) {
return new Promise(function(resolve, reject) {
var files = [];
filewalker(directory)
.on('file', function(file) {
if (file.endsWith(fileSuffix)) {
files.push(file);
}
})
.on('done', function() {
var addLazyReaderCurried = _.curry(addLazyReader);
resolve(_.fmap(addLazyReaderCurried(directory), files));
})
.walk();
});
}
function addLazyReader(directory, file) {
return {
name: directory+file,
getContents: function() {
return fs.readFileSync(directory+file, 'utf8');
}
};
}
|
/**
* 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 invariant = require('invariant');
/**
* @typedef {object} request
* @property {string} method
* @property {string} route - string like /abc/:abc
* @property {string} params
* @property {object} [body]
* @property {object} headers
*/
/**
* @typedef {object} reponse
* @property {Error} error - an error which occured during req or res
* @property {object} body - content received from server (parsed)
* @property {object} headers - set additional request headers
* @property {number} status - http status code; 0 on failure
*/
/**
* XHR wrapper for same-domain requests with Content-Type: application/json
*
* @param {request} request
* @return {Promise}
*/
export default function implore(request) {
return new Promise(resolve => {
const response = {
error: null
};
invariant(
request,
'implore requires a `request` argument'
);
invariant(
typeof request.route === 'string',
'implore requires parameter `route` to be a string'
);
invariant(
typeof request.method === 'string',
'implore requires parameter `method` to be a string'
);
const xhr = new XMLHttpRequest();
xhr.open(request.method, getURLFromRequest(request));
switch (request.method) {
case 'POST':
case 'PUT':
case 'PATCH':
xhr.setRequestHeader('Content-Type', 'application/json');
break;
}
if (request.headers) {
invariant(
typeof request.headers === 'object',
'implore requires parameter `headers` to be an object'
);
Object.keys(request.headers).forEach((header) => {
xhr.setRequestHeader(header, request.headers[header]);
});
}
xhr.onreadystatechange = function onreadystatechange() {
let responseText;
if (xhr.readyState === 4) {
responseText = xhr.responseText;
response.status = xhr.status;
response.type = xhr.getResponseHeader('Content-Type');
if (response.type === 'application/json') {
try {
response.body = JSON.parse(responseText);
}
catch (err) {
err.message = err.message + ' while parsing `' +
responseText + '`';
response.body = {};
response.status = xhr.status || 0;
response.error = err;
}
}
else {
response.body = responseText;
}
return resolve({
request,
response
});
}
};
try {
if (request.body) {
xhr.send(JSON.stringify(request.body));
}
else {
xhr.send();
}
}
catch (err) {
response.body = {};
response.status = 0;
response.error = err;
return resolve({
request,
response
});
}
});
}
implore.get = function get(options) {
options.method = 'GET';
return implore(options);
};
implore.post = function post(options) {
options.method = 'POST';
return implore(options);
};
implore.put = function put(options) {
options.method = 'PUT';
return implore(options);
};
implore.delete = function httpDelete(options) {
options.method = 'DELETE';
return implore(options);
};
/**
* Combine the route/params/query of a request into a complete URL
*
* @param {request} request
* @param {object|array} request.query
* @return {string} url
*/
function getURLFromRequest(request) {
const queryString = makeQueryString(request.query || {});
let formatted = request.route;
let name;
let value;
let regexp;
for (name in request.params) {
if (request.params.hasOwnProperty(name)) {
value = request.params[name];
regexp = new RegExp(':' + name + '(?=(\\\/|$))');
formatted = formatted.replace(regexp, value);
}
}
return formatted + (queryString ? '?' + queryString : '');
}
/**
* Take a simple object and turn it into a queryString, recursively.
*
* @param {object} obj - query object
* @param {string} prefix - used in recursive calls to keep track of the parent
* @return {string} queryString without the '?''
*/
function makeQueryString(obj, prefix='') {
const str = [];
let prop;
let key;
let value;
for (prop in obj) {
if (obj.hasOwnProperty(prop)) {
key = prefix ?
prefix + '[' + prop + ']' :
prop;
value = obj[prop];
str.push(typeof value === 'object' ?
makeQueryString(value, key) :
encodeURIComponent(key) + '=' + encodeURIComponent(value));
}
}
return str.join('&');
}
|
/*
* Copyright 2016 Amadeus s.a.s.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"use strict";
const co = require("co");
const path = require("path");
const assertFilesEqual = require("../helpers/assertFilesEqual");
const exec = require("../helpers/exec");
module.exports = function (results) {
const outDir = results.outDir;
const atDiffExecutable = require.resolve("../../bin/at-diff");
const filesToCompare = [
// The .json extension is automatically added
"version1.parse",
"version2.parse",
"user.parse",
"at.parse",
"version1to2.diff",
"filteredVersion1to2.diff",
"impactsOnUser.diff",
"filteredImpactsOnUser.diff"
];
filesToCompare.forEach((fileName) => {
const nonDeterministicFileName = `${fileName}.json`;
it(nonDeterministicFileName, co.wrap(function *() {
this.timeout(10000);
const transformCommand = /\.parse$/.test(fileName) ? "reformat" : "reserialize";
const deterministicFileName = `${fileName}.deterministic.json`;
yield exec(atDiffExecutable, [transformCommand, nonDeterministicFileName, "--json-output", deterministicFileName, "--deterministic-output", "--json-beautify"], {
cwd: outDir
});
yield assertFilesEqual(path.join(outDir, deterministicFileName), path.join(__dirname, "..", "expected-output", deterministicFileName));
}));
});
};
|
/*
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.
Initial implementation:
* http://www.mudynamics.com
* http://labs.mudynamics.com
* http://www.pcapr.net
*/
(function($) {
var now = new Date().getTime();
var millisInHHour = 1000*60*30;
$.jscouch = $.jscouch || {};
$.jscouch.documents = $.jscouch.documents || {};
$.extend($.jscouch.documents, {
load: function() {
// popluate the DB with initial entries
$.jscouch.couchdb.put({
name: 'fish.jpg',
created_at: new Date(now + millisInHHour*Math.random()).toUTCString(),
user: 'bob',
type: 'jpeg',
camera: 'nikon',
info: {
width: 100,
height: 200,
size: 12345
},
tags: [ 'tuna', 'shark' ]
});
$.jscouch.couchdb.put({
name: 'trees.jpg',
created_at: new Date(now + millisInHHour*Math.random()).toUTCString(),
user: 'john',
type: 'jpeg',
camera: 'canon',
info: {
width: 30,
height: 250,
size: 32091
},
tags: [ 'oak' ]
});
$.jscouch.couchdb.put({
name: 'snow.png',
created_at: new Date(now + millisInHHour*Math.random()).toUTCString(),
user: 'john',
type: 'png',
camera: 'canon',
info: {
width: 64,
height: 64,
size: 1253
},
tags: [ 'tahoe', 'powder' ]
});
$.jscouch.couchdb.put({
name: 'hawaii.png',
created_at: new Date(now + millisInHHour*Math.random()).toUTCString(),
user: 'john',
type: 'png',
camera: 'nikon',
info: {
width: 128,
height: 64,
size: 92834
},
tags: [ 'maui', 'tuna' ]
});
$.jscouch.couchdb.put({
name: 'hawaii.gif',
created_at: new Date(now + millisInHHour*Math.random()).toUTCString(),
user: 'bob',
type: 'gif',
camera: 'canon',
info: {
width: 320,
height: 128,
size: 49287
},
tags: [ 'maui' ]
});
$.jscouch.couchdb.put({
name: 'island.gif',
created_at: new Date(now + millisInHHour*Math.random()).toUTCString(),
user: 'zztop',
type: 'gif',
camera: 'nikon',
info: {
width: 640,
height: 480,
size: 50398
},
tags: [ 'maui' ]
});
}
});
})(jQuery);
|
define(function (require) {
var SymbolDraw = require('../helper/SymbolDraw');
var LargeSymbolDraw = require('../helper/LargeSymbolDraw');
require('../../echarts').extendChartView({
type: 'scatter',
init: function () {
this._normalSymbolDraw = new SymbolDraw();
this._largeSymbolDraw = new LargeSymbolDraw();
},
render: function (seriesModel, ecModel, api) {
var data = seriesModel.getData();
var largeSymbolDraw = this._largeSymbolDraw;
var normalSymbolDraw = this._normalSymbolDraw;
var group = this.group;
var symbolDraw = seriesModel.get('large') && data.count() > seriesModel.get('largeThreshold')
? largeSymbolDraw : normalSymbolDraw;
this._symbolDraw = symbolDraw;
symbolDraw.updateData(data);
group.add(symbolDraw.group);
group.remove(
symbolDraw === largeSymbolDraw
? normalSymbolDraw.group : largeSymbolDraw.group
);
},
updateLayout: function (seriesModel) {
this._symbolDraw.updateLayout(seriesModel);
},
remove: function (ecModel, api) {
this._symbolDraw && this._symbolDraw.remove(api, true);
}
});
});
|
/**
* @author fanguozhu
*/
$(function()
{
var tab = new TabPanel("tab",true);
var f_tree = new Fieldset("f_tree","公司列表",{
state: Fieldset.OPEN_STATE,
topdown: false
});
var mytree = new PorTreeT("tree", "-1", "手机公司",{isDefaultClick:0} );
var dw = new DataWrapper();
dw.service("PRtree");
mytree.dataWrapper(dw);
tab.dataWrapper(dw);
tab.addChangeObserver(function(src, msg){
var dw = this.dataWrapper();
if (!dw) return;
var label = msg.data.label;
var name = msg.data.name;
for (var i=1;i<=3;i++) {
if (label) {
this.setTitle(i,"["+name+"]公司产品["+i+"]");
} else {
this.setTitle(i,"全部公司产品["+i+"]");
}
}
},PorMessage.MSG_TREE_ONCLICK);
var dw1 = new DataWrapper();
dw1.service("PR02");
var dw2 = new DataWrapper();
dw2.service("PR02");
var dw3 = new DataWrapper();
dw3.service("PR02");
var dg1 = new DataGrid("grid_1",{autoDraw:true,readonly:true});
dg1.dataWrapper(dw1);
var dg2 = new DataGrid("grid_2",{autoDraw:true,readonly:true});
dg2.dataWrapper(dw2);
var dg3 = new DataGrid("grid_3",{autoDraw:true,readonly:true});
dg3.dataWrapper(dw3);
var mapping = {
master:["label"],
sub:["company"]
};
PorUtil.linkTreeAndGrid( dw,[{
sub:dw1,
mapping:mapping,
tabs:{
tab:[0,1] //配置在'tab'的第1个tab页需要加载
}
},{
sub:dw2,
mapping:mapping,
tabs:{
tab:[2] //配置在'tab'的第2个tab页需要加载
}
},{
sub:dw3,
mapping:mapping,
tabs:{
tab:[3] //配置在'tab'的第3个tab页需要加载
}
}]);
mytree.init();
});
|
module.exports = unbuild
unbuild.usage = "npm unbuild <folder>\n(this is plumbing)"
var readJson = require("read-package-json")
, rm = require("./utils/gently-rm.js")
, gentlyRm = require("./utils/gently-rm.js")
, npm = require("./npm.js")
, path = require("path")
, fs = require("graceful-fs")
, lifecycle = require("./utils/lifecycle.js")
, asyncMap = require("slide").asyncMap
, chain = require("slide").chain
, log = require("npmlog")
, build = require("./build.js")
// args is a list of folders.
// remove any bins/etc, and then DELETE the folder.
function unbuild (args, silent, cb) {
if (typeof silent === 'function') cb = silent, silent = false
asyncMap(args, unbuild_(silent), cb)
}
function unbuild_ (silent) { return function (folder, cb_) {
function cb (er) {
cb_(er, path.relative(npm.root, folder))
}
folder = path.resolve(folder)
delete build._didBuild[folder]
log.info(folder, "unbuild")
readJson(path.resolve(folder, "package.json"), function (er, pkg) {
// if no json, then just trash it, but no scripts or whatever.
if (er) return rm(folder, cb)
readJson.cache.del(folder)
chain
( [ [lifecycle, pkg, "preuninstall", folder, false, true]
, [lifecycle, pkg, "uninstall", folder, false, true]
, !silent && function(cb) {
console.log("unbuild " + pkg._id)
cb()
}
, [rmStuff, pkg, folder]
, [lifecycle, pkg, "postuninstall", folder, false, true]
, [rm, folder] ]
, cb )
})
}}
function rmStuff (pkg, folder, cb) {
// if it's global, and folder is in {prefix}/node_modules,
// then bins are in {prefix}/bin
// otherwise, then bins are in folder/../.bin
var parent = path.dirname(folder)
, gnm = npm.dir
, top = gnm === parent
readJson.cache.del(path.resolve(folder, "package.json"))
log.verbose([top, gnm, parent], "unbuild " + pkg._id)
asyncMap([rmBins, rmMans], function (fn, cb) {
fn(pkg, folder, parent, top, cb)
}, cb)
}
function rmBins (pkg, folder, parent, top, cb) {
if (!pkg.bin) return cb()
var binRoot = top ? npm.bin : path.resolve(parent, ".bin")
log.verbose([binRoot, pkg.bin], "binRoot")
asyncMap(Object.keys(pkg.bin), function (b, cb) {
if (process.platform === "win32") {
chain([ [rm, path.resolve(binRoot, b) + ".cmd"]
, [rm, path.resolve(binRoot, b) ] ], cb)
} else {
gentlyRm( path.resolve(binRoot, b)
, !npm.config.get("force") && folder
, cb )
}
}, cb)
}
function rmMans (pkg, folder, parent, top, cb) {
if (!pkg.man
|| !top
|| process.platform === "win32"
|| !npm.config.get("global")) {
return cb()
}
var manRoot = path.resolve(npm.config.get("prefix"), "share", "man")
asyncMap(pkg.man, function (man, cb) {
if (Array.isArray(man)) {
man.forEach(rm)
} else {
rm(man)
}
function rm(man) {
var parseMan = man.match(/(.*)\.([0-9]+)(\.gz)?$/)
, stem = parseMan[1]
, sxn = parseMan[2]
, gz = parseMan[3] || ""
, bn = path.basename(stem)
, manDest = path.join( manRoot
, "man"+sxn
, (bn.indexOf(pkg.name) === 0 ? bn
: pkg.name + "-" + bn)
+ "." + sxn + gz
)
gentlyRm( manDest
, !npm.config.get("force") && folder
, cb )
}
}, cb)
}
|
var gplay = require('google-play-scraper');
var fs = require('fs')
var Promise = require('promise');
var myArgs = process.argv.slice(2);
var passed_appid = myArgs[0];
var passed_appcount = myArgs[1];
console.log(passed_appid);
var read = Promise.denodeify(fs.readFile);
var write = Promise.denodeify(fs.writeFile);
var dir = './dataset/' + passed_appcount;
gplay.app({appId: passed_appid})
.then(function (str) {
if(JSON.stringify(str, null, ' ').indexOf("title") > -1) {
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
return write(dir + '/meta.json', JSON.stringify(str, null, ' '), 'utf8')
} else {
console.log('app doesnt exist');
return false
}
})
.then(function (){process.exit()});
|
// Models
app.SearchModel = Backbone.Model.extend({
idAttribute: "session_token",
urlRoot: function() {
var u = '/search/' + this.id;
return u;
}
});
// Collections
app.SearchCollection = Backbone.Collection.extend({
model: app.SearchModel,
url: function() {
if (typeof this.id === 'undefined')
return '/search';
else
return '/search/' + this.id;
},
initialize: function(options) {
if (typeof options != 'undefined')
this.id = options.session_token;
}
});
// Views
app.cardList = Backbone.View.extend({
el: '#cardList'
});
app.cardView = Backbone.View.extend({
tagName: 'div',
initialize: function(card) {
this.card = card;
},
template: _.template($("#card-template").html()),
render: function(cardList) {
this.$el.html(this.template({
card: this.card
}));
this.$el.addClass('card');
cardList.$el.append(this.el);
return this;
}
});
|
function htmlEncode(value){
return $('<div/>').text(value).html();
}
var app = angular.module("oasassets",[]).controller("snippetsController",function($scope){
$scope.snippet = function(item){
var elem = $("#"+item);
var contents = elem.html().trim();
elem.html(htmlEncode(contents));
$('pre code').each(function(i, block) {
hljs.highlightBlock(block);
});
};
$scope.loadMenu = function(){
$('#side-menu').metisMenu();
};
});
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const options_1 = require("./options");
class TslintFixTask {
constructor(configOrPath, options) {
if (options) {
this._configOrPath = configOrPath;
this._options = options;
}
else {
this._options = configOrPath;
this._configOrPath = null;
}
}
toConfiguration() {
const path = typeof this._configOrPath == 'string' ? { tslintPath: this._configOrPath } : {};
const config = typeof this._configOrPath == 'object' && this._configOrPath !== null
? { tslintConfig: this._configOrPath }
: {};
const options = {
...this._options,
...path,
...config,
};
return { name: options_1.TslintFixName, options };
}
}
exports.TslintFixTask = TslintFixTask;
|
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var dbg = require('debug');
// process.env.TABTAB_DEBUG = process.env.TABTAB_DEBUG || '/tmp/tabtab.log';
var out = process.env.TABTAB_DEBUG ? fs.createWriteStream(process.env.TABTAB_DEBUG, { flags: 'a' }) : null;
module.exports = debug;
// Internal: Facade to debug module, which provides the exact same interface.
//
// The added benefit is with the TABTAB_DEBUG environment variable, which when
// defined, will write debug output to the specified filename.
//
// Usefull when debugging tab completion, as logs on stdout / stderr are either
// shallowed or used as tab completion results.
//
// namespace - The String namespace to use when TABTAB_DEBUG is not defined,
// delegates to debug module.
//
// Examples
//
// // Use with following command to redirect output to file
// // TABTAB_DEBUG="debug.log" tabtab ...
// debug('Foo');
function debug(namespace) {
var log = dbg(namespace);
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
args = args.map(function (arg) {
if (typeof arg === 'string') return arg;
return JSON.stringify(arg);
});
out && out.write(util.format.apply(util, args) + '\n');
out || log.apply(null, args);
};
}
|
// Copyright (c) 2015-2016 Yuya Ochiai
// Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import AutoLaunch from 'auto-launch';
import {app} from 'electron';
function shouldQuitApp(cmd) {
if (process.platform !== 'win32') {
return false;
}
const squirrelCommands = ['--squirrel-install', '--squirrel-updated', '--squirrel-uninstall', '--squirrel-obsolete'];
return squirrelCommands.includes(cmd);
}
async function setupAutoLaunch(cmd) {
const appLauncher = new AutoLaunch({
name: app.getName(),
isHidden: true,
});
if (cmd === '--squirrel-uninstall') {
// If we're uninstalling, make sure we also delete our auto launch registry key
await appLauncher.disable();
} else if (cmd === '--squirrel-install' || cmd === '--squirrel-updated') {
// If we're updating and already have an registry entry for auto launch, make sure to update the path
const enabled = await appLauncher.isEnabled();
if (enabled) {
await appLauncher.enable();
}
}
}
export default function squirrelStartup(callback) {
if (process.platform === 'win32') {
const cmd = process.argv[1];
setupAutoLaunch(cmd).then(() => {
if (require('electron-squirrel-startup') && callback) { // eslint-disable-line global-require
callback();
}
});
return shouldQuitApp(cmd);
}
return false;
}
|
[
{
"title": "Ventes véhicules",
"url": "",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": "1",
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published",
"children": [
{
"title": "http://portail.inetpsa.com/sites/gpmobile/PublishingImages/car2.jpg",
"url": "http://portail.inetpsa.com/sites/gpmobile/PublishingImages/car2.jpg",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 0,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published"
},
{
"title": "Ventes véhicules Peugeot",
"url": "https://docinfogroupe.psa-peugeot-citroen.com/ead/dom/1000788899.fd",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 1,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "edited"
},
{
"title": "Ventes véhicules DS",
"url": "https://docinfogroupe.psa-peugeot-citroen.com/ead/dom/1000779116.fd",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg",
"language": "fr-FR",
"order": 2,
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published"
}
]
},
{
"title": "Webmail",
"url": "https://webmail.mpsa.com/",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/webmail.jpg",
"language": "en-US",
"order": "0",
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "published",
"children": []
},
{
"title": "Net'RH congés",
"url": "https://fr-rh.mpsa.com/rib00/ribdnins.nsf/fc583fb6947d633ac12569450031fbd2/755dcfb785421c6cc1256c7f003107c2?OpenDocument",
"imageUrl": "http://lim.local.inetpsa.com/application/images/service/holiday.jpg",
"language": "fr-FR",
"order": "3",
"workplace": "All",
"department": "All",
"categoryPro": "All",
"status": "unpublished",
"children": []
}
]
|
sap.ui.define(["sap/ui/integration/Designtime"], function (
Designtime
) {
"use strict";
return function () {
return new Designtime({
"form": {
"items": {
"validationGroup": {
"type": "group",
"label": "Validation"
},
"OrderID": {
"manifestpath": "/sap.card/configuration/parameters/OrderID/value",
"label": "Order Id",
"type": "integer",
"required": true
},
"stringphone": {
"manifestpath": "/sap.card/configuration/parameters/string/value",
"label": "String with Pattern validation",
"type": "string",
"translatable": false,
"required": true,
"placeholder": "555-4555",
"validation": {
"type": "error",
"maxLength": 20,
"minLength": 1,
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$",
"message": "The string does not match a telefone number"
}
},
"stringphonenomessage": {
"manifestpath": "/sap.card/configuration/parameters/string/value",
"label": "String with default validation message",
"type": "string",
"translatable": false,
"required": true,
"placeholder": "555-4555",
"validation": {
"type": "warning",
"maxLength": 20,
"minLength": 1,
"pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$"
}
},
"stringmaxmin": {
"manifestpath": "/sap.card/configuration/parameters/string/value",
"label": "String with Length Constrained",
"type": "string",
"translatable": false,
"required": true,
"placeholder": "MinMaxlength",
"validation": {
"type": "warning",
"maxLength": 20,
"minLength": 3
},
"hint": "Please refer to the <a href='https://www.sap.com'>documentation</a> lets see how this will behave if the text is wrapping to the next line and has <a href='https://www.sap.com'>two links</a>. good?"
},
"integerrequired": {
"manifestpath": "/sap.card/configuration/parameters/integerrequired/value",
"label": "Integer with Required",
"type": "integer",
"translatable": false,
"required": true
},
"integervalidation": {
"manifestpath": "/sap.card/configuration/parameters/integer/value",
"label": "Integer with Min Max value",
"type": "integer",
"visualization": {
"type": "Slider",
"settings": {
"value": "{currentSettings>value}",
"min": 0,
"max": 16,
"width": "100%",
"showAdvancedTooltip": true,
"showHandleTooltip": false,
"inputsAsTooltips": true,
"enabled": "{currentSettings>editable}"
}
},
"validations": [
{
"type": "warning",
"minimum": 5,
"message": "The minimum is 5."
},
{
"type": "error",
"exclusiveMaximum": 16,
"message": "The maximum is 15."
},
{
"type": "error",
"multipleOf": 5,
"message": "Has to be multiple of 5"
}
]
},
"numberrequired": {
"manifestpath": "/sap.card/configuration/parameters/number/value",
"label": "Number with validation",
"type": "number",
"translatable": false,
"required": true,
"validation": {
"type": "error",
"minimum": 0,
"maximum": 100,
"exclusiveMaximum": true,
"message": "The value should be equal or greater than 0 and be less than 100."
}
}
}
},
"preview": {
"modes": "AbstractLive"
}
});
};
});
|
//// [/lib/initial-buildOutput.txt]
/lib/tsc --b /src/core --verbose
12:01:00 AM - Projects in this build:
* src/core/tsconfig.json
12:01:00 AM - Project 'src/core/tsconfig.json' is out of date because output file 'src/core/anotherModule.js' does not exist
12:01:00 AM - Building project '/src/core/tsconfig.json'...
exitCode:: ExitStatus.Success
//// [/src/core/anotherModule.js]
"use strict";
exports.__esModule = true;
exports.World = "hello";
//// [/src/core/index.js]
"use strict";
exports.__esModule = true;
exports.someString = "HELLO WORLD";
function leftPad(s, n) { return s + n; }
exports.leftPad = leftPad;
function multiply(a, b) { return a * b; }
exports.multiply = multiply;
//// [/src/core/tsconfig.json]
{
"compilerOptions": {
"incremental": true,
"module": "commonjs"
}
}
//// [/src/core/tsconfig.tsbuildinfo]
{
"program": {
"fileInfos": {
"../../lib/lib.d.ts": {
"version": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };",
"signature": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };"
},
"./anothermodule.ts": {
"version": "-2676574883-export const World = \"hello\";\r\n",
"signature": "-8396256275-export declare const World = \"hello\";\r\n"
},
"./index.ts": {
"version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n",
"signature": "1874987148-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n"
},
"./some_decl.d.ts": {
"version": "-9253692965-declare const dts: any;\r\n",
"signature": "-9253692965-declare const dts: any;\r\n"
}
},
"options": {
"incremental": true,
"module": 1,
"configFilePath": "./tsconfig.json"
},
"referencedMap": {},
"exportedModulesMap": {},
"semanticDiagnosticsPerFile": [
"../../lib/lib.d.ts",
"./anothermodule.ts",
"./index.ts",
"./some_decl.d.ts"
]
},
"version": "FakeTSVersion"
}
|
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
define(function(require){
return 'acls-tab';
});
|
'use strict';
module.exports = function(config) {
config.set({
files: [
'tests/main.js',
{pattern: 'app/js/**/*.js', included: false},
{pattern: 'app/bower_components/**/*.js', included: false},
{pattern: 'tests/specs/**/*.js', included: false},
{pattern: 'tests/fixtures/**/*.js', included: false}
],
basePath: '../',
frameworks: ['jasmine', 'requirejs'],
reporters: ['progress'],
runnerPort: 9000,
singleRun: true,
browsers: ['PhantomJS', 'Chrome'],
logLevel: 'ERROR'
});
};
|
// Copyright 2017 The Oppia 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.
/**
* @fileoverview Factory for creating new frontend instances of Interaction
* domain objects.
*/
oppia.factory('InteractionObjectFactory', [
'AnswerGroupObjectFactory', 'HintObjectFactory', 'OutcomeObjectFactory',
'SolutionObjectFactory',
function(
AnswerGroupObjectFactory, HintObjectFactory, OutcomeObjectFactory,
SolutionObjectFactory) {
var Interaction = function(
answerGroups, confirmedUnclassifiedAnswers, customizationArgs,
defaultOutcome, hints, id, solution) {
this.answerGroups = answerGroups;
this.confirmedUnclassifiedAnswers = confirmedUnclassifiedAnswers;
this.customizationArgs = customizationArgs;
this.defaultOutcome = defaultOutcome;
this.hints = hints;
this.id = id;
this.solution = solution;
};
Interaction.prototype.toBackendDict = function() {
return {
answer_groups: this.answerGroups.map(function(answerGroup) {
return answerGroup.toBackendDict();
}),
confirmed_unclassified_answers: this.confirmedUnclassifiedAnswers,
customization_args: this.customizationArgs,
default_outcome:
this.defaultOutcome ? this.defaultOutcome.toBackendDict() : null,
hints: this.hints.map(function(hint) {
return hint.toBackendDict();
}),
id: this.id,
solution: this.solution ? this.solution.toBackendDict() : null
};
};
Interaction.createFromBackendDict = function(interactionDict) {
var defaultOutcome;
if (interactionDict.default_outcome) {
defaultOutcome = OutcomeObjectFactory.createFromBackendDict(
interactionDict.default_outcome);
} else {
defaultOutcome = null;
}
return new Interaction(
generateAnswerGroupsFromBackend(interactionDict.answer_groups),
interactionDict.confirmed_unclassified_answers,
interactionDict.customization_args,
defaultOutcome,
generateHintsFromBackend(interactionDict.hints),
interactionDict.id,
interactionDict.solution ? (
generateSolutionFromBackend(interactionDict.solution)) : null);
};
var generateAnswerGroupsFromBackend = function(answerGroupBackendDicts) {
return answerGroupBackendDicts.map(function(
answerGroupBackendDict) {
return AnswerGroupObjectFactory.createFromBackendDict(
answerGroupBackendDict);
});
};
var generateHintsFromBackend = function(hintBackendDicts) {
return hintBackendDicts.map(function(hintBackendDict) {
return HintObjectFactory.createFromBackendDict(hintBackendDict);
});
};
var generateSolutionFromBackend = function(solutionBackendDict) {
return SolutionObjectFactory.createFromBackendDict(solutionBackendDict);
};
return Interaction;
}
]);
|
$.FAQ = function(){
$self = this;
this.url = "/faq"
this.send = function(inputs){
var params = new FormData();
// var csrf = $("#csrf").val();
// params.append("csrf_ID", csrf);
$.each(inputs, function(key, val){
params.append(key,val);
});
$.ajax({
url : $self.url,
type: 'POST',
async: true,
processData: false,
data: params,
success: function(response){
response = JSON.parse(response);
$self.fillQAs(response.qadata);
$self.createPagination(response.metadata)
},
});
};
this.fillQAs = function(data){
var qaBox = $("#faq-container .faq-item").clone();
$("#faq-container .faq-item").remove();
$.each(data, function(obj){
var $div = qaBox.clone();
$div.find(".faq-item-question h2").html(obj.question);
$div.find(".faq-item-answer p").html(obj.answer);
});
};
this.createPagination = function(metadata){
};
this.load = function(data){
var limit = (data.limit > 0) ? data.limit : 5;
var offset = (data.page_num - 1)*limit;
var inputs = {
action : 'loadFaq',
limit : limit,
offset : offset
};
$self.send(inputs);
};
this.init = function(){
var inputs = {
limit : 5,
page_num : 1
};
$self.load(inputs);
};
};
|
/* The all pages that do not require authentication */
function UnAuthenticatedHandler() {
"use strict";
this.displayAboutPage = function(req, res, next) {
return res.render("about");
};
this.displayContactPage = function(req, res, next) {
return res.render("contact");
};
this.displayHomePage = function(req, res, next) {
return res.render("home");
};
this.displayChatPage = function(req, res, next) {
return res.render("chat");
};
}
module.exports = UnAuthenticatedHandler;
|
function $childNode(o) {
return window.frames[o]
}
function animationHover(o, e) {
o = $(o), o.hover(function () {
o.addClass("animated " + e)
}, function () {
window.setTimeout(function () {
o.removeClass("animated " + e)
}, 2e3)
})
}
function WinMove() {
var o = "[class*=col]", e = ".ibox-title", i = "[class*=col]";
$(o).sortable({
handle: e,
connectWith: i,
tolerance: "pointer",
forcePlaceholderSize: !0,
opacity: .8
}).disableSelection()
}
var $parentNode = window.parent.document;
if ($(".tooltip-demo").tooltip({
selector: "[data-toggle=tooltip]",
container: "body"
}), $(".modal").appendTo("body"), $("[data-toggle=popover]").popover(), $(".collapse-link").click(function () {
var o = $(this).closest("div.ibox"), e = $(this).find("i"), i = o.find("div.ibox-content");
i.slideToggle(200), e.toggleClass("fa-chevron-up").toggleClass("fa-chevron-down"), o.toggleClass("").toggleClass("border-bottom"), setTimeout(function () {
o.resize(), o.find("[id^=map-]").resize()
}, 50)
}), $(".close-link").click(function () {
var o = $(this).closest("div.ibox");
o.remove()
}), top == this) {
}
|
/*!
* Module requirements
*/
var NeopreneError = require('../error')
/**
* Document Validation Error
*
* @api private
* @param {Document} instance
* @inherits NeopreneError
*/
function ValidationError (instance) {
NeopreneError.call(this, "Validation failed");
Error.captureStackTrace(this, arguments.callee);
this.name = 'ValidationError';
this.errors = instance.errors = {};
};
/**
* Console.log helper
* @api private
*/
ValidationError.prototype.toString = function () {
return this.name + ': ' + Object.keys(this.errors).map(function (key) {
return String(this.errors[key]);
}, this).join(', ');
};
/*!
* Inherits from NeopreneError.
*/
ValidationError.prototype.__proto__ = NeopreneError.prototype;
/*!
* Module exports
*/
module.exports = exports = ValidationError;
|
/**
* App routes.
*/
var homepage = require('./homepage');
var user = require('./user');
var news = require('./news');
var test = require('./test');
var passport = require('passport');
function ensureAuthenticated(req, res, next) {
if (req.isAuthenticated()) { return next(); }
req.flash('error', '抱歉,您尚未登录。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensureAdmin(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin) { return next(); }
req.flash('error', '抱歉,您不是管理员。');
return res.redirect('/user/signin?redirect=' + req.path);
}
function ensurePermission(req, res, next) {
if (req.isAuthenticated() && req.user.isadmin)
{ return next(); }
if (req.isAuthenticated() &&
req.user.username == req.params.id)
{ return next(); }
req.flash('error', '抱歉,您没有权限。');
return res.redirect('/user/signin?redirect=' + req.path);
}
module.exports = function(app) {
app.get('/', homepage.index);
app.get('/user', ensureAdmin, user.showList);
app.get('/user/page/:page(\\d+)', ensureAdmin, user.showList);
app.get('/user/register', user.showRegister);
app.post('/user/register', user.doRegister);
app.get('/user/signin', user.showSignin);
app.post('/user/signin', passport.authenticate('local',
{ successRedirect: '/',
successFlash: '登录成功,欢迎回来。',
failureRedirect: 'back',
failureFlash: '抱歉,手机号或密码错误。',
}));
app.get('/user/signout', user.doSignout);
app.get('/user/:id(\\d{8,13})/edit', ensurePermission, user.showEditUser);
app.post('/user/:id(\\d{8,13})/edit', ensurePermission, user.doEditUser);
app.get('/user/:id(\\d{8,13})/setadmin', ensureAdmin, user.setAdmin);
app.get('/news', news.showList);
app.get('/news/page/:page(\\d+)', news.showList);
app.get('/news/:id(\\d+)', news.showItem);
app.get('/news/:id(\\d+)/edit', ensureAdmin, news.showEditItem);
app.post('/news/:id(\\d+)/edit', ensureAdmin, news.doEditItem);
app.get('/news/:id(\\d+)/delete', ensureAdmin, news.doDeleteItem);
app.get('/news/post', ensureAdmin, news.showNewItem);
app.post('/news/post', ensureAdmin, news.doNewItem);
app.get('/test', test);
app.get('*', function(req, res){
return res.render('homepage', {title: '404'});
});
}
|
/* COPYRIGHT 2012 SUPERMAP
* 本程序只能在有效的授权许可下使用。
* 未经许可,不得以任何手段擅自使用或传播。*/
/**
* @requires SuperMap/Util.js
* @requires SuperMap/REST.js
*/
/**
* Class: SuperMap.REST.ChartQueryParameters
* 海图查询参数类,该类用于设置海图查询时的相关参数,海图查询分为海图属性
* 查询和海图范围查询两类,通过属性queryMode指定查询模式。必设属性有:
* queryMode、chartLayerNames、chartQueryFilterParameters。当进行海图范围查询时,必设属性还包括bounds。
*/
SuperMap.REST.ChartQueryParameters = SuperMap.Class({
/**
* APIProperty: queryMode
* {String} 海图查询模式类型,SuperMap iClient for JavaScript对海图支持两种
* 查询方式:海图属性查询("ChartAttributeQuery")和海图空间查询
* ("ChartBoundsQuery") 。
*/
queryMode:null,
/**
* APIProperty: bounds
* {<SuperMap.Bounds>} 海图查询范围。
*/
bounds:null,
/**
* APIProperty: chartLayerNames
* {Array(String)} 查询的海图图层的名称。
*/
chartLayerNames:null,
/**
* APIProperty: chartQueryFilterParameters
* {Array <SuperMap.REST.ChartQueryFilterParameter>} 海图查询过滤参数。
* 包括:物标代码、物标可应用对象的选择(是否查询点、线或面)、属性字
* 段过滤条件。
*/
chartQueryFilterParameters:null,
/**
* Property: returnContent
* {Boolean} 获取或设置是返回查询结果记录集 recordsets,还是返回查询结果的
* 资源 resourceInfo。默认为 true,表示返回 recordsets。
*
* note: Recordsets 和 ResourceInfo 都存储在查询结果类 QueryResult 中。
* 当
* (start code)
* ReturnContent = true
* (end)
* 表示返回查询记录集,这时
* 查询结果存储在
* (start code)
* QueryResult.Recordsets
* (end)
* 中,而
* (start code)
* QueryResult.ResourceInfo
* (end)
* 为空;当
* (start code)
* ReturnContent = false
* (end)
* 时,表示返回查询结果资源,这时查询结果存储在
* (start code)
* QueryResult.ResourceInfo
* (end)
* 中,而
* (start code)
* QueryResult.Recordsets
* (end)
* 为空。
*/
returnContent:true,
/**
* APIProperty: startRecord
* {Number} 查询起始记录位置,默认为0。
*/
startRecord:0,
/**
* APIProperty: expectCount
* {Number} 期望查询结果返回的记录数,该值大于0。
*/
expectCount:null,
/**
* Constructor: SuperMap.REST.ChartQueryParameters
* 初始化 ChartQueryParameters 类的新实例。
*
* Parameters:
* options - {Object} 参数。
*
* Allowed options properties:
* queryMode - {String} 海图查询模式类型,SuperMap iClient for JavaScript对
* 海图支持两种查询方式:海图属性查询("ChartAttributeQuery")和海图空
* 间查询("ChartBoundsQuery") 。
* bounds - {<SuperMap.Bounds>} 海图查询范围。
* chartLayerNames - {Array(String)} 查询的海图图层的名称。
* chartQueryFilterParameters - {Array <SuperMap.REST.ChartQueryFilterParameter>}
* 海图查询过滤参数。包括:物标代码、物标可应用对象的选择(是否查询点、
* 线或面)、属性字段过滤条件。
* returnContent - {Boolean} 获取或设置是返回查询结果记录集 recordsets,还
* 是返回查询结果的资源 resourceInfo。默认为 true,表示返回 recordsets。
* startRecord - {Number} 查询起始记录位置,默认为0。
* expectCount - {Number} 期望查询结果返回的记录数,该值大于0。
*/
initialize:function (options) {
if (!options) {
return;
}
SuperMap.Util.extend(this, options);
},
/**
* APIMethod: destroy
* 释放资源,将引用资源的属性置空。
*/
destroy:function () {
var me = this;
me.queryMode = null;
me.bounds = null;
me.chartLayerNames = null;
me.chartQueryFilterParameters = null;
me.returnContent = true;
me.startRecord = 0;
me.expectCount = null;
},
/**
* Method: getVariablesJson
* 将属性信息转换成能够被服务识别的JSON格式字符串。
*/
getVariablesJson:function () {
var json="";
json += "\"queryMode\":\"" + this.queryMode + "\",";
if (this.chartLayerNames && this.chartLayerNames.length) {
var chartLayersArray = [];
var layerLength = this.chartLayerNames.length;
for (var i = 0; i < layerLength; i++)
{
chartLayersArray.push("\""+this.chartLayerNames[i]+"\"");
}
var layerNames = "[" + chartLayersArray.join(",") + "]";
json += "\"chartLayerNames\":" + layerNames + ",";
}
if (this.queryMode === "ChartBoundsQuery" && this.bounds) {
json += "\"bounds\":" + "{" + "\"leftBottom\":" + "{" + "\"x\":" + this.bounds.left + "," +
"\"y\":" + this.bounds.bottom + "}" + "," + "\"rightTop\":" + "{" + "\"x\":" + this.bounds.right + "," +
"\"y\":" + this.bounds.top + "}" + "},";
}
if (this.chartQueryFilterParameters && this.chartQueryFilterParameters.length) {
var chartParamArray = [];
var chartLength = this.chartQueryFilterParameters.length;
for (var j = 0; j < chartLength; j++)
{
var chartQueryFilterParameter = new SuperMap.REST.ChartQueryFilterParameter();
chartQueryFilterParameter = this.chartQueryFilterParameters[j];
chartParamArray.push(chartQueryFilterParameter.toJson());
}
var chartParamsJson = "[" + chartParamArray.join(",") + "]";
chartParamsJson = "\"chartQueryParams\":" + chartParamsJson + ",";
chartParamsJson += "\"startRecord\":" + this.startRecord + ",";
chartParamsJson += "\"expectCount\":" + this.expectCount;
chartParamsJson = "{" + chartParamsJson + "}";
json += "\"chartQueryParameters\":" + chartParamsJson;
}
json = "{" + json + "}";
return json;
},
CLASS_NAME:"SuperMap.REST.ChartQueryParameters"
})
|
'use strict';
var chai = require('chai');
var promised = require('chai-as-promised');
chai.use(promised);
global.expect = chai.expect;
exports.config = {
// The timeout for each script run on the browser. This should be longer
// than the maximum time your application needs to stabilize between tasks.
allScriptsTimeout: 15000,
// Capabilities to be passed to the webdriver instance.
capabilities: {
'browserName': 'chrome',
'loggingPrefs': {
'browser': 'ALL'
}
},
// ----- What tests to run -----
//
// Spec patterns are relative to the location of the spec file. They may
// include glob patterns.
specs: [
'admin/specs/admin-user-spec.js',
'admin/specs/users-spec.js',
'admin/specs/groups-spec.js',
'admin/specs/system-spec.js',
'admin/specs/authorizations-spec.js',
'cockpit/specs/dashboard-spec.js',
'cockpit/specs/process-definition-spec.js',
'cockpit/specs/decision-definition-spec.js',
'cockpit/specs/process-instance-spec.js',
'cockpit/specs/process-definition-filter-spec.js',
'cockpit/specs/variable-spec.js',
'cockpit/specs/suspension-spec.js',
'tasklist/specs/filter-basic-spec.js',
'tasklist/specs/filter-permissions-spec.js',
'tasklist/specs/filter-criteria-spec.js',
'tasklist/specs/filter-vg-spec.js',
'tasklist/specs/process-stariables-spec.js',
'tasklist/specs/task-claiminart-spec.js',
'tasklist/specs/tasklist-sorting-spec.js',
'tasklist/specs/tasklist-search-spec.js',
'tasklist/specs/task-detail-view-spec.js',
'tasklist/specs/task-dates-spec.js'
],
// A base URL for your application under test. Calls to protractor.get()
// with relative paths will be prepended with this.
baseUrl: 'http://localhost:8080',
// ----- The test framework -----
//
// Jasmine is fully supported as a test and assertion framework.
// Mocha has limited beta support. You will need to include your own
// assertion framework if working with mocha.
framework: 'mocha',
// ----- Options to be passed to minijasminenode -----
//
// Options to be passed to Mocha-node.
// See the full list at https://github.com/juliemr/minijasminenode
mochaOpts: {
timeout: 15000,
colors: false,
reporter: 'xunit-file',
slow: 3000
}
};
|
/*
* @class TableExamplesService
*/
export default class TableExamplesService {
constructor($http) {
this.$http = $http;
}
static getClassName() { return 'TableExamplesService'; }
getClassName() { return TableExamplesService.getClassName(); }
/*
* @func getColumns
* @desc getes a list of columns representing the dataset that
* allows data tables to map the array of data to the table
*/
getColumns() {
return this.$http.get('http://localhost:3001/api/DataTable/Columns/People');
}
/*
* @func addColumn
* @desc adds a col
* allows data tables to map the array of data to the table
*/
addColumn(item) {
return this.$http.post('http://localhost:3001/api/DataTable/Columns/People', item);
}
/*
* @func getData
* @desc gets a list of items from the api
*/
getData() {
return this.$http.get('http://localhost:3001/api/People');
}
/*
* @func addData
* @desc adds an item to the api
* @param item
*/
addData(item) {
return this.$http.post('http://localhost:3001/api/People', item);
}
}
|
describe('app.components.SaveProfileModal', function() {
beforeEach(function () {
module('app.components', 'ui.bootstrap', 'gettext');
});
describe('service', function () {
var callbackObject;
var saveSpy;
var doNotSaveSpy;
var cancelSpy;
beforeEach(function () {
bard.inject('SaveProfileModal', '$rootScope', '$document');
callbackObject = {
save: function () {},
doNotSave: function () {},
cancel: function () {},
}
saveSpy = sinon.spy(callbackObject, "save");
doNotSaveSpy = sinon.spy(callbackObject, "doNotSave");
cancelSpy = sinon.spy(callbackObject, "cancel");
});
xit('should show the modal', function () {
var modal = SaveProfileModal.showModal(callbackObject.save, callbackObject.doNotSave, callbackObject.cancel);
$rootScope.$digest();
var saveDialog = $document.find('.save-profile-modal');
expect(saveDialog.length).to.eq(1);
var saveButton = $document.find('.save-profile-modal .btn.btn-primary');
expect(saveButton.length).to.eq(1);
eventFire(saveButton[0], 'click');
$rootScope.$digest();
expect(saveSpy).to.have.been.called;
var closeButtons = $document.find('.save-profile-modal .btn.btn-default');
expect(closeButtons.length).to.eq(2);
eventFire(closeButtons[0], 'click');
$rootScope.$digest();
expect(cancelSpy).to.have.been.called;
eventFire(closeButtons[1], 'click');
$rootScope.$digest();
expect(doNotSaveSpy).to.have.been.called;
});
});
});
|
"use strict";
var router_1 = require('@angular/router');
var authorize_component_1 = require('./authorize/authorize-component');
var user_component_1 = require('./User/user-component');
var welcome_component_1 = require('./welcome-component');
exports.routes = [
{ path: '', component: welcome_component_1.welcome },
{ path: 'login', component: authorize_component_1.AuthorizeComponent },
{ path: 'dashboard', component: user_component_1.UserComponent },
];
exports.APP_ROUTER_PROVIDERS = [
router_1.provideRouter(exports.routes)
];
//# sourceMappingURL=app.route.js.map
|
ngDefine(
'cockpit.plugin.statistics-plugin.controllers',
function(module) {
module
.controller(
'processDefinitionCtrl',
[
'$scope',
'DataFactory',
'Uri',
function($scope, DataFactory, Uri) {
$scope.options = {
chart : {
type : 'pieChart',
height : 500,
x : function(d) {
return d.key;
},
y : function(d) {
return d.y;
},
showLabels : true,
transitionDuration : 500,
labelThreshold : 0.01,
tooltips : true,
tooltipContent : function(key, y, e, graph) {
if (key == "finished") {
return '<h3>' + key + '</h3>' + '<p>count:<b>' + y
+ '</b><br/>' + 'average Duration:<b>'
+ (e.point.avg / 1000 / 60).toFixed(2)
+ ' min</b><br/>minimal Duration:<b>'
+ (e.point.min / 1000 / 60).toFixed(2)
+ ' min</b><br/>maximal Duration:<b>'
+ (e.point.max / 1000 / 60).toFixed(2)
+ ' min</b></p>'
} else {
return '<h3>' + key + '</h3>' + '<p>' + y + '</p>'
}
},
noData : "No Processes met the requirements",
legend : {
margin : {
top : 5,
right : 5,
bottom : 5,
left : 5
}
}
}
};
DataFactory
.getAllProcessInstanceCountsByState(
$scope.processDefinition.key)
.then(
function() {
var processDefinitionCounts = DataFactory.allProcessInstanceCountsByState[$scope.processDefinition.key];
var counts = [];
counts
.push({
"key" : "running",
"y" : processDefinitionCounts[0].runningInstanceCount
});
counts
.push({
"key" : "failed",
"y" : processDefinitionCounts[0].failedInstanceCount
});
counts
.push({
"key" : "finished",
"y" : processDefinitionCounts[0].endedInstanceCount,
"avg" : processDefinitionCounts[0].duration,
"min" : processDefinitionCounts[0].minDuration,
"max" : processDefinitionCounts[0].maxDuration
});
$scope.statesOfDefinition = counts;
});
} ]);
});
|
/**
* Red Hat Open Innovation Labs API
* A generic model to support automation at all levels of the application and infrastructure lifecycle.
*
* OpenAPI spec version: 0.3.0-alpha
* Contact: rhc-open-innovation-labs@redhat.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*
* 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.
*/
(function(root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['ApiClient', 'model/Port'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports, like Node.
module.exports = factory(require('../ApiClient'), require('./Port'));
} else {
// Browser globals (root is window)
if (!root.RedHatOpenInnovationLabsApi) {
root.RedHatOpenInnovationLabsApi = {};
}
root.RedHatOpenInnovationLabsApi.Service = factory(root.RedHatOpenInnovationLabsApi.ApiClient, root.RedHatOpenInnovationLabsApi.Port);
}
}(this, function(ApiClient, Port) {
'use strict';
/**
* The Service model module.
* @module model/Service
* @version 0.3.0-alpha
*/
/**
* Constructs a new <code>Service</code>.
* @alias module:model/Service
* @class
*/
var exports = function() {
var _this = this;
};
/**
* Constructs a <code>Service</code> from a plain JavaScript object, optionally creating a new instance.
* Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not.
* @param {Object} data The plain JavaScript object bearing properties of interest.
* @param {module:model/Service} obj Optional instance to populate.
* @return {module:model/Service} The populated <code>Service</code> instance.
*/
exports.constructFromObject = function(data, obj) {
if (data) {
obj = obj || new exports();
if (data.hasOwnProperty('id')) {
obj['id'] = ApiClient.convertToType(data['id'], 'Number');
}
if (data.hasOwnProperty('name')) {
obj['name'] = ApiClient.convertToType(data['name'], 'String');
}
if (data.hasOwnProperty('ports')) {
obj['ports'] = ApiClient.convertToType(data['ports'], [Port]);
}
}
return obj;
}
/**
* @member {Number} id
*/
exports.prototype['id'] = undefined;
/**
* @member {String} name
*/
exports.prototype['name'] = undefined;
/**
* @member {Array.<module:model/Port>} ports
*/
exports.prototype['ports'] = undefined;
return exports;
}));
|
(function($) {
module("referenceReads1");
// Test case : Reference Reads 1
_asyncTest("Reference Reads 1", function()
{
expect(6);
GitanaTest.authenticateFullOAuth().then(function() {
var platform = this;
// create a few things
var repository = null;
this.createRepository().then(function() {
repository = this;
});
var domain = null;
this.createDomain().then(function() {
domain = this;
});
var registrar = null;
this.createRegistrar().then(function() {
registrar = this;
});
var stack = null;
this.createStack().then(function() {
stack = this;
});
var team = null;
this.then(function() {
this.subchain(stack).createTeam("abc-" + new Date().getTime()).then(function() {
team = this;
});
});
this.then(function() {
var repositoryReference = "repository://" + platform.getId() + "/" + repository.getId();
var domainReference = "domain://" + platform.getId() + "/" + domain.getId();
var registrarReference = "registrar://" + platform.getId() + "/" + registrar.getId();
var stackReference = "stack://" + platform.getId() + "/" + stack.getId();
var teamReference = "team://stack/" + platform.getId() + "/" + stack.getId() + "/" + team.getKey();
var entries = [{
"ref": repositoryReference
}, {
"ref": domainReference
}, {
"ref": registrarReference
}, {
"ref": stackReference
}, {
"ref": teamReference
}];
this.referenceReads(entries, function(results) {
// check that they all came back
ok(results.length == entries.length, "Found the right number of results");
for (var i = 0; i < results.length; i++)
{
ok(results[i].entry, "Found entry #" + i);
}
// done
start();
});
});
});
});
}(jQuery) );
|
$(function () {
var controller = new ScrollMagic.Controller({
globalSceneOptions: {
triggerHook: 'onLeave',
reverse: true
}
});
// $('.homepage .panel').each(function () {
// var element = $(this);
// console.log(element);
// new ScrollMagic.Scene({triggerElement: element})
// .setPin(element)
// .setClassToggle(element,'active')
// .addTo(controller)
// })
// var actual_positions = [0];
// var mid_points = [];
// var all_scenes = [];
// $('.services .panel').each(function (index) {
// if($(this).hasClass('main')) {
// new ScrollMagic.Scene({triggerElement: '.services .main'})
// .setPin('.services .main')
// .setClassToggle('.services .main','active')
// .addTo(controller)
// }
// else {
// var element_id = $(this).attr('id');
// var element_id_with_hash = '#' + $(this).attr('id');
// var scene = new ScrollMagic.Scene({triggerElement: element_id_with_hash})
// .setPin(element_id_with_hash)
// .setClassToggle(element_id_with_hash,'show-bottom-nav')
// .addTo(controller)
// all_scenes.push({
// id: element_id,
// scene: scene
// });
// actual_positions.push(Math.ceil(scene.triggerPosition()));
// if(actual_positions.length > 1) {
// mid_points.push((actual_positions[index] + actual_positions [index-1]) / 2)
// }
// }
// })
// $('a[href*=#]:not([href=#])').click(function () {
// var id = $(this).attr('href').replace('#','');
// if($(this).parent().parent().parent().hasClass('bottom-nav')) {
// var index = $('.bottom-nav ul li a').index($(this));
// }else {
// var index = $('ul.wrap li a').index($(this));
// }
// if(id == 'down') {
// setTimeout(function () {
// $('.bottom-nav').addClass('fixed')
// },1100)
// }
// else {
// var targetted_scene = all_scenes[index];
// if(targetted_scene.id == id) {
// $('html,body').animate({scrollTop: targetted_scene.scene.scrollOffset()},1000);
// return false;
// }
// }
// })
// var add_and_remove_active_class = function (index) {
// $('.bottom-nav').addClass('fixed')
// $('.bottom-nav ul li').removeClass('active');
// $('.bottom-nav ul li:nth-child(' + index + ')').children('a').parent().last().addClass('active');
// }
// $(window).scroll(function () {
// if ($(".show-bottom-nav")[0]){
// $('.bottom-nav').addClass('fixed')
// }else{
// $('.bottom-nav').removeClass('fixed')
// }
// for(var index=0; index<mid_points.length; index++) {
// var next_index = index+1;
// var last_index = mid_points.length-1
// /* check between mid point ranges and set active class to the respective nav item. */
// if($(window).scrollTop() > mid_points[index] && $(window).scrollTop() < mid_points[next_index]) {
// add_and_remove_active_class(next_index);
// break;
// /* if nothing matches and reaches to last index then set active active to last nav item. */
// }else if ($(window).scrollTop() > mid_points[last_index]) {
// add_and_remove_active_class(mid_points.length);
// /* remove from all if its rolled back to the top*/
// }else {
// $('.bottom-nav ul li').removeClass('active');
// }
// }
// });
});
//change navigation color on scroll
/*
var offset_top_news_section = $('.color-light').offset().top;
var offset_top_contact_section = $('.pattern').offset().top;
console.log(offset_top_contact_section, offset_top_news_section);
$(window).scroll(function (event) {
var scroll = $(window).scrollTop();
console.log(scroll);
if(scroll < offset_top_contact_section && scroll >= offset_top_news_section) {
$('.homepage nav').addClass('change-color');
} else {
$('.homepage nav').removeClass('change-color');
}
});
*/
|
angular.module('aac.controllers.main', [])
/**
* Main layout controller
* @param $scope
*/
.controller('MainCtrl', function($scope, $rootScope, $location, Data, Utils) {
$scope.go = function(v) {
$location.path(v);
}
$scope.activeView = function(view) {
return view == $rootScope.currentView ? 'active' : '';
};
$scope.signOut = function() {
window.document.location = "./logout";
};
Data.getProfile().then(function(data) {
data.fullname = data.name + ' ' + data.surname;
$rootScope.user = data;
}).catch(function(err) {
Utils.showError(err);
});
})
.controller('HomeController', function($scope, $rootScope, $location) {
})
.controller('AccountsController', function($scope, $rootScope, $location, Data, Utils) {
Data.getAccounts().then(function(data) {
Data.getProviders().then(function(providers) {
providers.sort(function(a,b) {
if (data.accounts[a] && !data.accounts[b]) return -1;
if (data.accounts[b] && !data.accounts[a]) return 1;
return a.localeCompare(b);
});
$scope.providers = providers;
var accounts = {};
for (var p in data.accounts) {
var amap = {};
for (var k in data.accounts[p]) {
if (k === 'it.smartcommunitylab.aac.surname') amap['surname'] = data.accounts[p][k];
else if (k === 'it.smartcommunitylab.aac.givenname') amap['givenname'] = data.accounts[p][k];
else if (k === 'it.smartcommunitylab.aac.username') amap['username'] = data.accounts[p][k];
else amap[k] = data.accounts[p][k];
}
accounts[p] = amap;
}
$scope.accounts = accounts;
}).catch(function(err) {
Utils.showError(err);
});
}).catch(function(err) {
Utils.showError(err);
});
$scope.confirmDeleteAccount = function() {
$('#deleteConfirm').modal({keyboard: false});
}
$scope.deleteAccount = function() {
$('#deleteConfirm').modal('hide');
Data.deleteAccount().then(function() {
window.location.href = './logout';
}).catch(function(err) {
Utils.showError(err);
});
}
})
.controller('ConnectionsController', function($scope, $rootScope, $location, Data, Utils) {
Data.getConnections().then(function(connections) {
$scope.connections = connections;
}).catch(function(err) {
Utils.showError(err);
});
$scope.confirmDeleteApp = function(app) {
$scope.clientId = app.clientId;
$('#deleteConfirm').modal({keyboard: false});
}
$scope.deleteApp = function() {
$('#deleteConfirm').modal('hide');
Data.removeConnection($scope.clientId).then(function(connections) {
$scope.connections = connections;
Utils.showSuccess();
}).catch(function(err) {
Utils.showError(err);
});
}
})
.controller('ProfileController', function($scope, $rootScope, $location, Data, Utils) {
$scope.profile = Object.assign($rootScope.user);
Data.getAccounts().then(function(data) {
if (!data.accounts.internal) {
$scope.password_required = true;
}
}).catch(function(err) {
Utils.showError(err);
});
$scope.cancel = function() {
window.history.back();
}
$scope.save = function() {
if (!$scope.profile.name ||
!$scope.profile.surname ||
!$scope.profile.username ||
$scope.profile.password && $scope.profile.password != $scope.profile.password2)
{
return;
}
Data.saveAccount($scope.profile).then(function(data) {
data.fullname = data.name + ' ' + data.surname;
$rootScope.user = data;
$scope.profile = Object.assign($rootScope.user);
$scope.password_required = false;
Utils.showSuccess();
}).catch(function(err) {
Utils.showError(err);
});
}
Utils.initUI();
})
;
|
jQuery(function($) {
//smooth scroll
$('.navbar-nav > li.anchor').click(function(event) {
//event.preventDefault();
var target = $(this).find('>a').prop('hash');
$('#navbar .active').removeClass('active');
$(this).addClass('active');
$('html, body').animate({
scrollTop: $(target).offset().top
}, 500);
});
//scrollspy
$('[data-spy="scroll"]').each(function () {
var $spy = $(this).scrollspy('refresh')
});
$(function() {
$(".navbar-btn").click(function() {
$("#options").toggle();
$(".navbar-btn .glyphicon").toggleClass("glyphicon-plus")
.toggleClass("glyphicon-minus");
});
});
});
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var STATIC_REG = /.*\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)$/;
var VER_REG = /[\W][\d\w]+(?=\.\w+$)/;
var _default = function _default(req, res, next) {
var filePaths = req.url.split('/');
if (STATIC_REG.test(req.path) && filePaths[2] === 'prd') {
filePaths.splice(2, 1);
req.url = filePaths.join('/').replace(VER_REG, '');
}
next();
};
exports["default"] = _default;
|
System.register([], function (exports_1, context_1) {
"use strict";
var __moduleName = context_1 && context_1.id;
function toSnakeCase(camelCase) {
if (!camelCase) {
throw new Error("Please provide camelCase.");
}
return camelCase.replace(/([A-Z])/g, "-$1").toLowerCase();
}
exports_1("toSnakeCase", toSnakeCase);
return {
setters: [],
execute: function () {
}
};
});
//# sourceMappingURL=to.snake.case.js.map
|
import { createStore, applyMiddleware, compose } from 'redux'
import logger from 'redux-logger'
import thunkMiddleware from 'redux-thunk'
import rootReducer from './reducers'
const configureStore = () => {
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
return createStore(rootReducer, /* preloadedState, */ composeEnhancers(
applyMiddleware(thunkMiddleware)
// applyMiddleware(logger)
));
}
export default configureStore
|
(function outer(modules, cache, entries){
/**
* Global
*/
var global = (function(){ return this; })();
/**
* Require `name`.
*
* @param {String} name
* @param {Boolean} jumped
* @api public
*/
function require(name, jumped){
if (cache[name]) return cache[name].exports;
if (modules[name]) return call(name, require);
throw new Error('cannot find module "' + name + '"');
}
/**
* Call module `id` and cache it.
*
* @param {Number} id
* @param {Function} require
* @return {Function}
* @api private
*/
function call(id, require){
var m = cache[id] = { exports: {} };
var mod = modules[id];
var name = mod[2];
var fn = mod[0];
fn.call(m.exports, function(req){
var dep = modules[id][1][req];
return require(dep ? dep : req);
}, m, m.exports, outer, modules, cache, entries);
// expose as `name`.
if (name) cache[name] = cache[id];
return cache[id].exports;
}
/**
* Require all entries exposing them on global if needed.
*/
for (var id in entries) {
if (entries[id]) {
global[entries[id]] = require(id);
} else {
require(id);
}
}
/**
* Duo flag.
*/
require.duo = true;
/**
* Expose cache.
*/
require.cache = cache;
/**
* Expose modules
*/
require.modules = modules;
/**
* Return newest require.
*/
return require;
})({
1: [function(require, module, exports) {
/** @jsx React.DOM */
React.renderComponent(
React.DOM.h1(null, "Hello, world!"),
document.getElementById('example')
);
}, {}]}, {}, {"1":""})
|
var addressBar = element(by.css("#addressBar")),
url = 'http://www.example.com/base/ratingList.html#!/path?a=b#h';
it("should show fake browser info on load", function(){
expect(addressBar.getAttribute('value')).toBe(url);
expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
expect(element(by.binding('$location.port()')).getText()).toBe('80');
expect(element(by.binding('$location.path()')).getText()).toBe('/path');
expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}');
expect(element(by.binding('$location.hash()')).getText()).toBe('h');
});
it("should change $location accordingly", function(){
var navigation = element.all(by.css("#navigation a"));
navigation.get(0).click();
expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/first?a=b");
expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
expect(element(by.binding('$location.port()')).getText()).toBe('80');
expect(element(by.binding('$location.path()')).getText()).toBe('/first');
expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}');
expect(element(by.binding('$location.hash()')).getText()).toBe('');
navigation.get(1).click();
expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/sec/ond?flag#hash");
expect(element(by.binding('$location.protocol()')).getText()).toBe('http');
expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com');
expect(element(by.binding('$location.port()')).getText()).toBe('80');
expect(element(by.binding('$location.path()')).getText()).toBe('/sec/ond');
expect(element(by.binding('$location.search()')).getText()).toBe('{"flag":true}');
expect(element(by.binding('$location.hash()')).getText()).toBe('hash');
});
|
"use strict";
define(["lib/three.min"], function() {
var Reality = function(sourceCanvas){
// Create a default camera and scene.
var camera = new THREE.Camera();
var scene = new THREE.Scene();
// Create a plane geometry to hold the sourceCanvas texture
var geometry = new THREE.PlaneGeometry(2, 2, 0);
// Create a material textured with the contents of sourceCanvas.
var texture = new THREE.Texture(sourceCanvas);
var material = new THREE.MeshBasicMaterial({
map: texture,
depthTest: false,
depthWrite: false
});
// Build a mesh and add it to the scene.
var mesh = new THREE.Mesh( geometry, material );
scene.add(mesh);
// We need to notify ThreeJS when the texture has changed.
function update() {
texture.needsUpdate = true;
}
return {
camera: camera,
scene: scene,
update: update,
}
}
var Scene = function() {
var scene = new THREE.Scene();
var camera = new THREE.Camera();
function add(object) {
scene.add(object);
}
function remove(object) {
scene.remove(object);
}
function setProjectionMatrix(matrix) {
camera.projectionMatrix.setFromArray( matrix );
}
return {
scene:scene,
camera:camera,
add:add,
remove:remove,
setProjectionMatrix:setProjectionMatrix,
}
}
var create = function(dimensions, sourceCanvas) {
// Create a canvas which will be used for WebGL
var glCanvas = document.createElement('canvas');
// Initialize the renderer and attach it to the canvas
var renderer = new THREE.WebGLRenderer({canvas:glCanvas});
renderer.setSize(dimensions.width, dimensions.height);
renderer.autoClear = false;
// Create a reality scene
var reality = new Reality(sourceCanvas);
var virtual = new Scene();
var light = new THREE.SpotLight(0xffffff);
light.position.set(0, 0, 9000);
light.lookAt( new THREE.Vector3(0,0,0) );
virtual.scene.add(light);
function render() {
// Render the reality scene
renderer.render(reality.scene, reality.camera);
// Render the augmented components on top of the reality scene.
renderer.render(virtual.scene, virtual.camera);
}
function update() {
// Notify the reality scene to update it's texture
reality.update();
}
function setCameraMatrix( matrix ) {
virtual.setProjectionMatrix( matrix );
}
function add( object ) {
virtual.add( object.model );
}
function remove( object ) {
virtual.remove( object.model );
}
return {
add: add,
remove: remove,
update: update,
render: render,
glCanvas: glCanvas,
setCameraMatrix: setCameraMatrix,
}
}
return {
create: create,
}
});
|
const $ = require('jquery');
const { BagItProfile } = require('../../bagit/bagit_profile');
const { Job } = require('../../core/job');
const { JobRunController } = require('./job_run_controller');
const { PackageOperation } = require('../../core/package_operation');
const path = require('path');
const { StorageService } = require('../../core/storage_service');
const { TestUtil } = require('../../core/test_util');
const { UITestUtil } = require('../common/ui_test_util');
const { UploadOperation } = require('../../core/upload_operation');
const { Util } = require('../../core/util');
beforeEach(() => {
TestUtil.deleteJsonFile('Job');
TestUtil.deleteJsonFile('StorageService');
});
afterAll(() => {
TestUtil.deleteJsonFile('Job');
TestUtil.deleteJsonFile('StorageService');
});
function getStorageService(name, proto, host) {
let ss = new StorageService({
name: name,
protocol: proto,
host: host
});
ss.save();
return ss;
}
function getUploadOp(name, proto, host) {
let ss = getStorageService(name, proto, host);
let op = new UploadOperation();
op.sourceFiles = ['/dev/null'];
op.storageServiceId = ss.id;
return op;
}
function getJob() {
var job = new Job();
job.packageOp = new PackageOperation('TestBag', '/dev/null');
job.packageOp.packageFormat = 'BagIt';
job.packageOp._trimLeadingPaths = false;
job.packageOp.sourceFiles = [
__dirname,
path.join(__dirname, '..', 'forms')
];
job.dirCount = 2;
job.fileCount = 12;
job.byteCount = 237174;
job.uploadOps = [
getUploadOp('target1', 's3', 'target1.com'),
getUploadOp('target2', 's3', 'target2.com')
];
job.bagItProfile = BagItProfile.load(path.join(__dirname, '..', '..', 'test', 'profiles', 'multi_manifest.json'));
job.save();
return job;
}
function getController() {
let job = getJob();
let params = new URLSearchParams({ id: job.id });
return new JobRunController(params);
}
test('constructor', () => {
let controller = getController();
expect(controller.model).toEqual(Job);
expect(controller.job).not.toBeNull();
});
test('show', () => {
let controller = getController();
let response = controller.show()
expect(response.container).toMatch(controller.job.packageOp.packageName);
expect(response.container).toMatch(controller.job.packageOp.outputPath);
expect(response.container).toMatch(controller.job.bagItProfile.name);
expect(response.container).toMatch(controller.job.bagItProfile.description);
expect(response.container).toMatch('2 Directories');
expect(response.container).toMatch('12 Files');
expect(response.container).toMatch('231.62 KB');
expect(response.container).toMatch(controller.job.packageOp.sourceFiles[0]);
expect(response.container).toMatch(controller.job.packageOp.sourceFiles[1]);
});
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var isPositiveInteger = require( '@stdlib/math/base/assert/is-positive-integer' );
var constantFunction = require( '@stdlib/utils/constant-function' );
var isfinite = require( '@stdlib/math/base/assert/is-finite' );
var round = require( '@stdlib/math/base/special/round' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var exp = require( '@stdlib/math/base/special/exp' );
var LN2 = require( '@stdlib/constants/float64/ln-two' );
var weights = require( './weights.js' );
// MAIN //
/**
* Returns a function for evaluating the cumulative distribution function (CDF) for the distribution of the Wilcoxon signed rank test statistic with `n` observations.
*
* @param {PositiveInteger} n - number of observations
* @returns {Function} CDF
*
* @example
* var cdf = factory( 8 );
* var y = cdf( 3.9 );
* // returns ~0.027
*
* y = cdf( 17.0 );
* // returns ~0.473
*/
function factory( n ) {
var mlim;
var pui;
if ( !isPositiveInteger( n ) || !isfinite( n ) ) {
return constantFunction( NaN );
}
pui = exp( -n * LN2 );
mlim = n * ( n + 1 ) / 2;
return cdf;
/**
* Evaluates the cumulative distribution function (CDF) for the distribution of the Wilcoxon signed rank test statistic.
*
* @private
* @param {number} x - input value
* @returns {Probability} evaluated CDF
*
* @example
* var y = cdf( 2 );
* // returns <number>
*/
function cdf( x ) {
var i;
var p;
if ( isnan( x ) ) {
return NaN;
}
if ( x < 0.0 ) {
return 0.0;
}
x = round( x );
if ( x >= mlim ) {
return 1.0;
}
p = 0;
for ( i = 0; i <= x; i++ ) {
p += weights( i, n ) * pui;
}
return p;
}
}
// EXPORTS //
module.exports = factory;
|
/**
* @license
* Copyright The Closure Library Authors.
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Displays and edits the value of a cookie.
* Intended only for debugging.
*/
goog.provide('goog.ui.CookieEditor');
goog.require('goog.asserts');
goog.require('goog.dom');
goog.require('goog.dom.TagName');
goog.require('goog.events.EventType');
goog.require('goog.net.Cookies');
goog.require('goog.string');
goog.require('goog.style');
goog.require('goog.ui.Component');
goog.requireType('goog.events.Event');
/**
* Displays and edits the value of a cookie.
* @final
* @unrestricted
*/
goog.ui.CookieEditor = class extends goog.ui.Component {
/**
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper.
*/
constructor(opt_domHelper) {
'use strict';
super(opt_domHelper);
}
/**
* Sets the cookie which this component will edit.
* @param {string} cookieKey Cookie key.
*/
selectCookie(cookieKey) {
'use strict';
goog.asserts.assert(goog.net.Cookies.getInstance().isValidName(cookieKey));
this.cookieKey_ = cookieKey;
if (this.textAreaElem_) {
this.textAreaElem_.value =
goog.net.Cookies.getInstance().get(cookieKey) || '';
}
}
/** @override */
canDecorate() {
'use strict';
return false;
}
/** @override */
createDom() {
'use strict';
// Debug-only, so we don't need i18n.
this.clearButtonElem_ = goog.dom.createDom(
goog.dom.TagName.BUTTON, /* attributes */ null, 'Clear');
this.updateButtonElem_ = goog.dom.createDom(
goog.dom.TagName.BUTTON, /* attributes */ null, 'Update');
var value =
this.cookieKey_ && goog.net.Cookies.getInstance().get(this.cookieKey_);
this.textAreaElem_ = goog.dom.createDom(
goog.dom.TagName.TEXTAREA, /* attibutes */ null, value || '');
this.valueWarningElem_ = goog.dom.createDom(
goog.dom.TagName.SPAN,
/* attibutes */ {'style': 'display:none;color:red'},
'Invalid cookie value.');
this.setElementInternal(goog.dom.createDom(
goog.dom.TagName.DIV,
/* attibutes */ null, this.valueWarningElem_,
goog.dom.createDom(goog.dom.TagName.BR), this.textAreaElem_,
goog.dom.createDom(goog.dom.TagName.BR), this.clearButtonElem_,
this.updateButtonElem_));
}
/** @override */
enterDocument() {
'use strict';
super.enterDocument();
this.getHandler().listen(
this.clearButtonElem_, goog.events.EventType.CLICK, this.handleClear_);
this.getHandler().listen(
this.updateButtonElem_, goog.events.EventType.CLICK,
this.handleUpdate_);
}
/**
* Handles user clicking clear button.
* @param {!goog.events.Event} e The click event.
* @private
*/
handleClear_(e) {
'use strict';
if (this.cookieKey_) {
goog.net.Cookies.getInstance().remove(this.cookieKey_);
}
this.textAreaElem_.value = '';
}
/**
* Handles user clicking update button.
* @param {!goog.events.Event} e The click event.
* @private
*/
handleUpdate_(e) {
'use strict';
if (this.cookieKey_) {
var value = this.textAreaElem_.value;
if (value) {
// Strip line breaks.
value = goog.string.stripNewlines(value);
}
if (goog.net.Cookies.getInstance().isValidValue(value)) {
goog.net.Cookies.getInstance().set(this.cookieKey_, value);
goog.style.setElementShown(this.valueWarningElem_, false);
} else {
goog.style.setElementShown(this.valueWarningElem_, true);
}
}
}
/** @override */
disposeInternal() {
'use strict';
this.clearButtonElem_ = null;
this.cookieKey_ = null;
this.textAreaElem_ = null;
this.updateButtonElem_ = null;
this.valueWarningElem_ = null;
}
};
/**
* Cookie key.
* @type {?string}
* @private
*/
goog.ui.CookieEditor.prototype.cookieKey_;
/**
* Text area.
* @type {HTMLTextAreaElement}
* @private
*/
goog.ui.CookieEditor.prototype.textAreaElem_;
/**
* Clear button.
* @type {HTMLButtonElement}
* @private
*/
goog.ui.CookieEditor.prototype.clearButtonElem_;
/**
* Invalid value warning text.
* @type {HTMLSpanElement}
* @private
*/
goog.ui.CookieEditor.prototype.valueWarningElem_;
/**
* Update button.
* @type {HTMLButtonElement}
* @private
*/
goog.ui.CookieEditor.prototype.updateButtonElem_;
// TODO(user): add combobox for user to select different cookies
|
/**
* @license Apache-2.0
*
* Copyright (c) 2020 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
// MODULES //
var Float32Array = require( '@stdlib/array/float32' );
var addon = require( './smin.native.js' );
// MAIN //
/**
* Computes the minimum value of a single-precision floating-point strided array.
*
* @param {PositiveInteger} N - number of indexed elements
* @param {Float32Array} x - input array
* @param {integer} stride - stride length
* @param {NonNegativeInteger} offset - starting index
* @returns {number} minimum value
*
* @example
* var Float32Array = require( '@stdlib/array/float32' );
* var floor = require( '@stdlib/math/base/special/floor' );
*
* var x = new Float32Array( [ 2.0, 1.0, 2.0, -2.0, -2.0, 2.0, 3.0, 4.0 ] );
* var N = floor( x.length / 2 );
*
* var v = smin( N, x, 2, 1 );
* // returns -2.0
*/
function smin( N, x, stride, offset ) {
var view;
if ( stride < 0 ) {
offset += (N-1) * stride;
}
view = new Float32Array( x.buffer, x.byteOffset+(x.BYTES_PER_ELEMENT*offset), x.length-offset ); // eslint-disable-line max-len
return addon( N, view, stride );
}
// EXPORTS //
module.exports = smin;
|
import props from './props';
import './view.html';
class NoteClab {
beforeRegister() {
this.is = 'note-clab';
this.properties = props;
}
computeClasses(type) {
var arr = ['input-note'];
if (type != undefined) arr.push(type);
return arr.join(' ');
}
}
Polymer(NoteClab);
|
/**
* Created by dmitry on 21.11.16.
*/
import React, { Component } from 'react';
import { Container, Content, Spinner } from 'native-base';
// TODO: Рядом лежат спиннеры, поди можно прикрячить
export default class Loading extends Component {
render() {
return (
<Container>
<Content contentContainerStyle={{
flex: 1,
flexDirection: 'row',
justifyContent: 'center'
}}>
<Spinner color="blue"/>
</Content>
</Container>
);
}
}
|
//main javascript
(function init() {
// If we need to load requirejs before loading butter, make it so
if (typeof define === "undefined") {
var rscript = document.createElement("script");
rscript.onload = function () {
init();
};
rscript.src = "require.js";
document.head.appendChild(rscript);
return;
}
require.config({
baseUrl: 'js/',
paths: {
// the left side is the module ID,
// the right side is the path to
// the jQuery file, relative to baseUrl.
// Also, the path should NOT include
// the '.js' file extension. This example
// is using jQuery 1.8.2 located at
// js/jquery-1.8.2.js, relative to
// the HTML page.
jquery: 'lib/jquery-2.1.3.min',
namedwebsockets: 'lib/namedwebsockets',
qrcode: 'lib/qrcode.min',
webcodecam:'lib/WebCodeCam.min',
qrcodelib:'lib/qrcodelib',
socketio: '/socket.io/socket.io',
shake: 'lib/shake'
}
});
// Start the main app logic.
define("mediascape", ["mediascape/Agentcontext/agentcontext",
"mediascape/Association/association",
"mediascape/Discovery/discovery",
"mediascape/DiscoveryAgentContext/discoveryagentcontext",
"mediascape/Sharedstate/sharedstate",
"mediascape/Mappingservice/mappingservice",
"mediascape/Applicationcontext/applicationcontext"], function ($, Modules) {
//jQuery, modules and the discovery/modules module are all.
//loaded and can be used here now.
//creation of mediascape and discovery objects.
var mediascape = {};
var moduleList = Array.prototype.slice.apply(arguments);
mediascape.init = function (options) {
mediascapeOptions = {};
_this = Object.create(mediascape);
for (var i = 0; i < moduleList.length; i++) {
var name = moduleList[i].__moduleName;
var dontCall = ['sharedState', 'mappingService', 'applicationContext'];
if (dontCall.indexOf(name) === -1) {
mediascape[name] = new moduleList[i](mediascape, "gq" + i, mediascape);
} else {
mediascape[name] = moduleList[i];
}
}
return _this;
};
mediascape.version = "0.0.1";
// See if we have any waiting init calls that happened before we loaded require.
if (window.mediascape) {
var args = window.mediascape.__waiting;
delete window.mediascape;
if (args) {
mediascape.init.apply(this, args);
}
}
window.mediascape = mediascape;
//return of mediascape object with discovery and features objects and its functions
return mediascape;
});
require(["mediascape"], function (mediascape) {
mediascape.init();
/**
*
* Polyfill for custonevents
*/
(function () {
function CustomEvent(event, params) {
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
})();
var event = new CustomEvent("mediascape-ready", {
"detail": {
"loaded": true
}
});
document.dispatchEvent(event);
});
}());
|
function Controller() {
function __alloyId24() {
__alloyId24.opts || {};
var models = __alloyId23.models;
var len = models.length;
var rows = [];
for (var i = 0; len > i; i++) {
var __alloyId9 = models[i];
__alloyId9.__transform = {};
var __alloyId10 = Ti.UI.createTableViewRow({
layout: "vertical",
font: {
fontSize: "16dp"
},
height: "auto",
title: "undefined" != typeof __alloyId9.__transform["nome"] ? __alloyId9.__transform["nome"] : __alloyId9.get("nome"),
model: "undefined" != typeof __alloyId9.__transform["alloy_id"] ? __alloyId9.__transform["alloy_id"] : __alloyId9.get("alloy_id"),
editable: "true"
});
rows.push(__alloyId10);
var __alloyId12 = Ti.UI.createView({
layout: "vertical"
});
__alloyId10.add(__alloyId12);
var __alloyId14 = Ti.UI.createLabel({
width: Ti.UI.SIZE,
height: Ti.UI.SIZE,
right: "10dp",
color: "blue",
font: {
fontSize: "16dp"
},
text: "undefined" != typeof __alloyId9.__transform["nome"] ? __alloyId9.__transform["nome"] : __alloyId9.get("nome")
});
__alloyId12.add(__alloyId14);
var __alloyId16 = Ti.UI.createView({
height: Ti.UI.SIZE,
width: Ti.UI.FILL
});
__alloyId12.add(__alloyId16);
var __alloyId18 = Ti.UI.createScrollView({
scrollType: "horizontal",
layout: "horizontal",
horizontalWrap: "false"
});
__alloyId16.add(__alloyId18);
var __alloyId20 = Ti.UI.createImageView({
top: "15dp",
image: "undefined" != typeof __alloyId9.__transform["foto1"] ? __alloyId9.__transform["foto1"] : __alloyId9.get("foto1"),
height: "180dp",
width: "320dp"
});
__alloyId18.add(__alloyId20);
var __alloyId22 = Ti.UI.createImageView({
top: "15dp",
image: "undefined" != typeof __alloyId9.__transform["foto2"] ? __alloyId9.__transform["foto2"] : __alloyId9.get("foto2"),
height: "180dp",
width: "320dp"
});
__alloyId18.add(__alloyId22);
}
$.__views.tableviewContatos.setData(rows);
}
function openAdd1() {
var add1 = Alloy.createController("add1");
add1.getView().open({
modal: true
});
}
function maisDetalhes(e) {
var contato = Alloy.Collections.contato.get(e.rowData.model);
var ctrl = Alloy.createController("detalhesContato", contato);
$.homeTab.open(ctrl.getView());
}
require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
this.__controllerPath = "home";
arguments[0] ? arguments[0]["__parentSymbol"] : null;
arguments[0] ? arguments[0]["$model"] : null;
arguments[0] ? arguments[0]["__itemTemplate"] : null;
var $ = this;
var exports = {};
var __defers = {};
$.__views.homeWindow = Ti.UI.createWindow({
backgroundColor: "white",
layout: "vertical",
id: "homeWindow",
titleid: "home"
});
$.__views.contatosSearch = Ti.UI.createSearchBar({
hinttextid: "procurarText",
height: "50dp",
id: "contatosSearch",
showCancel: "false"
});
$.__views.homeWindow.add($.__views.contatosSearch);
$.__views.Btadd = Ti.UI.createButton({
top: "10dp",
width: "200dp",
height: "auto",
borderRadius: "10dp",
font: {
fontSize: "17dp"
},
title: L("adicionar"),
id: "Btadd"
});
$.__views.homeWindow.add($.__views.Btadd);
openAdd1 ? $.__views.Btadd.addEventListener("click", openAdd1) : __defers["$.__views.Btadd!click!openAdd1"] = true;
$.__views.tableviewContatos = Ti.UI.createTableView({
id: "tableviewContatos"
});
$.__views.homeWindow.add($.__views.tableviewContatos);
var __alloyId23 = Alloy.Collections["contato"] || contato;
__alloyId23.on("fetch destroy change add remove reset", __alloyId24);
maisDetalhes ? $.__views.tableviewContatos.addEventListener("click", maisDetalhes) : __defers["$.__views.tableviewContatos!click!maisDetalhes"] = true;
$.__views.homeTab = Ti.UI.createTab({
backgroundSelectedColor: "#C8C8C8 ",
backgroundFocusedColor: "#999",
icon: "/images/ic_home.png",
window: $.__views.homeWindow,
id: "homeTab",
titleid: "home"
});
$.__views.homeTab && $.addTopLevelView($.__views.homeTab);
exports.destroy = function() {
__alloyId23.off("fetch destroy change add remove reset", __alloyId24);
};
_.extend($, $.__views);
Alloy.Collections.contato.fetch();
var contatos = Alloy.Collections.contato;
contatos.fetch();
$.tableviewContatos.search = $.contatosSearch;
__defers["$.__views.Btadd!click!openAdd1"] && $.__views.Btadd.addEventListener("click", openAdd1);
__defers["$.__views.tableviewContatos!click!maisDetalhes"] && $.__views.tableviewContatos.addEventListener("click", maisDetalhes);
_.extend($, exports);
}
var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;
module.exports = Controller;
|
/**
* @license 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';
/**
* Expected Lighthouse audit values for redirects tests
*/
const cacheBuster = Number(new Date());
module.exports = [
{
initialUrl: `http://localhost:10200/online-only.html?delay=500&redirect=%2Foffline-only.html%3Fcb=${cacheBuster}%26delay=500%26redirect%3D%2Fredirects-final.html`,
url: 'http://localhost:10200/redirects-final.html',
audits: {
'redirects': {
score: '<100',
rawValue: '>=500',
details: {
items: {
length: 3,
},
},
},
},
},
{
initialUrl: `http://localhost:10200/online-only.html?delay=300&redirect=%2Fredirects-final.html`,
url: 'http://localhost:10200/redirects-final.html',
audits: {
'redirects': {
score: 100,
rawValue: '>=250',
details: {
items: {
length: 2,
},
},
},
},
},
];
|
describe("", function() {
var rootEl;
beforeEach(function() {
rootEl = browser.rootEl;
browser.get("build/docs/examples/example-example60/index.html");
});
it('should check ng-bind', function() {
var nameInput = element(by.model('name'));
expect(element(by.binding('name')).getText()).toBe('Whirled');
nameInput.clear();
nameInput.sendKeys('world');
expect(element(by.binding('name')).getText()).toBe('world');
});
});
|
import React from 'react';
import { action } from '@storybook/addon-actions';
import Checkbox from '.';
const onChange = action('onChange');
const defaultProps = {
id: 'id1',
onChange,
};
const intermediate = {
id: 'id2',
onChange,
intermediate: true,
};
const checked = {
id: 'id3',
onChange,
checked: true,
};
const disabled = {
id: 'id4',
onChange,
disabled: true,
};
const withLabel = {
id: 'id5',
onChange,
label: 'Some label',
};
export default {
title: 'Form/Controls/Checkbox',
};
export const Default = () => (
<div style={{ padding: 30 }}>
<h1>Checkbox</h1>
<h2>Definition</h2>
<p>The Checkbox component is basically a fancy checkbox like you have in your iphone</p>
<h2>Examples</h2>
<form>
<h3>Default Checkbox</h3>
<Checkbox {...defaultProps} />
<h3>
Checkbox with <code>intermediate: true</code>
</h3>
<Checkbox {...intermediate} />
<h3>
Checkbox with <code>checked: true</code>
</h3>
<Checkbox {...checked} />
<h3>
Checkbox with <code>disabled: true</code>
</h3>
<Checkbox {...disabled} />
<h3>
Checkbox with <code>label: Some label</code>
</h3>
<Checkbox {...withLabel} />
</form>
</div>
);
|
var editMode = portal.request.mode == 'edit';
var content = portal.content;
var component = portal.component;
var layoutRegions = portal.layoutRegions;
var body = system.thymeleaf.render('view/layout-70-30.html', {
title: content.displayName,
path: content.path,
name: content.name,
editable: editMode,
resourcesPath: portal.url.createResourceUrl(''),
component: component,
leftRegion: layoutRegions.getRegion("left"),
rightRegion: layoutRegions.getRegion("right")
});
portal.response.body = body;
portal.response.contentType = 'text/html';
portal.response.status = 200;
|
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
Ext.define("seava.ad.ui.extjs.frame.DateFormatMask_Ui", {
extend: "e4e.ui.AbstractUi",
alias: "widget.DateFormatMask_Ui",
/**
* Data-controls definition
*/
_defineDcs_: function() {
this._getBuilder_().addDc("mask", Ext.create(seava.ad.ui.extjs.dc.DateFormatMask_Dc,{multiEdit: true}))
;
},
/**
* Components definition
*/
_defineElements_: function() {
this._getBuilder_()
.addDcFilterFormView("mask", {name:"maskFilter", xtype:"ad_DateFormatMask_Dc$Filter"})
.addDcEditGridView("mask", {name:"maskEditList", xtype:"ad_DateFormatMask_Dc$EditList", frame:true})
.addPanel({name:"main", layout:"border", defaults:{split:true}});
},
/**
* Combine the components
*/
_linkElements_: function() {
this._getBuilder_()
.addChildrenTo("main", ["maskFilter", "maskEditList"], ["north", "center"])
.addToolbarTo("main", "tlbMaskList");
},
/**
* Create toolbars
*/
_defineToolbars_: function() {
this._getBuilder_()
.beginToolbar("tlbMaskList", {dc: "mask"})
.addTitle().addSeparator().addSeparator()
.addQuery().addSave().addCancel()
.addReports()
.end();
}
});
|
'use strict';
/**
* @ngdoc function
* @name freshcardUiApp.controller:TemplatesCtrl
* @description
* # TemplatesCtrl
* Controller of the freshcardUiApp
*/
angular.module('freshcardUiApp')
.controller('TemplatesCtrl', function (
$scope,
$rootScope,
$localStorage,
$filter,
$timeout,
FileUploader,
OrganizationService,
configuration
) {
$scope.templateLayoutSaved = false;
$scope.templateLayoutError = false;
$scope.templateLayoutPublished = false;
$scope.templateLayoutPublishError = false;
$scope.templateImagePath = $rootScope.currentOrganizationTemplate;
$scope.fields = [ false, false, false, false, false, false, false ];
$scope.fieldNames = [
'NAME',
'EMAIL_ADDRESS',
'STREET_ADDRESS',
'POSTAL_CODE',
'CITY',
'PHONE_NUMBER',
'WEBSITE'
];
$scope.fieldMappings = [
$filter('translate')('NAME'),
$filter('translate')('EMAIL_ADDRESS'),
$filter('translate')('STREET_ADDRESS'),
$filter('translate')('POSTAL_CODE'),
$filter('translate')('CITY'),
$filter('translate')('PHONE_NUMBER'),
$filter('translate')('WEBSITE')
];
$scope.showGrid = false;
$scope.snapToGrid = false;
$scope.fonts = [ 'Helvetica Neue', 'Open Sans', 'Helvetica', 'Arial', 'Times New Roman' ];
$scope.fontSizes = [ 14, 16, 18, 20, 24, 28 ];
$scope.selectedFont = $scope.fonts[0];
$scope.selectedFontSize = $scope.fontSizes[3];
$scope.templateLayout = { fields: { }, font: $scope.selectedFont, fontSize: $scope.selectedFontSize, showGrid: $scope.showGrid, snapToGrid: $scope.snapToGrid };
OrganizationService.get(
{
organizationId: $rootScope.user.currentOrganizationId
},
function(organization) {
if (organization.templateLayout) {
$scope.templateLayout = JSON.parse(organization.templateLayout);
$scope.selectedFont = $scope.templateLayout.font;
$scope.selectedFontSize = $scope.templateLayout.fontSize;
$scope.fields = [ false, false, false, false, false, false, false ];
for (var field in $scope.templateLayout.fields) {
for (var i = 0; i < $scope.fieldMappings.length; i++) {
if ($scope.fieldMappings[i] === $filter('translate')(field)) {
$scope.fields[i] = true;
}
}
}
}
}
);
var imageUploader = $scope.imageUploader = new FileUploader(
{
url: configuration.apiRootURL + 'api/v1/organizations/uploadTemplateImage/' + $rootScope.user.currentOrganizationId,
headers: {
'X-Auth-Token': $rootScope.authToken
}
}
);
imageUploader.onAfterAddingFile = function() {
$scope.imageUploadCompleted = false;
};
imageUploader.onCompleteItem = function(fileItem, response) {
if (response.imagePath !== null && response.imagePath !== undefined) {
$scope.templateImagePath = $localStorage.currentOrganizationTemplate = $rootScope.currentOrganizationTemplate = response.imagePath;
$scope.imageUploadCompleted = true;
}
};
$scope.saveTemplate = function() {
$scope.templateLayout.font = $scope.selectedFont;
$scope.templateLayout.fontSize = $scope.selectedFontSize;
var svgResult = $scope.canvas.toSVG();
for (var i = 0; i < $scope.fieldMappings.length; i++) {
svgResult = svgResult.replace($scope.fieldMappings[i], $scope.fieldNames[i]);
}
OrganizationService.update(
{
id: $rootScope.user.currentOrganizationId,
templateLayout: JSON.stringify($scope.templateLayout),
templateAsSVG: svgResult
},
function() {
$scope.templateLayoutPublished = false;
$scope.templateLayoutPublishError = false;
$scope.templateLayoutSaved = true;
$scope.templateLayoutError = false;
$timeout(
function() {
$scope.templateLayoutSaved = false;
},
5000
);
},
function() {
$scope.templateLayoutPublished = false;
$scope.templateLayoutPublishError = false;
$scope.templateLayoutSaved = false;
$scope.templateLayoutError = true;
}
);
};
$scope.publishTemplate = function() {
OrganizationService.publishTemplate(
{
id: $rootScope.user.currentOrganizationId
},
function() {
$scope.templateLayoutPublished = true;
$scope.templateLayoutPublishError = false;
$scope.templateLayoutSaved = false;
$scope.templateLayoutError = false;
$timeout(
function() {
$scope.templateLayoutPublished = false;
},
5000
);
},
function() {
$scope.templateLayoutPublished = false;
$scope.templateLayoutPublishError = true;
$scope.templateLayoutSaved = false;
$scope.templateLayoutError = false;
}
);
};
});
|
// NOTE: this file should only be included when embedding the inspector - no other files should be included (this will do everything)
// If gliEmbedDebug == true, split files will be used, otherwise the cat'ed scripts will be inserted
(function() {
var pathRoot = "";
var useDebug = window["gliEmbedDebug"];
// Find self in the <script> tags
var scripts = document.head.getElementsByTagName("script");
for (var n = 0; n < scripts.length; n++) {
var scriptTag = scripts[n];
var src = scriptTag.src.toLowerCase();
if (/core\/embed.js$/.test(src)) {
// Found ourself - strip our name and set the root
var index = src.lastIndexOf("embed.js");
pathRoot = scriptTag.src.substring(0, index);
break;
}
}
function insertHeaderNode(node) {
var targets = [ document.body, document.head, document.documentElement ];
for (var n = 0; n < targets.length; n++) {
var target = targets[n];
if (target) {
if (target.firstElementChild) {
target.insertBefore(node, target.firstElementChild);
} else {
target.appendChild(node);
}
break;
}
}
}
;
function insertStylesheet(url) {
var link = document.createElement("link");
link.rel = "stylesheet";
link.href = url;
insertHeaderNode(link);
return link;
}
;
function insertScript(url) {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = url;
insertHeaderNode(script);
return script;
}
;
if (useDebug) {
// Fall through below and use the loader to get things
} else {
var jsurl = pathRoot + "lib/gli.all.js";
var cssurl = pathRoot + "lib/gli.all.css";
window.gliCssUrl = cssurl;
insertStylesheet(cssurl);
insertScript(jsurl);
}
// Always load the loader
if (useDebug) {
var script = insertScript(pathRoot + "loader.js");
function scriptLoaded() {
gliloader.pathRoot = pathRoot;
if (useDebug) {
// In debug mode load all the scripts
gliloader.load([ "host", "replay", "ui" ]);
}
}
;
script.onreadystatechange = function() {
if (("loaded" === script.readyState || "complete" === script.readyState) && !script.loadCalled) {
this.loadCalled = true;
scriptLoaded();
}
};
script.onload = function() {
if (!script.loadCalled) {
this.loadCalled = true;
scriptLoaded();
}
};
}
// Hook canvas.getContext
var originalGetContext = HTMLCanvasElement.prototype.getContext;
if (!HTMLCanvasElement.prototype.getContextRaw) {
HTMLCanvasElement.prototype.getContextRaw = originalGetContext;
}
HTMLCanvasElement.prototype.getContext = function() {
var ignoreCanvas = this.internalInspectorSurface;
if (ignoreCanvas) {
return originalGetContext.apply(this, arguments);
}
var contextNames = [ "moz-webgl", "webkit-3d", "experimental-webgl", "webgl" ];
var requestingWebGL = contextNames.indexOf(arguments[0]) != -1;
if (requestingWebGL) {
// Page is requesting a WebGL context!
// TODO: something
}
var result = originalGetContext.apply(this, arguments);
if (result == null) {
return null;
}
if (requestingWebGL) {
// TODO: pull options from somewhere?
result = gli.host.inspectContext(this, result);
var hostUI = new gli.host.HostUI(result);
result.hostUI = hostUI; // just so we can access it later for
// debugging
}
return result;
};
})();
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
function getDecimals(n) {
n = n + '';
var i = n.indexOf('.');
return (i == -1) ? 0 : n.length - i - 1;
}
function getVF(n, opt_precision) {
var v = opt_precision;
if (undefined === v) {
v = Math.min(getDecimals(n), 3);
}
var base = Math.pow(10, v);
var f = ((n * base) | 0) % base;
return {v: v, f: f};
}
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u04d5\u043c\u0431\u0438\u0441\u0431\u043e\u043d\u044b \u0440\u0430\u0437\u043c\u04d5",
"\u04d5\u043c\u0431\u0438\u0441\u0431\u043e\u043d\u044b \u0444\u04d5\u0441\u0442\u04d5"
],
"DAY": [
"\u0445\u0443\u044b\u0446\u0430\u0443\u0431\u043e\u043d",
"\u043a\u044a\u0443\u044b\u0440\u0438\u0441\u04d5\u0440",
"\u0434\u044b\u0446\u0446\u04d5\u0433",
"\u04d5\u0440\u0442\u044b\u0446\u0446\u04d5\u0433",
"\u0446\u044b\u043f\u043f\u04d5\u0440\u04d5\u043c",
"\u043c\u0430\u0439\u0440\u04d5\u043c\u0431\u043e\u043d",
"\u0441\u0430\u0431\u0430\u0442"
],
"ERANAMES": [
"\u043d.\u0434.\u0430.",
"\u043d.\u0434."
],
"ERAS": [
"\u043d.\u0434.\u0430.",
"\u043d.\u0434."
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"\u044f\u043d\u0432\u0430\u0440\u044b",
"\u0444\u0435\u0432\u0440\u0430\u043b\u044b",
"\u043c\u0430\u0440\u0442\u044a\u0438\u0439\u044b",
"\u0430\u043f\u0440\u0435\u043b\u044b",
"\u043c\u0430\u0439\u044b",
"\u0438\u044e\u043d\u044b",
"\u0438\u044e\u043b\u044b",
"\u0430\u0432\u0433\u0443\u0441\u0442\u044b",
"\u0441\u0435\u043d\u0442\u044f\u0431\u0440\u044b",
"\u043e\u043a\u0442\u044f\u0431\u0440\u044b",
"\u043d\u043e\u044f\u0431\u0440\u044b",
"\u0434\u0435\u043a\u0430\u0431\u0440\u044b"
],
"SHORTDAY": [
"\u0445\u0446\u0431",
"\u043a\u0440\u0441",
"\u0434\u0446\u0433",
"\u04d5\u0440\u0442",
"\u0446\u043f\u0440",
"\u043c\u0440\u0431",
"\u0441\u0431\u0442"
],
"SHORTMONTH": [
"\u044f\u043d\u0432.",
"\u0444\u0435\u0432.",
"\u043c\u0430\u0440.",
"\u0430\u043f\u0440.",
"\u043c\u0430\u044f",
"\u0438\u044e\u043d\u044b",
"\u0438\u044e\u043b\u044b",
"\u0430\u0432\u0433.",
"\u0441\u0435\u043d.",
"\u043e\u043a\u0442.",
"\u043d\u043e\u044f.",
"\u0434\u0435\u043a."
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE, d MMMM, y '\u0430\u0437'",
"longDate": "d MMMM, y '\u0430\u0437'",
"medium": "dd MMM y '\u0430\u0437' HH:mm:ss",
"mediumDate": "dd MMM y '\u0430\u0437'",
"mediumTime": "HH:mm:ss",
"short": "dd.MM.yy HH:mm",
"shortDate": "dd.MM.yy",
"shortTime": "HH:mm"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "GEL",
"DECIMAL_SEP": ",",
"GROUP_SEP": "\u00a0",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "-\u00a4\u00a0",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "os",
"pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
angular.module('ssAuth').factory('SessionService', ['$http', '$cookies', '$q', function($http, $cookies, $q){
var currentUser = {};
var currentFetch;
currentUser.isAdmin = function() {
return currentUser && currentUser.groups && currentUser.groups['Admins'];
};
var getCurrentUser = function(forceUpdate) {
var deferred = $q.defer();
if(forceUpdate)
{
return fetchUpdatedUser();
}
if(currentUser.lastUpdated)
{
var diffMS = (new Date()).getTime() - new Date(currentUser.lastUpdated).getTime();
var diffMin = ((diffMS/60)/60);
if(diffMin < 5)
{
deferred.resolve(currentUser);
return deferred.promise;
}
}
return fetchUpdatedUser();
};
var restoreFromCookie = function() {
var cookie = $cookies['ag-user'];
if(!cookie)
return;
var user = JSON.parse(cookie);
angular.extend(currentUser, user);
return currentUser;
};
var saveToCookie = function() {
$cookies['ag-user'] = JSON.stringify(currentUser);
};
var fetchUpdatedUser = function() {
//we've already made a call for the current user
//just hold your horses
if(currentFetch) {
return currentFetch;
}
var deferred = $q.defer();
currentFetch = deferred.promise;
$http.get('/session').success(function(user){
angular.extend(currentUser, user);
currentUser.lastUpdated = new Date();
saveToCookie();
deferred.resolve(currentUser);
currentFetch = undefined;
});
return deferred.promise;
};
return {
getCurrentUser: getCurrentUser,
restore: restoreFromCookie,
userUpdated: currentUser.lastUpdated
};
}]);
|
/**
* @license 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';
/* eslint-env mocha */
const OptimizedImages =
require('../../../../gather/gatherers/dobetterweb/optimized-images');
const assert = require('assert');
let options;
let optimizedImages;
const fakeImageStats = {
jpeg: {base64: 100, binary: 80},
webp: {base64: 80, binary: 60},
};
const traceData = {
networkRecords: [
{
_url: 'http://google.com/image.jpg',
_mimeType: 'image/jpeg',
_resourceSize: 10000,
_resourceType: {_name: 'image'},
finished: true,
},
{
_url: 'http://google.com/transparent.png',
_mimeType: 'image/png',
_resourceSize: 11000,
_resourceType: {_name: 'image'},
finished: true,
},
{
_url: 'http://google.com/image.bmp',
_mimeType: 'image/bmp',
_resourceSize: 12000,
_resourceType: {_name: 'image'},
finished: true,
},
{
_url: 'http://google.com/image.bmp',
_mimeType: 'image/bmp',
_resourceSize: 12000,
_resourceType: {_name: 'image'},
finished: true,
},
{
_url: 'http://google.com/vector.svg',
_mimeType: 'image/svg+xml',
_resourceSize: 13000,
_resourceType: {_name: 'image'},
finished: true,
},
{
_url: 'http://gmail.com/image.jpg',
_mimeType: 'image/jpeg',
_resourceSize: 15000,
_resourceType: {_name: 'image'},
finished: true,
},
{
_url: 'data: image/jpeg ; base64 ,SgVcAT32587935321...',
_mimeType: 'image/jpeg',
_resourceType: {_name: 'image'},
_resourceSize: 14000,
finished: true,
},
{
_url: 'http://google.com/big-image.bmp',
_mimeType: 'image/bmp',
_resourceType: {_name: 'image'},
_resourceSize: 12000,
finished: false, // ignore for not finishing
},
{
_url: 'http://google.com/not-an-image.bmp',
_mimeType: 'image/bmp',
_resourceType: {_name: 'document'}, // ignore for not really being an image
_resourceSize: 12000,
finished: true,
},
],
};
describe('Optimized images', () => {
// Reset the Gatherer before each test.
beforeEach(() => {
optimizedImages = new OptimizedImages();
options = {
url: 'http://google.com/',
driver: {
evaluateAsync: function() {
return Promise.resolve(fakeImageStats);
},
sendCommand: function() {
return Promise.reject(new Error('wasn\'t found'));
},
},
};
});
it('returns all images', () => {
return optimizedImages.afterPass(options, traceData).then(artifact => {
assert.equal(artifact.length, 4);
assert.ok(/image.jpg/.test(artifact[0].url));
assert.ok(/transparent.png/.test(artifact[1].url));
assert.ok(/image.bmp/.test(artifact[2].url));
// skip cross-origin for now
// assert.ok(/gmail.*image.jpg/.test(artifact[3].url));
assert.ok(/data: image/.test(artifact[3].url));
});
});
it('computes sizes', () => {
const checkSizes = (stat, original, webp, jpeg) => {
assert.equal(stat.originalSize, original);
assert.equal(stat.webpSize, webp);
assert.equal(stat.jpegSize, jpeg);
};
return optimizedImages.afterPass(options, traceData).then(artifact => {
assert.equal(artifact.length, 4);
checkSizes(artifact[0], 10000, 60, 80);
checkSizes(artifact[1], 11000, 60, 80);
checkSizes(artifact[2], 12000, 60, 80);
// skip cross-origin for now
// checkSizes(artifact[3], 15000, 60, 80);
checkSizes(artifact[3], 20, 80, 100); // uses base64 data
});
});
it('handles partial driver failure', () => {
let calls = 0;
options.driver.evaluateAsync = () => {
calls++;
if (calls > 2) {
return Promise.reject(new Error('whoops driver failed'));
} else {
return Promise.resolve(fakeImageStats);
}
};
return optimizedImages.afterPass(options, traceData).then(artifact => {
const failed = artifact.find(record => record.failed);
assert.equal(artifact.length, 4);
assert.ok(failed, 'passed along failure');
assert.ok(/whoops/.test(failed.err.message), 'passed along error message');
});
});
it('supports Audits.getEncodedResponse', () => {
options.driver.sendCommand = (method, params) => {
const encodedSize = params.encoding === 'webp' ? 60 : 80;
return Promise.resolve({encodedSize});
};
return optimizedImages.afterPass(options, traceData).then(artifact => {
assert.equal(artifact.length, 5);
assert.equal(artifact[0].originalSize, 10000);
assert.equal(artifact[0].webpSize, 60);
assert.equal(artifact[0].jpegSize, 80);
// supports cross-origin
assert.ok(/gmail.*image.jpg/.test(artifact[3].url));
});
});
});
|
// TODO split modules, controllers, services
// info separate files and concat/uglify them
let remote = require('remote')
let fs = require('fs')
let mysql = require('promise-mysql')
let app = angular.module('ttableinstaller', ['ngRoute'])
photon.start(document)
app.config(($routeProvider) => {
$routeProvider
.when('/', {
templateUrl: 'templates/main.html',
controller: 'MainController'
})
.otherwise({
redirectTo: '/'
})
})
|
app.controller('PickerController', function ($scope, $modalInstance, itemColor) {
$scope.showCarrierColors = true;
$scope.brandColors = [
{
name: 'Brand Blue',
hex: '#276681'
},
{
name: 'Brand Green',
hex: '#66b245'
},
{
name: 'Brand Blue Desaturated',
hex: '#417c95'
},
{
name: 'Brand Green Desaturated',
hex: '#75b86f'
},
{
name: 'Bluest',
hex: '#5baebf'
},
{
name: 'Blue',
hex: '#66b7bb'
},
{
name: 'Blue Green',
hex: '#76beb6'
},
{
name: 'Green Blue',
hex: '#84c6ae'
},
{
name: 'Green',
hex: '#96cca7'
},
{
name: 'Greenest',
hex: '#a4d49a'
},
{
name: 'Level 2 Blend',
hex: '#7fced8'
},
{
name: 'Level 2 Blend',
hex: '#8fd4d6'
},
{
name: 'Level 2 Blend',
hex: '#a5d7d3'
},
{
name: 'Level 2 Blend',
hex: '#b5dcce'
},
{
name: 'Level 2 Blend',
hex: '#bfe0ca'
},
{
name: 'Level 2 Blend',
hex: '#c8e5c2'
},
{
name: 'Level 3 Blend',
hex: '#b0e2e7'
},
{
name: 'Level 3 Blend',
hex: '#bce5e6'
},
{
name: 'Level 3 Blend',
hex: '#c8e6e4'
},
{
name: 'Level 3 Blend',
hex: '#d3eae2'
},
{
name: 'Level 3 Blend',
hex: '#d8ecdf'
},
{
name: 'Level 3 Blend',
hex: '#ddefda'
},
{
name: 'Illustration Stroke Darkest',
hex: '#54636a'
},
{
name: 'Illustration Stroke Medium',
hex: '#7f8a8f'
},
{
name: 'Illustration Stroke Light',
hex: '#a9b1b4'
},
{
name: 'Illustration Stroke Lightest',
hex: '#d4d8da'
},
{
name: 'Yellow',
hex: '#f5db77'
},
{
name: 'Medium Yellow',
hex: '#f8e499'
},
{
name: 'Light Yellow',
hex: '#faedbb'
},
{
name: 'Lightest Yellow',
hex: '#fdf6dd'
},
{
name: 'Tang',
hex: '#f38871'
},
{
name: 'Medium Tang',
hex: '#f7a593'
},
{
name: 'Light Tang',
hex: '#fbc1b4'
},
{
name: 'Lightest Tang',
hex: '#ffded6'
},
{
name: 'Black',
hex: '#555555'
},
{
name: 'Dark Gray',
hex: '#797979'
},
{
name: 'Medium Gray',
hex: '#9c9c9c'
},
{
name: 'Light Gray',
hex: '#c0c0c0'
},
{
name: 'Lightest Gray',
hex: '#e3e3e3'
},
{
name: 'Off White',
hex: '#f9f9f9'
}
];
$scope.carrierColors = [
{
carrier: 'Verizon',
hex: '#ca5b59'
},
{
carrier: 'AT&T',
hex: '#5694b4'
},
{
carrier: 'T-Mobile',
hex: '#d45da0'
},
{
carrier: 'Sprint',
hex: '#e9b444'
},
{
carrier: 'Cricket',
hex: '#008752'
},
{
carrier: 'Cricket',
hex: '#439474'
},
{
carrier: 'MetroPCS',
hex: '#6764b3'
},
{
carrier: 'EE',
hex: '#2e9a9c'
},
{
carrier: 'O2',
hex: '#2566a8'
},
{
carrier: 'Orange',
hex: '#ff6c42'
},
{
carrier: 'Three',
hex: '#333333'
},
{
carrier: 'Vodafone',
hex: '#eb5247'
},
{
carrier: 'Bell',
hex: '#2876a5'
},
{
carrier: 'Leap',
hex: '#330066'
},
{
carrier: 'Rogers',
hex: '#d63e3e'
},
{
carrier: 'Telus',
hex: '#4e5cb5'
},
{
carrier: 'Videotron',
hex: '#fcc622'
},
{
carrier: 'Wind',
hex: '#ec7c23'
},
{
carrier: 'Tie',
hex: '#999999'
}
]
$scope.ok = function () {
$modalInstance.close(itemColor);
};
$scope.closeModal = function(color) {
$modalInstance.close(color);
}
});
|
app.service('UserService', ['$http', function($http) {
return {
getLogged: function(successCallback) {
$http.get('/api/user/logged').then(successCallback);
},
putPin: function(user, successCallback) {
$http.post('/api/user/pin/', user).then(successCallback);
}
};
}]);
|
//*************************************************************
// Filename: socket.js
//
// Author: Jake Higgins <jth7036@rit.edu>
//*************************************************************
var Socket;
function addSocketListeners() {
Socket = new io();
Socket.on('sync objects', function(objects, room, caller) {
console.log(objects);
if(CallerID == caller) {
console.log(objects);
$.each(objects, function(key, object) {
createStroke(object);
});
CanvasManager.render();
}
});
Socket.on('add object', function(object, room, caller) {
if(CallerID != caller && RoomID == room) {
createStroke(object);
CanvasManager.clearCanvas();
}
});
Socket.on('move object', function(object, room, caller) {
console.log('move object');
if(CallerID != caller && RoomID == room) {
var targetObj = ObjectManager.findObject(object.objectID);
console.log(targetObj);
if(targetObj != null) {
targetObj.max = object.max;
targetObj.min = object.min;
$(targetObj.container).css({
top: targetObj.min.y,
left: targetObj.min.x
});
}
}
});
Socket.on('delete object', function(object, room, caller) {
if(CallerID != caller && RoomID == room)
{
ObjectManager.deleteObject(object.objectID);
}
});
Socket.on('clear objects', function(room, caller) {
console.log('clear');
if(CallerID != caller && RoomID == room) {
CanvasManager.clear(true);
}
});
Socket.on('draw', function(drawData, room, caller) {
if(CallerID != caller && RoomID == room) {
Drawing.draw(drawData, true);
}
});
// ======== Chat =============/
// Comes in the format message/roomID/caller
// if(roomID == this.roomID) // pseudocode for now
// add chat to chat thingy
Socket.on('receiveMessage', function(message, room, caller)
{
if ( RoomID == room )
{
// Proceed
Chat.write(message, caller);
}
});
}
function createStroke(stroke) {
console.log(stroke);
var obj = new object("stroke");
obj.initialize();
obj.imageData = stroke.imageData;
obj.layer = stroke.layer;
obj.max = stroke.max;
obj.min = stroke.min;
obj.objectID = stroke.objectID;
obj.type = "stroke";
obj.objectData = {
imageData: obj.imageData,
layer: obj.layer,
max: obj.max,
min: obj.min,
objectID: obj.objectID,
objectType: obj.type,
};
obj.createImage();
ObjectManager.addObject(obj);
}
|
/**
* Created by raj on 19/8/14.
*/
var fs = require('fs');
var content = fs.read ('animeEpisode.json');
console.log(JSON.stringify(JSON.parse(content)[1][0].title));
videolinks=JSON.parse(content);
links=[];
function pages(k) {
var page = new WebPage();
page.open('http://www.gogoanime.com/', function (status) {
console.log('opened gogoanime :++++ ', status);
if (status==fail){
page.close();
pages(k);
}
if (status == success) {
page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function () {
console.log('jq included')
var data = page.evaluate(function (data) {
var tempdata=[];
for (var i = 0; i <$('.post div:eq(1) table tbody tr td:eq(0) ul').length; i = i + 1) {
data.links.push($('.post div:eq(1) table tbody tr td:eq(0) ul li a').attr('href'));
}
return JSON.stringify(data);
});
links[k][m] = JSON.parse(data);
console.log(data);
if (m < links[k].length - 1) {
page.close();
console.log('next episoide called');
pages(k, m + 1);
}
;
if (m == links[k].length - 1) {
page.close();
console.log('next anime called');
var path = 'links.json';
fs.write(path, links[k], 'w');
pages(k + 1, 1);
}
if (k == links.length - 1) {
var path = 'links.json';
fs.write(path, links, 'w');
}
});
}
});
}
pages(1,1);
|
var a02307 =
[
[ "GenericVector", "a02307.html#a60d42eebf02708482a8b506edd417990", null ],
[ "GenericVector", "a02307.html#a28a69767bcadb6058a2a9df4afecd5fc", null ],
[ "GenericVector", "a02307.html#a2b61cd1cd756770518f5ac30f817a9bf", null ],
[ "~GenericVector", "a02307.html#a49840c8743a063b87839baef7e19b968", null ],
[ "back", "a02307.html#a48b82547ebbaa5fedecfdebe7e2f155a", null ],
[ "binary_search", "a02307.html#ad561e19e75a0fb30f0118774d7fa5621", null ],
[ "bool_binary_search", "a02307.html#a8c261f66a24da67aac1acca7aa8f650a", null ],
[ "choose_nth_item", "a02307.html#a5c4218ef833d0fe5db9b9749abd81ea5", null ],
[ "choose_nth_item", "a02307.html#ae1e555b0cdded2c36dd6cf15345f659f", null ],
[ "clear", "a02307.html#a9cdbff49b186574b83e43afba606fdd9", null ],
[ "compact", "a02307.html#a080f7786e007523bcaa3f69913a82882", null ],
[ "compact_sorted", "a02307.html#a8cb22ff55d6dd125d93cd03fd73bf8ad", null ],
[ "contains", "a02307.html#a997e0fcaaa6b6533401dc54c0691e2e5", null ],
[ "contains_index", "a02307.html#ac1aae0b1c22248f264dad02481123398", null ],
[ "delete_data_pointers", "a02307.html#a98f62dccd75224a60437c2761bd215cd", null ],
[ "DeSerialize", "a02307.html#aa4f5b1bc0d044fbd1fc77363b798c39c", null ],
[ "DeSerialize", "a02307.html#a2e4fca9599eff590b76affc0a0aa0a2b", null ],
[ "DeSerializeClasses", "a02307.html#a698ebd328d22f1edc114053ca2eba48e", null ],
[ "DeSerializeClasses", "a02307.html#ade729c7d5429fbd5be304e3493a8a95f", null ],
[ "dot_product", "a02307.html#a6f6dfbc607499173e7809656c6c505bc", null ],
[ "double_the_size", "a02307.html#af0214c8c21da9eb57dfebc78611d0cd6", null ],
[ "empty", "a02307.html#a172c4aa23ba397e24319ae095281cbcc", null ],
[ "get", "a02307.html#abd0a875f98a1d78613ed3521d96e5300", null ],
[ "get_index", "a02307.html#a6dee574daf4a3d4f0fc7048964f8f252", null ],
[ "init", "a02307.html#a5b010723588fe15f303e4f3474d8479e", null ],
[ "init_to_size", "a02307.html#a6751521fd3eb461d81fc83ef93a0def3", null ],
[ "insert", "a02307.html#a57ca5259541548a97bcfd4d0925a27ff", null ],
[ "length", "a02307.html#a6af4e0a2a30dda267d19bf783ae22eb7", null ],
[ "move", "a02307.html#abae057ce589be25aae9b80958f84e34c", null ],
[ "operator+=", "a02307.html#af73fadcdb08f0a12a5615f2bcf6fa6a8", null ],
[ "operator+=", "a02307.html#acc7df2256174b32632e4d5b6c8d05d29", null ],
[ "operator=", "a02307.html#af6fd5b3891b276c10add96f9411bec05", null ],
[ "operator[]", "a02307.html#afd51f3f981284adb20bdf3b0bfd1c1f7", null ],
[ "pop_back", "a02307.html#a0621dd57ce58dae3cb5f3d61e76bd233", null ],
[ "push_back", "a02307.html#a0dc89fe2a365b04a61017f9d78c1a303", null ],
[ "push_back_new", "a02307.html#a393f9f8dcc55ad759a5c7fbdc4840a89", null ],
[ "push_front", "a02307.html#ae08e7cece0097ad356b5e565cbb2cf0b", null ],
[ "read", "a02307.html#a10a273cab07e56c1654b2167f8aa9408", null ],
[ "remove", "a02307.html#a3fd37a240a42f1c3052e8d28614d3702", null ],
[ "reserve", "a02307.html#aa225ea3fc9374961482bc804028317eb", null ],
[ "resize_no_init", "a02307.html#a09005e8f2b51d033d60eb5690aa5d112", null ],
[ "reverse", "a02307.html#a58f6d73009cc3c56d0efb0d96ad35b5b", null ],
[ "Serialize", "a02307.html#a206a6fe71c3780d862d97ef7c5fc9546", null ],
[ "Serialize", "a02307.html#a3e994fd938468ff4fc4b4a902e970876", null ],
[ "SerializeClasses", "a02307.html#ad0e8164e4c5c82e9e367c8a6d9b755b1", null ],
[ "SerializeClasses", "a02307.html#a7d0060c687429049a0ea5cf21d067b8e", null ],
[ "set", "a02307.html#a067b7833ee66238b7b5e230404525fcb", null ],
[ "set_clear_callback", "a02307.html#af2bbca5b3258035a333b62679835a253", null ],
[ "set_compare_callback", "a02307.html#aa3ec670c7f68a95f84641a0ded8cb61f", null ],
[ "size", "a02307.html#a20cfad5c58c50cb85a9529d8ddbd96af", null ],
[ "size_reserved", "a02307.html#a1c273622446ec7b5a6669fa9c9fdd8e5", null ],
[ "sort", "a02307.html#a999bbd8ff336c81fe1198ea714c7936d", null ],
[ "sort", "a02307.html#a461142d4ff7c61f22119552b7c0b2755", null ],
[ "swap", "a02307.html#ac10b1de04fdfd4f5e4b90ac6d03f35b9", null ],
[ "truncate", "a02307.html#a980882b5ebc3e72fdedbdbe345196f21", null ],
[ "unsigned_size", "a02307.html#a47bd2385b28d536e8b6e87b689d61ede", null ],
[ "WithinBounds", "a02307.html#a367914d03777eef59176d48155d06b72", null ],
[ "write", "a02307.html#a8745d1d8394e852d12398d0458684dee", null ],
[ "clear_cb_", "a02307.html#a57a833bdcc07a53e9a7b57d07cac2131", null ],
[ "compare_cb_", "a02307.html#acd69761952fb39cbe7d7b43a6b06a432", null ],
[ "data_", "a02307.html#ab88657a46d06c175dcfc76c0fcdaac7d", null ],
[ "size_reserved_", "a02307.html#a4a02eb2a4ed31e8454cd8ae06eb8d7c5", null ],
[ "size_used_", "a02307.html#a99185b084a6ace7536818ce2f17b11fb", null ]
];
|
var crypto = require("crypto"),
Request = require("./../request"),
Response = require("./../response");
module.exports = sessionCookie;
/**
* A middleware for storing and retrieving session data using HTTP cookies.
* The `options` may be any of the following:
*
* - secret A secret string to use to verify the cookie's contents,
* defaults to `null`. If this is set the session's contents
* will be cleared if the cookie has been tampered with
* - name The name of the cookie, defaults to "strata.session"
* - path The path of the cookie, defaults to "/"
* - domain The cookie's domain, defaults to `null`
* - expireAfter A number of seconds after which this cookie will expire,
* defaults to `null`
* - secure True to only send this cookie over HTTPS, defaults to `false`
* - httpOnly True to only send this cookie over HTTP, defaults to `true`
*/
function sessionCookie(app, options) {
var readSession = sessionCookieReader(options);
var writeSession = sessionCookieWriter(options);
return function (env, callback) {
if (env.session) {
app(env, callback);
return;
}
readSession(env, function (err, session) {
if (err) {
env.session = {};
} else {
env.session = session;
}
app(env, function (status, headers, body) {
var res = new Response(body, headers, status);
writeSession(env, res);
res.send(callback);
});
});
}
}
function sessionCookieReader(options) {
options = sessionCookieOptions(options);
return function readSessionCookie(env, callback) {
var req = new Request(env);
req.cookies(function (err, cookies) {
if (err) {
callback(err, cookies);
return;
}
var cookie = cookies[options.name];
if (cookie) {
cookie = new Buffer(cookie, "base64").toString("utf8");
var parts = cookie.split("--"),
data = parts[0],
digest = parts[1];
if (digest === sessionDigest(data, options.secret)) {
try {
callback(null, JSON.parse(data));
return;
} catch (e) {
// The cookie does not contain valid JSON.
callback(e, {});
return;
}
}
}
callback(null, {});
});
}
}
function sessionCookieWriter(options) {
options = sessionCookieOptions(options);
return function writeSessionCookie(env, res) {
var session = env.session;
if (session) {
var data = JSON.stringify(session);
var digest = sessionDigest(data, options.secret);
var cookie = new Buffer(data + "--" + digest, "utf8").toString("base64");
if (cookie.length > 4096) {
env.error.write("Session cookie data size exceeds 4k; content dropped\n");
return;
}
var cookieOptions = {
value: cookie,
path: options.path,
domain: options.domain,
secure: options.secure,
httpOnly: options.httpOnly
};
if (options.expireAfter) {
// expireAfter is given in seconds.
var expires = new Date().getTime() + (options.expireAfter * 1000);
cookieOptions.expires = new Date(expires);
}
res.setCookie(options.name, cookieOptions);
}
}
}
function sessionDigest(data, secret) {
var shasum = crypto.createHash("sha1");
shasum.update(data);
if (secret) {
shasum.update(secret);
}
return shasum.digest("hex");
}
/**
* Creates a new options object from the given session cookie `options` with
* sane defaults.
*/
function sessionCookieOptions(options) {
options = options || {};
var opts = {
secret: options.secret || null,
name: options.name || "strata.session",
path: options.path || "/",
domain: options.domain || null,
expireAfter: options.expireAfter || null,
secure: options.secure || false
};
if ("httpOnly" in options) {
opts.httpOnly = options.httpOnly || false;
} else {
opts.httpOnly = true;
}
return opts;
}
|
// Diamond-in-the-Rough
// Code Wars program written in JavaScript for the RingoJS environment
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Lee Jenkins
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
var stdin = require("system").stdin;
var stdout = require("system").stdout;
"use strict";
(function SpiralTriangles() {
function run() {
var inputData = readDiamondInfo();
while( inputData.size > 0 ) {
printDiamonds( inputData );
inputData = readDiamondInfo();
}
};
function printDiamonds( inputData ) {
var midSize = inputData.size / 2;
for( var gridRow=0; gridRow<inputData.rows; ++gridRow ) {
for( var diamondRow=0; diamondRow<inputData.size; ++diamondRow ) {
var line = "";
for( var gridCol=0; gridCol<inputData.cols; ++gridCol ) {
for( var diamondCol=0; diamondCol<inputData.size; ++diamondCol ) {
var c = "#";
if( diamondRow < midSize ) { // top half
if( diamondCol >= (midSize-(diamondRow+1)) && diamondCol < midSize ) {
c = "/";
}
else if( diamondCol >= midSize && diamondCol <= (midSize+diamondRow) ) {
c = "\\";
}
}
else { // bottom half
if( diamondCol >= (diamondRow-midSize) && diamondCol < midSize ) {
c = "\\";
}
else if( diamondCol >= midSize && diamondCol < (inputData.size+midSize-diamondRow) ) {
c = "/";
}
}
line += c;
}
}
print( line );
}
}
};
function readDiamondInfo() {
var tokens = stdin.readLine().split(/\s+/);
return {
size: parseInt( tokens[0] ),
rows: parseInt( tokens[1] ),
cols: parseInt( tokens[2] )
};
};
run();
}) ();
|
/**
* @private
* @providesModule CustomTabsAndroid
* @flow
*/
'use strict';
import { NativeModules } from 'react-native';
import type { TabOption } from './TabOption';
const CustomTabsManager = NativeModules.CustomTabsManager;
/**
* To open the URL of the http or https in Chrome Custom Tabs.
* If Chrome is not installed, opens the URL in other browser.
*/
export default class CustomTabsAndroid {
/**
* Opens the URL on a Custom Tab.
*
* @param url the Uri to be opened.
* @param option the Option to customize Custom Tabs of look & feel.
*/
static openURL(url: string, option: TabOption = {}): Promise<boolean> {
return CustomTabsManager.openURL(url, option)
}
}
|
/**
* Copyright 2019, Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const functions = require('firebase-functions');
const { google } = require('googleapis');
const { firestore } = require('../admin');
/**
* Return a Promise to obtain the device from Cloud IoT Core
*/
function getDevice(client, deviceId) {
return new Promise((resolve, reject) => {
const projectId = process.env.GCLOUD_PROJECT;
const parentName = `projects/${projectId}/locations/${functions.config().cloudiot.region}`;
const registryName = `${parentName}/registries/${functions.config().cloudiot.registry}`;
const request = {
name: `${registryName}/devices/${deviceId}`
};
client.projects.locations.registries.devices.get(request, (err, resp) => {
if (err) {
return reject(err);
} else {
resolve(resp.data);
}
});
});
}
/**
* Validate that the public key provided by the pending device matches
* the key currently stored in IoT Core for that device id.
*
* Method throws an error if the keys do not match.
*/
function verifyDeviceKey(pendingDevice, deviceKey) {
// Convert the pending key into PEM format
const chunks = pendingDevice.public_key.match(/(.{1,64})/g);
chunks.unshift('-----BEGIN PUBLIC KEY-----');
chunks.push('-----END PUBLIC KEY-----');
const pendingKey = chunks.join('\n');
if (deviceKey !== pendingKey) throw new Error(`Public Key Mismatch:\nExpected: ${deviceKey}\nReceived: ${pendingKey}`);
}
/**
* Cloud Function: Verify IoT device and add to user
*/
module.exports = functions.firestore.document('pending/{device}').onWrite(async (change, context) => {
const deviceId = context.params.device;
// Verify this is either a create or update
if (!change.after.exists) {
console.log(`Pending device removed for ${deviceId}`);
return;
}
console.log(`Pending device created for ${deviceId}`);
const pending = change.after.data();
// Create a new Cloud IoT client
const auth = await google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/cloud-platform']
});
const client = google.cloudiot({
version: 'v1',
auth: auth
});
try {
// Verify device does NOT already exist in Firestore
const deviceRef = firestore.doc(`devices/${deviceId}`);
const deviceDoc = await deviceRef.get();
if (deviceDoc.exists) throw new Error(`${deviceId} is already registered to another user`);
// Verify device exists in IoT Core
const result = await getDevice(client, deviceId);
// Verify the device public key
verifyDeviceKey(pending, result.credentials[0].publicKey.key.trim());
// Verify the device type
let configValue = null;
switch (pending.type) {
case 'light':
configValue = require('./default-light.json');
break;
case 'thermostat':
configValue = require('./default-thermostat.json');
break;
default:
throw new Error(`Invalid device type found in ${deviceId}: ${pending.type}`);
}
// Commit the following changes together
const batch = firestore.batch();
// Insert valid device for the requested owner
const device = {
name: pending.serial_number,
owner: pending.owner,
type: pending.type,
online: false
};
batch.set(deviceRef, device);
// Generate a default configuration
const configRef = firestore.doc(`device-configs/${deviceId}`);
const config = {
owner: pending.owner,
value: configValue
};
batch.set(configRef, config);
// Remove the pending device entry
batch.delete(change.after.ref);
await batch.commit();
console.log(`Added device ${deviceId} for user ${pending.owner}`);
} catch (error) {
// Device does not exist in IoT Core or key doesn't match
console.error('Unable to register new device', error);
}
});
|
var assert = require("assert"),
expect = require('expect.js'),
cda = require("../utils/xml.js").cda,
DOMParser = require('xmldom').DOMParser,
XmlSerializer = require('xmldom').XMLSerializer,
xmlUtils = require("../utils/xml.js").xml,
FunctionalStatusSectionCreator = require("../Model/FunctionalStatusSection.js"),
FunctionalStatusEntryCreator = require("../Model/FunctionalStatusEntry.js"),
FunctionalStatusPainScaleEntryCreator = require("../Model/FunctionalStatusPainScaleEntry.js"),
Σ = xmlUtils.CreateNode,
A = xmlUtils.CreateAttributeWithNameAndValue,
adapter = require("../CDA/ModeltoCDA.js").cda;
var createMockEntry = function(num) {
var entry = FunctionalStatusEntryCreator.create();
entry.Name = "Name " + num;
entry.Value = "Value " + num;
entry.EffectiveTime = new Date().toString();
return entry;
};
var createMockPainScaleEntry = function (num) {
var entry = FunctionalStatusPainScaleEntryCreator.create();
entry.id = num;
entry.PainScore = 1;
entry.PainScoreEffectiveTime = '2/1/2013';
return entry;
};
describe("Build Functional Status Section.", function() {
it("Should be able to generate an entry for each type.", function() {
var e = new adapter.FunctionalStatusSection();
var document = new DOMParser().parseFromString("<?xml version='1.0' standalone='yes'?><ClinicalDocument xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xsi:schemaLocation='urn:hl7-org:v3 CDA/infrastructure/cda/CDA_SDTC.xsd' xmlns='urn:hl7-org:v3' xmlns:cda='urn:hl7-org:v3' xmlns:sdtc='urn:hl7-org:sdtc'></ClinicalDocument>", "text/xml");
var section = FunctionalStatusSectionCreator.create();
section.Capabilities.push(createMockEntry(1));
section.Cognitions.push(createMockEntry(1));
section.DailyLivings.push(createMockEntry(1));
section.PainScales.push(createMockPainScaleEntry(1));
var cdaAdapter = new adapter.FunctionalStatusSection();
var node = cdaAdapter.BuildAll(section, document);
assert.equal(node.getElementsByTagName("title")[0].childNodes[0].nodeValue, "FUNCTIONAL STATUS");
assert.equal(node.getElementsByTagName("templateId")[0].getAttributeNode("root").value, "2.16.840.1.113883.10.20.22.2.14");
assert.equal(node.getElementsByTagName("code")[0].getAttributeNode("code").value, "47420-5");
//var output = new XmlSerializer().serializeToString(node);
//console.log(output);
});
});
|
'use strict';
goog.provide('Blockly.JavaScript.serial');
goog.require('Blockly.JavaScript');
Blockly.JavaScript.serial_print = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"'
var code = 'serial.writeString(\'\' + '+content+');\n';
return code;
};
Blockly.JavaScript.serial_println = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '\"\"'
var code = 'serial.writeLine(\'\' + '+content+');\n';
return code;
};
Blockly.JavaScript.serial_print_hex = function() {
var content = Blockly.JavaScript.valueToCode(this, 'CONTENT', Blockly.JavaScript.ORDER_ATOMIC) || '0';
var code = 'serial.writeLine('+content+'.toString(16));\n';
return code;
};
Blockly.JavaScript.serial_receive_data_event = function() {
var char_marker = Blockly.JavaScript.valueToCode(this, 'char_marker', Blockly.JavaScript.ORDER_ATOMIC) || ';';
var branch = Blockly.JavaScript.statementToCode(this, 'DO');
Blockly.JavaScript.definitions_['func_serial_receive_data_event_' + char_marker.charCodeAt(1)] = "serial.onDataReceived(" + char_marker + ", () => {\n" + branch + "};\n";
};
Blockly.JavaScript.serial_readstr = function() {
var code ="serial.readString()";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_readline = function() {
var code ="serial.readLine()";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_readstr_until = function() {
var char_marker = this.getFieldValue('char_marker');
var code ="serial.readUntil("+char_marker + ")";
return [code,Blockly.JavaScript.ORDER_ATOMIC];
};
Blockly.JavaScript.serial_softserial = function () {
var dropdown_pin1 = Blockly.JavaScript.valueToCode(this, 'RX',Blockly.JavaScript.ORDER_ATOMIC);
var dropdown_pin2 = Blockly.JavaScript.valueToCode(this, 'TX',Blockly.JavaScript.ORDER_ATOMIC);
var baudrate = this.getFieldValue('baudrate');
return "serial.redirect(" + dropdown_pin1 + ", " + dropdown_pin2 + ", BaudRate.BaudRate" + baudrate + ");\n";
};
|
/*jslint browser: true*/
/*global $, jQuery, alert*/
(function ($) {
"use strict";
$(document).ready(function () {
$("input[name=dob]").datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
showOtherMonths: true
});
});
$(document).ready(function () {
$("input[name='rep_password']").focusout(function () {
var p1 = $('input[name="password"]').val(), p2 = $('input[name="rep_password"]').val();
if (p1 !== p2) {
$('#passDM').show(300);
} else if (p1 === "") {
$('#passDM').show(300);
} else {
$('#passDM').hide(300);
}
});
});
$(document).ready(function () {
$("input[name=password]").focusin(function () {
$('#passDM').hide(300);
});
$("input[name=rep_password]").focusin(function () {
$('#passDM').hide(300);
});
});
}(jQuery));
|
/* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'chapter4-components',
environment: environment,
baseURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
contentSecurityPolicy: {
'default-src': "'none'",
'script-src': "'self' 'unsafe-inline' 'unsafe-eval' *",
'font-src': "'self' *",
'connect-src': "'self' *",
'img-src': "'self' *",
'style-src': "'self' 'unsafe-inline' *",
'frame-src': "*"
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
|
// This file was procedurally generated from the following sources:
// - src/dstr-binding/obj-ptrn-id-init-unresolvable.case
// - src/dstr-binding/error/for-of-let.template
/*---
description: Destructuring initializer is an unresolvable reference (for-of statement)
esid: sec-for-in-and-for-of-statements-runtime-semantics-labelledevaluation
es6id: 13.7.5.11
features: [destructuring-binding]
flags: [generated]
info: |
IterationStatement :
for ( ForDeclaration of AssignmentExpression ) Statement
[...]
3. Return ForIn/OfBodyEvaluation(ForDeclaration, Statement, keyResult,
lexicalBinding, labelSet).
13.7.5.13 Runtime Semantics: ForIn/OfBodyEvaluation
[...]
3. Let destructuring be IsDestructuring of lhs.
[...]
5. Repeat
[...]
h. If destructuring is false, then
[...]
i. Else
i. If lhsKind is assignment, then
[...]
ii. Else if lhsKind is varBinding, then
[...]
iii. Else,
1. Assert: lhsKind is lexicalBinding.
2. Assert: lhs is a ForDeclaration.
3. Let status be the result of performing BindingInitialization
for lhs passing nextValue and iterationEnv as arguments.
[...]
13.3.3.7 Runtime Semantics: KeyedBindingInitialization
SingleNameBinding : BindingIdentifier Initializeropt
[...]
6. If Initializer is present and v is undefined, then
a. Let defaultValue be the result of evaluating Initializer.
b. Let v be GetValue(defaultValue).
c. ReturnIfAbrupt(v).
6.2.3.1 GetValue (V)
1. ReturnIfAbrupt(V).
2. If Type(V) is not Reference, return V.
3. Let base be GetBase(V).
4. If IsUnresolvableReference(V), throw a ReferenceError exception.
---*/
assert.throws(ReferenceError, function() {
for (let { x = unresolvableReference } of [{}]) {
return;
}
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.