text
stringlengths 2
6.14k
|
|---|
/**
* @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 resolve = require( 'path' ).resolve;
var bench = require( '@stdlib/bench' );
var randu = require( '@stdlib/random/base/randu' );
var isnan = require( '@stdlib/math/base/assert/is-nan' );
var pow = require( '@stdlib/math/base/special/pow' );
var Float32Array = require( '@stdlib/array/float32' );
var tryRequire = require( '@stdlib/utils/try-require' );
var pkg = require( './../package.json' ).name;
// VARIABLES //
var sapxsumors = tryRequire( resolve( __dirname, './../lib/sapxsumors.native.js' ) );
var opts = {
'skip': ( sapxsumors instanceof Error )
};
// FUNCTIONS //
/**
* Creates a benchmark function.
*
* @private
* @param {PositiveInteger} len - array length
* @returns {Function} benchmark function
*/
function createBenchmark( len ) {
var x;
var i;
x = new Float32Array( len );
for ( i = 0; i < x.length; i++ ) {
x[ i ] = ( randu()*20.0 ) - 10.0;
}
return benchmark;
function benchmark( b ) {
var v;
var i;
b.tic();
for ( i = 0; i < b.iterations; i++ ) {
v = sapxsumors( x.length, 5.0, x, 1 );
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
}
b.toc();
if ( isnan( v ) ) {
b.fail( 'should not return NaN' );
}
b.pass( 'benchmark finished' );
b.end();
}
}
// MAIN //
/**
* Main execution sequence.
*
* @private
*/
function main() {
var len;
var min;
var max;
var f;
var i;
min = 1; // 10^min
max = 6; // 10^max
for ( i = min; i <= max; i++ ) {
len = pow( 10, i );
f = createBenchmark( len );
bench( pkg+'::native:len='+len, opts, f );
}
}
main();
|
var searchData=
[
['timeout',['timeout',['../class_student_record.html#ad47a915212011045af181ea6012641efa90272dda245ae1fb3cf197e91a8689dc',1,'StudentRecord']]],
['true_5ffalse',['true_false',['../class_student_record.html#a00e060bc8aa9829e5db087e2cba21009a151c33bae13714896d7b8b06d0addc93',1,'StudentRecord']]]
];
|
/*
* Copyright 2015 Alexander Pustovalov
*
* 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.
*/
var path = require('path');
var initEnv = require('../init.js');
var {storage, commons, config, gengine} = require('../../distr/index.js');
initEnv()
.then(() => {
return storage.getComponentTree();
})
.then(tree => {
const sourceCode = tree.modules['TestGroup'].reducerSourceCode;
// console.log(JSON.stringify(tree, null, 4));
const newSourceCode = gengine.injectModuleReducer(
sourceCode,
'test',
'test',
'./containers/Test/reducer.js'
);
console.log(newSourceCode);
const reducersSourceCode = tree.reducersSourceCode;
// console.log(reducersSourceCode);
const newReducersCode = gengine.injectReducer(reducersSourceCode, 'TestGroup', 'TestGroup', 'modules/TestGroup/reducer.js');
console.log(newReducersCode);
})
.catch(error => console.error(error));
|
const http = require('http');
const url = require('url');
const assert = require('assert');
const STEP_TIMEOUT = 60000;
const CaronteProxy = require('../');
const PROXY_HOST = 'localhost';
const PROXY_PORT = 9999;
const PROXY_AUTH_USERNAME = 'virgilio';
const PROXY_AUTH_PASSWORD = 'dante';
const PROXY_AUTHORIZATION_HEADER_VALUE = 'Basic ' + Buffer.from(PROXY_AUTH_USERNAME + ':' + PROXY_AUTH_PASSWORD).toString('base64');
var httpProxyAgent = new (require('http-proxy-agent'))('http://' + PROXY_HOST + ':' + PROXY_PORT);
var proxyRequestCounter = 0;
var proxyRequestErrorCounter = 0;
var proxy = CaronteProxy({
auth: {
username: PROXY_AUTH_USERNAME,
password: PROXY_AUTH_PASSWORD
}
},function (req, res, err) {
if (!err) {
++proxyRequestCounter;
} else {
++proxyRequestErrorCounter;
}
});
describe('Caronte Proxy - HTTP - Auth', function () {
before(function startProxy(done) {
proxy.on('listening', done);
proxy.listen(PROXY_PORT);
});
it('should let authenticated HTTP traffic through, and remove "Proxy-Authorization" header in transit', function (done) {
this.timeout(STEP_TIMEOUT);
var reqOpts = url.parse('http://httpbin.org/headers');
reqOpts.agent = httpProxyAgent;
reqOpts.headers = {
'Test-Header-1': 'Test-Value-1',
'Test-Header-2': 'Test-Value-2',
'Proxy-Authorization': PROXY_AUTHORIZATION_HEADER_VALUE
};
var resBody = [];
http.request(reqOpts, function (res) {
assert.equal(res.statusCode, 200);
assert.equal(proxyRequestCounter, 1);
assert.equal(proxyRequestErrorCounter, 0);
res
.on('data', function (chunk) {
resBody.push(chunk);
})
.on('end', function () {
resBody = Buffer.concat(resBody).toString();
reqHeaders = JSON.parse(resBody).headers;
assert(!!reqHeaders['Test-Header-1']);
assert.strictEqual(reqHeaders['Test-Header-1'], 'Test-Value-1');
assert(!!reqHeaders['Test-Header-2']);
assert.strictEqual(reqHeaders['Test-Header-2'], 'Test-Value-2');
assert(!reqHeaders['Proxy-Authorization']);
done();
});
}).end();
});
// TODO / FIXME: httpbin.org redirection endpoints are having issues
// it('should let authenticated HTTP redirects through', function (done) {
// this.timeout(STEP_TIMEOUT);
// var reqOpts = url.parse('http://httpbin.org/redirect-to?url=http://httpbin.org/headers');
// reqOpts.agent = httpProxyAgent;
// reqOpts.headers = {
// 'Proxy-Authorization': PROXY_AUTHORIZATION_HEADER_VALUE
// };
// http.request(reqOpts, function (res) {
// assert.equal(res.statusCode, 302);
// assert.equal(proxyRequestCounter, 2);
// assert.equal(proxyRequestErrorCounter, 0);
// assert(!!res.headers['location']);
// assert.strictEqual(res.headers['location'], 'http://httpbin.org/headers');
// done();
// }).end();
// });
it('should reject un-authenticated HTTP traffic', function(done) {
this.timeout(STEP_TIMEOUT);
var reqOpts = url.parse('http://httpbin.org/headers');
reqOpts.agent = httpProxyAgent;
http.request(reqOpts, function (res) {
assert.equal(res.statusCode, 407);
assert.equal(proxyRequestCounter, 1); // TODO Restore '2' once the httpbin.org issue above is resolved
assert.equal(proxyRequestErrorCounter, 1);
done();
}).end();
});
after(function stopProxy(done) {
proxy.on('close', done);
proxy.close();
});
});
|
(function() {
'use strict';
// Load various angular modules
angular.module('belgradeJS.controllers', []);
angular.module('belgradeJS.services', []);
angular.module('belgradeJS.models', []);
angular.module('belgradeJS.filters', []);
angular.module('belgradeJS.directives', []);
var belgradeJSApp = angular.module('belgradeJS', [
'ngRoute',
'belgradeJS.controllers',
'belgradeJS.services',
'belgradeJS.models',
'belgradeJS.filters',
'belgradeJS.directives'
]);
belgradeJSApp.config([
'$routeProvider', '$locationProvider',
function($routeProvider, $locationProvider) {
$routeProvider
// home page
.when('/', {
templateUrl: 'views/users.html',
controller: 'UsersCtrl'
})
.when('/user/:user_id', {
templateUrl: 'views/profile.html',
controller: 'ProfileCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}
]);
})();
|
/**
* @ngdoc service
* @name app.service:userSvc
* @requires $http
* @requires $q
* @requires $cookies
* @requires $state
* @requires Notification
*
* @description
* A service that handles the creation, modification, and deletion of users,
* as well as managing the current user's user object.
*/
angular
.module('app')
.factory('userSvc', ['$http', '$q', '$cookies', '$state', 'Notification', function($http, $q, $cookies, $state, Notification) {
'use strict';
var userSvc = {
users: [],
user: {},
initiated: false
};
/**
* @ngdoc method
* @name init
* @methodOf app.service:userSvc
*
* @description
* Method to initialize the userSvc with data from the server.
*
* @returns {Object} A future promise.
*/
userSvc.init = function() {
// Check to see if we are already initiated.
if (userSvc.initiated) {
return userSvc;
}
var deferred = $q.defer();
$http.get('/api/users')
.then(function(res) {
userSvc.roles = res.data.roles;
userSvc.users = res.data.users;
userSvc.user = JSON.parse($cookies.get('user'));
userSvc.initiated = true;
deferred.resolve(userSvc);
});
return deferred.promise;
};
/**
* @ngdoc method
* @name remove
* @methodOf app.service:userSvc
*
* @description
* Method to delete a user.
*
* @param {String} userToDelete The id of the user to delete.
*/
userSvc.remove = function(userToDelete) {
// Create the request object.
var req = {
method: 'DELETE',
url: '/api/user/' + userToDelete
};
$http(req).success(function(data) {
// Hooray the user was deleted! Now let's find them in the list and
// remove them.
userSvc.users.forEach(function(el, index) {
if (el._id === userToDelete) {
// This is our guy. Remove!
userSvc.users.splice(index, 1);
}
});
Notification.success('User deleted.');
}).error(function() {
Notification.error('Sorry, there was a problem.');
});
};
/**
* @ngdoc method
* @name create
* @methodOf app.service:userSvc
*
* @description
* Method to create a user.
*
* @param {Object} newUser User object to create.
* @param {Function} next Callback function.
*/
userSvc.create = function(newUser, next) {
// Create the request object.
var req = {
method: 'POST',
url: '/api/user',
data: {
data: newUser
}
};
$http(req).success(function(data) {
// We have a new user! Add them to the list!
userSvc.users.push(data);
Notification.success('New user has been created.');
// Trigger the callback in the controller to reset the newUser object.
next();
}).error(function() {
Notification.error('Sorry, there was a problem.');
});
};
/**
* @ngdoc method
* @name update
* @methodOf app.service:userSvc
*
* @description
* Method to update the users.
*/
userSvc.update = function() {
var req = {
method: 'POST',
url: '/api/users',
data: {
data: userSvc.users
}
};
$http(req).success(function(data) {
Notification.success('Users have been updated.');
}).error(function() {
Notification.error('Sorry, there was a problem.');
});
};
/**
* @ngdoc method
* @name login
* @methodOf app.service:userSvc
*
* @description
* Method to login a user.
*
* @param {Object} user User object containing an email address and password
* to validate the user.
*/
userSvc.login = function(user) {
var showNotification = true;
if (arguments.length > 1) {
showNotification = arguments[1];
}
var req = {
method: 'POST',
url: '/api/user/login',
data: user
};
$http(req).success(function(data) {
userSvc.user = data;
userSvc.isLoggedIn = true;
if (showNotification) {
Notification.success('Login successful!');
}
$state.go('search');
}).error(function() {
Notification.error('Login failed.');
});
};
/**
* @ngdoc method
* @name logout
* @methodOf app.service:userSvc
*
* @description
* Method to log a user out of the site.
*/
userSvc.logout = function() {
var req = {
method: 'POST',
url: '/api/user/logout'
};
$http(req).success(function(data) {
userSvc.user = {};
userSvc.isLoggedIn = false;
Notification.success('You are now logged out.');
$state.go('home');
}).error(function() {
});
return false;
};
return userSvc;
}]);
|
/* Copyright (C) 2013-2014 Computer Sciences Corporation
*
* 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. */
var EzConfigurationLoader = require('./ezConfigurationLoader');
var _ = require('lodash-node');
PropertiesConfigurationLoader.prototype = new EzConfigurationLoader();
PropertiesConfigurationLoader.prototype.constructor = PropertiesConfigurationLoader;
function PropertiesConfigurationLoader(properties){
EzConfigurationLoader.call(this);
if(_.isObject(properties)){
this.loadedProperties = properties;
}
this.logger.debug('Loading Directory Configuration Loader with directory: ' + this.loadedProperties);
}
PropertiesConfigurationLoader.prototype.loadConfiguration = function(){
var _this = this; //when using lodash, this becomes overrided
_.each(_this.loadedProperties, function(value, key){
_this._setProperty(key, value);
});
return _this.properties;
};
PropertiesConfigurationLoader.prototype.isLoadable = function(){
var propertiesExist = _.isObject(this.loadedProperties);
this.logger.debug('Is Properties Configuration Loader loadable: ' + propertiesExist);
return propertiesExist;
};
module.exports = PropertiesConfigurationLoader;
|
/**
*
*/
function TimeDurationConstant() {
this.value = "";
this.datatype = "TimeDuration";
this.largeDuration = 0;
// 0:workday; 1:day; 2:week: 3:month; 4:quarter
this.largeDurationUnit = 0;
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.milliseconds = 0;
};
TimeDurationConstant.prototype = new Constant();
TimeDurationConstant.prototype.clone = function(owner) {
var d = new TimeDurationConstant();
d.value = this.value;
d.largeDuration = this.largeDuration;
d.largeDurationUnit = this.largeDurationUnit
d.hours = this.hours;
d.minutes = this.minutes;
d.seconds = this.seconds;
d.milliseconds = this.milliseconds;
return d;
};
// to string for storage.
TimeDurationConstant.prototype.toExpressionString = function() {
var v = this.largeDuration + "|" + this.largeDurationUnit + "|"
+ this.hours + "|" + this.minutes + "|" + this.seconds + "|"
+ this.milliseconds;
return "C@" + this.datatype + "@" + v;
};
// parse a .
TimeDurationConstant.prototype.parseString = function(str) {
var ary = str.split("@");
this.datatype = ary[1];
var ary1 = ary[2].split("|");
this.largeDuration = parseInt(ary1[0]);
// 0:workday; 1:day; 2:week: 3:month; 4:quarter;
this.largeDurationUnit = parseInt(ary1[1]);
this.hours = parseInt(ary1[2]);
this.minutes = parseInt(ary1[3]);
this.seconds = parseInt(ary1[4]);
this.milliseconds = parseInt(ary1[5]);
};
TimeDurationConstant.prototype.parseObject = function(o) {
this.datatype = o.datatype;
this.largeDuration = o.largeDuration;
this.largeDurationUnit = o.largeDurationUnit;
this.hours = o.hours;
this.minutes = o.minutes;
this.seconds = o.seconds;
this.milliseconds = o.milliseconds;
};
// return milliseconds
TimeDurationConstant.prototype.getValue = function() {
return 0;
};
TimeDurationConstant.prototype.toString = function() {
return (this.largeDuration == 0 ? "" : this.largeDuration
+ largeduration[this.largeDurationUnit])
+ (this.hours == 0 ? "" : this.hours + largeduration[5])
+ (this.minutes == 0 ? "" : this.minutes + largeduration[6])
+ (this.seconds == 0 ? "" : this.seconds + largeduration[7])
+ (this.milliseconds == 0 ? "" : this.milliseconds
+ largeduration[8]);
};
|
$(function() {
$("#name_error_message").hide();
$("#surname_error_message").hide();
$("#password_error_message").hide();
$("#retype_password_error_message").hide();
$("#email_error_message").hide();
var error_name = false;
var error_surname = false;
var error_password = false;
var error_retype_password = false;
var error_email = false;
$("#funcionario_nome").focusout(function() {
checkName();
});
$("#funcionario_sobrenome").focusout(function() {
checkSurname();
});
$("#funcionario_senha").focusout(function() {
checkPassword();
});
$("#funcionario_confirma_senha").focusout(function() {
checkRetypePassword();
});
$("#funcionario_email").focusout(function() {
checkEmail();
});
function checkName() {
var name = $("#funcionario_nome").val();
if(name == ""){
$("#name_error_message").html("O espaco deve ser preenchido");
$("#name_error_message").show();
error_username = true;
}else {
/^[a-zA-Z]*$/.test(name);
$("#name_error_message").hide();
}
}
function checkSurname() {
var name = $("#funcionario_sobrenome").val();
if(name == ""){
$("#surname_error_message").html("O espaco deve ser preenchido");
$("#surname_error_message").show();
error_username = true;
}else {
/^[a-zA-Z]*$/.test(name);
$("#surname_error_message").hide();
}
}
function checkPassword(){
var passLength = $("#funcionario_senha").val().length;
if("#funcionario_senha" == ""){
$("#password_error_message").html("O espaco deve ser preenchido");
$("#password_error_message".show();
error_password = true;
}else if(passLength < 6){
$("#password_error_message").html("A senha deve conter pelo menos 6 caracteres");
$("#password_error_message".show();
error_password = true;
}else{
$("#password_error_message".hide();
}
}
function checkRetypePassword(){
var password = $("#funcionario_senha").val();
var retypePassword = $("#funcionario_confirma_senha").val();
if (password != retypePassword) {
$("#retype_password_error_message").html("As senhas sao diferentes modafoca");
$("#retype_password_error_message").show();
error_retype_password = true;
}else{
$("#retype_password_error_message").hide();
}
}
function checkEmail(){
var pattern = new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/);
if(pattern.test($("#funcionario_email").val())) {
$("#emai_error_message").hide();
}else{
$("#emai_error_message").html("Email invalido");
$("#emai_error_message").show();
error_email = true;
}
});
|
function(cont,targs,$mptypes){
var mm=this.tipo.$m$;
if (cont!==nothingType$meta$model() && !extendsType({t:cont.tipo},{t:mm.$cont}))
throw IncompatibleTypeException$meta$model("Incompatible Container specified");
var _t={t:this.tipo};
if ($mptypes.Type$memberInterfaceApply.a)_t.a=$mptypes.Type$memberInterfaceApply.a;
validate$typeparams(_t,mm.tp,targs);
var rv=AppliedMemberInterface$jsint(this.tipo,
{Container$AppliedMemberInterface:$mptypes.Container$memberInterfaceApply,Type$AppliedMemberInterface:_t});
if (_t.a)rv.$targs=_t.a;
return rv;
}
|
/**
* Created by vmurali on 7/11/16.
*/
'use strict';
var _ = require('lodash');
// Initial setup
var cross = function (A, B) {
var result = [];
for (var i = 0; i < A.length; i++) {
for (var j = 0; j < B.length; j++) {
result.push(A[i] + B[j]);
}
}
return result;
};
var i, j;
var rows = 'ABCDEFGHI';
var columns = '123456789';
var squares = cross(rows, columns);
var unitlist = [];
for (i = 0; i < rows.length; i++) {
unitlist.push(cross(rows[i], columns));
}
for (i = 0; i < columns.length; i++) {
unitlist.push(cross(rows, columns[i]));
}
for (i = 0; i < rows.length; i += 3) {
var rowsSub = rows.slice(i, i + 3);
for (j = 0; j < columns.length; j += 3) {
var columnsSub = columns.slice(j, j + 3);
unitlist.push(cross(rowsSub, columnsSub));
}
}
var units = {};
unitlist.forEach(function (unit) {
unit.forEach(function (square) {
if (!units[square]) {
units[square] = [unit];
} else {
units[square].push(unit);
}
});
});
var peers = {};
squares.forEach(function (square) {
units[square].forEach(function (unit) {
if (!peers[square]) {
peers[square] = _.without(unit, square);
} else {
_.without(unit, square).forEach(function (peer) {
if (peers[square].indexOf(peer) === -1) {
peers[square].push(peer);
}
});
}
});
});
var getGridValues = function (grid) {
var gridValues = {};
for (var i = 0; i < grid.length; i++) {
var square = squares[i];
var value = grid[i];
gridValues[square] = (columns.indexOf(value) !== -1 ? value : '.');
}
return gridValues;
};
var parseGrid = function (grid) {
var values = {};
squares.forEach(function (square) {
values[square] = columns;
});
var gridValues = getGridValues(grid);
for (var s in gridValues) {
var d = gridValues[s];
if (columns.indexOf(d) !== -1 && !assign(values, s, d)) {
return false;
}
}
return values;
};
var assign = function (values, s, d) {
var otherValues = values[s].replace(d, '');
var res = true;
for (var i = 0; i < otherValues.length; i++) {
var d2 = otherValues[i];
if (!eliminate(values, s, d2)) {
res = false;
}
}
return res ? values : false;
};
var eliminate = function (values, s, d) {
if (values[s].indexOf(d) === -1) {
return values;
}
values[s] = values[s].replace(d, '');
if (values[s].length === 0) {
return false;
} else if (values[s].length === 1) {
var d2 = values[s];
var res = true;
peers[s].forEach(function (s2) {
if (!eliminate(values, s2, d2)) {
res = false;
}
});
if (!res) {
return false;
}
}
for (var i = 0; i < units[s].length; i++) {
var u = units[s][i];
var dplaces = [];
for (var k = 0; k < u.length; k++) {
var sq = u[k];
if (values[sq].indexOf(d) !== -1) {
dplaces.push(sq);
}
}
if (dplaces.length === 0) {
return false;
} else if (dplaces.length === 1) {
if (!assign(values, dplaces[0], d)) {
return false;
}
}
}
return values;
};
var solve = function (grid) {
return search(parseGrid(grid));
};
var search = function (values) {
if (values === false) {
return false;
}
var solved = _.every(squares, function (s) {
return (values[s].length === 1);
});
if (solved) {
return values;
}
var n = 9;
var sq = 'A1';
for (var k = 0; k < squares.length; k++) {
var s = squares[k];
if (values[s].length > 1 && values[s].length < n) {
n = values[s].length;
sq = s;
}
}
var resArray = [];
for (var k = 0; k < values[sq].length; k++) {
var d = values[sq][k];
var newvalues = assign(_.clone(values), sq, d);
var res = search(newvalues);
resArray.push(res);
}
return some(resArray);
};
var some = function (seq) {
for (var i = 0; i < seq.length; i++) {
var e = seq[i];
if (e) {
return e;
}
}
return false;
};
var validate = function (grid) {
var values = parseGrid(grid);
for (var i = 0; i < unitlist.length; i++) {
var unit = unitlist[i];
var validUnit = [false, false, false, false, false, false, false, false, false];
for (var k = 0; k < unit.length; k++) {
var square = unit[k];
var index = Number(values[square]) - 1;
validUnit[index] = true;
}
if (!_.every(validUnit, Boolean)) {
return false;
}
}
return true;
};
var gridToString = function (values) {
if (values) {
var solution = '';
Object.keys(values).sort().forEach(function (square) {
solution += values[square];
});
return solution;
} else {
return values;
}
};
module.exports = {
solve: solve,
validate: validate,
stringToGrid: parseGrid,
gridToString: gridToString
};
|
//// [classAndVariableWithSameName.js]
var C = (function () {
function C() {
}
return C;
})();
var C = '';
var M;
(function (M) {
var D = (function () {
function D() {
}
return D;
})();
var D = 1;
})(M || (M = {}));
|
define({
name : 'HEX_COLOR',
keys : 6,
pattern: '#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])(?:([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9]))?',
parser : function (o) {'use strict';
var f = o[6],
r = f ? o[1] + o[2] : o[1] + o[1],
g = f ? o[3] + o[4] : o[2] + o[2],
b = f ? o[5] + f : o[3] + o[3],
p = parseInt;
return {
red : p(r, 16),
green: p(g, 16),
blue : p(b, 16),
alpha: 1,
match: o.match
};
}
});
/**
* 处理 {@link https://developer.mozilla.org/en-US/docs/Web/CSS/color_value 十六进制 RGB 格式色彩值} 的正则表达式模板。
* @see {@link Sumi.Pattern.RGBA_COLOR}
* @see {@link Sumi.Pattern.HSLA_COLOR}
* @var {Sumi.Match} Sumi.Pattern.HEX_COLOR
* @example
* var match = Sumi.Pattern.HEX_COLOR;
*
* console.log(match.parse('#F03'));
* // [ { red: 255, green: 0, blue: 51, alpha: 1, match: '#F03' } ]
*
* console.log(match.parse('#FF0033'));
* // [ { red: 255, green: 0, blue: 51, alpha: 1, match: '#FF0033' } ]
*
* console.log(match.is('#H03')); // false
* console.log(match.is('#f03')); // true
*/
|
'use strict';
const BSON = require('../../lib/bson');
describe('string tests', function() {
it('can serialize and deserialize 0xFFFD', function() {
const unicodeString = String.fromCharCode(0x41, 0x42, 0xfffd, 0x43, 0x44); // "AB�CD"
const serialized = BSON.serialize({ value: unicodeString });
BSON.deserialize(serialized);
});
});
|
var ikubeServices = angular.module('ikube-services', []);
ikubeServices.service('databaseService', function($rootScope, $http, $timeout) {
this.getEntities = function(klass, startIndex, endIndex) {
var entities = [];
return $timeout(function() {
return entities;
}, 250);
};
});
ikubeServices.service('CreateController', function($rootScope, $http) {
this.createEntity = function(entity) {
}
});
|
/*!
* ${copyright}
*/
// Provides type sap.m.upload.UploaderHttpRequestMethod
sap.ui.define([], function() {
"use strict";
/**
* Types of HTTP request methods.
*
* @enum {string}
* @alias sap.m.upload.UploaderHttpRequestMethod
* @public
* @since 1.90
* @ui5-metamodel This enumeration will also be described in the SAPUI5 (legacy) design time metamodel
*/
var UploaderHttpRequestMethod = {
/**
* HTTP request POST method.
* @public
*/
Post : "POST",
/**
* HTTP request PUT method.
* @public
*/
Put : "PUT"
};
return UploaderHttpRequestMethod;
});
|
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2015, 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) {
require('jgrowl');
var Locale = require('utils/locale');
//Notification of submission of action
var _notifySubmit = function(action, args, extra_param) {
var action_text = action.replace(/OpenNebula\./, '').replace(/\./, ' ');
var msg = "";
if (!args || (typeof args == 'object' && args.constructor != Array)) {
msg += action_text;
} else {
msg += action_text + ": " + args;
};
if (extra_param && extra_param.constructor != Object) {
msg += " >> " + extra_param;
};
$.jGrowl(msg, {theme: "jGrowl-notify-submit", position: "bottom-right"});
}
//Notification on error
var _notifyError = function(msg) {
$.jGrowl(msg, {theme: "jGrowl-notify-error", position: "bottom-right", sticky: true});
}
//Standard notification
var _notifyMessage = function(msg) {
$.jGrowl(msg, {theme: "jGrowl-notify-submit", position: "bottom-right"});
}
var _notifyCustom = function(title, msg, sticky) {
msg = (title ? title : "") + msg;
$.jGrowl(msg, {theme: "jGrowl-notify-submit", position: "bottom-right", sticky: sticky});
}
//standard handling for the server errors on ajax requests.
//Pops up a message with the information.
var _onError = function(request, error_json, container) {
var method;
var action;
var object;
var id;
var reason;
var m;
var message = error_json.error.message;
//redirect to login if unauthenticated
if (error_json.error.http_status == "401") {
window.location.href = "login";
return false;
};
if (!message) {
_notifyError(Locale.tr("Cannot contact server: is it running and reachable?"));
return false;
};
if (error_json.error.http_status == "404") {
_notifyError(message);
return false;
}
if (container) {
container.show();
return false;
}
if (message.match(/^Network is unreachable .+$/)) {
_notifyError(Locale.tr("Network is unreachable: is OpenNebula running?"));
return false;
};
//Parse known errors:
var get_error = /^\[(\w+)\] Error getting ([\w ]+) \[(\d+)\]\.$/;
var auth_error = /^\[(\w+)\] User \[(\d+)\] not authorized to perform action on ([\w ]+).$/;
if (m = message.match(get_error)) {
method = m[1];
action = "Show";
object = m[2];
id = m[3];
} else if (m = message.match(auth_error)) {
method = m[1];
object = m[3];
reason = Locale.tr("Unauthorized");
};
if (m) {
var rows;
var i;
var value;
rows = ["method", "action", "object", "id", "reason"];
message = "";
for (i = 0; i < rows.length; i++) {
key = rows[i];
value = eval(key);
if (value)
message += "<tr><td class=\"key_error\">" + key + "</td><td>" + value + "</td></tr>";
}
message = "<table>" + message + "</table>";
};
_notifyError(message);
return true;
}
return {
'notifySubmit': _notifySubmit,
'notifyError': _notifyError,
'notifyMessage': _notifyMessage,
'notifyCustom': _notifyCustom,
'onError': _onError
}
});
|
/*
* @license
* Copyright 2018 Brigham Young University
*
* 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 {html, oneLine} = require('common-tags');
const {URL} = require('url');
const mime = require('mime');
module.exports = function processBasicUsage(usage, baseUrl) {
if (!usage) {
return undefined;
}
let {head, body} = usage;
if (!head && !body) {
return undefined;
}
return {head: processHead(head, baseUrl), body}
};
function processHead(head, baseUrl) {
if (!head) {
return undefined;
}
if (typeof head === 'string') {
return head;
}
const {meta = [], preload = [], styles = [], scripts = []} = head;
const sections = [
renderPreload(preload),
renderMeta(meta),
renderStyles(styles),
renderScripts(scripts)
];
return html`
${sections.join('\n\n')}
`;
function renderMeta(meta) {
if (!meta || !meta.length) {
return '';
}
return html`
<!-- Meta -->
${meta.map(m => html`<meta name="${m.name}" content="${m.content}">`)}
`;
}
function renderPreload(preload) {
if (!preload || !preload.length) {
return '';
}
const mapped = preload.map(p => {
if (typeof p === 'string') {
p = {href: p};
}
const {type, as: computedAs} = computeTypeInfo(p.href);
let {href, as = computedAs, crossorigin, media} = p;
let tag = `<link rel="preload" href="${resolve(href)}" as="${as}" type="${type}"`;
if (as === 'font' && !crossorigin) {
crossorigin = 'anonymous';
}
if (crossorigin) {
tag += ` crossorigin="${crossorigin}"`;
}
if (media) {
tag += ` media="${media}"`;
}
tag += '>';
return tag;
});
return html`
<!-- Preload Resources -->
${mapped}
`;
}
function renderStyles(tags) {
if (!tags || !tags.length) {
return '';
}
const mapped = tags.map(href => html`<link rel="stylesheet" href="${resolve(href)}" type="text/css">`);
return html`
<!-- Stylesheets -->
${mapped}
`;
}
function renderScripts(tags) {
if (!tags || !tags.length) {
return '';
}
const mapped = tags.map(tag => {
if (typeof tag === 'string') {
tag = {src: tag};
}
let {
src,
type = 'application/javascript',
async = false,
crossorigin,
defer = false,
integrity,
nomodule = false,
} = tag;
if (async && defer) {
async = false;
}
const open = oneLine`
<script src="${resolve(src)}"
${async ? 'async' : ''}
${defer ? 'defer': ''}
${nomodule ? `nomodule` : ''}
type="${type}"
${crossorigin ? `crossorigin="${crossorigin}"` : ''}
${integrity ? `integrity="${integrity}"` : ''}
`;
return open + '></script>';
});
return html`
<!-- Scripts -->
${mapped}
`;
}
function resolve(link) {
return new URL(link, baseUrl).toString();
}
}
function computeTypeInfo(href) {
const type = mime.getType(href);
if (!type) {
return undefined;
}
return {type, as: preloadAs(type)};
}
function preloadAs(type) {
if (type.includes('javascript')) {
return 'script';
} else if (type === 'text/css') {
return 'stylesheet';
} else if (type.startsWith('font/') || type.startsWith('application/font-')) {
return 'font';
} else if (type.startsWith('image/')) {
return 'image';
} else if (type.startsWith('video/')) {
return 'video';
}
return null;
}
|
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var path = require('path');
var util = require('util');
// receive zmq messages
var zmq = require('zmq');
var subscriber = zmq.socket('sub');
if (process.argv[2]) {
console.log('zmq binding to address ' + process.argv[2]);
subscriber.bindSync(process.argv[2]);
} else {
console.log('zmq binding to address ' + 'ipc:///tmp/relaylog');
subscriber.bindSync('ipc:///tmp/relaylog');
}
subscriber.subscribe('');
console.log('zmq initialized')
// when a client connects via websockets,
// forward relevant zmq message data to the client
io.on('connection', function (socket) {
subscriber.on('message', function () {
var payload = JSON.parse(arguments[1].toString());
if (payload.PV) {
socket.emit('pvdata', {y: payload.PV});
}
if (payload.MV) {
socket.emit('mvdata', {y: payload.MV});
}
if (payload.SP) {
socket.emit('spdata', {y: payload.SP});
}
});
});
// configure webserver
app.engine('.html', require('ejs').__express);
var port = 8080;
server.listen(port);
app.use('/vendor', express.static(path.join(__dirname, '..', '/vendor')));
app.get('/', function (req, res) {
res.render(
path.join(__dirname, 'index.html'),
{webserver_url: util.format('http://%s:%s', req.hostname, port)});
});
|
exports.DataSet = require('./lib/DataSet');
exports.DataView = require('./lib/DataView');
exports.Timeline = require('./lib/timeline/Timeline');
|
// Copyright 2015 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
var assert = require('assert');
var agent = require('../../..');
assert(agent.get().isActive());
console.log('Preload test passed.');
// Exit explicitly since the process is being held open by retries to the
// metadata service.
process.exit(0);
|
function FirstView (options) {
var win = Ti.UI.createWindow({
title: "ViewPager Demo",
backgroundColor: "#000000",
modal: true
});
var pagerModule = require("net.bajawa.pager");
var viewPager = pagerModule.createViewPager(options);
win.add(viewPager);
return win;
}
module.exports = FirstView;
|
var fs = require( 'fs' ),
auth = require( './auth' ),
Survey = require( '../models/survey' ),
surveyTemplate = require( '../lib/survey_template' );
var OverviewController = function() {
this.index = function( req, res ) {
if( !req.survey ) {
return res.redirect( '/404' );
}
res.locals.classes.push( 'overview' );
var template = surveyTemplate.getSurvey( req.survey.version );
res.render( 'survey/' + template.render + '/overview', {
survey: req.survey,
validPermissions: Survey.validPermissions(),
csrfToken: req.csrfToken()
} );
};
this.detail = function( req, res ) {
var template = surveyTemplate.getSurvey( req.survey.version );
fs.exists( __dirname + '/../views/survey/' + template.render + '/detail.jade', function( exists ) {
if( exists ) {
res.render( 'survey/' + template.render + '/detail', {
survey: req.survey,
validPermissions: Survey.validPermissions(),
csrfToken: req.csrfToken()
} );
} else {
// if no scores template exists, head back to the overview
res.redirect( '/view/' + req.param( 'key' ) );
}
} );
};
this.domain = function( req, res ) {
var template = surveyTemplate.getSurvey( req.survey.version ),
domain = req.param( 'domain' );
domain = domain[ 0 ].toUpperCase() + domain.slice( 1 );
fs.exists( __dirname + '/../views/survey/' + template.render + '/scores.jade', function( exists ) {
if( exists ) {
res.render( 'survey/' + template.render + '/scores', {
survey: req.survey,
domain: domain,
validPermissions: Survey.validPermissions(),
csrfToken: req.csrfToken()
} );
} else {
// if no scores template exists, head back to the overview
res.redirect( '/view/' + req.param( 'key' ) );
}
} );
};
};
exports.setup = function( app ) {
var overview = new OverviewController();
app.get( '/view/:key', auth.canAccessSurvey, overview.index );
app.get( '/view/:key/detail', auth.canAccessSurvey, overview.detail );
app.get( '/view/:key/scores/:domain', auth.canAccessSurvey, overview.domain );
};
|
(function () {
angular.module('myApp.controllers', []);
angular.module('myApp.services', ['ngResource', 'ngAnimate']);
var myApp = angular.module('myApp', [
'myApp.controllers',
'myApp.services',
'long2know',
'ngSanitize',
'ui.bootstrap',
'ui.router',
'ui']);
var myController = function ($scope, $timeout, $animate, $log) {
var vm = this,
initItems = function () {
vm.items = [];
for (var i = 0; i < 10; i++) {
vm.items.push({ name: "Item " + i.toString() });
}
},
init = function () {
$timeout(function () { setTimeout(initItems(), 2000) }, 0);
};
vm.addItem = function () {
vm.items.push({ name: "Item " + vm.items.length.toString() });
};
$animate.enabled(false);
var listener = $scope.$on('ngRepeatFinished', function () {
$log.log("Message received - turning animations on");
$animate.enabled(true);
$log.log("Unregistering listener");
listener();
listener = null;
});
init();
};
var newItem = function ($timeout, $log) {
var animation = {
enter: function (element, done) {
element.addClass('new-item');
$timeout(function () {
element.removeClass('new-item');
done();
}, 2000);
}
};
return animation;
};
newItem.$inject = ['$timeout', '$log'];
angular.module('myApp.services')
.animation('.new-list-item', newItem);
myController.$inject = ['$scope', '$timeout', '$animate', '$log'];
angular.module('myApp.controllers')
.controller('myCtrl', myController);
myApp.run(['$log', function ($log) { $log.log("Start."); }]);
})()
|
import L from 'leaflet';
import { Util } from 'esri-leaflet';
import { fetchMetadata } from './Util';
export var Basemap = L.Layer.extend({
statics: {
URLPREFIX: 'https://www.arcgis.com/sharing/rest/content/items/',
URLSUFFIX: '/resources/styles/root.json',
STYLES: {
'OpenStreetMap': '3e1a00aeae81496587988075fe529f71',
// v2
'Streets': 'de26a3cf4cc9451298ea173c4b324736',
'StreetsRelief': 'b266e6d17fc345b498345613930fbd76',
// 7dc6cea0b1764a1f9af2e679f642f0f5 doesnt pass validation
'Topographic': '7a6bf0e8cb5a418085e66c0485e74d19',
// 86f556a2d1fd468181855a35e344567f doesnt pass validation
'StreetsNight': '93554006894c45a88136127535878fca',
'Newspaper': 'dfb04de5f3144a80bc3f9f336228d24a',
'Navigation': '63c47b7177f946b49902c24129b87252',
'Nova': '75f4dfdff19e445395653121a95a85db',
'ColoredPencil': '4cf7e1fb9f254dcda9c8fbadb15cf0f8',
'Hybrid': '30d6b8271e1849cd9c3042060001f425',
'Gray': '291da5eab3a0412593b66d384379f89f', // no labels
'DarkGray': '5e9b3685f4c24d8781073dd928ebda50', // no labels
'HumanGeography': '2afe5b807fa74006be6363fd243ffb30', // no labels
'HumanGeographyDetail': '97fa1365da1e43eabb90d0364326bc2d', // no labels
'DarkHumanGeography': 'd7397603e9274052808839b70812be50', // no labels
'DarkHumanGeographyDetail': '1ddbb25aa29c4811aaadd94de469856a', // no labels
'ChartedTerritory': '1c365daf37a744fbad748b67aa69dac8',
'MidCentury': '7675d44bb1e4428aa2c30a9b68f97822'
// 'ModernAntique': 'effe3475f05a4d608e66fd6eeb2113c0' // throws mismatched image size error
}
},
initialize: function (options) {
// L.Layer expects a JSON object literal to be passed in constructor
options = {
key: options
};
this._basemap = options.key;
if (typeof options.key === 'string' && Basemap.STYLES[options.key]) {
var url = Basemap.URLPREFIX + Basemap.STYLES[options.key] + Basemap.URLSUFFIX;
fetchMetadata(url, this);
} else {
throw new Error('L.esri.Vector.Basemap: Invalid parameter. Use one of "DarkGray", "Gray", "Hybrid", "Navigation", "Streets", "StreetsNight", "StreetsRelief", "Topographic"');
}
},
onAdd: function (map) {
this._map = map;
Util.setEsriAttribution(map);
if (map.attributionControl) {
if (this._basemap === 'OpenStreetMap') {
map.attributionControl.setPrefix('<a href="http://leafletjs.com" title="A JS library for interactive maps">Leaflet</a>');
map.attributionControl.addAttribution('<span class="esri-dynamic-attribution">© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors, map layer by Esri</span>');
} else {
Util._getAttributionData('https://static.arcgis.com/attribution/World_Street_Map', map);
map.attributionControl.addAttribution('<span class="esri-dynamic-attribution">USGS, NOAA</span>');
}
}
if (this._ready) {
this._asyncAdd();
} else {
this.once('ready', function () {
this._asyncAdd();
}, this);
}
},
onRemove: function (map) {
map.off('moveend', Util._updateMapAttribution);
map.removeLayer(this._mapboxGL);
if (map.attributionControl) {
var vectorAttribution = document.getElementsByClassName('esri-dynamic-attribution')[0].outerHTML;
// this doesn't work, not sure why.
map.attributionControl.removeAttribution(vectorAttribution);
}
},
_asyncAdd: function () {
var map = this._map;
// thought it was just me, but apparently its not easy to mixin two different styles
// https://github.com/mapbox/mapbox-gl-js/issues/4000
// set the background color of the map to the background color of the tiles
map.getContainer().style.background = this._mapboxGL.options.style.layers[0].paint['background-color'] || '#e1e3d0';
map.on('moveend', Util._updateMapAttribution);
this._mapboxGL.addTo(map, this);
// map._gl = this._mapboxGL;
}
});
export function basemap (key) {
return new Basemap(key);
}
export default Basemap;
|
import {
autobind
}
from 'core-decorators';
const dialogOptions = {
controller: 'SectionsDialogController',
controllerAs: 'SectionsDialogCtrl',
templateUrl: 'views/dialogs/sections.dlg.html',
clickOutsideToClose: false,
parent: angular.element(document.body)
};
@autobind
class ProfesorsController {
constructor($mdDialog, $mdToast, Profesores, Auth) {
this.$mdDialog = $mdDialog;
this.$mdToast = $mdToast;
this.Profesores = Profesores;
this.Auth = Auth;
this.active();
this.profesors = Profesores.all();
}
active() {
console.log('Teaching...');
this.resetModes();
}
resetModes() {
console.info('Reseting Modes...');
this.editing = false;
this.creating = false;
this.currentSaveIcon = 'edit';
this.modeSaveMessage = 'Editar';
this.modeCancelMessage = 'Eliminar';
this.currentCancelIcon = 'delete';
this.currentProfesor = undefined;
}
changeMode() {
if (this.creating) {
// If is Saving/Inactive
this.saveProfesor(this.currentProfesor);
} else if (!(this.editing && this.creating)) {
if (this.editing) {
this.editProfesor(this.currentProfesor.$id, this.currentProfesor);
}
this.editing = !this.editing;
this.modeCancelMessage = 'Cancelar edicion de';
this.currentCancelIcon = 'cancel';
this.currentSaveIcon = 'save';
this.modeSaveMessage = 'Guardar';
}
}
addProfesor() {
this.currentSaveIcon = 'save';
this.modeSaveMessage = 'Guardar';
this.currentCancelIcon = 'cancel';
this.modeCancelMessage = 'Cancelar edicion de';
this.editing = true;
this.creating = true;
this.currentProfesor = {};
}
selectProfesor(profesorId) {
this.Profesores.get(profesorId)
.then(profesor => this.currentProfesor = profesor)
.catch(console.error.bind(console));
}
cancelMode() {
if (this.modeCancelMessage === 'Eliminar') {
// If is Saving/Inactive
this.deleteProfesor(this.currentProfesor.$id);
} else {
// If is active
this.resetModes();
}
}
editProfesor(pid, pinfo) {
this.Profesores.edit(pid, pinfo)
.then(() => {
this.$mdToast.show(
this.$mdToast.simple()
.content(`Profesor ${pinfo.name} editado`)
.position('right bottom'));
})
.catch(console.error.bind(console));
}
saveProfesor(pinfo) {
this.Profesores.create(pinfo)
.then(ref => {
this.$mdToast.show(
this.$mdToast.simple()
.content(`Profesor ${ref.key()} creado`)
.position('right bottom')
);
this.resetModes();
})
.catch(console.error.bind(console));
}
deleteProfesor(pid) {
this.Profesores.remove(pid)
.then(() => {
this.$mdToast.show(
this.$mdToast.simple()
.content(`${pid} Elminado`)
.position('right bottom')
);
this.resetModes();
})
.catch(console.error.bind(console));
}
openSections(event, pid) {
this.Profesores.get(pid)
.then(pinfo => {
let config = {
event: event,
profesor: pinfo,
secciones: this.Profesores.getSections(pid)
};
let createDialog = Object.assign(config, dialogOptions);
this.$mdDialog.show(createDialog)
.then(message => {
this.$mdToast.show(
this.$mdToast.simple()
.content(message)
.position('right bottom')
);
})
.catch(console.error.bind(console));
}).catch(console.error.bind(console));
}
}
ProfesorsController.$inject = ['$mdDialog', '$mdToast', 'Profesores', 'Auth'];
export default ProfesorsController;
|
import { fetchURL, fetchJSON, removePrefix } from './utils'
export async function getHash(hash) {
return fetchJSON(`/api/public/share/${hash}`)
}
export async function get(url) {
url = removePrefix(url)
return fetchJSON(`/api/share${url}`)
}
export async function remove(hash) {
const res = await fetchURL(`/api/share/${hash}`, {
method: 'DELETE'
})
if (res.status !== 200) {
throw new Error(res.status)
}
}
export async function create(url, expires = '', unit = 'hours') {
url = removePrefix(url)
url = `/api/share${url}`
if (expires !== '') {
url += `?expires=${expires}&unit=${unit}`
}
return fetchJSON(url, {
method: 'POST'
})
}
|
var auth = require('../lib/auth')
var express = require('express')
var router = express.Router()
var mongoose = require('mongoose')
var Channel = mongoose.model('channels', require('../schemas/channel'))
router.get('/channels', function (req, res) {
auth.authorize(req.query.token, function (success, user) {
if (success) {
Channel.find({}, function (err, channels) {
if (err) console.log(err)
res.send(channels)
})
} else {
res.status(401).send({error: 'invalid token'})
}
})
})
router.post('/channels', function (req, res) {
auth.authorize(req.query.token, function (success, user) {
if (success) {
Channel.create({id: req.body.id, name: req.body.name, thumbnail: req.body.thumbnail},
function (err, channel) {
if (err) console.log(err)
res.send(channel)
})
} else {
res.status(401).send({error: 'invalid token'})
}
})
})
router.delete('/channels/:id', function (req, res) {
auth.authorize(req.query.token, function (success, user) {
if (success) {
Channel.find({id: req.params.id}).remove(
function (err) {
if (err) console.log(err)
res.send({error: null})
})
} else {
res.status(401).send({error: 'invalid token'})
}
})
})
router.post('/login', function (req, res) {
auth.login(req.body.username, req.body.password,
function (success, user) {
if (success) {
res.send({
token: user.token,
name: user.name,
thumbnail: user.thumbnail
})
} else {
res.status(401).send({error: 'invalid credentials'})
}
})
})
router.post('/register', function (req, res) {
auth.register(req.body.username, req.body.password, req.body.name, req.body.thumbnail,
function (success, user) {
if (success) {
res.send({
token: user.token,
name: user.name,
thumbnail: user.thumbnail
})
} else {
res.status(500).send({error: 'error creating user'})
}
})
})
router.post('/profile', function (req, res) {
auth.authorize(req.body.token, function (success, user) {
if (success) {
auth.update(user, req.body, function (success, user) {
if (success) {
res.send({
name: user.name,
thumbnail: user.thumbnail
})
} else {
res.status(401).send({error: 'error while updating'})
}
})
} else {
res.status(401).send({error: 'invalid token'})
}
})
})
router.post('/auth', function (req, res) {
auth.authorize(req.body.token, function (success, user) {
if (success) {
res.send({
name: user.name,
thumbnail: user.thumbnail
})
} else {
res.status(401).send({error: 'invalid token'})
}
})
})
module.exports = router
|
var index = 0;
var numProjects = 8;
var animating = false;
$(document).ready(function() {
$(".js-fade").addClass("fadeUp"); // must be remove right before animation
/*** allows the user to scroll through projects ***/
$('.project').bind('mousewheel', function(e) {
if(!animating) {
if(e.originalEvent.wheelDelta / 120 > 0) {
//alert('up');
previousProject();
} else {
//alert('down');
nextProject();
}
}
});
/*** controls the cool underline effect for the project title ***/
$( ".project__title" ).mousemove(function( event ) {
var x = (event.pageX - $('.project__title').offset().left) / $(".project__title").width() * 100;
var fraction = (1-(x/100))*100;
// console.log("Handler for .mousemove() called at " + event.pageX + ", " + event.pageY);
// 180% is left, 0% is right
$( ".project__title").css("background-position", fraction + "% 88%");
});
$( ".project__title" ).mouseleave(function() {
$( ".project__title").css("background-position", "0 88%");
});
// $(".project__img").click(function() {
//// $(".project:not(.project__img)").css("filter", "brightness(0.1)");
// $(".overlay").removeClass("hide");
// $(".project__img").addClass("unfilter");
// });
//
// $(".overlay").click(function() {
// $(".overlay").addClass("hide");
// $(".project__img").removeClass("unfilter");
// });
});
function nextProject() {
if(index == 0) {
$(".js-fade").removeClass("fadeUp");
}
if(index < (2*numProjects-2)) { // must be less than (2 * #projects - 2)
prepNextProject();
animating = true;
hideToLeft();
index += 2;
window.setTimeout(function() {
showFromRight();
animating = false;
}, 500);
}
}
function previousProject() {
if(index > 0) {
animating = true;
hideToRight();
index -= 2;
window.setTimeout(function() {
hideOldProject()
showFromLeft();
animating = false;
}, 500);
}
}
function hideToLeft() {
// var e1 = document.getElementsByClassName("js-proj")[index]; // image
// var e2 = document.getElementsByClassName("js-proj")[index + 1]; // description
$e1 = $(".js-proj:eq(" + index + ")");
$e2 = $(".js-proj:eq(" + (index+1) + ")");
$e1.addClass("exit");
window.setTimeout(function() {
$e2.addClass("exit");
}, 0);
}
function hideToRight() {
$e1 = $(".js-proj:eq(" + index + ")");
$e2 = $(".js-proj:eq(" + (index+1) + ")");
$e1.addClass("enter");
window.setTimeout(function() {
$e2.addClass("enter");
}, 0);
}
function showFromLeft() {
$e1 = $(".js-proj:eq(" + index + ")");
$e2 = $(".js-proj:eq(" + (index+1) + ")");
$e1.removeClass("exit");
window.setTimeout(function() {
$e2.removeClass("exit");
}, 0);
}
function showFromRight() {
$e1 = $(".js-proj:eq(" + index + ")");
$e2 = $(".js-proj:eq(" + (index+1) + ")");
$e1.removeClass("enter");
window.setTimeout(function() {
$e2.removeClass("enter");
}, 0);
}
function prepNextProject() {
$e3 = $(".js-proj:eq(" + index+2 + ")");
$e4 = $(".js-proj:eq(" + (index+3) + ")");
$e3.removeClass("hide");
$e4.removeClass("hide");
}
function hideOldProject() {
$e3 = $(".js-proj:eq(" + index+2 + ")");
$e4 = $(".js-proj:eq(" + (index+3) + ")");
$e3.addClass("hide");
$e4.addClass("hide");
}
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var App = require('app');
App.MainHostMenuView = Em.CollectionView.extend({
tagName: 'ul',
classNames: ["nav", "nav-tabs", "background-text"],
host: null,
content: function () {
return [
Em.Object.create({
name: 'summary',
label: Em.I18n.t('common.summary'),
routing: 'summary',
id: 'host-details-summary-tab'
}),
Em.Object.create({
name: 'configs',
label: Em.I18n.t('common.configs'),
routing: 'configs',
id: 'host-details-summary-configs'
}),
Em.Object.create({
name: 'alerts',
label: Em.I18n.t('hosts.host.alerts.label'),
routing: 'alerts',
badgeText: '0',
badgeClasses: 'label',
id: 'host-details-summary-alerts'
}),
Em.Object.create({
name: 'versions',
label: Em.I18n.t('hosts.host.menu.stackVersions'),
routing: 'stackVersions',
hidden: !App.get('stackVersionsAvailable'),
id: 'host-details-summary-version'
}),
Em.Object.create({
name: 'logs',
label: Em.I18n.t('hosts.host.menu.logs'),
routing: 'logs',
hidden: function () {
if (App.get('supports.logSearch')) {
return !(App.Service.find().someProperty('serviceName', 'LOGSEARCH') && App.isAuthorized('SERVICE.VIEW_OPERATIONAL_LOGS'));
}
return true;
}.property('App.supports.logSearch'),
id: 'host-details-summary-logs'
})
];
}.property('App.stackVersionsAvailable'),
/**
* Update Alerts menu option counter text and class
*/
updateAlertCounter: function () {
var criticalWarningCount = this.get('host.criticalWarningAlertsCount');
var criticalCount = this.get('host.alertsSummary.CRITICAL');
var warningCount = this.get('host.alertsSummary.WARNING');
var badgeText = "" + criticalWarningCount;
var badgeClasses = "label";
if (criticalCount > 0) {
badgeClasses += " alerts-crit-count";
} else if (warningCount > 0) {
badgeClasses += " alerts-warn-count";
}
var alertOption = this.get('content').findProperty('name', 'alerts');
alertOption.set('badgeText', badgeText);
alertOption.set('badgeClasses', badgeClasses);
}.observes('host.alertsSummary.CRITICAL', 'host.alertsSummary.WARNING', 'host.criticalWarningAlertsCount'),
init: function () {
this._super();
this.updateAlertCounter();
this.activateView();
},
activateView: function () {
var defaultRoute = App.router.get('currentState.name') || "summary";
$.each(this._childViews, function () {
this.set('active', (this.get('content.routing') == defaultRoute ? "active" : ""));
});
},
deactivateChildViews: function () {
this.get('_childViews').setEach('active', '');
},
itemViewClass: Em.View.extend({
classNameBindings: ["active"],
active: "",
template: Ember.Handlebars.compile('{{#unless view.content.hidden}}<a {{action hostNavigate view.content.routing }} {{bindAttr id="view.content.id"}} href="#"> {{unbound view.content.label}} ' +
'{{#if view.content.badgeText}} ' +
'<span {{bindAttr class="view.content.badgeClasses"}}> ' +
'{{view.content.badgeText}}' +
'</span> {{/if}}</a>{{/unless}}')
})
});
|
var path = require('path');
var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");
var config = require("./webpack.config.js");
var reverseProxyPort = 9001
var nodeServerPort = 8000
var cmsPort = 8080
var loadDashboardFromCms = false
var dashboardRedirectUrl = '127.0.0.1:' + nodeServerPort
if (loadDashboardFromCms !== false) {
dashboardRedirectUrl = '127.0.0.1:' + cmsPort + '/dashboard/'
}
// https://www.npmjs.com/package/redwire
var RedWire = require('redwire');
var redwire = new RedWire({
http: {
port: reverseProxyPort,
websockets: true
}
});
/**
* Cerberus is a couple services behind a router so we can simulate that locally
*/
// load the dashboard version from CMS (there are now versioned together)
redwire.http('http://localhost:' + reverseProxyPort + '/dashboard/version', '127.0.0.1:' + cmsPort + '/dashboard/version')
redwire.http('http://127.0.0.1:' + reverseProxyPort + '/dashboard/version', '127.0.0.1:' + cmsPort + '/dashboard/version')
// redirect dashboard to CMS or Webpack to live reload local development changes
redwire.http('http://localhost:' + reverseProxyPort + '/dashboard', dashboardRedirectUrl)
redwire.http('http://127.0.0.1:' + reverseProxyPort + '/dashboard', dashboardRedirectUrl)
redwire.http('http://localhost:' + reverseProxyPort + '/', dashboardRedirectUrl)
redwire.http('http://127.0.0.1:' + reverseProxyPort + '/', dashboardRedirectUrl)
// redirect /secret to CMS
redwire.http('http://localhost:' + reverseProxyPort + '/v1/secret', '127.0.0.1:' + cmsPort + '/v1/secret')
redwire.http('http://127.0.0.1:' + reverseProxyPort + '/v1/secret', '127.0.0.1:' + cmsPort + '/v1/secret')
// redirect rule for Cerberus Management Service
redwire.http('http://localhost:' + reverseProxyPort + '/v1', '127.0.0.1:' + cmsPort + '/v1')
redwire.http('http://127.0.0.1:' + reverseProxyPort + '/v1', '127.0.0.1:' + cmsPort + '/v1')
redwire.http('http://localhost:' + reverseProxyPort + '/v2', '127.0.0.1:' + cmsPort + '/v2')
redwire.http('http://127.0.0.1:' + reverseProxyPort + '/v2', '127.0.0.1:' + cmsPort + '/v2')
// configure proxy for hot module web socket
redwire.http('http://localhost:' + reverseProxyPort + '/sockjs-node', 'http://127.0.0.1:' + nodeServerPort + '/sockjs-node');
config.entry.app.unshift('webpack-dev-server/client?http://localhost:' + nodeServerPort + '/', 'webpack/hot/dev-server');
// run the local server
var compiler = webpack(config);
var server = new WebpackDevServer(compiler, {
contentBase: path.resolve(__dirname, "build"),
hot: true,
inline: true,
historyApiFallback: true,
// webpack-dev-middleware options
quiet: false,
noInfo: false,
lazy: false,
filename: 'browser-bundle.js',
watchOptions: {
aggregateTimeout: 300,
poll: 1000
},
stats: { colors: false }
});
server.listen(nodeServerPort, "0.0.0.0", function() {})
|
import React, { Component } from 'react';
import { storiesOf, action } from '@storybook/react';
import Table from '../../components/Table';
import TableHead from '../../components/TableHead'
import TableHeader from '../../components/TableHeader';
import TableBody from '../../components/TableBody';
import TableRow from '../../components/TableRow';
import TableRowExpanded from '../../components/TableRowExpanded';
import TableData from '../../components/TableData';
class NestedTable extends Component {
state = {
toggle: [],
}
toggleRow = (index) => {
const toggle = this.state.toggle;
toggle[index] = toggle[index] ? !toggle[index] : true;
this.setState({
toggle,
});
}
render() {
const data = [
[
'Harry',
'Potter',
'Gryffindor',
],
[
'Hermoine',
'Granger',
'Slytherin!?',
],
[
'Jon',
'Snow',
'Stark',
],
];
const relatedData = [
<p>The main character in Harry Potter</p>,
<p>The other main character</p>,
(
<Table>
<TableHead>
<TableRow header>
<TableHeader>First Name</TableHeader>
<TableHeader>Last Name</TableHeader>
<TableHeader>House</TableHeader>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableData>Harry</TableData>
<TableData>Potter</TableData>
<TableData>Gryffindor</TableData>
</TableRow>
</TableBody>
</Table>
),
];
const rowData = data.map((character, index) => {
const toggleState = this.state.toggle[index] ? this.state.toggle[index] : false;
const charArray = character.map((trait, charIndex) => <TableData key={`d${charIndex}`}>{trait}</TableData>);
return [
<TableData
onClick={() => this.toggleRow(index)}
key={`a${index}`}
expanded={toggleState}
/>,
...charArray,
];
});
const createRows = rowData.map((row, index) => (
<TableRow key={`b${index}`}>
{row}
</TableRow>
));
const createExpandedRows = relatedData.map((row, index) => {
const toggleState = this.state.toggle[index] ? this.state.toggle[index] : false;
return (
<TableRowExpanded
expanded={toggleState}
colSpan={4}
key={`c${index}`}
>
{row}
</TableRowExpanded>
);
});
const createTableBody = createRows.map((character, index) => [
character,
createExpandedRows[index],
]);
return (
<Table>
<TableHead>
<TableRow header>
<TableHeader />
<TableHeader>First Name</TableHeader>
<TableHeader>Last Name</TableHeader>
<TableHeader>House</TableHeader>
</TableRow>
</TableHead>
<TableBody>
{createTableBody}
</TableBody>
</Table>
);
}
}
storiesOf('Table', module)
.addWithInfo(
'Simple Table',
`
The Table component is the data-table implementation of blueix-components.
Create a table using Table, TableHead, Table Row, TableHeader, and TableBody. Each component maps to their HTML counterpart,
wrapped with carbon components styles.
Table doesn't do data-fetch for you or height/width calculations, it auto-fills it
to the native HTML spec. Any overrides you want to do can be passed in via props.
`,
() => (
<Table>
<TableHead>
<TableRow header>
<TableHeader>First Name</TableHeader>
<TableHeader>Last Name</TableHeader>
<TableHeader>House</TableHeader>
</TableRow>
</TableHead>
<TableBody>
<TableRow>
<TableData>Harry</TableData>
<TableData>Potter</TableData>
<TableData>Gryffindor</TableData>
</TableRow>
<TableRow>
<TableData>Hermoine</TableData>
<TableData>Granger</TableData>
<TableData>Gryffindor</TableData>
</TableRow>
<TableRow>
<TableData>Blaise</TableData>
<TableData>Zambini</TableData>
<TableData>Slytherin</TableData>
</TableRow>
<TableRow>
<TableData>Jon</TableData>
<TableData>Snow</TableData>
<TableData>Stark</TableData>
</TableRow>
</TableBody>
</Table>
),
)
.addWithInfo(
'Nested Table',
`
Nested table shows the expansion capabilities of the basic tables. Note that
this functionality is driven (like most of our components) through your application
altering props on the elements
`,
() => (
<NestedTable />
),
);
|
import { createTypes } from '../utils';
export default createTypes([
'GLOBAL_NAV_ON_MODULE_CHANGE'
]);
|
var Donation = BaseModel.extend({
urlRoot: "/api/donation",
defaults: {
accountNumber: null,
payee: null,
taxItem: "No Tax Item",
amount: null,
description: null
}
});
|
// ---------------------------------------
if (require.main === module)
throw (new Error ());
// ---------------------------------------
var crypto = require ("crypto");
var printf = require ("printf");
var riak = require ("riak-js");
var configuration = require ("./configuration")
var transcript = require ("./transcript") (module, configuration.libTranscriptLevel);
// ---------------------------------------
function _createConnector (_configuration) {
return (riak.getClient (_configuration));
}
function _generateFeedKey (_url) {
return (new crypto.Hash ("md5") .update (_url) .digest ("hex"));
}
function _generateFeedItemKey (_url, _id) {
return (new crypto.Hash ("md5") .update (_url) .update ("#") .update (_id) .digest ("hex"));
}
function _generateFeedTimelineKey (_url, _sequence) {
return (new crypto.Hash ("md5") .update (_url) .update ("#") .update (printf ("%08x", _sequence)) .digest ("hex"));
}
function _generateFeedDataKey (_url, _data) {
return (new crypto.Hash ("md5") .update (_data) .digest ("hex"));
}
function _generateFeedTaskKey (_url, _type) {
return (new crypto.Hash ("md5") .update (_url) .update ("#") .update (_type) .digest ("hex"));
}
// ---------------------------------------
function _createFeedMetaData (_riak, _key, _callback) {
var _feedMetaData = {
key : _key,
sequence : 0
};
_update (_riak, configuration.feedMetaDataBucket, _key, _feedMetaData, {contentType : "application/json"}, _callback);
}
function _fetchFeedMetaData (_riak, _key, _callback) {
_fetch (_riak, configuration.feedMetaDataBucket, _key, null,
function (_error, _feedMetaData, _riakMetaData) {
if (_error !== null) {
if (_feedMetaData === null)
_createFeedMetaData (_riak, _key, _callback);
else
_callback (_error, undefined, undefined);
} else
_callback (null, _feedMetaData, _riakMetaData);
});
}
function _updateFeedMetaData (_riak, _key, _feedMetaData, _riakMetaData, _callback) {
if (_riakMetaData) {
_riakMetaData.contentType = "application/json";
_riakMetaData.contentEncoding = undefined;
}
_update (_riak, configuration.feedMetaDataBucket, _key, _feedMetaData, _riakMetaData, _callback);
}
// ---------------------------------------
function _createFeedTimeline (_riak, _key, _feedTimeline, _callback) {
_update (_riak, configuration.feedTimelineBucket, _key, _feedTimeline, {contentType : "application/json"}, _callback);
}
// ---------------------------------------
function _createFeedItem (_riak, _key, _feedItem, _callback) {
_update (_riak, configuration.feedItemBucket, _key, _feedItem, {contentType : "application/json"}, _callback);
}
// ---------------------------------------
function _fetchFeedData (_riak, _key, _callback) {
_fetch (_riak, configuration.feedDataBucket, _key, {responseEncoding : "binary"}, _callback);
}
function _updateFeedData (_riak, _key, _feedData, _riakMetaData, _callback) {
_update (_riak, configuration.feedDataBucket, _key, _feedData, _riakMetaData, _callback);
}
// ---------------------------------------
function _fetchFeedTask (_riak, _key, _callback) {
_fetch (_riak, configuration.feedTaskBucket, _key, null, _callback);
}
function _updateFeedTask (_riak, _key, _feedTask, _riakMetaData, _callback) {
if (_riakMetaData) {
_riakMetaData.contentType = "application/json";
_riakMetaData.contentEncoding = undefined;
}
_update (_riak, configuration.feedTaskBucket, _key, _feedTask, _riakMetaData, _callback);
}
// ---------------------------------------
function _fetch (_riak, _bucket, _key, _riakMetaData, _callback) {
transcript.traceDebugging ("fetching `%s/%s`...", _bucket, _key);
_riak.get (_bucket, _key, _riakMetaData,
function (_error, _value, _riakMetaData) {
if (_error) {
if ((_riakMetaData !== undefined) && (_riakMetaData.statusCode == 404)) {
_riakMetaData.contentType = undefined;
_riakMetaData.contentEncoding = undefined;
_riakMetaData.contentRange = undefined;
_riakMetaData.etag = undefined;
_callback (null, null, _riakMetaData);
} else {
transcript.traceWarning ("failed fetching `%s/%s`: %s...", _bucket, _key, _error.toString ());
_callback ({reason : "unexpected-riak-error", message : _error.toString (), bucket : _bucket, key : _key, riakMetaData : _riakMetaData});
}
} else {
transcript.traceDebugging ("succeeded fetching `%s/%s`", _bucket, _key);
_callback (null, _value, _riakMetaData);
}
});
}
function _update (_riak, _bucket, _key, _value, _riakMetaData, _callback) {
transcript.traceDebugging ("updating `%s/%s`...", _bucket, _key);
if (_riakMetaData) {
_riakMetaData.headers = undefined;
_riakMetaData.etag = undefined;
_riakMetaData.contentRange = undefined;
}
_riak.save (_bucket, _key, _value, _riakMetaData,
function (_error, _riakMetaData) {
if (_error) {
transcript.traceWarning ("failed updating `%s/%s`: %s", _bucket, _key, _error.toString ());
_callback ({reason : "unexpected-riak-error", message : _error.toString (), bucket : _bucket, key : _key, riakMetaData : _riakMetaData});
} else {
transcript.traceDebugging ("succeeded updating `%s/%s`", _bucket, _key);
_callback (null, _value, _riakMetaData);
}
});
}
// ---------------------------------------
module.exports.createConnector = _createConnector;
module.exports.generateFeedKey = _generateFeedKey;
module.exports.generateFeedTimelineKey = _generateFeedTimelineKey;
module.exports.generateFeedItemKey = _generateFeedItemKey;
module.exports.generateFeedDataKey = _generateFeedDataKey;
module.exports.generateFeedTaskKey = _generateFeedTaskKey;
module.exports.fetchFeedMetaData = _fetchFeedMetaData;
module.exports.updateFeedMetaData = _updateFeedMetaData;
module.exports.createFeedTimeline = _createFeedTimeline;
module.exports.createFeedItem = _createFeedItem;
module.exports.fetchFeedData = _fetchFeedData;
module.exports.updateFeedData = _updateFeedData;
module.exports.fetchFeedTask = _fetchFeedTask;
module.exports.updateFeedTask = _updateFeedTask;
// ---------------------------------------
|
export default {
"typography.body.lineHeight": {
value: { ref: "basics.lineHeights.highExtraLarge" }
},
"typography.caption.lineHeight": {
value: { ref: "basics.lineHeights.highMedium" }
},
"typography.h1.lineHeight": {
value: { ref: "basics.lineHeights.highSmall" }
},
"typography.h2.lineHeight": {
value: { ref: "basics.lineHeights.highLarge" }
},
"typography.h3.lineHeight": {
value: { ref: "basics.lineHeights.highExtraExtraLarge" }
}
};
|
var canvasOverlay = null, viewport = null, map = null;
export class myCanvasOverlay {
constructor(viewport) {
this.state = {
canvas: null,
render: render,
viewport: viewport,
}
this.state.canvas = createOverlay();
canvasOverlay = this.state.canvas;
viewport = this.state.viewport;
}
}
function createOverlay() {
var canvasContainer = document.querySelector(".mapboxgl-canvas-container"),
mapboxCanvas = document.querySelector(".mapboxgl-canvas");
canvasOverlay = document.createElement("canvas");
canvasOverlay.style.position = "absolute";
canvasOverlay.className = "overlay-canvas";
canvasOverlay.width = parseInt(mapboxCanvas.style.width);
canvasOverlay.height = parseInt(mapboxCanvas.style.height);
canvasContainer.appendChild(canvasOverlay);
return canvasOverlay;
}
export function render(objs) {
if (canvasOverlay) {
var ctx = canvasOverlay.getContext("2d");
// ctx.clearRect(0,0,canv.width, canv.height);
_preSetCtx(ctx);
ctx.save();
// ctx.fillStyle = "rgba(240,200,20,.7)";
// ctx.fillRect(0,0,canv.width, canv.height);
ctx.shadowBlur = 4;
ctx.shadowColor = "rgba(255,255,255,.4)";
for(var i=0;i<objs.length;i++) {
var x = objs[i]['lon'], y = objs[i]['lat'],
pix = trans2pix(x, y);
if (pix == null) continue;
ctx.fillStyle = objs[i]['color'];
ctx.beginPath();
ctx.arc(pix[0], pix[1], 2, 0, Math.PI*2);
ctx.fill();
ctx.closePath();
}
ctx.restore()
}
}
function trans2pix(lng, lat) {
if (map != undefined && map.project instanceof Function) {
var lnglat = map.project(new mapboxgl.LngLat(
lng, lat));
var x = lnglat.x;
var y = lnglat.y;
return [x, y];
} else if (viewport && viewport.project) {
var lnglat = viewport.project([
lng, lat]);
var x = lnglat.x;
var y = lnglat.y;
return [x, y];
}
return [lng, lat];
}
function _preSetCtx(context) {
//默认值为source-over
var prev = context.globalCompositeOperation;
//只显示canvas上原图像的重叠部分 source-in, source, destination-in
context.globalCompositeOperation = 'destination-in';
//设置主canvas的绘制透明度
context.globalAlpha = 0.95;
//这一步目的是将canvas上的图像变的透明
// context.fillStyle = "rgba(0,0,0,.95)";
context.fillRect(0, 0, context.canvas.width, context.canvas.height);
//在原图像上重叠新图像
context.globalCompositeOperation = prev;
}
|
/**
* @description Risk SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M14,10 L15,10 L15,9 L14,9 L14,10 Z M18,10 L19,10 L19,9 L18,9 L18,10 Z M18,6 L19,6 L19,5 L18,5 L18,6 Z M14,6 L15,6 L15,5 L14,5 L14,6 Z M9,19 L10,19 L10,18 L9,18 L9,19 Z M5,15 L6,15 L6,14 L5,14 L5,15 Z M10,10 L1,10 L1,23 L14,23 L14,14 M10,14 L23,14 L23,1 L10,1 L10,14 Z"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-risk`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'risk');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M14,10 L15,10 L15,9 L14,9 L14,10 Z M18,10 L19,10 L19,9 L18,9 L18,10 Z M18,6 L19,6 L19,5 L18,5 L18,6 Z M14,6 L15,6 L15,5 L14,5 L14,6 Z M9,19 L10,19 L10,18 L9,18 L9,19 Z M5,15 L6,15 L6,14 L5,14 L5,15 Z M10,10 L1,10 L1,23 L14,23 L14,14 M10,14 L23,14 L23,1 L10,1 L10,14 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Risk';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
exports.STYLE_HINT = "hint";
exports.STYLE_LABEL = "label";
exports.TYPE_DATETIME = "datetime";
exports.TYPE_DATE = "date";
exports.TYPE_TIME = "time";
exports.TYPE_EMAIL = "email";
exports.TYPE_NUMBER = "number";
exports.TYPE_PASSWORD = "password";
exports.TYPE_PHONE = "phone";
exports.TYPE_PICKER = "picker";
exports.TYPE_TEXT = "text";
exports.TYPE_TEXTAREA = "textarea";
exports.TYPE_SUBMIT = "submit";
var isAndroid = true;
var textFieldDefaults = {
height: "40dp",
width: "250dp",
top: "10dp",
color: "#222",
borderStyle: Titanium.UI.INPUT_BORDERSTYLE_ROUNDED
};
var keyboardMap = {};
keyboardMap[exports.TYPE_EMAIL] = Ti.UI.KEYBOARD_EMAIL;
keyboardMap[exports.TYPE_NUMBER] = Ti.UI.KEYBOARD_NUMBER_PAD;
keyboardMap[exports.TYPE_PASSWORD] = Ti.UI.KEYBOARD_DEFAULT;
keyboardMap[exports.TYPE_PHONE] = Ti.UI.KEYBOARD_NUMBER_PAD;
keyboardMap[exports.TYPE_TEXT] = Ti.UI.KEYBOARD_DEFAULT;
var handleStyle = function(form, textField, title) {
if (form.fieldStyle === exports.STYLE_HINT && textField) textField.hintText = title; else {
form.container.add(Ti.UI.createLabel({
text: title,
top: "10dp",
left: "35dp",
color: "#222",
font: {
fontSize: "16dp",
fontWeight: "bold"
},
height: "auto",
width: "auto"
}));
textField && (textField.top = "5dp");
}
};
var ctr = 1;
var addField = function(field, fieldRefs) {
var title = field.title || "field" + ctr++;
var id = field.id || title;
var type = field.type || exports.TYPE_TEXT;
var form = this;
var fieldObject = void 0;
if (type === exports.TYPE_TEXT || type === exports.TYPE_EMAIL || type === exports.TYPE_NUMBER || type === exports.TYPE_PHONE || type === exports.TYPE_PASSWORD) {
fieldObject = Ti.UI.createTextField(textFieldDefaults);
fieldObject.keyboardType = keyboardMap[type];
fieldObject.passwordMask = type === exports.TYPE_PASSWORD;
handleStyle(form, fieldObject, title);
} else if (type === exports.TYPE_TEXTAREA) {
fieldObject = Ti.UI.createTextArea({
height: "150dp",
width: "250dp",
top: "10dp",
color: "#222",
borderWidth: 2,
borderColor: "#bbb",
borderRadius: 5,
keyboardType: Ti.UI.KEYBOARD_DEFAULT,
suppressReturn: false
});
handleStyle(form, fieldObject, title);
} else if (type === exports.TYPE_DATETIME) {
fieldObject = Ti.UI.createPicker({
type: Ti.UI.PICKER_TYPE_DATE_AND_TIME,
bottom: 0,
minDate: new Date(),
selectionIndicator: true
});
handleStyle(form, void 0, title);
} else if (type === exports.TYPE_DATE) {
fieldObject = Ti.UI.createPicker({
type: Ti.UI.PICKER_TYPE_DATE,
bottom: 0,
minDate: new Date(),
selectionIndicator: true
});
handleStyle(form, void 0, title);
} else if (type === exports.TYPE_TIME) {
fieldObject = Ti.UI.createPicker({
type: Ti.UI.PICKER_TYPE_TIME,
bottom: 0,
minDate: new Date(),
selectionIndicator: true
});
handleStyle(form, void 0, title);
} else if (type === exports.TYPE_PICKER) {
fieldObject = Ti.UI.createPicker({
type: Ti.UI.PICKER_TYPE_PLAIN,
width: "250dp"
});
handleStyle(form, void 0, title);
for (var i in field.data) fieldObject.add(Ti.UI.createPickerRow({
title: field.data[i]
}));
} else if (type === exports.TYPE_SUBMIT) {
var button = Ti.UI.createButton({
title: title,
height: "40dp",
width: "100dp",
top: "10dp"
});
button.addEventListener("click", function() {
var values = {};
for (var i in fieldRefs) values[i] = fieldRefs[i].value;
form.fireEvent(id, {
values: values
});
});
form.container.add(button);
}
if (fieldObject) {
form.container.add(fieldObject);
fieldRefs[id] = fieldObject;
}
};
var addFields = function(fields, fieldRefs) {
for (var i in fields) this.addField(fields[i], fieldRefs);
};
exports.createForm = function(o) {
var container = Ti.UI.createView({
layout: "vertical",
height: "auto"
});
var fieldRefs = {};
var form = Ti.UI.createScrollView({
contentHeight: "auto",
contentWidth: "auto",
showVerticalScrollIndicator: true,
showHorizontalScrollIndicator: true,
container: container,
fieldStyle: o.style || exports.STYLE_HINT,
addField: addField,
addFields: addFields
});
form.addFields(o.fields, fieldRefs);
form.add(container);
form.fieldRefs = fieldRefs;
return form;
};
|
// Copyright 2012 Applied Geographics, Inc. Licensed under the Apache License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0
$(function () {
var $all = $("body").find("*");
var $labRefreshing = $("#labRefreshing");
$("#cmdReloadConfiguration").on("click", function () {
$all.css("cursor", "wait");
$labRefreshing.show();
$.get("?reload=1&v=" + (new Date()).valueOf(), function (result) {
$all.css("cursor", "");
$labRefreshing.hide();
});
});
$(".ReportHeader")
.on("dragstart selectstart", function (e) { e.preventDefault(); })
.on("click", function (e) {
var $this = $(this);
if (!e.shiftKey) {
$this.toggleClass("Closed").toggleClass("Opened").nextUntil(".ReportSpacer").toggle($this.hasClass("Opened"));
}
else {
var close = $this.hasClass("Opened");
$(".ReportHeader").toggleClass("Closed", close).toggleClass("Opened", !close);
$(".ReportRow").toggle(!close);
}
});
});
|
var todo = {};
todo.Todo = function(data) {
this.description = m.prop(data.description);
this.done = m.prop(false);
};
todo.TodoList = Array;
// ビュー・モデル
todo.vm = (function () {
var vm = {}
vm.init = function () {
// アクティブなToDoのリスト
vm.list = new todo.TodoList();
// 新しいToDo作成用
vm.description = m.prop("");
// ToDoをリストに登録する
vm.add = function () {
if (vm.description()) {
vm.list.push(new todo.Todo({description: vm.description()}));
vm.description("");
}
};
}
return vm
}())
// コントローラ
// モデルのどの部分が現在のページと関連するのかを定義する
// この場合は1つのビュー・モデルですべてを取り仕切っている
todo.controller = function () {
todo.vm.init()
}
// ビュー
todo.view = function () {
return m("html", [
m("body", [
m("input", {onchange: m.withAttr("value", todo.vm.description), value: todo.vm.description()}),
m("button", {onclick: todo.vm.add}, "追加"),
m("table", [
todo.vm.list.map(function (task, index) {
return m("tr", [
m("td", [
m("input[type=checkbox]", {onclick: m.withAttr("checked", task.done), checked: task.done()})
]),
m("td", {style: {textDecoration: task.done() ?"line-through" : "none"}}, task.description()),
])
})
])
])
]);
};
// アプリケーションの初期化
m.mount(document, {controller: todo.controller, view: todo.view});
|
Vericall = (function() {
var apikey, missCall, vericallApiCall, verify;
apikey = process.env.VERICALL_APIKEY;
if (!apikey) console.log('Can not find VERICALL_APIKEY');
vericallApiCall = function(url, data, cb) {
if (!(url && data)) return false;
var callParams = {
params: data,
headers: {"Content-Type": "application/x-www-form-urlencoded"}
};
callParams.params.api_key = apikey;
try {
if (typeof cb === 'function') {
return HTTP.post(url, callParams, function(err, res) {
var jres;
if (err) return cb(err);
jres = JSON.parse(res.content);
if (!jres.status) return cb(new Meteor.Error(404, jres.message));
return cb(null, jres);
});
} else {
res = HTTP.post(url, callParams);
return JSON.parse(res.content);
}
} catch (error) {
if (typeof cb === 'function') return cb(new Meteor.Error(400, 'vericall_connection'));
return {status: false, message: 'Vericall Connection Error'};
}
};
missCall = function(to_number, cb) {
if (!to_number) return false;
return vericallApiCall("http://api.vericall.org/api/call_request", {
to_number: to_number
}, cb);
};
verify = function(request_id, token, cb) {
if (!(request_id && token)) return false;
return vericallApiCall("http://api.vericall.org/api/verify", {
from_number: token,
request_id: request_id
}, cb);
};
return {
missCall: missCall,
verify: verify
};
})();
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { useFeature } from 'flagged';
import {
useCallback,
useMemo,
useState,
useEffect,
} from '@googleforcreators/react';
import { trackEvent } from '@googleforcreators/tracking';
import { getMsFromHMS } from '@googleforcreators/media';
/**
* Internal dependencies
*/
import { useCanvas, useStory, useAPI, useLocalMedia } from '../../app';
import useFFmpeg from '../../app/media/utils/useFFmpeg';
function useVideoTrimMode() {
const isVideoTrimEnabled = useFeature('enableVideoTrim');
const { isEditing, isTrimMode, setEditingElementWithState, clearEditing } =
useCanvas(
({
state: { isEditing, editingElementState: { isTrimMode } = {} },
actions: { setEditingElementWithState, clearEditing },
}) => ({
isEditing,
isTrimMode,
setEditingElementWithState,
clearEditing,
})
);
const { selectedElement } = useStory(({ state: { selectedElements } }) => ({
selectedElement: selectedElements.length === 1 ? selectedElements[0] : null,
}));
const {
actions: { getMediaById },
} = useAPI();
const [videoData, setVideoData] = useState(null);
const { isCurrentResourceUploading } = useLocalMedia(
({ state: { isCurrentResourceUploading } }) => ({
isCurrentResourceUploading,
})
);
const getVideoData = useCallback(() => {
const { resource } = selectedElement;
const { trimData } = resource;
const defaultVideoData = {
element: selectedElement,
resource,
start: 0,
end: null,
};
if (getMediaById && trimData?.original) {
// First clear any existing data
setVideoData(null);
// Load correct video resource
getMediaById(trimData.original)
.then(
// If exists, use as resource with offsets
(originalResource) => ({
element: selectedElement,
resource: originalResource,
start: getMsFromHMS(trimData.start),
end: getMsFromHMS(trimData.end),
}),
// If load fails, pretend there's no original
() => defaultVideoData
)
// Regardless, set resulting data as video data
.then((data) => setVideoData(data));
} else {
setVideoData(defaultVideoData);
}
}, [getMediaById, selectedElement]);
useEffect(() => {
if (selectedElement?.resource?.trimData) {
getVideoData();
}
}, [selectedElement, getVideoData]);
const toggleTrimMode = useCallback(() => {
if (isEditing) {
clearEditing();
} else {
setEditingElementWithState(selectedElement.id, {
isTrimMode: true,
hasEditMenu: true,
showOverflow: false,
});
getVideoData();
}
trackEvent('video_trim_mode_toggled', {
status: isEditing ? 'closed' : 'open',
});
}, [
isEditing,
clearEditing,
setEditingElementWithState,
selectedElement,
getVideoData,
]);
const { isTranscodingEnabled } = useFFmpeg();
const hasTrimMode = useMemo(() => {
if (selectedElement?.type !== 'video' || !selectedElement?.resource) {
return false;
}
const { id, isExternal } = selectedElement.resource;
return (
isVideoTrimEnabled &&
isTranscodingEnabled &&
!isExternal &&
!isCurrentResourceUploading(id)
);
}, [
selectedElement,
isVideoTrimEnabled,
isTranscodingEnabled,
isCurrentResourceUploading,
]);
return {
isTrimMode: Boolean(isEditing && isTrimMode),
hasTrimMode,
toggleTrimMode,
videoData,
};
}
export default useVideoTrimMode;
|
import onError from '../src/onError';
import { store as mock } from '../src/mock';
window.addEventListener = jest.fn();
window.removeEventListener = jest.fn();
function activateSentry() {
window.Sentry = {
captureException: jest.fn(),
configureScope: jest.fn(),
init: jest.fn(c => {
if (c.dsn === 'fail') {
throw new Error('mock fail');
}
}),
withScope: jest.fn(),
};
}
describe('onError', () => {
let store;
let state;
let config;
beforeEach(() => {
state = { foo: { ok: 'should be kept', password: 'secret', keyUndefined: undefined } };
store = mock.store(state);
window.addEventListener.mockClear();
store.dispatch = jest.fn();
console.error = jest.fn();
config = {
onError: {
reportURL: '/api/v1/report',
},
};
process.env.NODE_ENV = 'production';
onError.bootstrap(config, store);
jest.clearAllMocks();
});
afterEach(() => {
delete process.env.NODE_ENV;
delete window.Sentry;
});
describe('getReportInfo', () => {
it('should fill internal values', () => {
expect(onError.hasReportURL()).toBe(true);
const info = onError.getReportInfo(new Error('my'));
expect(info.actions).toEqual([]);
expect(info.browser.startsWith('Mozilla')).toBeTruthy();
expect(info.error).toMatchObject({
message: 'my',
name: 'Error',
stack: expect.anything(),
});
});
});
describe('report', () => {
it('should dispatch ERROR action if no serverURL', () => {
config = {
onError: {},
};
onError.bootstrap(config, store);
expect(store.dispatch).not.toHaveBeenCalled();
const error = new Error('my');
onError.report(error);
expect(store.dispatch).toHaveBeenCalled();
const action = store.dispatch.mock.calls[0][0];
expect(action.type).toBe('REACT_CMF.ERROR');
expect(action.reported).toBe(false);
expect(action.error.message).toBe('my');
});
});
describe('middleware', () => {
it('should let normal action happens', () => {
const mid = onError.middleware();
const next = jest.fn();
const action = {
type: 'TEST',
};
mid(next)(action);
expect(next).toHaveBeenCalledWith(action);
});
it('should report if next throw exception', () => {
const mid = onError.middleware();
const next = () => {
throw new Error('sth bad');
};
const action = {
type: 'TEST',
};
expect(console.error).not.toHaveBeenCalled();
mid(next)(action);
expect(console.error).toHaveBeenCalled();
const log = console.error.mock.calls[0][0];
expect(log.message).toBe('sth bad');
const dispatched = store.dispatch.mock.calls[0][0];
expect(dispatched.type).toBe('POST');
expect(dispatched.body).toContain('sth bad');
});
it('should add action in singleton', () => {
const mid = onError.middleware();
const next = jest.fn();
const action = {
type: 'FOO',
sensitive: true,
};
mid(next)(action);
const info = onError.getReportInfo(new Error('my'));
expect(info.actions.length).toBe(1);
expect(info.actions[0]).toBe('FOO');
});
it('should keep last 20 actions', () => {
// eslint-disable-next-line no-plusplus
const mid = onError.middleware();
const next = jest.fn();
for (let index = 0; index < 30; index++) {
mid(next)({ type: `FOO ${index}`, password: 'secret' });
}
const info = onError.getReportInfo(new Error('my'));
expect(info.actions.length).toBe(20);
expect(info.actions[0]).toBe('FOO 10');
});
});
describe('createObjectURL', () => {
it('should use window.URL.createObjectURL', () => {
window.URL.createObjectURL = jest.fn();
const error = new Error('sth bad 2');
onError.createObjectURL(error);
expect(window.URL.createObjectURL).toHaveBeenCalled();
const blob = window.URL.createObjectURL.mock.calls[0][0];
expect(blob.name).toBe('report.json');
expect(blob.type).toBe('application/json');
expect(blob.size).toBeGreaterThan(0);
});
});
describe('revokeObjectURL', () => {
it('should use window.URL.revokeObjectURL', () => {
const url = {};
window.URL.revokeObjectURL = jest.fn();
onError.revokeObjectURL(url);
expect(window.URL.revokeObjectURL).toHaveBeenCalledWith(url);
});
});
describe('sentry', () => {
it('report should call captureException', () => {
config = {
onError: {},
};
activateSentry();
onError.bootstrap(config, store);
const error = new Error('foo');
onError.report(error);
expect(window.Sentry.captureException).toHaveBeenCalledWith(error);
});
it('report should call withScope with options.tags', () => {
config = {
onError: {},
};
activateSentry();
onError.bootstrap(config, store);
const options = { tags: [{ key: 'tag', value: 'value' }] };
const error = new Error('foo');
const setTag = jest.fn();
onError.report(error, options);
expect(window.Sentry.withScope).toHaveBeenCalled();
const onScope = window.Sentry.withScope.mock.calls[0][0];
onScope({ setTag });
expect(setTag).toHaveBeenCalledWith('tag', 'value');
});
});
});
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
/**
* Todo App Demo for Tungsten.js
*/
'use strict';
import { Backbone } from 'tungstenjs';
var history = Backbone.history;
var Router = Backbone.Router;
var app, router;
var TodoRouter = Router.extend({
routes: {
'*filter': 'setFilter'
},
setFilter: function (filter) {
// Trigger a collection filter event, causing hiding/unhiding of Todo view items
app.trigger('filter', filter || '');
}
});
module.exports = {
init: function(a) {
app = a;
if (!history.started) {
router = new TodoRouter();
history.start();
}
}
};
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var Linter = require( 'eslint' ).Linter;
var rule = require( './../lib' );
var linter = new Linter();
var result;
var code;
// Generate our source code:
code = [
'/**',
'* Beep boop.',
'*',
'* ## Beep ##',
'*',
'* boop',
'*',
'* Boop',
'* ----',
'*',
'* beep',
'*',
'* @param {string} str - input value',
'* @returns {string} output value',
'*',
'* @example',
'* var out = beep( "boop" );',
'* // returns "beepboop"',
'*/',
'function beep( str ) {',
'\treturn "beep" + str;',
'}'
].join( '\n' );
// Register the ESLint rule:
linter.defineRule( 'jsdoc-heading-style', rule );
// Lint the code:
result = linter.verify( code, {
'rules': {
'jsdoc-heading-style': 'error'
}
});
console.log( result );
/* =>
[
{
'ruleId': 'jsdoc-heading-style',
'severity': 2,
'message': 'Headings should use atx',
'line': 4,
'column': 3,
'nodeType': null,
'source': '* ## Boop ##',
'endLine': 19,
'endColumn': 3
},
{
'ruleId': 'jsdoc-heading-style',
'severity': 2,
'message': 'Headings should use atx',
'line': 8,
'column': 3,
'nodeType': null,
'source': '* Boop',
'endLine': 19,
'endColumn': 3
}
]
*/
|
/*
* KodeBlox Copyright 2020 Sayak Mukhopadhyay
*
* 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 express = require('express')
const path = require('path')
const logger = require('morgan')
const bodyParser = require('body-parser')
const secrets = require('./secrets')
const bugsnagClient = require('./server/bugsnag').bugsnagClient
const app = express()
let bugsnagClientMiddleware = {}
if (secrets.bugsnag_use) {
bugsnagClientMiddleware = bugsnagClient.getPlugin('express')
app.use(bugsnagClientMiddleware.requestHandler)
}
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'dist')))
app.all('*', (req, res) => {
res.status(200).sendFile(path.join(__dirname, 'dist', 'index.html'))
});
// error handlers
if (secrets.bugsnag_use) {
app.use(bugsnagClientMiddleware.errorHandler)
}
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(logger('dev'))
app.use(function (err, req, res, next) {
res.status(err.status || 500)
res.send({
message: err.message,
error: err
})
console.log(err)
})
}
// production error handler
// no stacktraces leaked to user
if (app.get('env') === 'production') {
app.use(logger('combined'))
app.use(function (err, req, res, next) {
res.status(err.status || 500)
res.send({
message: err.message,
error: {}
})
})
}
module.exports = app
|
exports.definition = {
config: {
columns: {
"name": "string",
"point": "interger"
},
adapter: {
type:"localstorage",
collection_name: "scoreboardlist"
}
},
extendModel: function(Model) {
_.extend(Model.prototype, {
// extended functions and properties go here
});
return Model;
},
extendCollection: function(Collection) {
_.extend(Collection.prototype, {
// extended functions and properties go here
});
return Collection;
}
};
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
var TableServerDeliveryServicesController = function(server, serverDeliveryServices, $scope, $state, locationUtils) {
$scope.server = server;
$scope.serverDeliveryServices = serverDeliveryServices;
$scope.cloneDsAssignments = function() {
alert('not hooked up yet: cloneDsAssignments');
};
$scope.addDeliveryService = function() {
alert('not hooked up yet: addDeliveryService to server');
};
$scope.removeDeliveryService = function() {
alert('not hooked up yet: removeDeliveryService from server');
};
$scope.refresh = function() {
$state.reload(); // reloads all the resolves for the view
};
$scope.navigateToPath = locationUtils.navigateToPath;
angular.element(document).ready(function () {
$('#deliveryServicesTable').dataTable({
"aLengthMenu": [[25, 50, 100, -1], [25, 50, 100, "All"]],
"iDisplayLength": 100
});
});
};
TableServerDeliveryServicesController.$inject = ['server', 'serverDeliveryServices', '$scope', '$state', 'locationUtils'];
module.exports = TableServerDeliveryServicesController;
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(project, resource, testPermissionsRequestResource) {
// [START compute_v1_generated_Images_TestIamPermissions_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Project ID for this request.
*/
// const project = 'my-project'
/**
* Name or id of the resource for this request.
*/
// const resource = 'abc123'
/**
* The body resource for this request
*/
// const testPermissionsRequestResource = {}
// Imports the Compute library
const {ImagesClient} = require('@google-cloud/compute').v1;
// Instantiates a client
const computeClient = new ImagesClient();
async function callTestIamPermissions() {
// Construct request
const request = {
project,
resource,
testPermissionsRequestResource,
};
// Run request
const response = await computeClient.testIamPermissions(request);
console.log(response);
}
callTestIamPermissions();
// [END compute_v1_generated_Images_TestIamPermissions_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
|
/**
* View Engine Configuration
* (sails.config.views)
*
* Server-sent views are a classic and effective way to get your app up
* and running. Views are normally served from controllers. Below, you can
* configure your templating language/framework of choice and configure
* Sails' layout support.
*
* For more information on views and layouts, check out:
* http://sailsjs.org/#/documentation/concepts/Views
*/
module.exports.views = {
/****************************************************************************
* *
* View engine (aka template language) to use for your app's *server-side* *
* views *
* *
* Sails+Express supports all view engines which implement TJ Holowaychuk's *
* `consolidate.js`, including, but not limited to: *
* *
* ejs, jade, handlebars, mustache underscore, hogan, haml, haml-coffee, *
* dust atpl, eco, ect, jazz, jqtpl, JUST, liquor, QEJS, swig, templayed, *
* toffee, walrus, & whiskers *
* *
* For more options, check out the docs: *
* https://github.com/balderdashy/sails-wiki/blob/0.9/config.views.md#engine *
* *
****************************************************************************/
// engine: 'ejs',
/****************************************************************************
* *
* Layouts are simply top-level HTML templates you can use as wrappers for *
* your server-side views. If you're using ejs or jade, you can take *
* advantage of Sails' built-in `layout` support. *
* *
* When using a layout, when one of your views is served, it is injected *
* into the `body` partial defined in the layout. This lets you reuse header *
* and footer logic between views. *
* *
* NOTE: Layout support is only implemented for the `ejs` view engine! *
* For most other engines, it is not necessary, since they implement *
* partials/layouts themselves. In those cases, this config will be *
* silently ignored. *
* *
* The `layout` setting may be set to one of the following: *
* *
* If `false`, layouts will be disabled. Otherwise, if a string is *
* specified, it will be interpreted as the relative path to your layout *
* file from `views/` folder. (the file extension, ".ejs", should be *
* omitted) *
* *
****************************************************************************/
layout: 'layout'
/****************************************************************************
* *
* Using Multiple Layouts with EJS *
* *
* If you're using the default engine, `ejs`, Sails supports the use of *
* multiple `layout` files. To take advantage of this, before rendering a *
* view, override the `layout` local in your controller by setting *
* `res.locals.layout`. (this is handy if you parts of your app's UI look *
* completely different from each other) *
* *
* e.g. your default might be *
* layout: 'layouts/public' *
* *
* But you might override that in some of your controllers with: *
* layout: 'layouts/internal' *
* *
****************************************************************************/
};
|
'use strict';
var config = require('../../config');
/*
* Code samples from:
* http://docs.basho.com/riak/latest/dev/advanced/bucket-types/
*/
var assert = require('assert');
var async = require('async');
var logger = require('winston');
var Riak = require('basho-riak-client');
function DevAdvancedBucketTypes(done) {
var client = config.createClient(function (err, c) {
if (err) {
throw new Error(err);
}
var funcs = [
default_type_example,
client_usage_example,
memes_example
];
async.parallel(funcs, function (err, rslts) {
if (err) {
throw new Error(err);
}
c.stop(function (err) {
if (err) {
logger.error('[DevAdvancedBucketTypes] err: %s', err);
}
done();
});
});
});
function default_type_example(async_cb) {
var obj1 = new Riak.Commands.KV.RiakObject();
obj1.setContentType('text/plain');
obj1.setBucketType('default');
obj1.setBucket('my_bucket');
obj1.setKey('my_key');
obj1.setValue('value');
client.storeValue({ value: obj1 }, function (err, rslt) {
if (err) {
throw new Error(err);
}
client.fetchValue({
bucketType: 'default', bucket: 'my_bucket', key: 'my_key'
}, function (err, rslt) {
if (err) {
throw new Error(err);
}
var obj2 = rslt.values.shift();
assert(obj1.value == obj2.value);
logger.info("[DevAdvancedBucketTypes] obj1 val: '%s', obj2 val: '%s'",
obj1.value.toString('utf8'), obj2.value.toString('utf8'));
async_cb();
});
});
}
function client_usage_example(async_cb) {
var obj = { name: 'Bob' };
client.storeValue({
bucketType: 'no_siblings', bucket: 'sensitive_user_data', key: 'user19735',
value: obj
}, function (err, rslt) {
if (err) {
throw new Error(err);
}
async_cb();
});
}
function memes_example(async_cb) {
var obj = new Riak.Commands.KV.RiakObject();
obj.setContentType('text/plain');
obj.setBucketType('no_siblings');
obj.setBucket('old_memes');
obj.setKey('all_your_base');
obj.setValue('all your base are belong to us');
client.storeValue({ value: obj }, function (err, rslt) {
if (err) {
throw new Error(err);
}
async_cb();
});
}
}
module.exports = DevAdvancedBucketTypes;
|
import * as actions from './constants';
import gardensApi from '../services/gardensApi';
import shortid from 'shortid';
import _ from 'lodash';
export function addPlantInstance(id) {
return dispatch => {
dispatch({ type: actions.ADDING_PLANT });
dispatch({
type: actions.ADDED_PLANT,
payload: id
});
};
}
export function newGarden(garden, goToGarden) {
return dispatch => {
dispatch({
type: actions.ADDING_GARDEN
});
gardensApi.add(garden)
.then(({savedGarden, slimUser}) => {
dispatch({
type: actions.ADDED_GARDEN,
payload: savedGarden
});
dispatch({
type: 'FETCHED_USER',
payload: slimUser
});
goToGarden(savedGarden._id);
}, error => {
dispatch({
type: actions.ADD_GARDEN_ERROR,
payload: error
});
});
};
}
export function getGardenById(id) {
return dispatch => {
dispatch({
type: actions.FETCHING_GARDEN
});
gardensApi.get(id)
.then(garden => {
dispatch({
type: actions.FETCHED_GARDEN,
payload: garden
});
}, error => {
dispatch({
type: actions.FETCHED_GARDEN_ERROR,
payload: error
});
});
};
}
export function plotClicked( garden, plantId, xPosition, yPosition) {
return (dispatch, getState) => {
const { activeAction } = getState();
if(activeAction === 'ADD') {
dispatch({
type: actions.ADDING_PLANT });
const newGardenPlot = _.cloneDeep(garden.plot) || [];
newGardenPlot.push({
plantId,
xPosition,
yPosition
});
gardensApi.updatePlot(garden._id, newGardenPlot)
.then( newGarden => {
dispatch({
type: actions.ADDED_PLANT,
payload: newGarden
});
})
.catch(error => {
dispatch({
type: actions.ADD_PLANT_ERROR,
payload: error
});
});
}
if(activeAction === 'REMOVE') {
dispatch({
type: actions.REMOVING_PLANT });
const newGarden = Object.create(garden);
newGarden.plot[plantId] = null;
gardensApi.update(newGarden)
.then(({savedGarden, slimUser}) => {
dispatch({
type: actions.ADDED_PLANT,
payload: savedGarden
});
dispatch({
type: 'FETCHED_USER',
payload: slimUser
});
})
.catch(error => {
dispatch({
type: actions.REMOVE_PLANT_ERROR,
payload: error
});
});
}
};
}
|
var a00911 =
[
[ "add_on", "a00911.html#a509b4ea71aff570b44c9498cb472561e", null ],
[ "next_one", "a00911.html#a42590f43649b9cb44df50a41cf419546", null ],
[ "count", "a00911.html#acd4ea858d7133e40518e0832ff9d94b2", null ],
[ "delete_d", "a00911.html#a1fa3ecce52a0563f595b8f1428cc1211", null ],
[ "delete_d", "a00911.html#a3ce6cf5774db75528fd783db17bfb307", null ],
[ "destroy", "a00911.html#a338e68bdadcbdf51db4c7268c4529409", null ],
[ "destroy_nodes", "a00911.html#a1a1efc1a269e5bb5bf16c1a174363ba4", null ],
[ "insert", "a00911.html#a32592fff9af11f3c35bd4c4f57733fd2", null ],
[ "is_same", "a00911.html#a401c3dd163e034a46805fc1544d4ed58", null ],
[ "is_same_node", "a00911.html#a741b51b53773baf5cc5597d6926b83e4", null ],
[ "join", "a00911.html#a185e827874145ed10ce9db702a34f671", null ],
[ "last", "a00911.html#ad9ec1d10cbd07fc3376ef300df603418", null ],
[ "nth_cell", "a00911.html#ae770a79e91f79e9bc159267eaf9a9a86", null ],
[ "pop", "a00911.html#a4a16ea0d766f4b3bc697142d5303a62c", null ],
[ "push", "a00911.html#a9c4294375af81ab4c133b6b5a3679a16", null ],
[ "push_last", "a00911.html#a1019c2e1108695bb4f33f83e02ee62ad", null ],
[ "reverse", "a00911.html#ade6fcdcd343af2f9b32c79583a5a0637", null ],
[ "reverse_d", "a00911.html#a1316854253b2d15102f4f50d2e7eee02", null ],
[ "s_adjoin", "a00911.html#aff044482629d5faed80f830b0fcf7513", null ],
[ "search", "a00911.html#a1d8af9328f064a9df6d6f88336dd054e", null ],
[ "search", "a00911.html#a100f61ca2625c14d958fff37058fcc52", null ]
];
|
/**
* ENV constant parse to boolean.
* @param {any} value Any type value
*/
export function boolean(value) {
return !!eval(value);
}
/**
* ENV constant parse to integer.
* @param {any} value Any type value
*/
export function integer(value) {
return parseInt(value);
}
/**
* ENV constant parse to float.
* @param {any} value Any type value
*/
export function float(value) {
return parseFloat(value);
}
|
// Copyright 2017 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
'use strict';
const express = require('express');
const path = require('path');
const proxyquire = require('proxyquire').noPreserveCache();
const request = require('supertest');
const sinon = require('sinon');
const assert = require('assert');
const SAMPLE_PATH = path.join(__dirname, '../app.js');
const getSample = () => {
const testApp = express();
const expressMock = sinon.stub().returns(testApp);
const app = proxyquire(SAMPLE_PATH, {
express: expressMock,
});
return {
app: app,
mocks: {
express: expressMock,
},
};
};
const stubConsole = function () {
sinon.stub(console, 'error');
};
const restoreConsole = function () {
console.error.restore();
};
beforeEach(stubConsole);
afterEach(restoreConsole);
it('sets up the sample', done => {
const sample = getSample();
assert.ok(sample.mocks.express.calledOnce);
done();
});
it('should echo a message', async () => {
const sample = getSample();
await request(sample.app)
.post('/echo')
.send({message: 'foo'})
.expect(200)
.expect(response => {
assert.strictEqual(response.body.message, 'foo');
});
});
it('should try to parse encoded info', async () => {
const sample = getSample();
await request(sample.app)
.get('/auth/info/googlejwt')
.expect(200)
.expect(response => {
assert.deepStrictEqual(response.body, {id: 'anonymous'});
});
});
it('should successfully parse encoded info', async () => {
const sample = getSample();
await request(sample.app)
.get('/auth/info/googlejwt')
.set(
'X-Endpoint-API-UserInfo',
Buffer.from(JSON.stringify({id: 'foo'})).toString('base64')
)
.expect(200)
.expect(response => {
assert.deepStrictEqual(response.body, {id: 'foo'});
});
});
|
/*
* Module dependencies
*/
var express = require('express')
, stylus = require('stylus')
, nib = require('nib');
global.config = require('konfig')();
var app = express()
function compile(str, path) {
return stylus(str)
.set('filename', path)
.use(nib())
}
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.logger('dev'))
app.use(stylus.middleware(
{ src: __dirname + '/public'
, compile: compile
}
))
app.use(express.static(__dirname + '/public'))
require('./routes/routes.js')(app);
app.listen(2999)
|
'use strict';
angular.module('starter.services').factory('publicationService', function($http, $log) {
var root = {};
root.setPublication = function(data, cb) {
var req = {
method: 'POST',
url: 'http://192.168.1.109:3000/publication',
headers: {
'Content-Type': 'multipart/form-data'
},
data: data
};
$http(req).then(function(data) {
return cb(null, data.data);
}, function(err) {
return cb(err);
});
};
return root;
});
|
/*
* Copyright 2018 Rundeck, Inc. (http://rundeck.com)
*
* 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.
*/
//= require knockout.min
//= require ko/handler-bootstrapPopover
//= require ko/handler-bootstrapTooltip
|
/*
Copyright 2017 SabzCity
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.
*/
import { Element as PolymerElement } from '../../@polymer/polymer/polymer-element.js'
import './a-style.js'
import { appDistinctions } from './a-app-distinctions.js'
class AppHTTP404 extends PolymerElement {
static get is() { return 'app-http-404' }
static get template() {
//
return `<span>404-Not Found</span>`
}
}
window.customElements.define(AppHTTP404.is, AppHTTP404);
|
t = db.mr_stored;
t.drop();
t.save({"partner": 1, "visits": 9});
t.save({"partner": 2, "visits": 9});
t.save({"partner": 1, "visits": 11});
t.save({"partner": 1, "visits": 30});
t.save({"partner": 2, "visits": 41});
t.save({"partner": 2, "visits": 41});
m = function(obj) {
emit(obj.partner, {stats: [obj.visits]});
};
r = function(k, v) {
var stats = [];
var total = 0;
for (var i = 0; i < v.length; i++) {
for (var j in v[i].stats) {
stats.push(v[i].stats[j]);
total += v[i].stats[j];
}
}
return {stats: stats, total: total};
};
// Test that map reduce works with stored javascript
db.system.js.save({_id: "mr_stored_map", value: m});
db.system.js.save({_id: "mr_stored_reduce", value: r});
res = t.mapReduce(
function() {
mr_stored_map(this);
},
function(k, v) {
return mr_stored_reduce(k, v);
},
{out: "mr_stored_out", scope: {xx: 1}});
// res.find().forEach( printjson )
z = res.convertToSingleObject();
assert.eq(2, Object.keySet(z).length, "A1");
assert.eq([9, 11, 30], z["1"].stats, "A2");
assert.eq([9, 41, 41], z["2"].stats, "A3");
res.drop();
m = function(obj) {
var x = "partner";
var y = "visits";
emit(obj[x], {stats: [obj[y]]});
};
db.system.js.save({_id: "mr_stored_map", value: m});
res = t.mapReduce(
function() {
mr_stored_map(this);
},
function(k, v) {
return mr_stored_reduce(k, v);
},
{out: "mr_stored_out", scope: {xx: 1}});
// res.find().forEach( printjson )
z = res.convertToSingleObject();
assert.eq(2, Object.keySet(z).length, "B1");
assert.eq([9, 11, 30], z["1"].stats, "B2");
assert.eq([9, 41, 41], z["2"].stats, "B3");
db.system.js.remove({_id: "mr_stored_map"});
db.system.js.remove({_id: "mr_stored_reduce"});
res.drop();
|
/**
* © OpenCORD
*
* Visit http://guide.xosproject.org/devguide/addview/ for more information
*
* Created by teone on 6/27/16.
*/
(function () {
'use strict';
angular.module('xos.ecordTopology')
.service('Uni', ($resource, _) => {
return $resource(`/api/service/metronetworkservice/SCA_ETH_FPP_UNI_N/:id`, {id: '@id'}, {
query: {
isArray: true,
interceptor: {
response: (res) => {
const augmentedUnis = _.map(res.data, (uni, i) => {
var latlng_val = uni.latlng;
var lat_val = latlng_val.substring(1, latlng_val.indexOf(',') - 1);
lat_val = lat_val.trim();
var lng_val = latlng_val.substring(latlng_val.indexOf(',') + 1, latlng_val.length - 1);
lng_val = lng_val.trim()
uni.latlng = [lat_val, lng_val];
return uni;
});
return augmentedUnis;
}
}
}
});
});
})();
|
export { CollapseDirective } from './collapseDirective';
export { CollapseModule } from './collapseModule';
//# sourceMappingURL=index.js.map
|
//// [validRegexp.ts]
var x = / [a - z /]$ / i;
var x1 = /[a-z/]$/i;
var x2 = /[a-z/]$ /i;
//// [validRegexp.js]
var x = / [a - z /]$ /, i;
var x1 = /[a-z/]$/i;
var x2 = /[a-z/]$ /i;
|
//
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to you under the Apache License, Version 2.0
// (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
// JScript.NET doesn't handle files with only custom attributes very well, adding
// an import functions as a workaround for this issue.
import System.Reflection;
[assembly: AssemblyVersion("1.2.15.0")]
[assembly: AssemblyInformationalVersionAttribute("1.2")]
@if (!@NETCF)
@if (!@SSCLI)
[assembly: AssemblyFileVersion("1.2.15.0")]
@end
@end
//
// Shared assembly settings
//
[assembly: AssemblyCompany("The Apache Software Foundation")]
[assembly: AssemblyCopyright("Copyright 2004-2015 The Apache Software Foundation.")]
[assembly: AssemblyTrademark("Apache and Apache log4net are trademarks of The Apache Software Foundation")]
|
/**
* @license Apache-2.0
*
* Copyright (c) 2018 The Stdlib Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
/**
* Return the prototype of a provided object.
*
* @module @stdlib/utils/get-prototype-of
*
* @example
* var getPrototype = require( '@stdlib/utils/get-prototype-of' );
*
* var proto = getPrototype( {} );
* // returns {}
*/
// MODULES //
var getPrototype = require( './get_prototype_of.js' );
// EXPORTS //
module.exports = getPrototype;
|
'use strict';
import { app, ipcMain, BrowserWindow, crashReporter } from 'electron';
import fs from 'fs';
import os from 'os';
import * as logger from './logging';
// Report crashes to our server.
crashReporter.start({
productName: 'Developer Platform Install',
companyName: 'Red Hat',
autoSubmit: true
});
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
let mainWindow = null;
ipcMain.on('crash', function(event, arg) {
process.crash(arg);
});
// Rebroadcasts installComplete event from Renderer back to Renderer.
// Bit of a hack, but it enables async messaging in UI.
ipcMain.on('installComplete', (event, arg) => {
event.sender.send('installComplete', arg);
});
ipcMain.on('downloadingComplete', (event, arg) => {
event.sender.send('downloadingComplete', arg);
});
ipcMain.on('checkComplete', (event, arg) => {
event.sender.send('checkComplete', arg);
});
// Setup logging listeners
ipcMain.on('install-root', (event, installRoot) => {
logger.init(installRoot, app.getVersion());
});
ipcMain.on('log', (event, arg) => {
logger.log(arg);
})
// Quit when all windows are closed.
app.on('window-all-closed', function() {
app.quit();
});
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1000,
height: 650,
'autoHideMenuBar': true
});
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/../browser/index.html');
if( process.env['PDKI_DEBUG'] !== undefined ) {
mainWindow.openDevTools();
}
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
});
|
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ** This file is automatically generated by gapic-generator-typescript. **
// ** https://github.com/googleapis/gapic-generator-typescript **
// ** All changes to this file may be overwritten. **
'use strict';
function main(name) {
// [START privateca_v1beta1_generated_CertificateAuthorityService_GetReusableConfig_async]
/**
* TODO(developer): Uncomment these variables before running the sample.
*/
/**
* Required. The name ReusableConfigs.name of the ReusableConfigs to get.
*/
// const name = 'abc123'
// Imports the Privateca library
const {CertificateAuthorityServiceClient} = require('@google-cloud/security-private-ca').v1beta1;
// Instantiates a client
const privatecaClient = new CertificateAuthorityServiceClient();
async function callGetReusableConfig() {
// Construct request
const request = {
name,
};
// Run request
const response = await privatecaClient.getReusableConfig(request);
console.log(response);
}
callGetReusableConfig();
// [END privateca_v1beta1_generated_CertificateAuthorityService_GetReusableConfig_async]
}
process.on('unhandledRejection', err => {
console.error(err.message);
process.exitCode = 1;
});
main(...process.argv.slice(2));
|
/**
* Embed IP.Board via iFrame
* Using old school JS, none of your fancy stuffs!
*
* (c) 2011 Invision Power Services, Inc.
* By Matt Mecham
*/
var _idx = window.IPBoard;
_idx.prototype.embedded = {
curHeight: null,
remoteMsg: null,
inFrame: ( top !== self ) ? true : false,
ajaxIsLoading: null,
init: function()
{
if ( this.inFrame )
{
/* We need to do two things: set up a setLocation and setMessage functions
* if we have everything > IE7 this is easy, see...
* So lets pretent IE7 does NOT exist.
*/
if ( 'postMessage' in parent )
{
this.setMessage = function( message, target )
{
Debug.write("SENDING msg: " + message + " to " + target );
return parent.postMessage( message, target );
};
this.setLocation = function( newLocation )
{
Debug.write( "Setting location to " + newLocation );
parent.window.frames[0].location.replace( newLocation );
};
this.setHeight = function()
{
var newHeight = document.body.offsetHeight;
if ( newHeight != this.curHeight )
{
this.curHeight = newHeight;
this.setMessage('height:' + this.curHeight, '*');
}
};
this.checkAjaxStatus = function()
{
if ( $('ajax_loading') )
{
if ( $('ajax_loading').visible() )
{
this.ajaxIsLoading = true;
this.setMessage( 'ajaxLoading', '*' );
}
else if ( this.ajaxIsLoading && ! $('ajax_loading').visible() )
{
this.ajaxIsLoading = false;
this.setMessage( 'ajaxDone', '*' );
}
}
}
this.aClicked = function( e, elem )
{
href = elem.readAttribute('href');
rel = '';
target = '';
try
{
rel = elem.readAttribute('rel');
target = elem.readAttribute('target');
} catch(e){}
if ( ( href.substr(0, 4) == 'http' ) && rel != 'external' && target != '_blank' )
{
/* One last check */
if ( ipb.vars['board_url'] == href.substr( 0, ipb.vars['board_url'].length ) )
{
Event.stop(e);
var path = href.substr( ipb.vars['board_url'].length );
var hashIndex = path.indexOf('#');
var hash = '';
if ( hashIndex > -1 )
{
hash = path.substr( hashIndex );
path = path.substr( 0, hashIndex );
}
ipb.embedded.setMessage('location:' + path, '*');
ipb.embedded.setLocation( ipb.vars['board_url'] + path + hash );
}
}
return true;
};
/* Intercept a links */
ipb.delegate.register( "a", this.aClicked );
/* Routintely check height */
setInterval( this.setHeight.bindAsEventListener(this), 300 );
/* And ajax status */
setInterval( this.checkAjaxStatus.bindAsEventListener(this), 300 );
Event.observe( document, 'unload', function() { this.setMessage('unload', '*').bindAsEventListener(this); } );
}
}
}
};
ipb.embedded.init();
|
// @flow
import { translate } from '../../../base/i18n';
import { IconShareDesktop } from '../../../base/icons';
import JitsiMeetJS from '../../../base/lib-jitsi-meet/_';
import { connect } from '../../../base/redux';
import { AbstractButton, type AbstractButtonProps } from '../../../base/toolbox/components';
import { isScreenVideoShared } from '../../../screen-share';
import { isDesktopShareButtonDisabled } from '../../functions';
type Props = AbstractButtonProps & {
/**
* Whether or not screensharing is initialized.
*/
_desktopSharingEnabled: boolean,
/**
* The tooltip key to use when screensharing is disabled. Or undefined
* if non to be shown and the button to be hidden.
*/
_desktopSharingDisabledTooltipKey: string,
/**
* Whether or not the local participant is screensharing.
*/
_screensharing: boolean,
/**
* The redux {@code dispatch} function.
*/
dispatch: Function,
};
/**
* Implementation of a button for sharing desktop / windows.
*/
class ShareDesktopButton extends AbstractButton<Props, *> {
accessibilityLabel = 'toolbar.accessibilityLabel.shareYourScreen';
label = 'toolbar.startScreenSharing';
icon = IconShareDesktop;
toggledLabel = 'toolbar.stopScreenSharing';
tooltip = 'toolbar.accessibilityLabel.shareYourScreen';
/**
* Retrieves tooltip dynamically.
*/
get tooltip() {
const { _desktopSharingDisabledTooltipKey, _desktopSharingEnabled, _screensharing } = this.props;
if (_desktopSharingEnabled) {
if (_screensharing) {
return 'toolbar.stopScreenSharing';
}
return 'toolbar.startScreenSharing';
}
return _desktopSharingDisabledTooltipKey;
}
/**
* Required by linter due to AbstractButton overwritten prop being writable.
*
* @param {string} _value - The icon value.
*/
set tooltip(_value) {
// Unused.
}
/**
* Indicates whether this button is in toggled state or not.
*
* @override
* @protected
* @returns {boolean}
*/
_isToggled() {
return this.props._screensharing;
}
/**
* Indicates whether this button is in disabled state or not.
*
* @override
* @protected
* @returns {boolean}
*/
_isDisabled() {
return !this.props._desktopSharingEnabled;
}
}
/**
* Function that maps parts of Redux state tree into component props.
*
* @param {Object} state - Redux state.
* @returns {Object}
*/
const mapStateToProps = state => {
let desktopSharingEnabled = JitsiMeetJS.isDesktopSharingEnabled();
const { enableFeaturesBasedOnToken } = state['features/base/config'];
let desktopSharingDisabledTooltipKey;
if (enableFeaturesBasedOnToken) {
// we enable desktop sharing if any participant already have this
// feature enabled
desktopSharingEnabled = state['features/base/participants'].haveParticipantWithScreenSharingFeature;
desktopSharingDisabledTooltipKey = 'dialog.shareYourScreenDisabled';
}
// Disable the screenshare button if the video sender limit is reached and there is no video or media share in
// progress.
desktopSharingEnabled = desktopSharingEnabled && !isDesktopShareButtonDisabled(state);
return {
_desktopSharingDisabledTooltipKey: desktopSharingDisabledTooltipKey,
_desktopSharingEnabled: desktopSharingEnabled,
_screensharing: isScreenVideoShared(state)
};
};
export default translate(connect(mapStateToProps)(ShareDesktopButton));
|
// @flow
import React, { useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { TouchableOpacity } from 'react-native';
import { Text } from 'react-native-paper';
import { useDispatch, useSelector } from 'react-redux';
import { createBreakoutRoomsEvent, sendAnalytics } from '../../../../../analytics';
import { hideDialog } from '../../../../../base/dialog/actions';
import BottomSheet from '../../../../../base/dialog/components/native/BottomSheet';
import {
Icon,
IconClose,
IconRingGroup
} from '../../../../../base/icons';
import { isLocalParticipantModerator } from '../../../../../base/participants';
import { closeBreakoutRoom, moveToRoom, removeBreakoutRoom } from '../../../../../breakout-rooms/actions';
import { getBreakoutRoomsConfig } from '../../../../../breakout-rooms/functions';
import styles from '../../../native/styles';
type Props = {
/**
* The room for which the menu is open.
*/
room: Object
}
const BreakoutRoomContextMenu = ({ room }: Props) => {
const dispatch = useDispatch();
const closeDialog = useCallback(() => dispatch(hideDialog()), [ dispatch ]);
const isLocalModerator = useSelector(isLocalParticipantModerator);
const { hideJoinRoomButton } = useSelector(getBreakoutRoomsConfig);
const { t } = useTranslation();
const onJoinRoom = useCallback(() => {
sendAnalytics(createBreakoutRoomsEvent('join'));
dispatch(moveToRoom(room.jid));
closeDialog();
}, [ dispatch, room ]);
const onRemoveBreakoutRoom = useCallback(() => {
dispatch(removeBreakoutRoom(room.jid));
closeDialog();
}, [ dispatch, room ]);
const onCloseBreakoutRoom = useCallback(() => {
dispatch(closeBreakoutRoom(room.id));
closeDialog();
}, [ dispatch, room ]);
return (
<BottomSheet
addScrollViewPadding = { false }
onCancel = { closeDialog }
showSlidingView = { true }>
{
!hideJoinRoomButton && (
<TouchableOpacity
onPress = { onJoinRoom }
style = { styles.contextMenuItem }>
<Icon
size = { 24 }
src = { IconRingGroup } />
<Text style = { styles.contextMenuItemText }>{t('breakoutRooms.actions.join')}</Text>
</TouchableOpacity>
)
}
{!room?.isMainRoom && isLocalModerator
&& (room?.participants && Object.keys(room.participants).length > 0
? <TouchableOpacity
onPress = { onCloseBreakoutRoom }
style = { styles.contextMenuItem }>
<Icon
size = { 24 }
src = { IconClose } />
<Text style = { styles.contextMenuItemText }>{t('breakoutRooms.actions.close')}</Text>
</TouchableOpacity>
: <TouchableOpacity
onPress = { onRemoveBreakoutRoom }
style = { styles.contextMenuItem }>
<Icon
size = { 24 }
src = { IconClose } />
<Text style = { styles.contextMenuItemText }>{t('breakoutRooms.actions.remove')}</Text>
</TouchableOpacity>
)
}
</BottomSheet>
);
};
export default BreakoutRoomContextMenu;
|
'use strict';
//console.log(needsGroup("admin"));
module.exports = function (app) {
app.get('/book/register', function (request, response) {
var isbn = request.query.isbn;
if (isbn) {
var books = require('google-books-search');
books.search(isbn, {
});
}
response.send({});
});
app.get('/book/add', function (request, response) {
var Book = require('../models/book');
response.send('hey');
});
};
|
'use strict';
goog.provide('grrUi.flow.flowFormDirective.FlowFormController');
goog.provide('grrUi.flow.flowFormDirective.FlowFormDirective');
goog.scope(function() {
/**
* Controller for FlowFormDirective.
*
* @param {!angular.Scope} $scope
* @param {!grrUi.core.reflectionService.ReflectionService} grrReflectionService
* @constructor
* @ngInject
*/
grrUi.flow.flowFormDirective.FlowFormController = function(
$scope, grrReflectionService) {
/** @private {!angular.Scope} */
this.scope_ = $scope;
/** @private {!grrUi.core.reflectionService.ReflectionService} */
this.grrReflectionService_ = grrReflectionService;
/** @type {Object} */
this.outputPluginsField;
/** @type {Object} */
this.outputPluginDescriptor;
this.grrReflectionService_.getRDFValueDescriptor('FlowRunnerArgs').then(
function(descriptor) {
angular.forEach(descriptor['fields'], function(field) {
if (field.name == 'output_plugins') {
this.outputPluginsField = field;
}
}.bind(this));
return this.grrReflectionService_.getRDFValueDescriptor(
'OutputPluginDescriptor');
}.bind(this)).then(function(descriptor) {
this.outputPluginDescriptor = descriptor;
}.bind(this));
this.scope_.$watch('flowRunnerArgs.value.output_plugins',
this.onOutputPluginsChanged_.bind(this));
};
var FlowFormController =
grrUi.flow.flowFormDirective.FlowFormController;
/**
* Handles changes in output plugins part of flow runner args binding.
* This function ensures that if withOutputPlugins binding is true, then
* flowRunnerArgs.value.output_plugins is always set to a defined value.
*
* @param {Array<Object>} newValue New output plugins value.
*
* @private
*/
FlowFormController.prototype.onOutputPluginsChanged_ = function(newValue) {
if (!this.scope_['withOutputPlugins']) {
return;
}
var flowRunnerArgs = this.scope_['flowRunnerArgs'];
if (angular.isUndefined(newValue) && angular.isDefined(flowRunnerArgs)) {
flowRunnerArgs['value']['output_plugins'] = [];
}
};
/**
* Displays a form to edit the flow.
*
* @return {angular.Directive} Directive definition object.
*/
grrUi.flow.flowFormDirective.FlowFormDirective = function() {
return {
scope: {
flowArgs: '=',
flowRunnerArgs: '=',
withOutputPlugins: '='
},
restrict: 'E',
templateUrl: '/static/angular-components/flow/flow-form.html',
controller: FlowFormController,
controllerAs: 'controller'
};
};
/**
* Directive's name in Angular.
*
* @const
* @export
*/
grrUi.flow.flowFormDirective.FlowFormDirective.directive_name =
'grrFlowForm';
}); // goog.scope
|
var Router = require("vertx-web-js/router");
var SockJSHandler = require("vertx-web-js/sock_js_handler");
var StaticHandler = require("vertx-web-js/static_handler");
var router = Router.router(vertx);
// Allow outbound traffic to the draw address
var options = {
"outboundPermitteds" : [{"address" : "draw"}],
"inboundPermitteds" : [{"address" : "draw"}]
};
router.route("/eventbus/*").handler(SockJSHandler.create(vertx).bridge(options).handle);
// Serve the static resources
router.route().handler(StaticHandler.create().handle);
vertx.createHttpServer().requestHandler(router.accept).listen(8080);
|
'use strict';
angular.module( 'sbAdminApp' )
.controller( 'DocCtrl', ['$stateParams', '$rootScope', '$scope', 'restFactory', 'generalServices',
function ( $stateParams, $rootScope, $scope, restFactory, generalServices ) {
restFactory.set_data( "is_doc", true )
$scope.mite_id = $stateParams.mite_id
$scope.api_id = $stateParams.api_id
$scope.loadApplication = function ( successHandler ) {
restFactory.getList( 'pbl/mite/' + $scope.mite_id, function ( response ) {
restFactory.set_data( "doc_app", response.data )
} )
}
$scope.loadDoc = function ( successHandler ) {
restFactory.getList( 'pbl/doc/' + $scope.mite_id, function ( response ) {
restFactory.set_data( "doc", response.data )
retrieveSelectedApi()
} )
function retrieveSelectedApi() {
if ( !$scope.api_id ) {
return
}
for (var i in $rootScope.doc.data){
for (var j in $rootScope.doc.data[i]){
if ($rootScope.doc.data[i][j].info && $rootScope.doc.data[i][j].info.id === $scope.api_id){
restFactory.set_data( "selected_api", $rootScope.doc.data[i][j].info )
return
}
}
}
}
}
$scope.loadApplication()
$scope.loadDoc()
}
]
);
|
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { render } from '@testing-library/react';
import { ThemeProvider } from 'styled-components';
import { theme } from '@googleforcreators/design-system';
const WithThemeProvider = ({ children }) => {
return <ThemeProvider theme={theme}>{children}</ThemeProvider>;
};
const renderWithTheme = (ui, options) =>
render(ui, {
wrapper: WithThemeProvider,
...options,
});
export default renderWithTheme;
|
"use strict";
const winston = require("winston");
const _ = require("lodash");
const levels = {
error: 0,
warn: 1,
info: 2,
verbose: 3,
debug: 4
};
const colors = {
error: "red",
warn: "yellow",
info: "green",
verbose: "blue",
debug: "cyan"
};
winston.addColors(colors);
const logger = new winston.createLogger({
format: winston.format.combine(
winston.format.splat(),
winston.format.cli()
),
level: "info",
levels: levels,
transports: [
new winston.transports.Console({
handleExceptions: true,
})
]
});
function increaseVerbosity() {
setLevel(_.findKey(levels, value => {
return value === levels[logger.level] + 1;
}));
}
function setLevel(level) {
if (_.has(levels, level)) {
logger.level = level;
}
}
module.exports = logger;
module.exports.increaseVerbosity = increaseVerbosity;
module.exports.setLevel = setLevel;
|
/**
* @author Morten
*/
/**
* shows popup box and calls servlet to change status of rekvisition then reloads table
*/
function bookRekvisition(id){
if (confirm("Er du sikker du vil booke rekvisitionen?") == true) {
$.get("BookingServlet?action=book&bookingId=" + id, function(data,status){
if(status == "success"){
location.reload(true);
}
});
}
}
function revisitRekvisition(id){
if(confirm("Er du sikker du vil få rekvisitionen visiteret igen?") == true){
$.get("BookingServlet?action=revisit&bookingId=" + id, function(data, status){
if(status == "success"){
//console.log("id="+id);
}
});
}
}
$(document).ready(function()
{
/* Get all rows from your 'table' but not the first one
* that includes headers. */
var rows = $(".rekvisitionList tr").not(":first");
/* Create 'click' event handler for rows */
rows.on("click", function(e)
{
/* Get current row */
var row = $(this);
/* Highlight one row and clean others */
rows.removeClass("highlight");
row.addClass("highlight");
getRekvisitation(e.target.id);
});
/* This 'event' is used just to avoid that the table text
* gets selected (just for styling).
* For example, when pressing 'Shift' keyboard key and clicking
* (without this 'event') the text of the 'table' will be selected.
* You can remove it if you want, I just tested this in
* Chrome v30.0.1599.69 */
$(document).on("selectstart dragstart", function(e) {
e.preventDefault(); return false;
});
});
function showOverlay()
{
$("#overlay").css("display", "block");
$("#overlayPanel").css("display", "block");
}
function getvisitationString(rekvisition_Id){
return "VisRekvisitionServlet?rekvisition_Id="+rekvisition_Id;
}
function getRekvisitation(rekvisition_Id){
$.get(getvisitationString(rekvisition_Id),function(data,status){
if(status = "success"){
//indsæt de hentede data i div element
$("#embededSite").html(data);
var visiterDiv = document.getElementById('embededSite');
visiterDiv.scrollTop = 0; //scroll til top af siden
}
});
$('input[name="rekIDSubmit"]').val(rekvisition_Id);
$('input[name="visiterAction"]').val("");
}
function getRekvisitation(rekvisition_Id){
$.get(getvisitationString(rekvisition_Id),function(data,status){
if(status = "success"){
//indsæt de hentede data i div element
$("#embededSite").html(data);
var visiterDiv = document.getElementById('embededSite');
visiterDiv.scrollTop = 0; //scroll til top af siden
}
});
$('input[name="rekIDSubmit"]').val(rekvisition_Id);
$('input[name="visiterAction"]').val("");
}
$(document).ready(function()
{
/* Get all rows from your 'table' but not the first one
* that includes headers. */
var rows = $("#rekvisitionList tr").not(":first");
/* Create 'click' event handler for rows */
rows.on("click", function(e)
{
/* Get current row */
var row = $(this);
/* Highlight one row and clean others */
rows.removeClass("highlight");
row.addClass("highlight");
});
/* This 'event' is used just to avoid that the table text
* gets selected (just for styling).
* For example, when pressing 'Shift' keyboard key and clicking
* (without this 'event') the text of the 'table' will be selected.
* You can remove it if you want, I just tested this in
* Chrome v30.0.1599.69 */
$(document).on("selectstart dragstart", function(e) {
e.preventDefault(); return false;
});
});
function showOverlay()
{
$("#overlay").css("display", "block");
$("#overlayPanel").css("display", "block");
}
|
/* @flow */
import customItem from './customItem';
import data from './data';
import importSyntax from './importSyntax';
import menu from './menu';
export default [importSyntax, menu, data, customItem];
|
var mongoose = require('mongoose');
var dbURI = 'mongodb://localhost/pcatalog';
mongoose.connect(dbURI);
mongoose.connection.on('connected', function() {
console.log('MongoDB connection opened to '+ dbURI);
});
mongoose.connection.on('err', function(err) {
console.log('MongoDB error:' + err);
});
mongoose.connection.on('disconnected', function() {
console.log('MongoDB connection disconnected')
});
process.on('SIGINT', function(){
mongoose.connection.close(function(){
console.log('MongoDB connection disconnected due to app termination');
process.exit(0);
});
});
//var pcatalog = require('./pcatalog');
|
var gulp = require('gulp');
var browserSync = require('browser-sync');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var cp = require('child_process');
var jade = require('gulp-jade');
var concat = require('gulp-concat')
var mergeStream = require('merge-stream');
var deploy = require("gulp-gh-pages");
var jekyll = process.platform === 'win32' ? 'jekyll.bat' : 'jekyll';
var messages = {
jekyllBuild: '<span style="color: grey">Running:</span> $ jekyll build'
};
/**
* Build the Jekyll Site
*/
gulp.task('jekyll-build', function (done) {
browserSync.notify(messages.jekyllBuild);
return cp.spawn( jekyll , ['build'], {stdio: 'inherit'})
.on('close', done);
});
/**
* Rebuild Jekyll & do page reload
*/
gulp.task('jekyll-rebuild', ['jekyll-build'], function () {
browserSync.reload();
});
/**
* Wait for jekyll-build, then launch the Server
*/
gulp.task('browser-sync', ['sass', 'jade', 'vendor', 'img', 'js', 'jekyll-build'], function() {
browserSync({
server: {
baseDir: '_site',
},
notify: false
});
});
/**
* Compile files from _scss into both _site/css (for live injecting) and site (for future jekyll builds)
*/
gulp.task('sass', function () {
return gulp.src('_assets/css/main.sass').pipe(
sass({
includePaths: ['scss', 'sass'],
onError: browserSync.notify
})
)
.pipe(prefix(['last 15 versions', '> 1%', 'ie 8', 'ie 7'], { cascade: true }))
.pipe(gulp.dest('_site/assets/css'))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest('assets/css'));
});
gulp.task('jade', function () {
return gulp.src('_jadefiles/*.jade')
.pipe(jade())
.pipe(gulp.dest('_includes'));
});
gulp.task('js', function() {
return gulp.src('_assets/js/**/*.js')
.pipe(concat('all.js'))
.pipe(gulp.dest("_site/assets/js"))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest("assets/js"));
});
gulp.task('vendor', function() {
gulp.src('bower_components/normalize-css/normalize.css')
.pipe(concat('vendor.css'))
.pipe(gulp.dest('_site/assets/css/vendor'))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest("assets/css/vendor"));
return gulp.src([
'bower_components/jquery/dist/jquery.min.js',
'bower_components/jquery.localScroll/jquery.localScroll.min.js',
'bower_components/jquery.scrollTo/jquery.scrollTo.min.js'
])
.pipe(concat('vendor.js'))
.pipe(gulp.dest("_site/assets/js/vendor"))
.pipe(browserSync.reload({stream:true}))
.pipe(gulp.dest("assets/js/vendor"));
})
gulp.task('img', function() {
return gulp.src('_assets/img/**')
.pipe(gulp.dest('assets/img'));
})
/**
* Watch scss files for changes & recompile
* Watch html/md files, run jekyll & reload BrowserSync
*/
gulp.task('watch', function () {
gulp.watch('_assets/css/**', ['sass']);
gulp.watch(['_assets/js/**/*.js'], ['js']);
gulp.watch(['_jadefiles/*.jade'], ['jade']);
gulp.watch(['index.html', '_layouts/*.html', '_includes/*'], ['jekyll-rebuild']);
});
gulp.task("deploy", ["jekyll-build"], function () {
return gulp.src("./_site/**/*")
.pipe(deploy({branch:"master"}));
});
/**
* Default task, running just `gulp` will compile the sass,
* compile the jekyll site, launch BrowserSync & watch files.
*/
gulp.task('default', ['browser-sync', 'watch']);
|
function loadText()
{
var txtLang = document.getElementsByName("txtLang");
txtLang[0].innerHTML = "Typ";
txtLang[1].innerHTML = "Namn";
txtLang[2].innerHTML = "V\u00E4rde";
var optLang = document.getElementsByName("optLang");
optLang[0].text = "Knapp"
optLang[1].text = "Skicka"
optLang[2].text = "Rensa"
document.getElementById("btnCancel").value = "Avbryt";
document.getElementById("btnInsert").value = "Infoga";
document.getElementById("btnApply").value = "Verkst\u00E4ll";
document.getElementById("btnOk").value = " OK ";
}
function writeTitle()
{
document.write("<title>Knapp</title>")
}
|
angular.module('bitvagas.jobs.controllers')
.controller('JobShowController', JobShowController);
JobShowController.$inject = ['$scope', '$stateParams', '$state', '$auth', '$window', 'JobService', 'Job', 'lodash', 'marked'];
function JobShowController($scope, $stateParams, $state, $auth, $window, JobService, Job, lodash, marked){
$scope.apply = {};
var job = Job.data;
$scope.job = job;
$scope.url = job.id + "-" + $stateParams.title + "-" + job.org.NAME;
$scope.tags = $scope.job.TAGS.join(', ');
AlreadyApplied();
$scope.toggle = function(){
$scope.toggled = true;
if($auth.isAuthenticated()){
$scope.apply.NAME = $scope.currentUser.NAME;
$scope.apply.EMAIL = $scope.currentUser.EMAIL;
}
$scope.otherEmail = $auth.isAuthenticated() ? false : true;
};
$scope.other = function(){
$scope.otherEmail = true;
};
$scope.applyJob = function(){
JobService.apply($scope.job, $scope.apply).then(function(){
JobService.findById($scope.job.id).then(function(data){
$scope.job = data.data;
$scope.toggled = false;
$scope.alreadyApplied = true;
});
});
};
function AlreadyApplied() {
if($scope.currentUser)
$scope.alreadyApplied = lodash.result(lodash.find($scope.currentUser.job_appliers, { JOB_ID: $scope.job.id }), 'EMAIL') !== undefined;
}
try {
if($window.twttr)
$window.twttr.widgets.load();
if($window.FB) {
$window.FB.init({
appId : '162990964082513',
status : true,
xfbml : true,
version : 'v2.5'
});
$window.FB.XFBML.parse();
}
} catch(err){
console.log(err);
}
}
|
'kiwi public';
/** @module */
/**
* Adds the +draft/typing IRCv3 spec to irc-framework
*/
export default function typingMiddleware() {
return function middleware(client, rawEvents, parsedEvents) {
addFunctionsToClient(client);
rawEvents.use(theMiddleware);
};
function theMiddleware(command, message, rawLine, client, next) {
if (
!(command === 'TAGMSG' && message.tags['+draft/typing']) &&
!(command === 'PRIVMSG' && message.nick)
) {
next();
return;
}
// if we are params[0] then the target is the sender (direct message)
let target = (message.params[0].toLowerCase() === client.user.nick.toLowerCase()) ?
message.nick :
message.params[0];
// if its a privmsg without typing tag emit done
let status = message.tags['+draft/typing'] || 'done';
client.emit('typing', {
target: target,
nick: message.nick,
ident: message.ident,
hostname: message.hostname,
status: status,
});
next();
}
}
function addFunctionsToClient(client) {
let typing = client.typing = {};
let activeTyping = Object.create(null);
function isEnabled() {
return client.network.cap.isEnabled('message-tags');
}
typing.start = function start(target) {
if (!isEnabled()) {
return;
}
let lastSentStatus = activeTyping[target.toLowerCase()];
if (lastSentStatus && lastSentStatus > Date.now() - 3000) {
return;
}
activeTyping[target.toLowerCase()] = Date.now();
let message = new client.Message('TAGMSG', target);
message.tags['+draft/typing'] = 'active';
client.raw(message);
};
typing.pause = function pause(target) {
if (!isEnabled()) {
return;
}
let message = new client.Message('TAGMSG', target);
message.tags['+draft/typing'] = 'paused';
client.raw(message);
};
typing.stop = function stop(target) {
if (!isEnabled()) {
return;
}
let message = new client.Message('TAGMSG', target);
message.tags['+draft/typing'] = 'done';
client.raw(message);
delete activeTyping[target.toLowerCase()];
};
}
|
var http = require('http');
var punycode = require('punycode');
var body = JSON.stringify({tuwenlist:[{title:punycode.encode("中文编码"),description:punycode.encode("中文编码1"),
picUrl : "http://weizhifeng.net/images/tech/composer.png",
url : "http://tv.sohu.com"},{title:punycode.encode("中文编码"),description:punycode.encode("中文编码1"),
picUrl : "http://weizhifeng.net/images/tech/composer.png",
url : "http://tv.sohu.com"},{title:punycode.encode("中文编码"),description:punycode.encode("中文编码1"),
picUrl : "http://weizhifeng.net/images/tech/composer.png",
url : "http://tv.sohu.com"},{title:punycode.encode("中文编码"),description:punycode.encode("中文编码1"),
picUrl : "http://weizhifeng.net/images/tech/composer.png",
url : "http://tv.sohu.com"}]});
console.log(body);
var options = {
hostname: 'ponyccemma.duapp.com',
port: 80,
path: '/puttuwen',
method: 'POST',
headers: {
'Content-Type': 'text/plain',
'Content-Length': body.length
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write(body);
req.end();
|
'use strict';
/**
* touch_no_data_no_index.js
*
* Bulk inserts documents in batches of 100, uses touch as a no-op,
* and queries to verify the number of documents inserted by the thread.
*/
load('jstests/concurrency/fsm_libs/extend_workload.js'); // for extendWorkload
load('jstests/concurrency/fsm_workloads/touch_base.js'); // for $config
var $config = extendWorkload($config, function($config, $super) {
$config.data.generateTouchCmdObj = function generateTouchCmdObj(collName) {
return {touch: collName, data: false, index: false};
};
$config.states.touch = function touch(db, collName) {
var res = db.runCommand(this.generateTouchCmdObj(collName));
// The command always fails because "index" and "data" are both false
assertAlways.commandFailed(res);
};
return $config;
});
|
Package.describe({
summary: "Cordova contacts plugin integration for Meteor",
version: "0.0.1",
name: "erdal:cordova-contacts",
git: "https://github.com/Erdou/cordova-plugin-contacts.git"
});
var both = ['client', 'server'];
var client = ['client'];
var server = ['server'];
var browser = ['web.browser'];
Cordova.depends({
'org.apache.cordova.contacts': '1.1.0'
});
Package.on_use(function(api) {
api.versionsFrom('1.0');
// import packages
api.use(['underscore'], both);
});
Package.on_test(function (api) {
api.use(['test-helpers', 'tinytest', 'erdal:cordova-contacts']);
api.add_files([
'tests/test.js'
], browser);
});
|
/*预加载*/
$(function(){
// 更改标题文字
var keyContent = $('#keyContent').val();
$('#page-name').text(keyContent);
// 按照关键字进行商品数据查询
getGoodsByKeyWord($('#content').val());
});
// 根据类型ID查询对应页的商品
function getGoodsByKeyWord(keyword) {
$.ajax({
url: 'goodsController/getGoodsListBySearch.do',
data: {
seachContent: keyword,
page: '0',
number: '12'
},
type: 'post',
dataType: 'json',
success: function(resultInfo) {
var resultCode = resultInfo.resultCode;
var resultMessage = resultInfo.resultMessage;
var ulBox = $('.category_bd .item-list');
ulBox.empty();
if(resultCode == '0000') {
var resultList = resultInfo.rows;
for(var i=0; i < resultList.length; i++) {
ulBox.append("<li class='product-item'>" +
"<a class='pro_item_pic' href='platform/goodsDetail.jsp?goodsId=" + resultList[i].GOODS_ID + "'>" +
"<img src='" + resultList[i].FILE_PATH + "'>" +
"</img>" +
"</a>" +
"<div class='pro_item_info'>" +
"<p class='pro_item_desc'>" +
"<a href='platform/goodsDetail.jsp?goodsId=" + resultList[i].GOODS_ID + "'>" + resultList[i].GOODS_TITLE + "</a>" +
"</p>" +
"<p class='pro_item_price'>" +
"<em>¥</em>" +
"<span>" + resultList[i].GOODS_RESALE + "</span>" +
"</p>" +
"</div>" +
"</li>");
}
// 刷新页面高度
window.parent.refreshIframeHeight();
}
},
error: function(resultInfo) {
alert('咦, 服务器跑路了~');
}
});
}
/* 获得总页数 */
function initPageInfo(typeId){
var userId = window.parent.getUserID();
$.ajax({
url:'goodsController/getGoodsTotalByListType.do',
data:{
typeId: typeId,
number: '12'
},
type:'post',
dataType:'json',
success: function(resultJson){
var resultCode = resultJson.resultCode;
var resultMessage = resultJson.resultMessage;
var pageDiv = $('#page_div');
pageDiv.empty();
if(resultCode=="0000"){
var resultData = resultJson.pageNum;
if(resultData==0){
pageDiv.remove();
}else{
var htmlStr = '<ul class="pagination pagination-lg clearfix">'
+ '<li onclick="changePageLeft(' + typeId + ')"><a href="javascript:void(0);">«</a></li>';
for(var i = 0; i < resultData; i++) {
if(i==0){
htmlStr += '<li onclick="changePage(this,' + (i) + ',' + typeId + ')" pageIndex=' + i + ' class="active"><a href="javascript:void(0);">' + (i+1) + '</a></li>';
}else{
htmlStr += '<li onclick="changePage(this,' + (i) + ',' + typeId + ')" pageIndex=' + i + '><a href="javascript:void(0);">' + (i+1) + '</a></li>'
}
}
htmlStr += '<li onclick="changePageRight(' + resultData + ',' + typeId + ')"><a href="javascript:void(0);">»</a></li></ul>';
pageDiv.append(htmlStr);
}
}else{
}
}
});
}
// 点击某一页切换样式并且请求对应页的数据
function changePage(ele, page, typeId){
$('#page_div li').removeClass('active');
$(ele).attr('class','active');
// 请求对应页的数据
getGoodsByTypeID(typeId, page);
}
// 点击上一页
function changePageLeft(typeId){
var page = $('#page_div').find('.active');
var pageIndex = $(page).attr('pageIndex');
if(pageIndex==0){
}else{
var pageIndexElement = $('#page_div li')[pageIndex];
$('#page_div li').removeClass('active');
$(pageIndexElement).attr('class','active');
if(typeId==null || typeId==undefined){
listId="";
}
getGoodsByTypeID(typeId, (pageIndex-1));
}
}
// 点击下一页
function changePageRight(total,typeId){
var page = $('#page_div').find('.active');
var pageIndex = $(page).attr('pageIndex');
if(pageIndex==(total-1)){
}else{
var pageIndexElement = $('#page_div li')[parseInt(pageIndex)+2];
$('#page_div li').removeClass('active');
$(pageIndexElement).attr('class','active');
if(typeId==null || typeId==undefined){
typeId="";
}
getGoodsByTypeID(typeId, (parseInt(pageIndex)+1));
}
}
|
/*
* Copyright 2016 The Closure Compiler 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.
*/
/**
* @fileoverview Runtime code to store the global object.
*/
'require base';
'declare global';
'declare window';
/**
* @param {!Object} maybeGlobal
* @return {!Object} The global object.
* @suppress {undefinedVars|reportUnknownTypes}
*/
$jscomp.getGlobal = function(maybeGlobal) {
// This logic can be simplified to be made more optimizable.
return (typeof window != 'undefined' && window === maybeGlobal) ?
maybeGlobal :
(typeof global != 'undefined' && global != null) ?
/** @type {!Object} */ (global) :
maybeGlobal;
};
// TODO(sdh): This should be typed as "the global object" now that the type
// of "Global" has landed in the type system.
/**
* The global object. For browsers we could just use `this` but in Node that
* doesn't work.
* @const {?}
*/
$jscomp.global = $jscomp.getGlobal(this);
|
var fs = require('fs-extra');
var mime = require('./mime.js');
function FileSystemCache(options) {
this.options = options || {};
if (this.options.refreshage && !this.options.maxage) {
throw new Error('"refreshage" param must be used in conjunction with "maxage"');
}
};
FileSystemCache.prototype._dir = function(x, y, z) {
if (y) return this.options.dir + '/' + z + '/' + x + '/' + y;
return this.options.dir + '/' + z + '/' + x;
};
FileSystemCache.prototype._file = function(req) {
var filename = req.filename;
var pattern = filename.indexOf('@') >= 0 ? filename.indexOf('@') : filename.indexOf('.');
var y = filename.replace(filename.substr(pattern), '');
if (parseInt(y) == req.y) return this._dir(req.x, null, req.z) + '/' + filename;
return this._dir(req.x, req.y, req.z) + '/' + filename;
};
FileSystemCache.prototype.init = function(server, callback) {
this.server = server;
fs.ensureDir(this.options.dir, callback);
};
FileSystemCache.prototype.ageTolerance = function(key, tile) {
var age = this.options[key];
if (typeof age === 'function') {
return age(this.server, tile)*1000;
}
return age*1000;
};
FileSystemCache.prototype.shouldServe = function(mtime, tile) {
// should the tile be served from disk?
var maxage = this.ageTolerance('maxage', tile);
if (isNaN(maxage)) return true;
return Date.now() - mtime < maxage;
};
FileSystemCache.prototype.shouldRefresh = function(mtime, tile) {
// should the tile be rebuilt in the background?
var refreshage = this.ageTolerance('refreshage', tile);
if (isNaN(refreshage)) return false;
return Date.now() - mtime > refreshage;
};
/**
* Retrieves a tile from the filesystem.
*
* @param {TileServer} server
* @param {TileRequest} req
* @param {function} callback(err, buffer, headers)
* @return {void}
*/
FileSystemCache.prototype.get = function(server, req, callback) {
var _fd;
var done = function(err, buffer, headers, refresh) {
if (_fd) {
return fs.close(_fd, function() { callback(err, buffer||null, headers, refresh); });
}
return callback(err, buffer||null, headers, refresh);
};
// don't even attempt the fs lookup if maxage=0
var maxage = this.ageTolerance('maxage', req);
if (maxage === 0) return done();
var self = this;
var file = this._file(req);
fs.open(file, 'r', function(err, fd) {
if (err) return callback(err);
_fd = fd;
fs.fstat(fd, function(err, stats) {
if (err) return done(err);
var mtime = stats.mtime.getTime();
var shouldServe = self.shouldServe(mtime, req);
if (!shouldServe) return done();
var shouldRefresh = self.shouldRefresh(mtime, req);
var headers = {'Content-Type': mime(file)};
var buffer = new Buffer(stats.size);
if (!stats.size) {
return done(null, buffer, headers, shouldRefresh);
}
fs.read(fd, buffer, 0, stats.size, 0, function(err) {
if (err) return done(err);
done(null, buffer, headers, shouldRefresh);
});
});
});
};
/**
* Stores a tile on the filesystem.
*
* @param {TileServer} server
* @param {TileRequest} req
* @param {Buffer} buffer
* @param {object} headers
* @param {Function} callback
*/
FileSystemCache.prototype.set = function(server, req, buffer, headers, callback) {
var maxage = this.ageTolerance('maxage', req);
if (maxage === 0) return callback();
fs.outputFile(this._file(req), buffer, callback);
};
module.exports = function(options) {
return new FileSystemCache(options);
};
|
//>>built
define("dojox/mobile/transition",["dojo/_base/Deferred","dojo/_base/config"],function(c,a){if(a.mblCSS3Transition){var b=new c;require([a.mblCSS3Transition],function(a){b.resolve(a)});return b}return null});
//# sourceMappingURL=transition.js.map
|
'use strict';
var logger = require('log4js').getLogger('cloudify.deploymentUpdates');
var FormData = FormData || require('form-data');
function DeploymentUpdatesClient( config ){
this.config = config;
}
DeploymentUpdatesClient.prototype.list = function(options, callback){
logger.trace('listing deployment updates');
return this.config.request({
'method': 'GET',
'json': true,
'url': this.config.endpoint + '/deployment-updates',
'qs': options
}, callback );
};
DeploymentUpdatesClient.prototype.get = function(updateId, callback){
logger.trace('getting deployment update '+updateId);
return this.config.request({
'method': 'GET',
'json': true,
'url': this.config.endpoint + '/deployment-updates/'+updateId
}, callback );
};
/**
* @param {string} [deploymentId] deployment id to update
* @param {object | string} [archive] the new deployment archive / url to archive
* @param {string} [fileName] the blueprint.yaml file name within the archive
* @param {object} [executionOptions] should run a custom exection?
* @param {string} [executionOptions.workflowId] the workflow id to execute on the changes
* @param {boolean} [executionOptions.skipInstall] should not install added
* @param {boolean} [executionOptions.skipUninstall] should not install removed
*/
DeploymentUpdatesClient.prototype.update = function (deploymentId, archive, inputs, fileName, executionOptions, callback) {
logger.trace('updating deployment '+deploymentId);
var json = true;
var qs = {};
var body = new FormData();
if(typeof archive === 'string'){
qs.blueprint_archive_url = archive;
} else if(archive !== undefined){
body.append('blueprint_archive', archive);
json = false;
}
if(inputs !== undefined){
body.append('inputs', inputs);
json = false;
}
qs.application_file_name = fileName !== undefined ? fileName : undefined;
if(typeof executionOptions === 'object'){
if(executionOptions.workflowId !== undefined){
qs.workflow_id = executionOptions.workflowId;
} else{
qs.skip_install = executionOptions.skipInstall;
qs.skip_uninstall = executionOptions.skipUninstall;
}
}
return this.config.request({
'method': 'POST',
'json': json,
'url': this.config.endpoint + '/deployment-updates/'+deploymentId+'/update/initiate',
'qs': qs,
'body': body
}, callback );
};
module.exports = DeploymentUpdatesClient;
|
"use strict";
const path = require("path");
const {_electron} = require("playwright-core");
const rimraf = require("rimraf");
const testsPkg = require("./package.json");
module.exports = {
createApp,
endTest,
resetTestDataDir,
};
// Runs Zulip Desktop.
// Returns a promise that resolves to an Electron Application once the app has loaded.
function createApp() {
return _electron.launch({
args: [path.join(__dirname)], // Ensure this dir has a package.json file with a 'main' entry piont
});
}
// Quit the app, end the test
async function endTest(app) {
await app.close();
}
function getAppDataDir() {
let base;
switch (process.platform) {
case "darwin":
base = path.join(process.env.HOME, "Library", "Application Support");
break;
case "linux":
base = process.env.XDG_CONFIG_HOME
? process.env.XDG_CONFIG_HOME
: path.join(process.env.HOME, ".config");
break;
case "win32":
base = process.env.APPDATA;
break;
default:
throw new Error("Could not detect app data dir base.");
}
console.log("Detected App Data Dir base:", base);
return path.join(base, testsPkg.productName);
}
// Resets the test directory, containing domain.json, window-state.json, etc
function resetTestDataDir() {
const appDataDir = getAppDataDir();
rimraf.sync(appDataDir);
}
|
export const LIST_HOUSES_SUCCESS = 'LIST_HOUSES_SUCCESS'
export const LIST_HOUSES_REQUEST = 'LIST_HOUSES_REQUEST'
export const LIST_HOUSES_ERROR = 'LIST_HOUSES_ERROR'
const isFetching = (state) =>
state.houses.isFetching
export const fetch = () => (dispatch, getState, api) => {
if(isFetching(getState())){
return Promise.resolve()
}
dispatch({
type: LIST_HOUSES_REQUEST
})
return api.fetchHouses().then(
response => {
dispatch({
type: LIST_HOUSES_SUCCESS,
response: response
})
},
error => {
dispatch({
type: LIST_HOUSES_ERROR,
response: error.message || 'Error when fetch houses'
})
}
)
}
|
'use strict';
// Load Dependencies
const _ = require('lodash');
const utils = rootRequire("criteria/utils");
exports = module.exports = class SpotifyArtist {
constructor(data) {
this.id = data.id;
this.name = data.name;
this.cardinality = data.cardinality;
}
criteriaScore(name, cardinality) {
// Release Count
const min_count = Math.min(cardinality, this.cardinality);
const max_count = Math.max(cardinality, this.cardinality);
// Critera Scores
const artist_criteria_name = utils.stringDistance(name, this.name);
const artist_criteria_cardinality = (min_count/max_count).toFixed(2);
// Overall Critera Scores
const scores = [artist_criteria_name, artist_criteria_cardinality];
const criteria_overall = utils.average(scores);
// Return Critera Scores
return { artist_criteria_name, artist_criteria_cardinality, artist_criteria_overall };
}
};
|
sap.ui.define([
"sap/ui/rta/enablement/elementActionTest"
], function(elementActionTest) {
'use strict';
// Remove and reveal actions
var fnConfirmTableIsInvisible = function (oUiComponent, oViewAfterAction, assert) {
assert.strictEqual(oViewAfterAction.byId("Table1").getVisible(), false, "then the Table element is invisible");
};
var fnConfirmTableIsVisible = function (oUiComponent, oViewAfterAction, assert) {
assert.strictEqual(oViewAfterAction.byId("Table1").getVisible(), true, "then the Table element is visible");
};
elementActionTest("Checking the remove action for Table", {
xmlView: '<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns:wc="sap.ui.webc.main">"' +
'<wc:Table id="Table1"/>' +
'</mvc:View>'
,
action: {
name: "remove",
controlId: "Table1",
parameter: function (oView) {
return {
removedElement: oView.byId("Table1")
};
}
},
afterAction: fnConfirmTableIsInvisible,
afterUndo: fnConfirmTableIsVisible,
afterRedo: fnConfirmTableIsInvisible
});
elementActionTest("Checking the reveal action for an Table", {
xmlView: '<mvc:View xmlns:mvc="sap.ui.core.mvc" xmlns:wc="sap.ui.webc.main">"' +
'<wc:Table id="Table1" visible="false"/>' +
'</mvc:View>'
,
action: {
name: "reveal",
controlId: "Table1"
},
afterAction: fnConfirmTableIsVisible,
afterUndo: fnConfirmTableIsInvisible,
afterRedo: fnConfirmTableIsVisible
});
});
|
sap.ui.define([], function() {
var reducer = function(state, action) {
if (!state) return {
test: 'test1',
list: [
'foo',
'bar'
],
obj: {
test: 0
}
};
if (action.type === 'TEST1') {
return {
test: 'test2',
list: [
'foo',
'bar'
]
}
}
return state;
};
return reducer;
});
|
var title = "== Password Generator ==";
var randomPassword = function(length, withNumber) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if( withNumber ){
possible += "0123456789";
}
if( !length ) {
length = 6;
}
for (var i = 0; i < length; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
};
var print = function(text) {
console.log(text);
}
print(title);
print("Password length = 5: " + randomPassword());
print("Password without number: " + randomPassword(10))
print("Password with number: " + randomPassword(10, true));
|
const util = require('../util')
const Struct = require('../struct')
const { SignalsEmitter } = require('../signal')
const PROP_OPTS = 0
class ScriptExported extends Struct {
constructor(document, obj) {
super(obj)
util.defineProperty(this, '$element', PROP_OPTS, document.element)
util.defineProperty(this, '$refs', PROP_OPTS, document.refs)
util.defineProperty(this, '$context', PROP_OPTS, () => document.context, null)
util.defineProperty(this, '$self', PROP_OPTS, this)
}
}
util.defineProperty(ScriptExported.prototype, 'constructor', PROP_OPTS, ScriptExported)
SignalsEmitter.createSignal(ScriptExported, 'on$RefsChange')
class Script {
constructor(document, script) {
class ComponentScript extends ScriptExported {}
this.document = document
this.produceInstanceFields = null
this.ExportedConstructor = ComponentScript
if (typeof script === 'function') {
this.produceInstanceFields = script
} else if (util.isObject(script)) {
Object.keys(script).forEach((key) => {
if (key !== 'default') ComponentScript.prototype[key] = script[key]
})
if (typeof script.default === 'function') {
this.produceInstanceFields = script.default
} else {
this.produceInstanceFields = () => script.default
}
} else {
this.produceInstanceFields = () => null
}
}
produceExported() {
// produce object with combined static methods and instance fields
const object = this.produceInstanceFields() || {}
// add props
Object.keys(this.document.props).forEach((prop) => {
if (!(prop in object)) {
object[prop] = null
}
})
// create struct
const exported = new this.ExportedConstructor(this.document, object)
// bind instance methods
Object.keys(object).forEach((field) => {
if (typeof object[field] === 'function') {
exported[field] = exported[field].bind(exported)
}
})
return exported
}
afterRender() {
if (typeof this.document.exported.onRender === 'function') this.document.exported.onRender()
}
beforeRevert() {
if (typeof this.document.exported.onRevert === 'function') this.document.exported.onRevert()
}
}
module.exports = Script
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.