code
stringlengths
2
1.05M
repo_name
stringlengths
5
114
path
stringlengths
4
991
language
stringclasses
1 value
license
stringclasses
15 values
size
int32
2
1.05M
/*jshint camelcase: false*/ module.exports = (grunt) => { 'use strict'; // load all grunt tasks require('time-grunt')(grunt); require('load-grunt-tasks')(grunt); // configurable paths const config = { app: 'app', dist: 'dist', distMac32: 'dist/MacOS32', distMac64: 'dist/MacOS64', distLinux32: 'dist/Linux32', distLinux64: 'dist/Linux64', distWin32: 'dist/Win32', distWin64: 'dist/Win64', distWin: 'dist/Win', tmp: 'buildTmp', resources: 'resources', appName: 'PlaylistPalace' }; grunt.initConfig({ config: config, clean: { dist: { files: [{ dot: true, src: [ `${ config.dist }/*`, `${ config.tmp }/*` ] }] }, distMac32: { files: [{ dot: true, src: [ `${ config.distMac32 }/*`, `${ config.tmp }/*` ] }] }, distMac64: { files: [{ dot: true, src: [ `${ config.distMac64 }/*`, `${ config.tmp }/*` ] }] }, distLinux64: { files: [{ dot: true, src: [ `${ config.distLinux64 }/*`, `${ config.tmp }/*` ] }] }, distLinux32: { files: [{ dot: true, src: [ `${ config.distLinux32 }/*`, `${ config.tmp }/*` ] }] }, distWin: { files: [{ dot: true, src: [ `${ config.distWin }/*`, `${ config.tmp }/*` ] }] }, distWin32: { files: [{ dot: true, src: [ `${ config.distWin32 }/*`, `${ config.tmp }/*` ] }] }, distWin64: { files: [{ dot: true, src: [ `${ config.distWin64 }/*`, `${ config.tmp }/*` ] }] } }, jshint: { options: { jshintrc: '.jshintrc' }, files: `${ config.app }/js/*.js` }, copy: { appLinux: { files: [{ expand: true, cwd: `${ config.app }`, dest: `${ config.distLinux64 }/app.nw`, src: '**' }] }, appLinux32: { files: [{ expand: true, cwd: `${ config.app }`, dest: `${ config.distLinux32 }/app.nw`, src: '**' }] }, appMacos32: { files: [{ expand: true, cwd: `${ config.app }`, dest: `${ config.distMac32 }/node-webkit.app/Contents/Resources/app.nw`, src: '**' }, { expand: true, cwd: `${ config.resources }/mac/`, dest: `${ config.distMac32 }/node-webkit.app/Contents/`, filter: 'isFile', src: '*.plist' }, { expand: true, cwd: `${ config.resources }/mac/`, dest: `${ config.distMac32 }/node-webkit.app/Contents/Resources/`, filter: 'isFile', src: '*.icns' }, { expand: true, cwd: `${ config.app }/../node_modules/`, dest: `${ config.distMac32 }/node-webkit.app/Contents/Resources/app.nw/node_modules/`, src: '**' }] }, appMacos64: { files: [{ expand: true, cwd: `${ config.app }`, dest: `${ config.distMac64 }/node-webkit.app/Contents/Resources/app.nw`, src: '**' }, { expand: true, cwd: `${ config.resources }/mac/`, dest: `${ config.distMac64 }/node-webkit.app/Contents/`, filter: 'isFile', src: '*.plist' }, { expand: true, cwd: `${ config.resources }/mac/`, dest: `${ config.distMac64 }/node-webkit.app/Contents/Resources/`, filter: 'isFile', src: '*.icns' }, { expand: true, cwd: `${ config.app }/../node_modules/`, dest: `${ config.distMac64 }/node-webkit.app/Contents/Resources/app.nw/node_modules/`, src: '**' }] }, webkit32: { files: [{ expand: true, cwd: `${ config.resources }/node-webkit/MacOS32`, dest: `${ config.distMac32 }/`, src: '**' }] }, webkit64: { files: [{ expand: true, cwd: `${ config.resources }/node-webkit/MacOS64`, dest: `${ config.distMac64 }/`, src: '**' }] }, copyWinToTmp: { files: [{ expand: true, cwd: `${ config.resources }/node-webkit/Windows/`, dest: `${ config.tmp }/`, src: '**' }] }, copyWin32ToTmp: { files: [{ expand: true, cwd: `${ config.resources }/node-webkit/Win32/`, dest: `${ config.tmp }/`, src: '**' }] }, copyWin64ToTmp: { files: [{ expand: true, cwd: `${ config.resources }/node-webkit/Win64/`, dest: `${ config.tmp }/`, src: '**' }] } }, compress: { appToTmp: { options: { archive: `${ config.tmp }/app.zip` }, files: [{ expand: true, cwd: `${ config.app }`, src: ['**'] }] }, finalWindowsApp: { options: { archive: `${ config.distWin }/${ config.appName }.zip` }, files: [{ expand: true, cwd: `${ config.tmp }`, src: ['**'] }] }, finalWindows32App: { options: { archive: `${ config.distWin32 }/${ config.appName }.zip` }, files: [{ expand: true, cwd: `${ config.tmp }`, src: ['**'] }] }, finalWindows64App: { options: { archive: `${ config.distWin64 }/${ config.appName }.zip` }, files: [{ expand: true, cwd: `${ config.tmp }`, src: ['**'] }] } }, rename: { macApp32: { files: [{ src: `${ config.distMac32 }/node-webkit.app`, dest: `${ config.distMac32 }/${ config.appName }.app` }] }, macApp64: { files: [{ src: `${ config.distMac64 }/node-webkit.app`, dest: `${ config.distMac64 }/${ config.appName }.app` }] }, zipToApp: { files: [{ src: `${ config.tmp }/app.zip`, dest: `${ config.tmp }/app.nw` }] } } }); grunt.registerTask('mkdir','Making directory if needed', () => { grunt.initConfig({ mkdir: { all: { options: { create: ['tmp_', 'test/ripper'] }, }, } }); }); grunt.registerTask('chmod32', 'Add lost Permissions.', () => { const fs = require('fs'), path = `./${config.distMac32}/${ config.appName}.app/Contents/`; console.log(path) fs.chmodSync(path + 'Frameworks/node-webkit Helper EH.app/Contents/MacOS/node-webkit Helper EH', '555') fs.chmodSync(path + 'Frameworks/node-webkit Helper NP.app/Contents/MacOS/node-webkit Helper NP', '555') fs.chmodSync(path + 'Frameworks/node-webkit Helper.app/Contents/MacOS/node-webkit Helper', '555') fs.chmodSync(path + 'MacOS/node-webkit', '555') }); grunt.registerTask('chmod64', 'Add lost Permissions.', () => { const fs = require('fs'), path = `${config.distMac64}/${ config.appName}.app/Contents/` fs.chmodSync(path + 'Frameworks/node-webkit Helper EH.app/Contents/MacOS/node-webkit Helper EH', '555') fs.chmodSync(path + 'Frameworks/node-webkit Helper NP.app/Contents/MacOS/node-webkit Helper NP', '555') fs.chmodSync(path + 'Frameworks/node-webkit Helper.app/Contents/MacOS/node-webkit Helper', '555') fs.chmodSync(path + 'MacOS/node-webkit', '555') }); grunt.registerTask('createLinuxApp', 'Create linux distribution.', (version) => { const done = this.async() const childProcess = require('child_process') const exec = childProcess.exec const path = './' + (version === 'Linux64' ? config.distLinux64 : config.distLinux32) exec(`mkdir -p ${path}; cp resources/node-webkit/${version}'/nw.pak ${path} && cp resources/node-webkit/${version}/nw ${path}/node-webkit`, (error, stdout, stderr) => { var result = true; if (stdout) { grunt.log.write(stdout); } if (stderr) { grunt.log.write(stderr); } if (error !== null) { grunt.log.error(error); result = false; } done(result); }); }); grunt.registerTask('createWindowsApp', 'Create windows distribution.', () => { const done = this.async(); const concat = require('concat-files'); concat([ 'buildTmp/nw.exe', 'buildTmp/app.nw' ], `buildTmp ${ config.appName }.exe`, function () { var fs = require('fs'); fs.unlink('buildTmp/app.nw', function (error, stdout, stderr) { if (stdout) { grunt.log.write(stdout); } if (stderr) { grunt.log.write(stderr); } if (error !== null) { grunt.log.error(error); done(false); } else { fs.unlink('buildTmp/nw.exe', (error, stdout, stderr) => { var result = true; if (stdout) { grunt.log.write(stdout); } if (stderr) { grunt.log.write(stderr); } if (error !== null) { grunt.log.error(error); result = false; } done(result); }); } }); }); }); grunt.registerTask('setVersion', 'Set version to all needed files', (version) => { const config = grunt.config.get(['config']) const appPath = config.app const resourcesPath = config.resources const mainPackageJSON = grunt.file.readJSON('package.json') const appPackageJSON = grunt.file.readJSON(`${appPath}/package.json`) const infoPlistTmp = grunt.file.read(`${resourcesPath}/mac/Info.plist.tmp`, { encoding: 'UTF8' }); const infoPlist = grunt.template.process(infoPlistTmp, { data: { version: version } }) mainPackageJSON.version = version appPackageJSON.version = version grunt.file.write('package.json', JSON.stringify(mainPackageJSON, null, 2), { encoding: 'UTF8' }) grunt.file.write(appPath + `${appPath}/package.json`, JSON.stringify(appPackageJSON, null, 2), { encoding: 'UTF8' }) grunt.file.write(resourcesPath + `${resourcesPath}/mac/Info.plist`, infoPlist, { encoding: 'UTF8' }) }) grunt.registerTask('dist-linux', [ 'clean:distLinux64', 'copy:appLinux', 'createLinuxApp:Linux64' ]) grunt.registerTask('dist-linux32', [ 'clean:distLinux32', 'copy:appLinux32', 'createLinuxApp:Linux32' ]) grunt.registerTask('dist-win', [ 'clean:distWin', 'copy:copyWinToTmp', 'compress:appToTmp', 'rename:zipToApp', 'createWindowsApp', 'compress:finalWindowsApp' ]) grunt.registerTask('dist-win32', [ 'clean:distWin32', 'copy:copyWin32ToTmp', 'compress:appToTmp', 'rename:zipToApp', 'createWindowsApp', 'compress:finalWindows32App' ]) grunt.registerTask('dist-win64', [ 'clean:distWin64', 'copy:copyWin64ToTmp', 'compress:appToTmp', 'rename:zipToApp', 'createWindowsApp', 'compress:finalWindows64App' ]) grunt.registerTask('dist-mac', [ 'clean:distMac64', 'copy:webkit64', 'copy:appMacos64', 'rename:macApp64', 'chmod64' ]) grunt.registerTask('dist-mac32', [ 'clean:distMac32', 'copy:webkit32', 'copy:appMacos32', 'rename:macApp32', 'chmod32' ]) grunt.registerTask('check', [ 'jshint' ]) grunt.registerTask('dmg', 'Create dmg from previously created app folder in dist.', () => { const p = new Promise( (resolve, reject) => { const createDmgCommand = `resources/mac/package.sh ${ config.appName }` require('child_process').exec(createDmgCommand, (error, stdout, stderr) => { if (stdout) { grunt.log.write(stdout) resolve(stdout) } if (stderr) { grunt.log.write(stderr) reject(stderr) } if (error !== null) { grunt.log.error(error) reject(error) } }) }) }) }
reduxdj/node-webkit-redux-custombuilder
Gruntfile.js
JavaScript
apache-2.0
12,611
/* * 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 Tests for user-defined Symbols. */ goog.require('goog.testing.jsunit'); const s1 = Symbol('example'); const s2 = Symbol('example'); /** @unrestricted */ const SymbolProps = class { [s1]() { return 's1'; } [s2]() { return 's2'; } } function testSymbols() { const sp = new SymbolProps(); assertEquals('s1', sp[s1]()); assertEquals('s2', sp[s2]()); } function testArrayIterator() { // Note: this test cannot pass in IE8 since we can't polyfill // Array.prototype methods and maintain correct for-in behavior. if (typeof Object.defineProperties !== 'function') return; const iter = [2, 4, 6][Symbol.iterator](); assertObjectEquals({value: 2, done: false}, iter.next()); assertObjectEquals({value: 4, done: false}, iter.next()); assertObjectEquals({value: 6, done: false}, iter.next()); assertTrue(iter.next().done); }
Medium/closure-compiler
test/com/google/javascript/jscomp/runtime_tests/symbol_test.js
JavaScript
apache-2.0
1,481
// Reset $('.touch .client-wrap').click(function(event){ var target = $( event.target ); if ( target.hasClass( "client-close" ) ) { $('.client-wrap div.client').addClass('reset'); } else{ $('.client-wrap div.client').removeClass('reset'); } }); // David Walsh simple lazy loading [].forEach.call(document.querySelectorAll('img[data-src]'), function(img) { img.setAttribute('src', img.getAttribute('data-src')); img.onload = function() { img.removeAttribute('data-src'); }; });
urban-knight/dmcc-website
public/js/clients.js
JavaScript
apache-2.0
512
(function() { 'use strict'; angular .module('sentryApp') .controller('TimeFrameController', TimeFrameController); TimeFrameController.$inject = ['$scope', '$state', 'TimeFrame', 'ParseLinks', 'AlertService', 'paginationConstants', 'pagingParams']; function TimeFrameController ($scope, $state, TimeFrame, ParseLinks, AlertService, paginationConstants, pagingParams) { var vm = this; vm.loadPage = loadPage; vm.predicate = pagingParams.predicate; vm.reverse = pagingParams.ascending; vm.transition = transition; vm.itemsPerPage = paginationConstants.itemsPerPage; loadAll(); function loadAll () { TimeFrame.query({ page: pagingParams.page - 1, size: vm.itemsPerPage, sort: sort() }, onSuccess, onError); function sort() { var result = [vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc')]; if (vm.predicate !== 'id') { result.push('id'); } return result; } function onSuccess(data, headers) { vm.links = ParseLinks.parse(headers('link')); vm.totalItems = headers('X-Total-Count'); vm.queryCount = vm.totalItems; vm.timeFrames = data; vm.page = pagingParams.page; } function onError(error) { AlertService.error(error.data.message); } } function loadPage(page) { vm.page = page; vm.transition(); } function transition() { $state.transitionTo($state.$current, { page: vm.page, sort: vm.predicate + ',' + (vm.reverse ? 'asc' : 'desc'), search: vm.currentSearch }); } } })();
quanticc/sentry
src/main/webapp/app/entities/time-frame/time-frame.controller.js
JavaScript
apache-2.0
1,937
/*price range*/ $('#sl2').slider(); var RGBChange = function() { $('#RGB').css('background', 'rgb('+r.getValue()+','+g.getValue()+','+b.getValue()+')') }; /*scroll to top*/ $(document).ready(function(){ $(function () { $.scrollUp({ scrollName: 'scrollUp', // Element ID scrollDistance: 300, // Distance from top/bottom before showing element (px) scrollFrom: 'top', // 'top' or 'bottom' scrollSpeed: 300, // Speed back to top (ms) easingType: 'linear', // Scroll to top easing (see http://easings.net/) animation: 'fade', // Fade, slide, none animationSpeed: 200, // Animation in speed (ms) scrollTrigger: false, // Set a custom triggering element. Can be an HTML string or jQuery object //scrollTarget: false, // Set a custom target element for scrolling to the top scrollText: '<i class="fa fa-angle-up"></i>', // Text for element, can contain HTML scrollTitle: false, // Set a custom <a> title if required. scrollImg: false, // Set true to use image activeOverlay: false, // Set CSS color to display scrollUp active point, e.g '#00FFFF' zIndex: 2147483647 // Z-Index for the overlay }); }); }); // Returns a random integer between min and max // Using Math.round() will give you a non-uniform distribution! function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } // Replace url parameter - WishlistItems function replaceUrlParam(url, paramName, paramValue) { var pattern = new RegExp('(' + paramName + '=).*?(&|$)') var newUrl = url if (url.search(pattern) >= 0) { newUrl = url.replace(pattern, '$1' + paramValue + '$2'); } else { newUrl = newUrl + (newUrl.indexOf('?') > 0 ? '&' : '?') + paramName + '=' + paramValue } return newUrl } // Scroll back to selected wishlist item if (window.location.hash != '') { var target = window.location.hash; //var $target = $(target); $('html, body').stop().animate({ //'scrollTop': $target.offset().top }, 900, 'swing', function () { window.location.hash = target; }); }
ReinID/ReinID
Samples/.Net/.Netproperty4u/Property4U/Scripts/main.js
JavaScript
apache-2.0
2,179
import { extend } from 'flarum/extend'; import PermissionGrid from 'flarum/components/PermissionGrid'; export default function() { extend(PermissionGrid.prototype, 'moderateItems', items => { items.add('tag', { icon: 'fas fa-tag', label: app.translator.trans('flarum-tags.admin.permissions.tag_discussions_label'), permission: 'discussion.tag' }, 95); }); }
drthomas21/WordPress_Tutorial
community_htdocs/vendor/flarum/tags/js/src/admin/addTagPermission.js
JavaScript
apache-2.0
389
const loopback = require('loopback'); const boot = require('loopback-boot'); const request = require('request-promise'); const config = require('./config.json'); const log = require('log4js').getLogger('server'); const jwt = require('jwt-simple'); var app = module.exports = loopback(); var apiUrl = config.restApiRoot + '/*'; function parseJwt (token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace('-', '+').replace('_', '/'); var json = new Buffer(base64, 'base64').toString('binary'); return JSON.parse(json); }; app.use(loopback.context()); app.use(['/api/todos'], function(req, res, next) { var accessToken = req.query.access_token || req.headers['Authorization']; if(accessToken) { app.accessTokenProvider.getUserInfo(accessToken) .then(userInfo => { log.debug('userInfo:', userInfo); loopback.getCurrentContext().set('userInfo', userInfo); next(); }).catch(error => { log.error(error); next(error); }); } else { log.debug('missing accessToken'); next({ name: 'MISSING_ACCESS_TOKEN', status: 401, message: 'tenant access token is required to access this endpoint' }); } }); app.start = () => { // start the web server return app.listen(() => { app.emit('started'); var baseUrl = app.get('url').replace(/\/$/, ''); log.info('Web server listening at: %s', baseUrl); if (app.get('loopback-component-explorer')) { var explorerPath = app.get('loopback-component-explorer').mountPath; log.info('Browse your REST API at %s%s', baseUrl, explorerPath); } }); }; // Bootstrap the application, configure models, datasources and middleware. // Sub-apps like REST API are mounted via boot scripts. boot(app, __dirname, function(err) { if (err) throw err; // start the server if `$ node server.js` if (require.main === module) app.start(); });
SaaSManager/todo-example
server/server.js
JavaScript
apache-2.0
1,921
'use strict'; angular.module('donetexampleApp') .service('ParseLinks', function () { this.parse = function (header) { if (header.length == 0) { throw new Error("input must not be of zero length"); } // Split parts by comma var parts = header.split(','); var links = {}; // Parse each part into a named link angular.forEach(parts, function (p) { var section = p.split(';'); if (section.length != 2) { throw new Error("section could not be split on ';'"); } var url = section[0].replace(/<(.*)>/, '$1').trim(); var queryString = {}; url.replace( new RegExp("([^?=&]+)(=([^&]*))?", "g"), function($0, $1, $2, $3) { queryString[$1] = $3; } ); var page = queryString['page']; if( angular.isString(page) ) { page = parseInt(page); } var name = section[1].replace(/rel="(.*)"/, '$1').trim(); links[name] = page; }); return links; } });
CyberCastle/DoNetExample
DoNetExample.Gui/scripts/components/util/parse-links.service.js
JavaScript
apache-2.0
1,252
var searchData= [ ['interactiontype',['InteractionType',['../class_student_record.html#a00e060bc8aa9829e5db087e2cba21009',1,'StudentRecord']]] ];
rstals/Unity-SCORM-Integration-Kit
Documentation/search/enums_2.js
JavaScript
apache-2.0
148
'use strict'; /** * @ngdoc function * @name lubriApp.controller:MembersCtrl * @description * # MembersCtrl * Controller of the lubriApp */ angular.module('lubriApp') .config(function($stateProvider) { $stateProvider.state('app.members', { abstract: true, url: '/members', templateUrl: 'views/members/main.html', controller: 'MembersCtrl' }) .state('app.members.list', { url: '', templateUrl: 'views/members/list.html', controller: 'MembersCtrl' }) .state('app.members.add', { url: '/add', templateUrl: 'views/members/form.html', controller: 'MembersCtrl' }) .state('app.members.import', { url: '/import', templateUrl: 'views/members/import.html', controller: 'MembersCtrl' }) .state('app.members.edit', { url: '/:id/edit', templateUrl: 'views/members/form.html', controller: 'MembersCtrl' }) .state('app.members.view', { url: '/:id', templateUrl: 'views/members/view.html', controller: 'MembersCtrl' }); }) .controller('MembersCtrl', function($scope, $state, $stateParams, $q, $interval, toasty, Member, SweetAlert, i18nService) { var memberId = $stateParams.id; i18nService.setCurrentLang('zh-cn'); $scope.importData = []; $scope.gridImportOptions = { enableGridMenu: true, importerDataAddCallback: function( grid, newObjects ) { $scope.importData = $scope.importData.concat( newObjects ); }, onRegisterApi: function(gridApi){ $scope.gridImportApi = gridApi; gridApi.rowEdit.on.saveRow($scope, $scope.saveRow); }, data: 'importData' }; $scope.saveRow = function( rowEntity ) { // create a fake promise - normally you'd use the promise returned by $http or $resource var promise = $q.defer(); $scope.gridImportApi.rowEdit.setSavePromise( $scope.gridImportApi.grid, rowEntity, promise.promise ); $interval( function() { promise.resolve(); }, 1000, 1); }; $scope.saveImport = function () { if ($scope.importData.length > 0) { var members = $scope.importData; for (var i=0;i<members.length;i++) { var member = members[i]; member.created = new Date(); delete member.$$hashKey; Member.upsert(member, function() { }, function(err) { console.log(err); }); }; toasty.pop.success({title: '组员导入成功', msg: members.length + '个组员成功导入到系统中!', sound: false}); loadItems(); $state.go('^.list'); }; }; if (memberId) { $scope.member = Member.findById({ id: memberId }, function() {}, function(err) { console.log(err); }); } else { $scope.member = {}; } $scope.gridOptions = { data: 'members', enableFiltering: true, paginationPageSizes: [5, 10, 15], paginationPageSize: 10, headerRowHeight: 39, rowHeight: 39, columnFooterHeight: 39, gridFooterHeight: 39, selectionRowHeaderWidth: 39, columnDefs: [ { name: 'Edit', width: 80, displayName: '编辑', enableSorting: false, enableFiltering: false, cellTemplate: '<a href="" class="ui-state-hover" ui-sref="^.edit({id: row.entity.id})"> <i class="fa fa-pencil fa-lg blue"></i></a> <a href="" class="ui-state-hover" style="margin-left:5px;" ng-click="getExternalScopes().delete({id: row.entity.id})"><i class="fa fa-trash-o fa-lg red"></i></a>' }, { name: 'name', displayName: '全称', cellTemplate: '<div class="ui-grid-cell-contents"><a href="" ui-sref="^.view({id: row.entity.id})"> {{ COL_FIELD }} </a></div>'} ,{ name: 'firstName', displayName: '姓' } ,{ name: 'lastName', displayName: '名' } ,{ name: 'displayName', displayName: '显示名' } ,{ name: 'position', displayName: '职位' } , { name: 'priority', displayName: '排序号' } ], enableGridMenu: true, enableSelectAll: true, exporterCsvFilename: 'members.csv', exporterSuppressColumns: ['Edit'], exporterPdfDefaultStyle: {fontSize: 9}, exporterPdfTableStyle: {margin: [30, 30, 30, 30]}, exporterPdfTableHeaderStyle: {fontSize: 10, bold: true, italics: true, color: 'red'}, exporterPdfHeader: { text: "Meeting Member Information", style: 'headerStyle' }, exporterPdfFooter: function ( currentPage, pageCount ) { return { text: currentPage.toString() + ' of ' + pageCount.toString(), style: 'footerStyle' }; }, exporterPdfCustomFormatter: function ( docDefinition ) { docDefinition.styles.headerStyle = { fontSize: 22, bold: true }; docDefinition.styles.footerStyle = { fontSize: 10, bold: true }; return docDefinition; }, exporterPdfOrientation: 'portrait', exporterPdfPageSize: 'LETTER', exporterPdfMaxGridWidth: 500, exporterCsvLinkElement: angular.element(document.querySelectorAll(".custom-csv-link-location")) }; $scope.gridOptions.onRegisterApi = function (gridApi) { $scope.gridApi = gridApi; }; function loadItems() { $scope.members = Member.find(); } loadItems(); $scope.viewActions = { delete : $scope.delete }; $scope.delete = function(id) { SweetAlert.swal({ title: '您确定要删除吗?', type: 'warning', showCancelButton: true, confirmButtonColor: '#DD6B55' }, function(isConfirm){ if (isConfirm) { Member.deleteById(id, function() { toasty.pop.success({title: '组员被删除', msg: '您成功删除了组员!', sound: false}); loadItems(); $state.go($state.current, {}, {reload: true}); //$state.go('app.members.list'); }, function(err) { toasty.pop.error({title: '删除组员出错', msg: '删除组员发生错误:' + err, sound: false}); }); } else { return false; } }); }; $scope.formFields = [{ key: 'name', type: 'text', label: '全名', required: true }, { key: 'firstName', type: 'text', label: '姓', required: true }, { key: 'lastName', type: 'text', label: '名', required: true }, { key: 'displayName', type: 'text', label: '显示名', required: true }, { key: 'position', type: 'text', label: '职位', required: true }, { key: 'priority', type: 'number', label: '排序号', required: true }]; $scope.formOptions = { uniqueFormId: true, hideSubmit: false, submitCopy: '保存' }; $scope.onSubmit = function() { if (($scope.member.created === null) || ($scope.member.created === undefined)){ $scope.member.created = new Date(); }; Member.upsert($scope.member, function() { toasty.pop.success({title: '组员保存成功', msg: '组员已成功保存到系统中!', sound: false}); loadItems(); $state.go('^.list'); }, function(err) { console.log(err); }); }; });
g8te/lubri
client/app/scripts/controllers/members.js
JavaScript
apache-2.0
7,033
/* Copyright 2015 Ricardo Tubio-Pardavila 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. */ angular.module('snRequestsDirective', [ 'ngMaterial', 'snCommonFilters', 'snApplicationBus', 'snRequestsFilters', 'snControllers', 'snJRPCServices' ]) .controller('snRequestSlotCtrl', [ '$scope', '$mdDialog', '$mdToast', 'satnetRPC', 'snDialog', 'snMessageBus', /** * Controller function for handling the SatNet requests dialog. * * @param {Object} $scope $scope for the controller */ function ($scope, $mdDialog, $mdToast, satnetRPC, snDialog, snMessageBus) { $scope.gui = { groundstation_id: '', spacecraft_id: '', primary: '', hide: { accept: true, drop: true, deny: true, }, slot: {} }; /** * Function that handles the process of accepting a given request that * has already been selected. */ $scope.accept = function () { satnetRPC.rCall( 'gs.operational.accept', [ $scope.groundstation_id, [$scope.slot.identifier] ] ).then(function (results) { snDialog.toastAction('Confirmed slot #',$scope.slot.identifier); $scope.slot.state = 'RESERVED'; snMessageBus.send( snMessageBus.CHANNELS.requests.id, snMessageBus.EVENTS.accepted.id, { gs_id: $scope.gui.groundstation_id, sc_id: $scope.gui.spacecraft_id, primary: $scope.gui.primary, slot: $scope.gui.slot } ); }).catch(function (c) { snDialog.exception('gs.operational.accept', '', c); }); }; /** * Function that handles the process of denying a given request that * has already been selected. * * TODO :: Temporary, it has been linked to the drop function so that * the slot does not stay forever with the DENIED state. */ $scope.deny = function () { satnetRPC.rCall( 'gs.operational.drop', [ $scope.groundstation_id, [$scope.slot.identifier] ] ).then(function (results) { snDialog.toastAction('Denied slot #', $scope.slot.identifier); $scope.slot.state = 'FREE'; snMessageBus.send( snMessageBus.CHANNELS.requests.id, snMessageBus.EVENTS.denied.id, { gs_id: $scope.gui.groundstation_id, sc_id: $scope.gui.spacecraft_id, primary: $scope.gui.primary, slot: $scope.gui.slot } ); }).catch(function (c) { snDialog.exception('gs.operational.drop', '', c); }); }; /** * Function that handles the process of droping a given request that * has already been booked. * * IMPORTANT: This function works both for spacecraft and for * groundstation slots; therefore, there is an inherent * level of complexity added in addition in order to * handle both cases. */ $scope.drop = function () { var rpc = ($scope.gui.primary === 'groundstation') ? 'gs.operational.drop' : 'sc.cancel', segment_id = ($scope.gui.primary === 'groundstation') ? $scope.groundstation_id : $scope.spacecraft_id; satnetRPC.rCall( rpc, [segment_id, [$scope.slot.identifier]] ).then(function (results) { snDialog.toastAction('Dropped slot #', $scope.slot.identifier); $scope.slot.state = 'FREE'; snMessageBus.send( snMessageBus.CHANNELS.requests.id, snMessageBus.EVENTS.dropped.id, { gs_id: $scope.gui.groundstation_id, sc_id: $scope.gui.spacecraft_id, primary: $scope.gui.primary, slot: $scope.gui.slot } ); }).catch(function (c) { snDialog.exception(rpc, '', c); }); }; /** * Function that returns whether o not the "accept" button should be * displayed, taking into account the state of the controller. */ $scope.showAccept = function () { return ($scope.gui.slot.state === 'SELECTED') && !($scope.gui.hide.accept); }; /** * Function that returns whether o not the "deny" button should be * displayed, taking into account the state of the controller. */ $scope.showDeny = function () { return ($scope.gui.slot.state === 'SELECTED') && !($scope.gui.hide.deny); }; /** * Function that returns whether o not the "drop" button should be * displayed, taking into account the state of the controller. */ $scope.showDrop = function () { if ($scope.gui.primary === 'spacecraft') { return !($scope.gui.hide.drop) && ( ($scope.gui.slot.state === 'SELECTED') || ($scope.gui.slot.state === 'RESERVED') ); } else { return !($scope.gui.hide.drop) && ( ($scope.gui.slot.state === 'RESERVED') ); } }; /** * Initialization of the controller. */ $scope.init = function () { $scope.gui.groundstation_id = $scope.gs; $scope.gui.spacecraft_id = $scope.sc; $scope.gui.primary = $scope.primary; $scope.gui.slot = $scope.slot; if ( $scope.gui.primary === 'spacecraft' ) { $scope.gui.hide.drop = false; } else { $scope.gui.hide.accept = false; $scope.gui.hide.deny = false; $scope.gui.hide.drop = false; } }; $scope.init(); } ]) .directive('snRequestSlot', /** * Function that creates the directive itself returning the object required * by Angular. * * @returns {Object} Object directive required by Angular, with restrict * and templateUrl */ function () { return { restrict: 'E', templateUrl: 'operations/templates/requests/slot.html', controller: 'snRequestSlotCtrl', scope: { sc: '@', gs: '@', primary: '@', slot: '=' } }; } ) .controller('snRequestsDlgCtrl', [ '$scope', '$log', '$mdDialog', 'satnetRPC','snDialog', 'snMessageBus', /** * Controller function for handling the SatNet requests dialog. * * @param {Object} $scope $scope for the controller */ function ($scope, $log, $mdDialog, satnetRPC, snDialog, snMessageBus) { $scope.events = { requests: { accepted: { id: snMessageBus.createName( snMessageBus.CHANNELS.requests.id, snMessageBus.EVENTS.accepted.id ) }, denied: { id: snMessageBus.createName( snMessageBus.CHANNELS.requests.id, snMessageBus.EVENTS.denied.id ) }, dropped: { id: snMessageBus.createName( snMessageBus.CHANNELS.requests.id, snMessageBus.EVENTS.dropped.id ) } } }; /** * This function finds the given slot within the dictionary/array of * slots within this controller. * * @param {String} segmentId Identifier of the segment * @param {String} slotId Identifier of the slot */ $scope._findSlot = function (segmentId, slotId) { var slots = $scope.gui.slots[segmentId]; if ((slots === undefined) || (slots.length === 0)) { throw 'No slots for ss = ' + segmentId; } for (var i = 0, L = slots.length; i < L; i++) { if (slots[i].identifier === slotId) { return { index: i, slot: slots[i] }; } } throw 'Slot not found for ss = ' + segmentId; }; /** * Updates the slots dictionary when the slot that triggered the event * was updated to the "FREE" state. * * @param {Object} data The data object attached to the event */ $scope._updateFree = function (data) { var ss_id = (data.primary === 'spacecraft') ? data.gs_id: data.sc_id, other_ss_id = (data.primary === 'spacecraft') ? data.sc_id: data.gs_id, slot = $scope._findSlot(ss_id, data.slot.identifier), slot_other = $scope._findSlot( other_ss_id, data.slot.identifier ); $scope.gui.slots[ss_id].splice(slot.index, 1); $scope.gui.slots[other_ss_id].splice(slot_other.index, 1); }; /** * Updates the slots dictionary when the slot that triggered the event * was not updated to the "FREE" state. * * @param {Object} data The data object attached to the event */ $scope._updateNonFree = function (data) { var ss_id = (data.primary === 'spacecraft') ? data.gs_id: data.sc_id, slot = $scope._findSlot(ss_id, data.slot.identifier); slot.slot.state = data.slot.state; }; /** * CALLBACK * This function is the callback that handles the event triggered * whenever a request slot has been accepted, canceled or denied. * * @param {String} event The name of the event * @param {Object} data The data object generated by the event */ $scope._updateRequestCb = function (event, data) { try { if (data.slot.state === 'FREE') { $scope._updateFree(data); } else { $scope._updateNonFree(data); } } catch (e) { $log.info(e); } }; $scope.$on( $scope.events.requests.accepted.id, $scope._updateRequestCb ); $scope.$on( $scope.events.requests.denied.id, $scope._updateRequestCb ); $scope.$on( $scope.events.requests.dropped.id, $scope._updateRequestCb ); $scope.gui = { gss: [], scs: [], slots: {}, filtered: {} }; /** * Function that closes the dialog. */ $scope.close = function () { $mdDialog.hide(); }; /** * This function is used to check whether the given slot has to be * discarded from amongst the other slots or not. * * @param {Object} slot The slot to be checked * @param {Boolean} 'true' if the slot has to be discarded */ $scope._filterByState = function(slot) { return (slot.state !== 'SELECTED') && (slot.state !== 'RESERVED'); }; /** * This function processes the slots received from the server in order * to adapt them to a more JavaScript "friendly" data structure. It * stores the results directly in the controller's data section. * * @param {String} segmentId Identifier of the segment * @param {Object} results Object with the results from the server */ $scope._processSlots = function (segmentId, results) { $scope.gui.slots[segmentId] = []; if ((results === null) || (angular.equals({}, results))) { return; } var ss_id = Object.keys(results)[0], slots = results[ss_id]; for (var i = 0, L = slots.length; i < L; i++) { if ($scope._filterByState(slots[i])) {continue;} slots[i].segment_id = ss_id; $scope.gui.slots[segmentId].push(slots[i]); } }; /** * This function retrieves the operational slots from the server for a * given segment and stores them internally in a single list for the * controller. * IMPORTANT: It processes the list so that it adds the reference to * the other segment related in the slot by place its id inside the * object of the slot rather than as a key to access the slot. * IMPORTANT 2: It filters out all the slots whose states are neither * 'SELECTED' nor 'BOOKED'. * * @param segmentType String that indicates whether the reference * segment is a ground station ('sc') or a * spacecraft ('sc') * @param segmentId String Identifier of the segment */ $scope._pullSlots = function (segmentType, segmentId) { var rpc_name = segmentType + '.operational'; satnetRPC.rCall(rpc_name, [segmentId]).then(function (results) { $scope._processSlots(segmentId, results); }).catch(function (cause) { snDialog.exception(segmentType + '.operational', '-', cause); }); }; /** * Retrieves the slots for all the ground stations owned by the * currently logged-in user. * @returns */ $scope._pullGsSlots = function () { satnetRPC.rCall('gs.list.mine', []).then(function (results) { $scope.gui.gss = results; for (var i = 0, l = $scope.gui.gss.length;i < l; i++) { $scope._pullSlots('gs', $scope.gui.gss[i]); } }).catch(function (cause) { snDialog.exception('gs.list.mine', '-', cause); }); }; /** * Retrieves the slots for all the spacecraft owned by the * currently logged-in user. * @returns */ $scope._pullScSlots = function () { satnetRPC.rCall('sc.list.mine', []).then(function (results) { $scope.gui.scs = results; for (var i = 0, l = $scope.gui.scs.length; i < l; i++ ) { $scope._pullSlots('sc', $scope.gui.scs[i]); } }).catch(function (cause) { snDialog.exception('sc.list.mine', '-', cause); }); }; /** * Initialization of the controller. */ $scope.init = function () { $scope._pullGsSlots(); $scope._pullScSlots(); }; $scope.init(); } ]) .controller('snRequestsCtrl', [ '$scope', '$mdDialog', /** * Controller function for opening the SatNet requests dialog. * * @param {Object} $scope $scope for the controller * @param {Object} $mdDialog Angular material Dialog service */ function ($scope, $mdDialog) { /** * Function that opens the dialog when the snRequests button is * clicked. */ $scope.openDialog = function () { $mdDialog.show({ templateUrl: 'operations/templates/requests/list.html', controller: 'snRequestsDlgCtrl' }); }; } ]) .directive('snRequests', /** * Function that creates the directive itself returning the object required * by Angular. * * @returns {Object} Object directive required by Angular, with restrict * and templateUrl */ function () { return { restrict: 'E', templateUrl: 'operations/templates/requests/menu.html', controller: 'snRequestsCtrl' }; } );
satnet-project/satnet-ng
src/operations/directives/Requests.js
JavaScript
apache-2.0
17,236
import Vue from 'vue' import { hasFetch, normalizeError, addLifecycleHook } from '../utils' const isSsrHydration = (vm) => vm.$vnode && vm.$vnode.elm && vm.$vnode.elm.dataset && vm.$vnode.elm.dataset.fetchKey const nuxtState = window.<%= globals.context %> export default { beforeCreate () { if (!hasFetch(this)) { return } this._fetchDelay = typeof this.$options.fetchDelay === 'number' ? this.$options.fetchDelay : 200 Vue.util.defineReactive(this, '$fetchState', { pending: false, error: null, timestamp: Date.now() }) this.$fetch = $fetch.bind(this) addLifecycleHook(this, 'created', created) addLifecycleHook(this, 'beforeMount', beforeMount) } } function beforeMount() { if (!this._hydrated) { return this.$fetch() } } function created() { if (!isSsrHydration(this)) { return } // Hydrate component this._hydrated = true this._fetchKey = +this.$vnode.elm.dataset.fetchKey const data = nuxtState.fetch[this._fetchKey] // If fetch error if (data && data._error) { this.$fetchState.error = data._error return } // Merge data for (const key in data) { Vue.set(this.$data, key, data[key]) } } async function $fetch() { this.$nuxt.nbFetching++ this.$fetchState.pending = true this.$fetchState.error = null this._hydrated = false let error = null const startTime = Date.now() try { await this.$options.fetch.call(this) } catch (err) { error = normalizeError(err) } const delayLeft = this._fetchDelay - (Date.now() - startTime) if (delayLeft > 0) { await new Promise(resolve => setTimeout(resolve, delayLeft)) } this.$fetchState.error = error this.$fetchState.pending = false this.$fetchState.timestamp = Date.now() this.$nextTick(() => this.$nuxt.nbFetching--) }
BigBoss424/portfolio
v6/node_modules/@nuxt/vue-app-edge/template/mixins/fetch.client.js
JavaScript
apache-2.0
1,830
/*! * Copyright 2012 Sakai Foundation (SF) Licensed under the * Educational Community License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may * obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ require(['jquery', 'oae.core'], function($, oae) { // Get the group id from the URL. The expected URL is /group/<groupId> var groupId = document.location.pathname.split('/')[2]; if (!groupId) { oae.api.util.redirect().login(); } // Variable used to cache the requested user's profile var groupProfile = null; // Variable used to cache the group's base URL var baseUrl = '/group/' + groupId; /** * Get the group's basic profile and set up the screen. If the groups * can't be found or is private to the current user, the appropriate * error page will be shown */ var getGroupProfile = function() { oae.api.group.getGroup(groupId, function(err, profile) { if (err && err.code === 404) { oae.api.util.redirect().notfound(); } else if (err && err.code === 401) { oae.api.util.redirect().accessdenied(); } groupProfile = profile; setUpClip(); setUpNavigation(); // Set the browser title oae.api.util.setBrowserTitle(groupProfile.displayName); }); }; $(document).on('oae.context.get', function() { $(document).trigger('oae.context.send', groupProfile); }); $(document).trigger('oae.context.send', groupProfile); /** * Render the group's clip, containing the profile picture, display name as well as the * group's admin options */ var setUpClip = function() { oae.api.util.template().render($('#group-clip-template'), {'group': groupProfile}, $('#group-clip-container')); // Only show the create and upload clips to managers if (groupProfile.isManager) { $('#group-actions').show(); } }; /** * Set up the left hand navigation with the me space page structure */ var setUpNavigation = function() { // Structure that will be used to construct the left hand navigation var lhNavigation = [ { 'id': 'activity', 'title': oae.api.i18n.translate('__MSG__RECENT_ACTIVITY__'), 'icon': 'icon-dashboard', 'layout': [ { 'width': 'span8', 'widgets': [ { 'id': 'activity', 'settings': { 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] }, { 'id': 'library', 'title': oae.api.i18n.translate('__MSG__LIBRARY__'), 'icon': 'icon-briefcase', 'layout': [ { 'width': 'span12', 'widgets': [ { 'id': 'library', 'settings': { 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] }, { 'id': 'members', 'title': oae.api.i18n.translate('__MSG__MEMBERS__'), 'icon': 'icon-user', 'layout': [ { 'width': 'span12', 'widgets': [ { 'id': 'participants', 'settings': { 'principalId': groupProfile.id, 'canManage': groupProfile.isManager } } ] } ] } ]; $(window).trigger('oae.trigger.lhnavigation', [lhNavigation, baseUrl]); $(window).on('oae.ready.lhnavigation', function() { $(window).trigger('oae.trigger.lhnavigation', [lhNavigation, baseUrl]); }); }; getGroupProfile(); });
Coenego/3akai-ux
ui/js/group.js
JavaScript
apache-2.0
5,033
angular.module('app.services', [ 'app.services.actions', 'app.services.connection', 'app.services.coverart', 'app.services.locale', 'app.services.logging', 'app.services.mopidy', 'app.services.paging', 'app.services.platform', 'app.services.router', 'app.services.servers', 'app.services.settings' ]);
tkem/mopidy-mobile
www/app/services/services.js
JavaScript
apache-2.0
324
/** * @license Highcharts JS v7.1.1 (2019-04-09) * * (c) 2014-2019 Highsoft AS * Authors: Jon Arild Nygard / Oystein Moseng * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { factory['default'] = factory; module.exports = factory; } else if (typeof define === 'function' && define.amd) { define('highcharts/modules/treemap', ['highcharts'], function (Highcharts) { factory(Highcharts); factory.Highcharts = Highcharts; return factory; }); } else { factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined); } }(function (Highcharts) { var _modules = Highcharts ? Highcharts._modules : {}; function _registerModule(obj, path, args, fn) { if (!obj.hasOwnProperty(path)) { obj[path] = fn.apply(null, args); } } _registerModule(_modules, 'mixins/tree-series.js', [_modules['parts/Globals.js']], function (H) { var extend = H.extend, isArray = H.isArray, isBoolean = function (x) { return typeof x === 'boolean'; }, isFn = function (x) { return typeof x === 'function'; }, isObject = H.isObject, isNumber = H.isNumber, merge = H.merge, pick = H.pick; // TODO Combine buildTree and buildNode with setTreeValues // TODO Remove logic from Treemap and make it utilize this mixin. var setTreeValues = function setTreeValues(tree, options) { var before = options.before, idRoot = options.idRoot, mapIdToNode = options.mapIdToNode, nodeRoot = mapIdToNode[idRoot], levelIsConstant = ( isBoolean(options.levelIsConstant) ? options.levelIsConstant : true ), points = options.points, point = points[tree.i], optionsPoint = point && point.options || {}, childrenTotal = 0, children = [], value; extend(tree, { levelDynamic: tree.level - (levelIsConstant ? 0 : nodeRoot.level), name: pick(point && point.name, ''), visible: ( idRoot === tree.id || (isBoolean(options.visible) ? options.visible : false) ) }); if (isFn(before)) { tree = before(tree, options); } // First give the children some values tree.children.forEach(function (child, i) { var newOptions = extend({}, options); extend(newOptions, { index: i, siblings: tree.children.length, visible: tree.visible }); child = setTreeValues(child, newOptions); children.push(child); if (child.visible) { childrenTotal += child.val; } }); tree.visible = childrenTotal > 0 || tree.visible; // Set the values value = pick(optionsPoint.value, childrenTotal); extend(tree, { children: children, childrenTotal: childrenTotal, isLeaf: tree.visible && !childrenTotal, val: value }); return tree; }; var getColor = function getColor(node, options) { var index = options.index, mapOptionsToLevel = options.mapOptionsToLevel, parentColor = options.parentColor, parentColorIndex = options.parentColorIndex, series = options.series, colors = options.colors, siblings = options.siblings, points = series.points, getColorByPoint, chartOptionsChart = series.chart.options.chart, point, level, colorByPoint, colorIndexByPoint, color, colorIndex; function variation(color) { var colorVariation = level && level.colorVariation; if (colorVariation) { if (colorVariation.key === 'brightness') { return H.color(color).brighten( colorVariation.to * (index / siblings) ).get(); } } return color; } if (node) { point = points[node.i]; level = mapOptionsToLevel[node.level] || {}; getColorByPoint = point && level.colorByPoint; if (getColorByPoint) { colorIndexByPoint = point.index % (colors ? colors.length : chartOptionsChart.colorCount ); colorByPoint = colors && colors[colorIndexByPoint]; } // Select either point color, level color or inherited color. if (!series.chart.styledMode) { color = pick( point && point.options.color, level && level.color, colorByPoint, parentColor && variation(parentColor), series.color ); } colorIndex = pick( point && point.options.colorIndex, level && level.colorIndex, colorIndexByPoint, parentColorIndex, options.colorIndex ); } return { color: color, colorIndex: colorIndex }; }; /** * Creates a map from level number to its given options. * * @private * @function getLevelOptions * * @param {object} params * Object containing parameters. * - `defaults` Object containing default options. The default options * are merged with the userOptions to get the final options for a * specific level. * - `from` The lowest level number. * - `levels` User options from series.levels. * - `to` The highest level number. * * @return {Highcharts.Dictionary<object>} * Returns a map from level number to its given options. */ var getLevelOptions = function getLevelOptions(params) { var result = null, defaults, converted, i, from, to, levels; if (isObject(params)) { result = {}; from = isNumber(params.from) ? params.from : 1; levels = params.levels; converted = {}; defaults = isObject(params.defaults) ? params.defaults : {}; if (isArray(levels)) { converted = levels.reduce(function (obj, item) { var level, levelIsConstant, options; if (isObject(item) && isNumber(item.level)) { options = merge({}, item); levelIsConstant = ( isBoolean(options.levelIsConstant) ? options.levelIsConstant : defaults.levelIsConstant ); // Delete redundant properties. delete options.levelIsConstant; delete options.level; // Calculate which level these options apply to. level = item.level + (levelIsConstant ? 0 : from - 1); if (isObject(obj[level])) { extend(obj[level], options); } else { obj[level] = options; } } return obj; }, {}); } to = isNumber(params.to) ? params.to : 1; for (i = 0; i <= to; i++) { result[i] = merge( {}, defaults, isObject(converted[i]) ? converted[i] : {} ); } } return result; }; /** * Update the rootId property on the series. Also makes sure that it is * accessible to exporting. * * @private * @function updateRootId * * @param {object} series * The series to operate on. * * @return {string} * Returns the resulting rootId after update. */ var updateRootId = function (series) { var rootId, options; if (isObject(series)) { // Get the series options. options = isObject(series.options) ? series.options : {}; // Calculate the rootId. rootId = pick(series.rootNode, options.rootId, ''); // Set rootId on series.userOptions to pick it up in exporting. if (isObject(series.userOptions)) { series.userOptions.rootId = rootId; } // Set rootId on series to pick it up on next update. series.rootNode = rootId; } return rootId; }; var result = { getColor: getColor, getLevelOptions: getLevelOptions, setTreeValues: setTreeValues, updateRootId: updateRootId }; return result; }); _registerModule(_modules, 'mixins/draw-point.js', [], function () { var isFn = function (x) { return typeof x === 'function'; }; /** * Handles the drawing of a component. * Can be used for any type of component that reserves the graphic property, and * provides a shouldDraw on its context. * * @private * @function draw * * @param {object} params * Parameters. * * TODO: add type checking. * TODO: export this function to enable usage */ var draw = function draw(params) { var component = this, graphic = component.graphic, animatableAttribs = params.animatableAttribs, onComplete = params.onComplete, css = params.css, renderer = params.renderer; if (component.shouldDraw()) { if (!graphic) { component.graphic = graphic = renderer[params.shapeType](params.shapeArgs).add(params.group); } graphic .css(css) .attr(params.attribs) .animate( animatableAttribs, params.isNew ? false : undefined, onComplete ); } else if (graphic) { var destroy = function () { component.graphic = graphic = graphic.destroy(); if (isFn(onComplete)) { onComplete(); } }; // animate only runs complete callback if something was animated. if (Object.keys(animatableAttribs).length) { graphic.animate(animatableAttribs, undefined, function () { destroy(); }); } else { destroy(); } } }; /** * An extended version of draw customized for points. * It calls additional methods that is expected when rendering a point. * * @param {object} params Parameters */ var drawPoint = function drawPoint(params) { var point = this, attribs = params.attribs = params.attribs || {}; // Assigning class in dot notation does go well in IE8 // eslint-disable-next-line dot-notation attribs['class'] = point.getClassName(); // Call draw to render component draw.call(point, params); }; return drawPoint; }); _registerModule(_modules, 'modules/treemap.src.js', [_modules['parts/Globals.js'], _modules['mixins/tree-series.js'], _modules['mixins/draw-point.js']], function (H, mixinTreeSeries, drawPoint) { /* * * (c) 2014-2019 Highsoft AS * * Authors: Jon Arild Nygard / Oystein Moseng * * License: www.highcharts.com/license */ var seriesType = H.seriesType, seriesTypes = H.seriesTypes, addEvent = H.addEvent, merge = H.merge, extend = H.extend, error = H.error, defined = H.defined, noop = H.noop, fireEvent = H.fireEvent, getColor = mixinTreeSeries.getColor, getLevelOptions = mixinTreeSeries.getLevelOptions, isArray = H.isArray, isBoolean = function (x) { return typeof x === 'boolean'; }, isNumber = H.isNumber, isObject = H.isObject, isString = H.isString, pick = H.pick, Series = H.Series, stableSort = H.stableSort, color = H.Color, eachObject = function (list, func, context) { context = context || this; H.objectEach(list, function (val, key) { func.call(context, val, key, list); }); }, // @todo find correct name for this function. // @todo Similar to reduce, this function is likely redundant recursive = function (item, func, context) { var next; context = context || this; next = func.call(context, item); if (next !== false) { recursive(next, func, context); } }, updateRootId = mixinTreeSeries.updateRootId; /** * @private * @class * @name Highcharts.seriesTypes.treemap * * @augments Highcharts.Series */ seriesType( 'treemap', 'scatter' /** * A treemap displays hierarchical data using nested rectangles. The data * can be laid out in varying ways depending on options. * * @sample highcharts/demo/treemap-large-dataset/ * Treemap * * @extends plotOptions.scatter * @excluding marker, jitter * @product highcharts * @optionparent plotOptions.treemap */ , { /** * When enabled the user can click on a point which is a parent and * zoom in on its children. Deprecated and replaced by * [allowTraversingTree](#plotOptions.treemap.allowTraversingTree). * * @sample {highcharts} highcharts/plotoptions/treemap-allowdrilltonode/ * Enabled * * @deprecated * @type {boolean} * @default false * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.allowDrillToNode */ /** * When enabled the user can click on a point which is a parent and * zoom in on its children. * * @sample {highcharts} highcharts/plotoptions/treemap-allowtraversingtree/ * Enabled * * @since 7.0.3 * @product highcharts */ allowTraversingTree: false, animationLimit: 250, /** * When the series contains less points than the crop threshold, all * points are drawn, event if the points fall outside the visible plot * area at the current zoom. The advantage of drawing all points * (including markers and columns), is that animation is performed on * updates. On the other hand, when the series contains more points than * the crop threshold, the series data is cropped to only contain points * that fall within the plot area. The advantage of cropping away * invisible points is to increase performance on large series. * * @type {number} * @default 300 * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.cropThreshold */ /** * Fires on a request for change of root node for the tree, before the * update is made. An event object is passed to the function, containing * additional properties `newRootId`, `previousRootId`, `redraw` and * `trigger`. * * @type {function} * @default undefined * @sample {highcharts} highcharts/plotoptions/treemap-events-setrootnode/ * Alert update information on setRootNode event. * @since 7.0.3 * @product highcharts * @apioption plotOptions.treemap.events.setRootNode */ /** * This option decides if the user can interact with the parent nodes * or just the leaf nodes. When this option is undefined, it will be * true by default. However when allowTraversingTree is true, then it * will be false by default. * * @sample {highcharts} highcharts/plotoptions/treemap-interactbyleaf-false/ * False * @sample {highcharts} highcharts/plotoptions/treemap-interactbyleaf-true-and-allowtraversingtree/ * InteractByLeaf and allowTraversingTree is true * * @type {boolean} * @since 4.1.2 * @product highcharts * @apioption plotOptions.treemap.interactByLeaf */ /** * The sort index of the point inside the treemap level. * * @sample {highcharts} highcharts/plotoptions/treemap-sortindex/ * Sort by years * * @type {number} * @since 4.1.10 * @product highcharts * @apioption plotOptions.treemap.sortIndex */ /** * When using automatic point colors pulled from the `options.colors` * collection, this option determines whether the chart should receive * one color per series or one color per point. * * @see [series colors](#plotOptions.treemap.colors) * * @type {boolean} * @default false * @since 2.0 * @product highcharts * @apioption plotOptions.treemap.colorByPoint */ /** * A series specific or series type specific color set to apply instead * of the global [colors](#colors) when * [colorByPoint](#plotOptions.treemap.colorByPoint) is true. * * @type {Array<Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject>} * @since 3.0 * @product highcharts * @apioption plotOptions.treemap.colors */ /** * Whether to display this series type or specific series item in the * legend. */ showInLegend: false, /** * @ignore-option */ marker: false, colorByPoint: false, /** * @since 4.1.0 */ dataLabels: { /** @ignore-option */ defer: false, /** @ignore-option */ enabled: true, /** @ignore-option */ formatter: function () { var point = this && this.point ? this.point : {}, name = isString(point.name) ? point.name : ''; return name; }, /** @ignore-option */ inside: true, /** @ignore-option */ verticalAlign: 'middle' }, tooltip: { headerFormat: '', pointFormat: '<b>{point.name}</b>: {point.value}<br/>' }, /** * Whether to ignore hidden points when the layout algorithm runs. * If `false`, hidden points will leave open spaces. * * @since 5.0.8 */ ignoreHiddenPoint: true, /** * This option decides which algorithm is used for setting position * and dimensions of the points. * * @see [How to write your own algorithm](https://www.highcharts.com/docs/chart-and-series-types/treemap) * * @sample {highcharts} highcharts/plotoptions/treemap-layoutalgorithm-sliceanddice/ * SliceAndDice by default * @sample {highcharts} highcharts/plotoptions/treemap-layoutalgorithm-stripes/ * Stripes * @sample {highcharts} highcharts/plotoptions/treemap-layoutalgorithm-squarified/ * Squarified * @sample {highcharts} highcharts/plotoptions/treemap-layoutalgorithm-strip/ * Strip * * @since 4.1.0 * @validvalue ["sliceAndDice", "stripes", "squarified", "strip"] */ layoutAlgorithm: 'sliceAndDice', /** * Defines which direction the layout algorithm will start drawing. * * @since 4.1.0 * @validvalue ["vertical", "horizontal"] */ layoutStartingDirection: 'vertical', /** * Enabling this option will make the treemap alternate the drawing * direction between vertical and horizontal. The next levels starting * direction will always be the opposite of the previous. * * @sample {highcharts} highcharts/plotoptions/treemap-alternatestartingdirection-true/ * Enabled * * @since 4.1.0 */ alternateStartingDirection: false, /** * Used together with the levels and allowTraversingTree options. When * set to false the first level visible to be level one, which is * dynamic when traversing the tree. Otherwise the level will be the * same as the tree structure. * * @since 4.1.0 */ levelIsConstant: true, /** * Options for the button appearing when drilling down in a treemap. * Deprecated and replaced by * [traverseUpButton](#plotOptions.treemap.traverseUpButton). * * @deprecated */ drillUpButton: { /** * The position of the button. * * @deprecated */ position: { /** * Vertical alignment of the button. * * @deprecated * @type {Highcharts.VerticalAlignValue} * @default top * @product highcharts * @apioption plotOptions.treemap.drillUpButton.position.verticalAlign */ /** * Horizontal alignment of the button. * * @deprecated * @type {Highcharts.AlignValue} */ align: 'right', /** * Horizontal offset of the button. * * @deprecated */ x: -10, /** * Vertical offset of the button. * * @deprecated */ y: 10 } }, /** * Options for the button appearing when traversing down in a treemap. */ traverseUpButton: { /** * The position of the button. */ position: { /** * Vertical alignment of the button. * * @type {Highcharts.VerticalAlignValue} * @default top * @product highcharts * @apioption plotOptions.treemap.traverseUpButton.position.verticalAlign */ /** * Horizontal alignment of the button. * * @type {Highcharts.AlignValue} */ align: 'right', /** * Horizontal offset of the button. */ x: -10, /** * Vertical offset of the button. */ y: 10 } }, /** * Set options on specific levels. Takes precedence over series options, * but not point options. * * @sample {highcharts} highcharts/plotoptions/treemap-levels/ * Styling dataLabels and borders * @sample {highcharts} highcharts/demo/treemap-with-levels/ * Different layoutAlgorithm * * @type {Array<*>} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels */ /** * Can set a `borderColor` on all points which lies on the same level. * * @type {Highcharts.ColorString} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.borderColor */ /** * Set the dash style of the border of all the point which lies on the * level. See <a href"#plotoptions.scatter.dashstyle"> * plotOptions.scatter.dashStyle</a> for possible options. * * @type {string} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.borderDashStyle */ /** * Can set the borderWidth on all points which lies on the same level. * * @type {number} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.borderWidth */ /** * Can set a color on all points which lies on the same level. * * @type {Highcharts.ColorString|Highcharts.GradientColorObject|Highcharts.PatternObject} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.color */ /** * A configuration object to define how the color of a child varies from * the parent's color. The variation is distributed among the children * of node. For example when setting brightness, the brightness change * will range from the parent's original brightness on the first child, * to the amount set in the `to` setting on the last node. This allows a * gradient-like color scheme that sets children out from each other * while highlighting the grouping on treemaps and sectors on sunburst * charts. * * @sample highcharts/demo/sunburst/ * Sunburst with color variation * * @since 6.0.0 * @product highcharts * @apioption plotOptions.treemap.levels.colorVariation */ /** * The key of a color variation. Currently supports `brightness` only. * * @type {string} * @since 6.0.0 * @product highcharts * @validvalue ["brightness"] * @apioption plotOptions.treemap.levels.colorVariation.key */ /** * The ending value of a color variation. The last sibling will receive * this value. * * @type {number} * @since 6.0.0 * @product highcharts * @apioption plotOptions.treemap.levels.colorVariation.to */ /** * Can set the options of dataLabels on each point which lies on the * level. * [plotOptions.treemap.dataLabels](#plotOptions.treemap.dataLabels) for * possible values. * * @type {object} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.dataLabels */ /** * Can set the layoutAlgorithm option on a specific level. * * @type {string} * @since 4.1.0 * @product highcharts * @validvalue ["sliceAndDice", "stripes", "squarified", "strip"] * @apioption plotOptions.treemap.levels.layoutAlgorithm */ /** * Can set the layoutStartingDirection option on a specific level. * * @type {string} * @since 4.1.0 * @product highcharts * @validvalue ["vertical", "horizontal"] * @apioption plotOptions.treemap.levels.layoutStartingDirection */ /** * Decides which level takes effect from the options set in the levels * object. * * @sample {highcharts} highcharts/plotoptions/treemap-levels/ * Styling of both levels * * @type {number} * @since 4.1.0 * @product highcharts * @apioption plotOptions.treemap.levels.level */ // Presentational options /** * The color of the border surrounding each tree map item. * * @type {Highcharts.ColorString} */ borderColor: '#e6e6e6', /** * The width of the border surrounding each tree map item. */ borderWidth: 1, /** * The opacity of a point in treemap. When a point has children, the * visibility of the children is determined by the opacity. * * @since 4.2.4 */ opacity: 0.15, /** * A wrapper object for all the series options in specific states. * * @extends plotOptions.heatmap.states */ states: { /** * Options for the hovered series * * @extends plotOptions.heatmap.states.hover * @excluding halo */ hover: { /** * The border color for the hovered state. */ borderColor: '#999999', /** * Brightness for the hovered point. Defaults to 0 if the * heatmap series is loaded first, otherwise 0.1. * * @type {number} * @default undefined */ brightness: seriesTypes.heatmap ? 0 : 0.1, /** * @extends plotOptions.heatmap.states.hover.halo */ halo: false, /** * The opacity of a point in treemap. When a point has children, * the visibility of the children is determined by the opacity. * * @since 4.2.4 */ opacity: 0.75, /** * The shadow option for hovered state. */ shadow: false } } // Prototype members }, { pointArrayMap: ['value'], directTouch: true, optionalAxis: 'colorAxis', getSymbol: noop, parallelArrays: ['x', 'y', 'value', 'colorValue'], colorKey: 'colorValue', // Point color option key trackerGroups: ['group', 'dataLabelsGroup'], /** * Creates an object map from parent id to childrens index. * * @private * @function Highcharts.Series#getListOfParents * * @param {Highcharts.SeriesTreemapDataOptions} data * List of points set in options. * * @param {Array<string>} existingIds * List of all point ids. * * @return {object} * Map from parent id to children index in data. */ getListOfParents: function (data, existingIds) { var arr = isArray(data) ? data : [], ids = isArray(existingIds) ? existingIds : [], listOfParents = arr.reduce(function (prev, curr, i) { var parent = pick(curr.parent, ''); if (prev[parent] === undefined) { prev[parent] = []; } prev[parent].push(i); return prev; }, { '': [] // Root of tree }); // If parent does not exist, hoist parent to root of tree. eachObject(listOfParents, function (children, parent, list) { if ((parent !== '') && (ids.indexOf(parent) === -1)) { children.forEach(function (child) { list[''].push(child); }); delete list[parent]; } }); return listOfParents; }, // Creates a tree structured object from the series points getTree: function () { var series = this, allIds = this.data.map(function (d) { return d.id; }), parentList = series.getListOfParents(this.data, allIds); series.nodeMap = []; return series.buildNode('', -1, 0, parentList, null); }, // Define hasData function for non-cartesian series. // Returns true if the series has points at all. hasData: function () { return !!this.processedXData.length; // != 0 }, init: function (chart, options) { var series = this, colorSeriesMixin = H.colorSeriesMixin; // If color series logic is loaded, add some properties if (H.colorSeriesMixin) { this.translateColors = colorSeriesMixin.translateColors; this.colorAttribs = colorSeriesMixin.colorAttribs; this.axisTypes = colorSeriesMixin.axisTypes; } // Handle deprecated options. addEvent(series, 'setOptions', function (event) { var options = event.userOptions; if ( defined(options.allowDrillToNode) && !defined(options.allowTraversingTree) ) { options.allowTraversingTree = options.allowDrillToNode; delete options.allowDrillToNode; } if ( defined(options.drillUpButton) && !defined(options.traverseUpButton) ) { options.traverseUpButton = options.drillUpButton; delete options.drillUpButton; } }); Series.prototype.init.call(series, chart, options); if (series.options.allowTraversingTree) { addEvent(series, 'click', series.onClickDrillToNode); } }, buildNode: function (id, i, level, list, parent) { var series = this, children = [], point = series.points[i], height = 0, node, child; // Actions ((list[id] || [])).forEach(function (i) { child = series.buildNode( series.points[i].id, i, (level + 1), list, id ); height = Math.max(child.height + 1, height); children.push(child); }); node = { id: id, i: i, children: children, height: height, level: level, parent: parent, visible: false // @todo move this to better location }; series.nodeMap[node.id] = node; if (point) { point.node = node; } return node; }, setTreeValues: function (tree) { var series = this, options = series.options, idRoot = series.rootNode, mapIdToNode = series.nodeMap, nodeRoot = mapIdToNode[idRoot], levelIsConstant = ( isBoolean(options.levelIsConstant) ? options.levelIsConstant : true ), childrenTotal = 0, children = [], val, point = series.points[tree.i]; // First give the children some values tree.children.forEach(function (child) { child = series.setTreeValues(child); children.push(child); if (!child.ignore) { childrenTotal += child.val; } }); // Sort the children stableSort(children, function (a, b) { return a.sortIndex - b.sortIndex; }); // Set the values val = pick(point && point.options.value, childrenTotal); if (point) { point.value = val; } extend(tree, { children: children, childrenTotal: childrenTotal, // Ignore this node if point is not visible ignore: !(pick(point && point.visible, true) && (val > 0)), isLeaf: tree.visible && !childrenTotal, levelDynamic: ( tree.level - (levelIsConstant ? 0 : nodeRoot.level) ), name: pick(point && point.name, ''), sortIndex: pick(point && point.sortIndex, -val), val: val }); return tree; }, /** * Recursive function which calculates the area for all children of a * node. * * @private * @function Highcharts.Series#calculateChildrenAreas * * @param {object} node * The node which is parent to the children. * * @param {object} area * The rectangular area of the parent. */ calculateChildrenAreas: function (parent, area) { var series = this, options = series.options, mapOptionsToLevel = series.mapOptionsToLevel, level = mapOptionsToLevel[parent.level + 1], algorithm = pick( ( series[level && level.layoutAlgorithm] && level.layoutAlgorithm ), options.layoutAlgorithm ), alternate = options.alternateStartingDirection, childrenValues = [], children; // Collect all children which should be included children = parent.children.filter(function (n) { return !n.ignore; }); if (level && level.layoutStartingDirection) { area.direction = level.layoutStartingDirection === 'vertical' ? 0 : 1; } childrenValues = series[algorithm](area, children); children.forEach(function (child, index) { var values = childrenValues[index]; child.values = merge(values, { val: child.childrenTotal, direction: (alternate ? 1 - area.direction : area.direction) }); child.pointValues = merge(values, { x: (values.x / series.axisRatio), width: (values.width / series.axisRatio) }); // If node has children, then call method recursively if (child.children.length) { series.calculateChildrenAreas(child, child.values); } }); }, setPointValues: function () { var series = this, xAxis = series.xAxis, yAxis = series.yAxis; series.points.forEach(function (point) { var node = point.node, values = node.pointValues, x1, x2, y1, y2, crispCorr = 0; // Get the crisp correction in classic mode. For this to work in // styled mode, we would need to first add the shape (without x, // y, width and height), then read the rendered stroke width // using point.graphic.strokeWidth(), then modify and apply the // shapeArgs. This applies also to column series, but the // downside is performance and code complexity. if (!series.chart.styledMode) { crispCorr = ( (series.pointAttribs(point)['stroke-width'] || 0) % 2 ) / 2; } // Points which is ignored, have no values. if (values && node.visible) { x1 = Math.round( xAxis.translate(values.x, 0, 0, 0, 1) ) - crispCorr; x2 = Math.round( xAxis.translate(values.x + values.width, 0, 0, 0, 1) ) - crispCorr; y1 = Math.round( yAxis.translate(values.y, 0, 0, 0, 1) ) - crispCorr; y2 = Math.round( yAxis.translate(values.y + values.height, 0, 0, 0, 1) ) - crispCorr; // Set point values point.shapeArgs = { x: Math.min(x1, x2), y: Math.min(y1, y2), width: Math.abs(x2 - x1), height: Math.abs(y2 - y1) }; point.plotX = point.shapeArgs.x + (point.shapeArgs.width / 2); point.plotY = point.shapeArgs.y + (point.shapeArgs.height / 2); } else { // Reset visibility delete point.plotX; delete point.plotY; } }); }, // Set the node's color recursively, from the parent down. setColorRecursive: function ( node, parentColor, colorIndex, index, siblings ) { var series = this, chart = series && series.chart, colors = chart && chart.options && chart.options.colors, colorInfo, point; if (node) { colorInfo = getColor(node, { colors: colors, index: index, mapOptionsToLevel: series.mapOptionsToLevel, parentColor: parentColor, parentColorIndex: colorIndex, series: series, siblings: siblings }); point = series.points[node.i]; if (point) { point.color = colorInfo.color; point.colorIndex = colorInfo.colorIndex; } // Do it all again with the children (node.children || []).forEach(function (child, i) { series.setColorRecursive( child, colorInfo.color, colorInfo.colorIndex, i, node.children.length ); }); } }, algorithmGroup: function (h, w, d, p) { this.height = h; this.width = w; this.plot = p; this.direction = d; this.startDirection = d; this.total = 0; this.nW = 0; this.lW = 0; this.nH = 0; this.lH = 0; this.elArr = []; this.lP = { total: 0, lH: 0, nH: 0, lW: 0, nW: 0, nR: 0, lR: 0, aspectRatio: function (w, h) { return Math.max((w / h), (h / w)); } }; this.addElement = function (el) { this.lP.total = this.elArr[this.elArr.length - 1]; this.total = this.total + el; if (this.direction === 0) { // Calculate last point old aspect ratio this.lW = this.nW; this.lP.lH = this.lP.total / this.lW; this.lP.lR = this.lP.aspectRatio(this.lW, this.lP.lH); // Calculate last point new aspect ratio this.nW = this.total / this.height; this.lP.nH = this.lP.total / this.nW; this.lP.nR = this.lP.aspectRatio(this.nW, this.lP.nH); } else { // Calculate last point old aspect ratio this.lH = this.nH; this.lP.lW = this.lP.total / this.lH; this.lP.lR = this.lP.aspectRatio(this.lP.lW, this.lH); // Calculate last point new aspect ratio this.nH = this.total / this.width; this.lP.nW = this.lP.total / this.nH; this.lP.nR = this.lP.aspectRatio(this.lP.nW, this.nH); } this.elArr.push(el); }; this.reset = function () { this.nW = 0; this.lW = 0; this.elArr = []; this.total = 0; }; }, algorithmCalcPoints: function ( directionChange, last, group, childrenArea ) { var pX, pY, pW, pH, gW = group.lW, gH = group.lH, plot = group.plot, keep, i = 0, end = group.elArr.length - 1; if (last) { gW = group.nW; gH = group.nH; } else { keep = group.elArr[group.elArr.length - 1]; } group.elArr.forEach(function (p) { if (last || (i < end)) { if (group.direction === 0) { pX = plot.x; pY = plot.y; pW = gW; pH = p / pW; } else { pX = plot.x; pY = plot.y; pH = gH; pW = p / pH; } childrenArea.push({ x: pX, y: pY, width: pW, height: H.correctFloat(pH) }); if (group.direction === 0) { plot.y = plot.y + pH; } else { plot.x = plot.x + pW; } } i = i + 1; }); // Reset variables group.reset(); if (group.direction === 0) { group.width = group.width - gW; } else { group.height = group.height - gH; } plot.y = plot.parent.y + (plot.parent.height - group.height); plot.x = plot.parent.x + (plot.parent.width - group.width); if (directionChange) { group.direction = 1 - group.direction; } // If not last, then add uncalculated element if (!last) { group.addElement(keep); } }, algorithmLowAspectRatio: function (directionChange, parent, children) { var childrenArea = [], series = this, pTot, plot = { x: parent.x, y: parent.y, parent: parent }, direction = parent.direction, i = 0, end = children.length - 1, group = new this.algorithmGroup( // eslint-disable-line new-cap parent.height, parent.width, direction, plot ); // Loop through and calculate all areas children.forEach(function (child) { pTot = (parent.width * parent.height) * (child.val / parent.val); group.addElement(pTot); if (group.lP.nR > group.lP.lR) { series.algorithmCalcPoints( directionChange, false, group, childrenArea, plot ); } // If last child, then calculate all remaining areas if (i === end) { series.algorithmCalcPoints( directionChange, true, group, childrenArea, plot ); } i = i + 1; }); return childrenArea; }, algorithmFill: function (directionChange, parent, children) { var childrenArea = [], pTot, direction = parent.direction, x = parent.x, y = parent.y, width = parent.width, height = parent.height, pX, pY, pW, pH; children.forEach(function (child) { pTot = (parent.width * parent.height) * (child.val / parent.val); pX = x; pY = y; if (direction === 0) { pH = height; pW = pTot / pH; width = width - pW; x = x + pW; } else { pW = width; pH = pTot / pW; height = height - pH; y = y + pH; } childrenArea.push({ x: pX, y: pY, width: pW, height: pH }); if (directionChange) { direction = 1 - direction; } }); return childrenArea; }, strip: function (parent, children) { return this.algorithmLowAspectRatio(false, parent, children); }, squarified: function (parent, children) { return this.algorithmLowAspectRatio(true, parent, children); }, sliceAndDice: function (parent, children) { return this.algorithmFill(true, parent, children); }, stripes: function (parent, children) { return this.algorithmFill(false, parent, children); }, translate: function () { var series = this, options = series.options, // NOTE: updateRootId modifies series. rootId = updateRootId(series), rootNode, pointValues, seriesArea, tree, val; // Call prototype function Series.prototype.translate.call(series); // @todo Only if series.isDirtyData is true tree = series.tree = series.getTree(); rootNode = series.nodeMap[rootId]; series.renderTraverseUpButton(rootId); series.mapOptionsToLevel = getLevelOptions({ from: rootNode.level + 1, levels: options.levels, to: tree.height, defaults: { levelIsConstant: series.options.levelIsConstant, colorByPoint: options.colorByPoint } }); if ( rootId !== '' && (!rootNode || !rootNode.children.length) ) { series.setRootNode('', false); rootId = series.rootNode; rootNode = series.nodeMap[rootId]; } // Parents of the root node is by default visible recursive(series.nodeMap[series.rootNode], function (node) { var next = false, p = node.parent; node.visible = true; if (p || p === '') { next = series.nodeMap[p]; } return next; }); // Children of the root node is by default visible recursive( series.nodeMap[series.rootNode].children, function (children) { var next = false; children.forEach(function (child) { child.visible = true; if (child.children.length) { next = (next || []).concat(child.children); } }); return next; } ); series.setTreeValues(tree); // Calculate plotting values. series.axisRatio = (series.xAxis.len / series.yAxis.len); series.nodeMap[''].pointValues = pointValues = { x: 0, y: 0, width: 100, height: 100 }; series.nodeMap[''].values = seriesArea = merge(pointValues, { width: (pointValues.width * series.axisRatio), direction: ( options.layoutStartingDirection === 'vertical' ? 0 : 1 ), val: tree.val }); series.calculateChildrenAreas(tree, seriesArea); // Logic for point colors if (series.colorAxis) { series.translateColors(); } else if (!options.colorByPoint) { series.setColorRecursive(series.tree); } // Update axis extremes according to the root node. if (options.allowTraversingTree) { val = rootNode.pointValues; series.xAxis.setExtremes(val.x, val.x + val.width, false); series.yAxis.setExtremes(val.y, val.y + val.height, false); series.xAxis.setScale(); series.yAxis.setScale(); } // Assign values to points. series.setPointValues(); }, /** * Extend drawDataLabels with logic to handle custom options related to * the treemap series: * * - Points which is not a leaf node, has dataLabels disabled by * default. * * - Options set on series.levels is merged in. * * - Width of the dataLabel is set to match the width of the point * shape. * * @private * @function Highcharts.Series#drawDataLabels */ drawDataLabels: function () { var series = this, mapOptionsToLevel = series.mapOptionsToLevel, points = series.points.filter(function (n) { return n.node.visible; }), options, level; points.forEach(function (point) { level = mapOptionsToLevel[point.node.level]; // Set options to new object to avoid problems with scope options = { style: {} }; // If not a leaf, then label should be disabled as default if (!point.node.isLeaf) { options.enabled = false; } // If options for level exists, include them as well if (level && level.dataLabels) { options = merge(options, level.dataLabels); series._hasPointLabels = true; } // Set dataLabel width to the width of the point shape. if (point.shapeArgs) { options.style.width = point.shapeArgs.width; if (point.dataLabel) { point.dataLabel.css({ width: point.shapeArgs.width + 'px' }); } } // Merge custom options with point options point.dlOptions = merge(options, point.options.dataLabels); }); Series.prototype.drawDataLabels.call(this); }, // Over the alignment method by setting z index alignDataLabel: function (point, dataLabel, labelOptions) { var style = labelOptions.style; // #8160: Prevent the label from exceeding the point's // boundaries in treemaps by applying ellipsis overflow. // The issue was happening when datalabel's text contained a // long sequence of characters without a whitespace. if ( !H.defined(style.textOverflow) && dataLabel.text && dataLabel.getBBox().width > dataLabel.text.textWidth ) { dataLabel.css({ textOverflow: 'ellipsis', // unit (px) is required when useHTML is true width: style.width += 'px' }); } seriesTypes.column.prototype.alignDataLabel.apply(this, arguments); if (point.dataLabel) { // point.node.zIndex could be undefined (#6956) point.dataLabel.attr({ zIndex: (point.node.zIndex || 0) + 1 }); } }, // Get presentational attributes pointAttribs: function (point, state) { var series = this, mapOptionsToLevel = ( isObject(series.mapOptionsToLevel) ? series.mapOptionsToLevel : {} ), level = point && mapOptionsToLevel[point.node.level] || {}, options = this.options, attr, stateOptions = (state && options.states[state]) || {}, className = (point && point.getClassName()) || '', opacity; // Set attributes by precedence. Point trumps level trumps series. // Stroke width uses pick because it can be 0. attr = { 'stroke': (point && point.borderColor) || level.borderColor || stateOptions.borderColor || options.borderColor, 'stroke-width': pick( point && point.borderWidth, level.borderWidth, stateOptions.borderWidth, options.borderWidth ), 'dashstyle': (point && point.borderDashStyle) || level.borderDashStyle || stateOptions.borderDashStyle || options.borderDashStyle, 'fill': (point && point.color) || this.color }; // Hide levels above the current view if (className.indexOf('highcharts-above-level') !== -1) { attr.fill = 'none'; attr['stroke-width'] = 0; // Nodes with children that accept interaction } else if ( className.indexOf('highcharts-internal-node-interactive') !== -1 ) { opacity = pick(stateOptions.opacity, options.opacity); attr.fill = color(attr.fill).setOpacity(opacity).get(); attr.cursor = 'pointer'; // Hide nodes that have children } else if (className.indexOf('highcharts-internal-node') !== -1) { attr.fill = 'none'; } else if (state) { // Brighten and hoist the hover nodes attr.fill = color(attr.fill) .brighten(stateOptions.brightness) .get(); } return attr; }, // Override drawPoints drawPoints: function () { var series = this, chart = series.chart, renderer = chart.renderer, points = series.points, styledMode = chart.styledMode, options = series.options, shadow = styledMode ? {} : options.shadow, borderRadius = options.borderRadius, withinAnimationLimit = chart.pointCount < options.animationLimit, allowTraversingTree = options.allowTraversingTree; points.forEach(function (point) { var levelDynamic = point.node.levelDynamic, animate = {}, attr = {}, css = {}, groupKey = 'level-group-' + levelDynamic, hasGraphic = !!point.graphic, shouldAnimate = withinAnimationLimit && hasGraphic, shapeArgs = point.shapeArgs; // Don't bother with calculate styling if the point is not drawn if (point.shouldDraw()) { if (borderRadius) { attr.r = borderRadius; } merge( true, // Extend object // Which object to extend shouldAnimate ? animate : attr, // Add shapeArgs to animate/attr if graphic exists hasGraphic ? shapeArgs : {}, // Add style attribs if !styleMode styledMode ? {} : series.pointAttribs( point, point.selected && 'select' ) ); // In styled mode apply point.color. Use CSS, otherwise the // fill used in the style sheet will take precedence over // the fill attribute. if (series.colorAttribs && styledMode) { // Heatmap is loaded extend(css, series.colorAttribs(point)); } if (!series[groupKey]) { series[groupKey] = renderer.g(groupKey) .attr({ // @todo Set the zIndex based upon the number of // levels, instead of using 1000 zIndex: 1000 - levelDynamic }) .add(series.group); } } // Draw the point point.draw({ animatableAttribs: animate, attribs: attr, css: css, group: series[groupKey], renderer: renderer, shadow: shadow, shapeArgs: shapeArgs, shapeType: 'rect' }); // If setRootNode is allowed, set a point cursor on clickables & // add drillId to point if (allowTraversingTree && point.graphic) { point.drillId = options.interactByLeaf ? series.drillToByLeaf(point) : series.drillToByGroup(point); } }); }, // Add drilling on the suitable points onClickDrillToNode: function (event) { var series = this, point = event.point, drillId = point && point.drillId; // If a drill id is returned, add click event and cursor. if (isString(drillId)) { point.setState(''); // Remove hover series.setRootNode(drillId, true, { trigger: 'click' }); } }, /** * Finds the drill id for a parent node. Returns false if point should * not have a click event. * * @private * @function Highcharts.Series#drillToByGroup * * @param {object} point * * @return {boolean|string} * Drill to id or false when point should not have a click * event. */ drillToByGroup: function (point) { var series = this, drillId = false; if ((point.node.level - series.nodeMap[series.rootNode].level) === 1 && !point.node.isLeaf ) { drillId = point.id; } return drillId; }, /** * Finds the drill id for a leaf node. Returns false if point should not * have a click event * * @private * @function Highcharts.Series#drillToByLeaf * * @param {object} point * * @return {boolean|string} * Drill to id or false when point should not have a click * event. */ drillToByLeaf: function (point) { var series = this, drillId = false, nodeParent; if ((point.node.parent !== series.rootNode) && point.node.isLeaf ) { nodeParent = point.node; while (!drillId) { nodeParent = series.nodeMap[nodeParent.parent]; if (nodeParent.parent === series.rootNode) { drillId = nodeParent.id; } } } return drillId; }, drillUp: function () { var series = this, node = series.nodeMap[series.rootNode]; if (node && isString(node.parent)) { series.setRootNode( node.parent, true, { trigger: 'traverseUpButton' } ); } }, // TODO remove this function at a suitable version. drillToNode: function (id, redraw) { error( 'WARNING: treemap.drillToNode has been renamed to treemap.' + 'setRootNode, and will be removed in the next major version.' ); this.setRootNode(id, redraw); }, /** * Sets a new root node for the series. * * @private * @function Highcharts.Series#setRootNode * * @param {string} id The id of the new root node. * @param {boolean} [redraw=true] Wether to redraw the chart or not. * @param {object} [eventArguments] Arguments to be accessed in * event handler. * @param {string} [eventArguments.newRootId] Id of the new root. * @param {string} [eventArguments.previousRootId] Id of the previous * root. * @param {boolean} [eventArguments.redraw] Wether to redraw the * chart after. * @param {object} [eventArguments.series] The series to update the root * of. * @param {string} [eventArguments.trigger] The action which * triggered the event. Undefined if the setRootNode is called * directly. */ setRootNode: function (id, redraw, eventArguments) { var series = this, eventArgs = extend({ newRootId: id, previousRootId: series.rootNode, redraw: pick(redraw, true), series: series }, eventArguments); /** * The default functionality of the setRootNode event. * * @private * @param {object} args The event arguments. * @param {string} args.newRootId Id of the new root. * @param {string} args.previousRootId Id of the previous root. * @param {boolean} args.redraw Wether to redraw the chart after. * @param {object} args.series The series to update the root of. * @param {string} [args.trigger=undefined] The action which * triggered the event. Undefined if the setRootNode is called * directly. */ var defaultFn = function (args) { var series = args.series; // Store previous and new root ids on the series. series.idPreviousRoot = args.previousRootId; series.rootNode = args.newRootId; // Redraw the chart series.isDirty = true; // Force redraw if (args.redraw) { series.chart.redraw(); } }; // Fire setRootNode event. fireEvent(series, 'setRootNode', eventArgs, defaultFn); }, renderTraverseUpButton: function (rootId) { var series = this, nodeMap = series.nodeMap, node = nodeMap[rootId], name = node.name, buttonOptions = series.options.traverseUpButton, backText = pick(buttonOptions.text, name, '< Back'), attr, states; if (rootId === '') { if (series.drillUpButton) { series.drillUpButton = series.drillUpButton.destroy(); } } else if (!this.drillUpButton) { attr = buttonOptions.theme; states = attr && attr.states; this.drillUpButton = this.chart.renderer.button( backText, null, null, function () { series.drillUp(); }, attr, states && states.hover, states && states.select ) .addClass('highcharts-drillup-button') .attr({ align: buttonOptions.position.align, zIndex: 7 }) .add() .align( buttonOptions.position, false, buttonOptions.relativeTo || 'plotBox' ); } else { this.drillUpButton.placed = false; this.drillUpButton.attr({ text: backText }) .align(); } }, buildKDTree: noop, drawLegendSymbol: H.LegendSymbolMixin.drawRectangle, getExtremes: function () { // Get the extremes from the value data Series.prototype.getExtremes.call(this, this.colorValueData); this.valueMin = this.dataMin; this.valueMax = this.dataMax; // Get the extremes from the y data Series.prototype.getExtremes.call(this); }, getExtremesFromAll: true, bindAxes: function () { var treeAxis = { endOnTick: false, gridLineWidth: 0, lineWidth: 0, min: 0, dataMin: 0, minPadding: 0, max: 100, dataMax: 100, maxPadding: 0, startOnTick: false, title: null, tickPositions: [] }; Series.prototype.bindAxes.call(this); H.extend(this.yAxis.options, treeAxis); H.extend(this.xAxis.options, treeAxis); }, /** * Workaround for `inactive` state. Since `series.opacity` option is * already reserved, don't use that state at all by disabling * `inactiveOtherPoints` and not inheriting states by points. * * @private */ setState: function (state) { this.options.inactiveOtherPoints = true; Series.prototype.setState.call(this, state, false); this.options.inactiveOtherPoints = false; }, utils: { recursive: recursive } // Point class }, { draw: drawPoint, getClassName: function () { var className = H.Point.prototype.getClassName.call(this), series = this.series, options = series.options; // Above the current level if (this.node.level <= series.nodeMap[series.rootNode].level) { className += ' highcharts-above-level'; } else if ( !this.node.isLeaf && !pick(options.interactByLeaf, !options.allowTraversingTree) ) { className += ' highcharts-internal-node-interactive'; } else if (!this.node.isLeaf) { className += ' highcharts-internal-node'; } return className; }, /** * A tree point is valid if it has han id too, assume it may be a parent * item. * * @private * @function Highcharts.Point#isValid */ isValid: function () { return this.id || isNumber(this.value); }, setState: function (state) { H.Point.prototype.setState.call(this, state); // Graphic does not exist when point is not visible. if (this.graphic) { this.graphic.attr({ zIndex: state === 'hover' ? 1 : 0 }); } }, setVisible: seriesTypes.pie.prototype.pointClass.prototype.setVisible, shouldDraw: function () { var point = this; return isNumber(point.plotY) && point.y !== null; } } ); /** * A `treemap` series. If the [type](#series.treemap.type) option is * not specified, it is inherited from [chart.type](#chart.type). * * @extends series,plotOptions.treemap * @excluding dataParser, dataURL, stack * @product highcharts * @apioption series.treemap */ /** * An array of data points for the series. For the `treemap` series * type, points can be given in the following ways: * * 1. An array of numerical values. In this case, the numerical values will be * interpreted as `value` options. Example: * ```js * data: [0, 5, 3, 5] * ``` * * 2. An array of objects with named values. The following snippet shows only a * few settings, see the complete options set below. If the total number of * data points exceeds the series' * [turboThreshold](#series.treemap.turboThreshold), * this option is not available. * ```js * data: [{ * value: 9, * name: "Point2", * color: "#00FF00" * }, { * value: 6, * name: "Point1", * color: "#FF00FF" * }] * ``` * * @sample {highcharts} highcharts/chart/reflow-true/ * Numerical values * @sample {highcharts} highcharts/series/data-array-of-objects/ * Config objects * * @type {Array<number|null|*>} * @extends series.heatmap.data * @excluding x, y * @product highcharts * @apioption series.treemap.data */ /** * The value of the point, resulting in a relative area of the point * in the treemap. * * @type {number|null} * @product highcharts * @apioption series.treemap.data.value */ /** * Serves a purpose only if a `colorAxis` object is defined in the chart * options. This value will decide which color the point gets from the * scale of the colorAxis. * * @type {number} * @since 4.1.0 * @product highcharts * @apioption series.treemap.data.colorValue */ /** * Only for treemap. Use this option to build a tree structure. The * value should be the id of the point which is the parent. If no points * has a matching id, or this option is undefined, then the parent will * be set to the root. * * @sample {highcharts} highcharts/point/parent/ * Point parent * @sample {highcharts} highcharts/demo/treemap-with-levels/ * Example where parent id is not matching * * @type {string} * @since 4.1.0 * @product highcharts * @apioption series.treemap.data.parent */ }); _registerModule(_modules, 'masters/modules/treemap.src.js', [], function () { }); }));
Qesy/Q-Frame
Static/bootstrap/Highcharts-7.1.1/modules/treemap.src.js
JavaScript
apache-2.0
92,176
// SERVER-4516 and SERVER-6913: test that update and findAndModify tolerate // an _id in the update document, as long as the _id will not be modified var t = db.jstests_server4516; var startingDoc = {_id: 1, a: 1}; function prepare() { t.drop(); t.save(startingDoc); } function update_succeeds(updateDoc, qid, resultDoc) { prepare(); t.update({_id: qid}, updateDoc, true); assert.eq(t.findOne({_id: qid}), resultDoc); prepare(); t.findAndModify({query: {_id: qid}, update: updateDoc, upsert: true}); assert.eq(t.findOne({_id: qid}), resultDoc); } update_succeeds({_id: 1, a: 2}, 1, {_id: 1, a: 2}); update_succeeds({$set: {_id: 1}}, 1, {_id: 1, a: 1}); update_succeeds({_id: 1, b: "a"}, 1, {_id: 1, b: "a"}); update_succeeds({_id: 2, a: 3}, 2, {_id: 2, a: 3}); function update_fails(updateDoc, qid) { prepare(); var res = t.update({_id: qid}, updateDoc, true); assert.writeError(res); assert.eq(t.count(), 1); assert.eq(t.findOne(), startingDoc); prepare(); assert.throws(function() { t.findAndModify({query: {_id: qid}, update: updateDoc, upsert: true}); }); assert.eq(t.count(), 1); assert.eq(t.findOne(), startingDoc); } update_fails({$set: {_id: 2}}, 1); update_fails({_id: 2, a: 3}, 1); update_fails({_id: 2, a: 3}, 3);
christkv/mongo-shell
test/jstests/core/update_find_and_modify_id.js
JavaScript
apache-2.0
1,313
/** * @fileoverview Defines compressors utility methods. * * @see https://google.github.io/styleguide/javascriptguide.xml * @see https://developers.google.com/closure/compiler/docs/js-for-compiler * @module glize/compressors */ import * as lzw from 'lzw-compressor'; /** * Enumeration of available compression types. * @enum {string} */ export const TYPE = { LZW: 'lzw' }; /** * Compress data string using specified compression type. * @param {string} data Data to compress. * @param {string=} [opt_type=TYPE.LZW] Optional compression type. * @return {string} Returns compressed data. * @method * @example * const result = compress( * 'Any string of any length. Any string of any length. Any string of any length.'); * console.log(result); * //> Any string of aā leĈth. ĀĂĄĆĈĊČĎĂđēĕėďĚćĉċčďġgĔ. */ export const compress = (data, opt_type = TYPE.LZW) => { let result = ''; if (TYPE.LZW === opt_type) { result = lzw.compress(data); } return result; }; /** * Decompress data string using specified compression type. * @param {string} data Data to compress. * @param {string=} [opt_type=TYPE.LZW] Optional compression type. * @return {string} Returns compressed data. * @method * @example * const result = decompress('Any string of aā leĈth. ĀĂĄĆĈĊČĎĂđēĕėďĚćĉċčďġgĔ.'); * console.log(result); * //> Any string of any length. Any string of any length. Any string of any length. */ export const decompress = (data, opt_type = TYPE.LZW) => { let result = ''; if (TYPE.LZW === opt_type) { result = lzw.decompress(data); } return result; };
Datamart/Glize
src/compressors/index.js
JavaScript
apache-2.0
1,646
// ---------------------------------------------------------------------------- // Module initialization var Config = require("config").config; var utils = require("utils"); var validators = require("validators"); // ---------------------------------------------------------------------------- // Setting class. function Setting() { $.title_label.text_id = this.args.title_id; $.title_label.text = Alloy.Globals.L(this.args.title_id); // This will trigger UI update. Ugly solution I know. $.setting.top = this.args.top || 0; if (typeof this.args.width !== 'undefined') { $.setting.width = this.args.width; } // Listen to the "SettingChanges" event. It simply updates the string // representation of the property that the view shows. this.addSettingsChangedHandler(this.updateValue); } // Inherits from Controller... Setting.prototype = new (require("controller"))( arguments[0], [$.title_label] ); // Read the actual value of the property that this setting is responsible for Setting.prototype.updateValue = function() { $.setting_value.text = Alloy.Globals.L(Config.getProperty(this.args.propertyName).stringValue()); }; Setting.prototype.handleClick = function (initial, use, validator) { var self = this; var arg = { useValue: function(value) { if (eval("validators." + validator + "(value)")) { use(self.args.propertyName, value); self.updateValue(); } else { alert(Alloy.Globals.L("illegal_value")); } }, value: initial, validator: validator }; utils.openWindowWithBottomClicksDisabled(this.args.controllerName, arg); }; Setting.prototype.clickHandler = function() { var initial = Config.getProperty(this.args.propertyName).get(); var validator = typeof this.args.validator !== 'undefined' ? this.args.validator : "ok"; function use(n, v) { Config.getProperty(n).set(v); } this.handleClick(initial, use, validator); }; // ---------------------------------------------------------------------------- // Create the object representing this particular setting var setting = new Setting(); // Handling button click event function onClick(e) { setting.clickHandler(); }
garlictech/APIXMobil
app/controllers/setting.js
JavaScript
apache-2.0
2,314
(function() { 'use strict'; angular .module('fitappApp') .controller('RequestResetController', RequestResetController); RequestResetController.$inject = ['$timeout', 'Auth']; function RequestResetController ($timeout, Auth) { var vm = this; vm.error = null; vm.errorEmailNotExists = null; vm.requestReset = requestReset; vm.resetAccount = {}; vm.success = null; $timeout(function (){angular.element('#email').focus();}); function requestReset () { vm.error = null; vm.errorEmailNotExists = null; Auth.resetPasswordInit(vm.resetAccount.email).then(function () { vm.success = 'OK'; }).catch(function (response) { vm.success = null; if (response.status === 400 && response.data === 'e-mail address not registered') { vm.errorEmailNotExists = 'ERROR'; } else { vm.error = 'ERROR'; } }); } } })();
tomkasp/fitapp
src/main/webapp/app/account/reset/request/reset.request.controller.js
JavaScript
apache-2.0
1,089
'use strict'; const { extend } = require('underscore'); const dbclient = require('abacus-dbclient'); const { testCollectedUsageID, testResourceID, testOrganizationID, testSpaceID, testConsumerID, testPlanID, testResourceType, testAccountID, testMeteringPlanID, testRatingPlanID, testPricingPlanID } = require('./fixtures/usageDocumentFieldsConstants'); const _commonBlueprint = { collected_usage_id: testCollectedUsageID, resource_id: testResourceID, organization_id: testOrganizationID, space_id: testSpaceID, consumer_id: testConsumerID, plan_id: testPlanID, resource_type: testResourceType, account_id: testAccountID, metering_plan_id: testMeteringPlanID, rating_plan_id: testRatingPlanID, pricing_plan_id: testPricingPlanID }; const buildUsage = (...builders) => { const usage = {}; for(let builder of builders) builder(usage); return extend(usage, { id: dbclient.kturi(usage.resource_instance_id, usage.processed) }); }; const withEndTimestamp = (timestamp) => (usage) => usage.end = timestamp; const withStartTimestamp = (timestamp) => (usage) => usage.start = timestamp; const withProcessedTimestamp = (timestamp) => (usage) => usage.processed = timestamp; const withBlueprint = (blueprint) => (usage) => extend(usage, blueprint); const withDefaultBlueprint = () => (usage) => extend(usage, _commonBlueprint); const withResourceInstanceId = (resourceInstanceId) => (usage) => usage.resource_instance_id = resourceInstanceId; const withAccumulatedUsage = (accumulatedUsage) => (usage) => usage.accumulated_usage = accumulatedUsage; const buildAccumulatedUsage = (...builders) => { const accumulatedUsage = { windows: [[null], [null], [null], [null, null, null, null, null, null], [null, null]] }; for(let builder of builders) builder(accumulatedUsage); return accumulatedUsage; }; const withMetricName = (metricName) => (accumulatedUsage) => accumulatedUsage.metric = metricName; const withCurrentDayQuantity = (quantity) => (accumulatedUsage) => accumulatedUsage.windows[3][0] = { quantity: quantity }; const withPreviousDayQuantity = (quantity) => (accumulatedUsage) => accumulatedUsage.windows[3][1] = { quantity: quantity }; const withCurrentMonthQuantity = (quantity) => (accumulatedUsage) => accumulatedUsage.windows[4][0] = { quantity: quantity }; module.exports = { buildUsage, withEndTimestamp, withStartTimestamp, withProcessedTimestamp, withBlueprint, withDefaultBlueprint, withResourceInstanceId, withAccumulatedUsage, buildAccumulatedUsage, withMetricName, withCurrentDayQuantity, withCurrentMonthQuantity, withPreviousDayQuantity };
cloudfoundry-incubator/cf-abacus
lib/aggregation/aggregator/src/test/usage-builder.js
JavaScript
apache-2.0
2,638
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var tape = require( 'tape' ); var Readable = require( 'readable-stream' ).Readable; var now = require( '@stdlib/time/now' ); var arcsine = require( '@stdlib/random/base/arcsine' ).factory; var isBuffer = require( '@stdlib/assert/is-buffer' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var isUint32Array = require( '@stdlib/assert/is-uint32array' ); var UINT32_MAX = require( '@stdlib/constants/uint32/max' ); var Uint32Array = require( '@stdlib/array/uint32' ); var minstd = require( '@stdlib/random/base/minstd' ); var inspectStream = require( '@stdlib/streams/node/inspect-sink' ); var randomStream = require( './../lib/main.js' ); // TESTS // tape( 'main export is a function', function test( t ) { t.ok( true, __filename ); t.equal( typeof randomStream, 'function', 'main export is a function' ); t.end(); }); tape( 'the function throws an error if minimum support `a` is not a number primitive', function test( t ) { var values; var i; values = [ '5', null, true, false, void 0, NaN, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( value, 2.0 ); }; } }); tape( 'the function throws an error if maximum support `b` is not a number primitive', function test( t ) { var values; var i; values = [ '5', null, true, false, void 0, NaN, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, value ); }; } }); tape( 'the function throws an error if minimum support `a` is greater than or equal to maximum support `b`', function test( t ) { var values; var i; values = [ [ 0.0, 0.0 ], [ -2.0, -4.0 ], [ 2.0, 1.0 ] ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( arr ) { return function badValue() { randomStream( arr[0], arr[1] ); }; } }); tape( 'the function throws an error if provided an options argument which is not an object', function test( t ) { var values; var i; values = [ 'abc', 5, null, true, false, void 0, NaN, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, value ); }; } }); tape( 'the function throws an error if provided an invalid `iter` option', function test( t ) { var values; var i; values = [ 'abc', -5, 3.14, null, true, false, void 0, NaN, [], {}, function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'iter': value }); }; } }); tape( 'if provided a `prng` option which is not a function, the function throws an error', function test( t ) { var values; var i; values = [ '5', 3.14, NaN, true, false, null, void 0, [], {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'prng': value }); }; } }); tape( 'if provided a `copy` option which is not a boolean, the function throws an error', function test( t ) { var values; var i; values = [ '5', 5, NaN, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'copy': value }); }; } }); tape( 'if provided a `seed` which is not a positive integer or a non-empty array-like object, the function throws an error', function test( t ) { var values; var i; values = [ '5', 3.14, 0.0, -5.0, NaN, true, false, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'seed': value }); }; } }); tape( 'the function throws a range error if provided a `seed` which is an integer greater than the maximum unsigned 32-bit integer', function test( t ) { var values; var i; values = [ UINT32_MAX + 1, UINT32_MAX + 2, UINT32_MAX + 3 ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), RangeError, 'throws a range error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'seed': value }); }; } }); tape( 'if provided a `state` option which is not a Uint32Array, the function throws an error', function test( t ) { var values; var i; values = [ '5', 5, NaN, true, false, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'state': value }); }; } }); tape( 'if provided an invalid `state` option, the function throws an error', function test( t ) { var values; var i; values = [ new Uint32Array( 0 ), new Uint32Array( 10 ), new Uint32Array( 100 ) ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), RangeError, 'throws an error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'state': value }); }; } }); tape( 'if provided an invalid readable stream option, the function throws an error', function test( t ) { var values; var i; values = [ '5', 5, NaN, null, void 0, {}, [], function noop() {} ]; for ( i = 0; i < values.length; i++ ) { t.throws( badValue( values[i] ), TypeError, 'throws a type error when provided '+values[i] ); } t.end(); function badValue( value ) { return function badValue() { randomStream( 2.0, 5.0, { 'objectMode': value }); }; } }); tape( 'the function is a constructor which returns a readable stream', function test( t ) { var RandomStream = randomStream; var s; s = new RandomStream( 2.0, 5.0 ); t.equal( s instanceof Readable, true, 'returns expected value' ); t.end(); }); tape( 'the constructor does not require the `new` operator', function test( t ) { var RandomStream = randomStream; var s; s = randomStream( 2.0, 5.0 ); t.equal( s instanceof RandomStream, true, 'returns expected value' ); t.end(); }); tape( 'the constructor returns a readable stream (no new)', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( s instanceof Readable, true, 'returns expected value' ); t.end(); }); tape( 'the returned stream provides a method to destroy a stream (object)', function test( t ) { var count = 0; var s; s = randomStream( 2.0, 5.0 ); t.equal( typeof s.destroy, 'function', 'has destroy method' ); s.on( 'error', onError ); s.on( 'close', onClose ); s.destroy({ 'message': 'beep' }); function onError( err ) { count += 1; if ( err ) { t.ok( true, err.message ); } else { t.ok( false, 'does not error' ); } if ( count === 2 ) { t.end(); } } function onClose() { count += 1; t.ok( true, 'stream closes' ); if ( count === 2 ) { t.end(); } } }); tape( 'the returned stream provides a method to destroy a stream (error object)', function test( t ) { var count = 0; var s; s = randomStream( 2.0, 5.0 ); t.equal( typeof s.destroy, 'function', 'has destroy method' ); s.on( 'error', onError ); s.on( 'close', onClose ); s.destroy( new Error( 'beep' ) ); function onError( err ) { count += 1; if ( err ) { t.ok( true, err.message ); } else { t.ok( false, 'does not error' ); } if ( count === 2 ) { t.end(); } } function onClose() { count += 1; t.ok( true, 'stream closes' ); if ( count === 2 ) { t.end(); } } }); tape( 'the returned stream does not allow itself to be destroyed more than once', function test( t ) { var s; s = randomStream( 2.0, 5.0 ); s.on( 'error', onError ); s.on( 'close', onClose ); // If the stream is closed twice, the test will error... s.destroy(); s.destroy(); function onClose() { t.ok( true, 'stream closes' ); t.end(); } function onError( err ) { t.ok( false, err.message ); } }); tape( 'attached to the returned stream is the underlying PRNG', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( typeof s.PRNG, 'function', 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.PRNG, minstd.normalized, 'has property' ); t.end(); }); tape( 'attached to the returned stream is the generator seed', function test( t ) { var s = randomStream( 2.0, 5.0, { 'seed': 12345 }); t.equal( isUint32Array( s.seed ), true, 'has property' ); t.equal( s.seed[ 0 ], 12345, 'equal to provided seed' ); s = randomStream( 2.0, 5.0, { 'seed': 12345, 'prng': minstd.normalized }); t.equal( s.seed, null, 'equal to `null`' ); t.end(); }); tape( 'attached to the returned stream is the generator seed (array seed)', function test( t ) { var actual; var seed; var s; var i; seed = [ 1234, 5678 ]; s = randomStream( 2.0, 5.0, { 'seed': seed }); actual = s.seed; t.equal( isUint32Array( actual ), true, 'has property' ); for ( i = 0; i < seed.length; i++ ) { t.equal( actual[ i ], seed[ i ], 'returns expected value for word '+i ); } t.end(); }); tape( 'attached to the returned stream is the generator seed length', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( typeof s.seedLength, 'number', 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.seedLength, null, 'equal to `null`' ); t.end(); }); tape( 'attached to the returned stream is the generator state', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( isUint32Array( s.state ), true, 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.state, null, 'equal to `null`' ); t.end(); }); tape( 'attached to the returned stream is the generator state length', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( typeof s.stateLength, 'number', 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.stateLength, null, 'equal to `null`' ); t.end(); }); tape( 'attached to the returned stream is the generator state size', function test( t ) { var s = randomStream( 2.0, 5.0 ); t.equal( typeof s.byteLength, 'number', 'has property' ); s = randomStream( 2.0, 5.0, { 'prng': minstd.normalized }); t.equal( s.byteLength, null, 'equal to `null`' ); t.end(); }); tape( 'the constructor returns a stream for generating pseudorandom numbers from an arcsine distribution', function test( t ) { var iStream; var result; var rand; var opts; var s; // Note: we assume that the underlying generator is the following PRNG... rand = arcsine( 2.0, 5.0, { 'seed': 12345 }); opts = { 'seed': 12345, 'iter': 10, 'sep': '\n' }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); result = ''; s.pipe( iStream ); function inspect( chunk ) { t.equal( isBuffer( chunk ), true, 'returns a buffer' ); result += chunk.toString(); } function onEnd() { var i; t.pass( 'stream ended' ); result = result.split( '\n' ); t.equal( result.length, 10, 'has expected length' ); for ( i = 0; i < result.length; i++ ) { t.equal( parseFloat( result[ i ] ), rand(), 'returns expected value. i: ' + i + '.' ); } t.end(); } }); tape( 'the constructor returns a stream for generating pseudorandom numbers from an arcsine distribution (object mode)', function test( t ) { var iStream; var count; var rand; var opts; var s; // Note: we assume that the underlying generator is the following PRNG... rand = arcsine( 2.0, 5.0, { 'seed': 12345 }); opts = { 'seed': 12345, 'objectMode': true }; s = randomStream( 2.0, 5.0, opts ); s.on( 'close', onClose ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); count = 0; s.pipe( iStream ); function inspect( v ) { count += 1; t.equal( rand(), v, 'returns expected value. i: '+count+'.' ); if ( count >= 10 ) { s.destroy(); } } function onClose() { t.pass( 'stream closed' ); t.end(); } }); tape( 'the constructor supports limiting the number of iterations', function test( t ) { var iStream; var count; var niter; var opts; var s; niter = 10; count = 0; opts = { 'iter': niter, 'objectMode': true }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); s.pipe( iStream ); function inspect( v ) { count += 1; t.equal( typeof v, 'number', 'returns expected value' ); } function onEnd() { t.equal( count === niter, true, 'performs expected number of iterations' ); t.end(); } }); tape( 'by default, the constructor generates newline-delimited pseudorandom numbers', function test( t ) { var iStream; var result; var opts; var s; opts = { 'iter': 10 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); iStream = inspectStream( inspect ); result = ''; s.pipe( iStream ); function inspect( chunk ) { result += chunk.toString(); } function onEnd() { var v; var i; result = result.split( '\n' ); t.equal( result.length, opts.iter, 'has expected length' ); for ( i = 0; i < result.length; i++ ) { v = parseFloat( result[ i ] ); t.equal( typeof v, 'number', 'returns expected value' ); t.equal( isnan( v ), false, 'is not NaN' ); } t.end(); } }); tape( 'the constructor supports providing a custom separator for streamed values', function test( t ) { var iStream; var result; var opts; var s; opts = { 'iter': 10, 'sep': '--++--' }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); iStream = inspectStream( inspect ); result = ''; s.pipe( iStream ); function inspect( chunk ) { result += chunk.toString(); } function onEnd() { var v; var i; result = result.split( opts.sep ); t.equal( result.length, opts.iter, 'has expected length' ); for ( i = 0; i < result.length; i++ ) { v = parseFloat( result[ i ] ); t.equal( typeof v, 'number', 'returns expected value' ); t.equal( isnan( v ), false, 'is not NaN' ); } t.end(); } }); tape( 'the constructor supports returning a seeded readable stream', function test( t ) { var iStream; var opts; var seed; var arr; var s1; var s2; var i; seed = now(); opts = { 'objectMode': true, 'seed': seed, 'iter': 10 }; s1 = randomStream( 2.0, 5.0, opts ); s1.on( 'end', onEnd1 ); s2 = randomStream( 2.0, 5.0, opts ); s2.on( 'end', onEnd2 ); t.notEqual( s1, s2, 'separate streams' ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect1 ); arr = []; i = 0; s1.pipe( iStream ); function inspect1( v ) { arr.push( v ); } function onEnd1() { var iStream; var opts; opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect2 ); s2.pipe( iStream ); } function inspect2( v ) { t.equal( v, arr[ i ], 'returns expected value' ); i += 1; } function onEnd2() { t.end(); } }); tape( 'the constructor supports specifying the underlying PRNG', function test( t ) { var iStream; var opts; var s; opts = { 'prng': minstd.normalized, 'objectMode': true, 'iter': 10 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); s.pipe( iStream ); function inspect( v ) { t.equal( typeof v, 'number', 'returns a number' ); } function onEnd() { t.end(); } }); tape( 'the constructor supports providing a seeded underlying PRNG', function test( t ) { var iStream1; var iStream2; var randu; var seed; var opts; var FLG; var s1; var s2; var r1; var r2; seed = now(); randu = minstd.factory({ 'seed': seed }); opts = { 'prng': randu.normalized, 'objectMode': true, 'iter': 10 }; s1 = randomStream( 2.0, 5.0, opts ); s1.on( 'end', onEnd ); randu = minstd.factory({ 'seed': seed }); opts = { 'prng': randu.normalized, 'objectMode': true, 'iter': 10 }; s2 = randomStream( 2.0, 5.0, opts ); s2.on( 'end', onEnd ); t.notEqual( s1, s2, 'separate streams' ); opts = { 'objectMode': true }; iStream1 = inspectStream( opts, inspect1 ); iStream2 = inspectStream( opts, inspect2 ); r1 = []; r2 = []; s1.pipe( iStream1 ); s2.pipe( iStream2 ); function inspect1( v ) { r1.push( v ); } function inspect2( v ) { r2.push( v ); } function onEnd() { if ( FLG ) { t.deepEqual( r1, r2, 'streams expected values' ); return t.end(); } FLG = true; } }); tape( 'the constructor supports specifying the underlying generator state', function test( t ) { var iStream; var state; var count; var opts; var arr; var s; opts = { 'objectMode': true, 'iter': 10, 'siter': 5 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'state', onState ); s.on( 'end', onEnd1 ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect1 ); count = 0; arr = []; // Move to a future state... s.pipe( iStream ); function onState( s ) { // Only capture the first emitted state... if ( !state ) { state = s; } } function inspect1( v ) { count += 1; if ( count > 5 ) { arr.push( v ); } } function onEnd1() { var iStream; var opts; var s; t.pass( 'first stream ended' ); // Create another stream using the captured state: opts = { 'objectMode': true, 'iter': 5, 'state': state }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd2 ); t.deepEqual( state, s.state, 'same state' ); // Create a new inspect stream: opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect2 ); // Replay previously generated values... count = 0; s.pipe( iStream ); } function inspect2( v ) { count += 1; t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' ); } function onEnd2() { t.pass( 'second stream ended' ); t.end(); } }); tape( 'the constructor supports specifying a shared underlying generator state', function test( t ) { var iStream; var shared; var state; var count; var opts; var arr; var s; opts = { 'objectMode': true, 'iter': 10, 'siter': 4 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'state', onState ); s.on( 'end', onEnd1 ); opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect1 ); count = 0; arr = []; // Move to a future state... s.pipe( iStream ); function onState( s ) { // Only capture the first emitted state... if ( !state ) { state = s; // Create a copy of the state (to prevent mutation) which will be shared by more than one PRNG: shared = new Uint32Array( state ); } } function inspect1( v ) { count += 1; if ( count > 4 ) { arr.push( v ); } } function onEnd1() { var iStream; var opts; var s; t.pass( 'first stream ended' ); // Create another stream using the captured state: opts = { 'objectMode': true, 'iter': 3, 'state': shared, 'copy': false }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd2 ); t.deepEqual( state, s.state, 'same state' ); // Create a new inspect stream: opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect2 ); // Replay previously generated values... count = 0; s.pipe( iStream ); } function inspect2( v ) { count += 1; t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' ); } function onEnd2() { var iStream; var opts; var s; t.pass( 'second stream ended' ); // Create another stream using the captured state: opts = { 'objectMode': true, 'iter': 3, 'state': shared, 'copy': false }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd3 ); t.notDeepEqual( state, s.state, 'different state' ); // Create a new inspect stream: opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect3 ); // Continue replaying previously generated values... s.pipe( iStream ); } function inspect3( v ) { count += 1; t.equal( v, arr[ count-1 ], 'returns expected value. i: '+(count-1)+'.' ); } function onEnd3() { t.pass( 'third stream ended' ); t.end(); } }); tape( 'the returned stream supports setting the underlying generator state', function test( t ) { var iStream; var state; var rand; var opts; var arr; var s; var i; rand = arcsine( 2.0, 5.0 ); // Move to a future state... for ( i = 0; i < 5; i++ ) { rand(); } // Capture the current state: state = rand.state; // Move to a future state... arr = []; for ( i = 0; i < 5; i++ ) { arr.push( rand() ); } // Create a random stream: opts = { 'objectMode': true, 'iter': 5 }; s = randomStream( 2.0, 5.0, opts ); s.on( 'end', onEnd ); // Set the PRNG state: s.state = state; // Create a new inspect stream: opts = { 'objectMode': true }; iStream = inspectStream( opts, inspect ); // Replay previously generated values: i = 0; s.pipe( iStream ); function inspect( v ) { t.equal( v, arr[ i ], 'returns expected value. i: ' + i + '.' ); i += 1; } function onEnd() { t.end(); } });
stdlib-js/stdlib
lib/node_modules/@stdlib/random/streams/arcsine/test/test.main.js
JavaScript
apache-2.0
23,031
"use strict"; import chai from "chai"; import chaiAsPromised from "chai-as-promised"; import sinon from "sinon"; import BusinessElementsClient from "../src"; import uuid from "uuid"; import * as requests from "../src/requests"; chai.use(chaiAsPromised); chai.should(); chai.config.includeStack = true; const FAKE_SERVER_URL = "http://api.fake-server"; /** @test {Attribute} */ describe("Attribute", () => { let sandbox, client, attributeId, attribute; beforeEach(() => { sandbox = sinon.sandbox.create(); client = new BusinessElementsClient(FAKE_SERVER_URL); attributeId = uuid.v4(); attribute = client.tenant("example.com").attributes().attribute(attributeId); }); afterEach(() => { sandbox.restore(); }); /** @test {Attribute#get} */ describe("#get()", () => { const data = {id: attributeId}; beforeEach(() => { sandbox.stub(client, "execute").returns(Promise.resolve(data)); }); it("should get capture", () => { attribute.get(); sinon.assert.calledWithMatch(client.execute, { path: `/attributes/${attributeId}` }); }); it("should return attribute data", () => { return attribute.get().should.become(data); }); }); /** @test {Attribute#edit} */ describe("#edit()", () => { const response = {status: "Ok"}; const schema = { "type": "object", "properties": { "type": { "title": "type", "type": "string" } } }; beforeEach(() => { sandbox.stub(client, "execute").returns(Promise.resolve(response)); sandbox.spy(requests, "updateAttribute"); }); it("should edit the attribute", () => { attribute.edit(schema, {}); sinon.assert.calledWithMatch(requests.updateAttribute, attributeId, schema); }); it("should return success", () => { return attribute.edit(schema, {}).should.eventually.become(response); }); }); /** @test {Attribute#remove} */ describe("#remove()", () => { const response = {status: "Ok"}; beforeEach(() => { sandbox.stub(client, "execute").returns(Promise.resolve(response)); sandbox.spy(requests, "deleteAttribute"); }); it("should delete the attribute", () => { attribute.remove({}); sinon.assert.calledWithMatch(requests.deleteAttribute, attributeId); }); it("should return success", () => { return attribute.remove({}).should.eventually.become(response); }); }); });
Product-Foundry/business-elements-client-js
test/attribute_test.js
JavaScript
apache-2.0
2,495
'use strict'; angular.module('playgroundApp', [ 'playgroundApp.filters', 'playgroundApp.services', 'playgroundApp.directives', 'ngRoute', 'ui.bootstrap', 'ui', ]) .config(function($locationProvider, $routeProvider, $httpProvider, $dialogProvider) { $locationProvider.html5Mode(true); // TODO: add list of promises to be resolved for injection // TODO: resolved promises are injected into controller // TODO: see http://www.youtube.com/watch?v=P6KITGRQujQ $routeProvider .when('/playground/', { templateUrl: '/playground/main.html', controller: MainController, }) .when('/playground/p/:project_id/', { templateUrl: '/playground/project.html', controller: ProjectController, reloadOnSearch: false, }); $httpProvider.interceptors.push('pgHttpInterceptor'); // TODO: test these defaults? $dialogProvider.options({ backdropFade: true, modalFade: true, }); }) .value('ui.config', { codemirror: { lineNumbers: true, matchBrackets: true, autofocus: true, undoDepth: 440, // default = 40 } });
jackpunt/playground
app/js/app.js
JavaScript
apache-2.0
1,117
define([ 'jquery', 'underscore', 'backbone', 'app' ], function ( $, _, Backbone, app ) { var Models = {}, Collections = {}, Views = {}; Models.Project = Backbone.Model.extend(); Collections.Projects = Backbone.Model.extend({ model: Models.Project, url: function() { return app.api('projects/' + this.get('platform') + (this.get('uri') ? '/' + this.get('uri') : '')); }, parse: function(res) { return { projects: res }; } }); Models.Project = Backbone.Model.extend({ url: function() { return app.api('projects?' + this.get('params')); } }); return { Models: Models, Collections: Collections, Views: Views }; });
Redmart/os-mobilizer
frontend/source/js/modules/Projects.js
JavaScript
apache-2.0
666
import App from '../containers/App'; import { PageNotFound } from '../components'; import homeRoute from '../features/home/route'; import taggrRoute from '../features/taggr/route'; const routes = [{ path: '/', component: App, childRoutes: [ homeRoute, taggrRoute, { path: '*', name: 'Page not found', component: PageNotFound }, ], }]; // Handle isIndex property of route config: // 1. remove the first child with isIndex=true from childRoutes // 2. assign it to the indexRoute property of the parent. function handleIndexRoute(route) { if (!route.childRoutes || !route.childRoutes.length) { return; } route.childRoutes = route.childRoutes.filter(child => { // eslint-disable-line if (child.isIndex) { /* istanbul ignore next */ if (process.env.NODE_ENV === 'dev' && route.indexRoute) { console.error('More than one index route: ', route); } /* istanbul ignore else */ if (!route.indexRoute) { delete child.path; // eslint-disable-line route.indexRoute = child; // eslint-disable-line return false; } } return true; }); route.childRoutes.forEach(handleIndexRoute); } routes.forEach(handleIndexRoute); export default routes;
thehig/taggr
src/common/routeConfig.js
JavaScript
apache-2.0
1,246
'use strict'; const Task = require('co-task'); const sql = require('../api/helpers/sql'); module.exports = { up: function (queryInterface, Sequelize) { return Task.spawn(function* () { yield queryInterface.addColumn('ClassicSalads', 'ClassicSaladCatagoryId', Sequelize.INTEGER); yield sql.foreignKeyUp(queryInterface, 'ClassicSalads', 'ClassicSaladCatagoryId', 'ClassicSaladCatagories', 'id'); }); }, down: function (queryInterface, Sequelize) { return Task.spawn(function* () { yield sql.foreignKeyDown(queryInterface, 'ClassicSalads', 'ClassicSaladCatagoryId', 'ClassicSaladCatagories', 'id'); yield queryInterface.removeColumn('ClassicSalads', 'ClassicSaladCatagoryId'); }); } };
arcana261/SaladioBackEnd
migrations/20161221201621-associate-classicsaladcatagory-and-classicsalad.js
JavaScript
apache-2.0
734
/*global describe, beforeEach, it*/ 'use strict'; var assert = require('yeoman-generator').assert; var helper = require('./helper'); describe('mcap:connections', function () { beforeEach(function (done) { var answers = { name: 'MyApp' }; // Creates a generateor with the default options / arguments helper.createAppGenerator({ answers: answers }, done); }); it('creates expected files', function (done) { var expectedFiles = [ 'connections/sap.json' ]; var expectedContent = { name: 'SAP', description: 'SAP API', type: 'rest', properties: { descriptorUrl: 'http://sap.mway.io', username: 'admin', password: 'root' } }; var answers = { name: 'SAP', description: 'SAP API', descriptorUrl: 'http://sap.mway.io', username: 'admin', password: 'root' }; helper.createSubGenerator('connection', {answers: answers}, function () { assert.file(expectedFiles); helper.deepEqual('connections/sap.json', expectedContent); done(); }); }); });
mwaylabs/mcap-cli
generators/generator-mcap/test/test-connections.js
JavaScript
apache-2.0
1,116
const browserSync = require('../../../'); const utils = require('../utils'); const register = require('../../../dist/plugins/clients').ClientEvents.register; const assert = require('chai').assert; describe('Client connection stream', function () { it('does not have duplicates', function (done) { browserSync.create({}).subscribe(function (bs) { const client = utils.getClientSocket(bs); client.emit(register, utils.getClient('123456')); client.emit(register, utils.getClient('123456')); bs.clients$.skip(1) .take(2) .toArray() .subscribe(function (clients) { assert.equal(clients[0].size, 1); assert.equal(clients[1].size, 1); const jsClients1 = clients[0].toList().toJS(); const jsClients2 = clients[1].toList().toJS(); assert.equal(jsClients1[0].id, '123456'); assert.equal(jsClients2[0].id, '123456'); bs.cleanup(); done(); }, function (err) {done(err)}); }); }); it('allows unique clients', function (done) { browserSync.create({}).subscribe(function (bs) { const client = utils.getClientSocket(bs); client.emit(register, utils.getClient('xyz')); client.emit(register, utils.getClient('zxy')); bs.clients$.skip(1) .take(2) .toArray() .subscribe(function (clients) { assert.equal(clients[0].size, 1); assert.equal(clients[1].size, 2); const jsClients1 = clients[0].toList().toJS(); const jsClients2 = clients[1].toList().toJS(); assert.equal(jsClients1[0].id, 'xyz'); assert.equal(jsClients2[0].id, 'xyz'); assert.equal(jsClients2[1].id, 'zxy'); bs.cleanup(); done(); }, function(err) { done(err) }); }); }); it('allows unique clients (stress)', function (done) { browserSync.create({}).subscribe(function (bs) { for (var i = 1, n = 51; i < n; i += 1) { utils.getClientSocket(bs).emit(register, utils.getClient('id-' + i)); } bs.clients$.skip(1) .take(50) .toArray() .subscribe(function (clients) { assert.equal(clients[49].size, 50); assert.ok(clients[49].get('id-40')); assert.equal(clients[49].get('id-40').get('id'), 'id-40'); bs.cleanup(); done(); }, function(err) { done(err) }); }); }); });
BrowserSync/browser-sync-core
test/mocha/api/clients$.js
JavaScript
apache-2.0
2,869
'use strict'; // https://github.com/tc39/proposal-iterator-helpers var aCallable = require('../internals/a-callable'); var anObject = require('../internals/an-object'); var getBuiltIn = require('../internals/get-built-in'); var getMethod = require('../internals/get-method'); var MAX_SAFE_INTEGER = 0x1FFFFFFFFFFFFF; var createMethod = function (TYPE) { var IS_TO_ARRAY = TYPE == 0; var IS_FOR_EACH = TYPE == 1; var IS_EVERY = TYPE == 2; var IS_SOME = TYPE == 3; return function (iterator, fn, target) { anObject(iterator); var Promise = getBuiltIn('Promise'); var next = aCallable(iterator.next); var index = 0; var MAPPING = fn !== undefined; if (MAPPING || !IS_TO_ARRAY) aCallable(fn); return new Promise(function (resolve, reject) { var closeIteration = function (method, argument) { try { var returnMethod = getMethod(iterator, 'return'); if (returnMethod) { return Promise.resolve(returnMethod.call(iterator)).then(function () { method(argument); }, function (error) { reject(error); }); } } catch (error2) { return reject(error2); } method(argument); }; var onError = function (error) { closeIteration(reject, error); }; var loop = function () { try { if (IS_TO_ARRAY && (index > MAX_SAFE_INTEGER) && MAPPING) { throw TypeError('The allowed number of iterations has been exceeded'); } Promise.resolve(anObject(next.call(iterator))).then(function (step) { try { if (anObject(step).done) { if (IS_TO_ARRAY) { target.length = index; resolve(target); } else resolve(IS_SOME ? false : IS_EVERY || undefined); } else { var value = step.value; if (MAPPING) { Promise.resolve(IS_TO_ARRAY ? fn(value, index) : fn(value)).then(function (result) { if (IS_FOR_EACH) { loop(); } else if (IS_EVERY) { result ? loop() : closeIteration(resolve, false); } else if (IS_TO_ARRAY) { target[index++] = result; loop(); } else { result ? closeIteration(resolve, IS_SOME || value) : loop(); } }, onError); } else { target[index++] = value; loop(); } } } catch (error) { onError(error); } }, onError); } catch (error2) { onError(error2); } }; loop(); }); }; }; module.exports = { toArray: createMethod(0), forEach: createMethod(1), every: createMethod(2), some: createMethod(3), find: createMethod(4) };
cloudfoundry-community/asp.net5-buildpack
fixtures/node_apps/angular_dotnet/ClientApp/node_modules/core-js/internals/async-iterator-iteration.js
JavaScript
apache-2.0
2,973
/*! * ${copyright} */ sap.ui.require([ "jquery.sap.global", "sap/ui/base/SyncPromise", "sap/ui/model/BindingMode", "sap/ui/model/ChangeReason", "sap/ui/model/ClientListBinding", "sap/ui/model/Context", "sap/ui/model/ContextBinding", "sap/ui/model/Filter", "sap/ui/model/MetaModel", "sap/ui/model/PropertyBinding", "sap/ui/model/Sorter", "sap/ui/model/odata/OperationMode", "sap/ui/model/odata/type/Int64", "sap/ui/model/odata/type/Raw", "sap/ui/model/odata/v4/AnnotationHelper", "sap/ui/model/odata/v4/Context", "sap/ui/model/odata/v4/lib/_Helper", "sap/ui/model/odata/v4/ODataMetaModel", "sap/ui/model/odata/v4/ODataModel", "sap/ui/model/odata/v4/ValueListType", "sap/ui/test/TestUtils", "sap/ui/thirdparty/URI" ], function (jQuery, SyncPromise, BindingMode, ChangeReason, ClientListBinding, BaseContext, ContextBinding, Filter, MetaModel, PropertyBinding, Sorter, OperationMode, Int64, Raw, AnnotationHelper, Context, _Helper, ODataMetaModel, ODataModel, ValueListType, TestUtils, URI) { /*global QUnit, sinon */ /*eslint max-nested-callbacks: 0, no-loop-func: 0, no-warning-comments: 0 */ "use strict"; // Common := com.sap.vocabularies.Common.v1 // tea_busi := com.sap.gateway.default.iwbep.tea_busi.v0001 // tea_busi_product.v0001 := com.sap.gateway.default.iwbep.tea_busi_product.v0001 // tea_busi_supplier.v0001 := com.sap.gateway.default.iwbep.tea_busi_supplier.v0001 // UI := com.sap.vocabularies.UI.v1 var mMostlyEmptyScope = { "$EntityContainer" : "empty.DefaultContainer", "$Version" : "4.0", "empty." : { "$kind" : "Schema" }, "empty.DefaultContainer" : { "$kind" : "EntityContainer" } }, sODataMetaModel = "sap.ui.model.odata.v4.ODataMetaModel", mProductScope = { "$EntityContainer" : "tea_busi_product.v0001.DefaultContainer", "$Reference" : { "../../../../default/iwbep/tea_busi_supplier/0001/$metadata" : { "$Include" : [ "tea_busi_supplier.v0001." ] } }, "$Version" : "4.0", "tea_busi_product.v0001." : { "$kind" : "Schema", "$Annotations" : { // Note: simulate result of _MetadataRequestor#read "tea_busi_product.v0001.Category/CategoryName" : { "@Common.Label" : "CategoryName from tea_busi_product.v0001." } } }, "tea_busi_product.v0001.Category" : { "$kind" : "EntityType", "CategoryName" : { "$kind" : "Property", "$Type" : "Edm.String" } }, "tea_busi_product.v0001.DefaultContainer" : { "$kind" : "EntityContainer" }, "tea_busi_product.v0001.Product" : { "$kind" : "EntityType", "Name" : { "$kind" : "Property", "$Type" : "Edm.String" }, "PRODUCT_2_CATEGORY" : { "$kind" : "NavigationProperty", "$Type" : "tea_busi_product.v0001.Category" }, "PRODUCT_2_SUPPLIER" : { "$kind" : "NavigationProperty", "$Type" : "tea_busi_supplier.v0001.Supplier" } } }, sSampleServiceUrl = "/sap/opu/odata4/sap/zui5_testv4/default/sap/zui5_epm_sample/0002/", mScope = { "$Annotations" : { "name.space.Id" : { "@Common.Label" : "ID" }, "tea_busi.DefaultContainer" : { "@DefaultContainer" : {} }, "tea_busi.DefaultContainer/T€AMS" : { "@T€AMS" : {} }, "tea_busi.TEAM" : { "@Common.Text" : { "$Path" : "Name" }, "@[email protected]" : { "$EnumMember" : "UI.TextArrangementType/TextLast" }, "@UI.Badge" : { "@Common.Label" : "Label inside", "$Type" : "UI.BadgeType", "HeadLine" : { "$Type" : "UI.DataField", "Value" : { "$Path" : "Name" } }, "Title" : { "$Type" : "UI.DataField", "Value" : { "$Path" : "Team_Id" } } }, "@[email protected]" : "Best Badge Ever!", "@UI.LineItem" : [{ "@UI.Importance" : { "$EnumMember" : "UI.ImportanceType/High" }, "$Type" : "UI.DataField", "Label" : "Team ID", "[email protected]" : "Team ID's Label", "Value" : { "$Path" : "Team_Id" } }] }, "tea_busi.TEAM/Team_Id" : { "@Common.Label" : "Team ID", "@Common.Text" : { "$Path" : "Name" }, "@[email protected]" : { "$EnumMember" : "UI.TextArrangementType/TextLast" } }, "tea_busi.Worker" : { "@UI.Facets" : [{ "$Type" : "UI.ReferenceFacet", "Target" : { // term cast "$AnnotationPath" : "@UI.LineItem" } }, { "$Type" : "UI.ReferenceFacet", "Target" : { // term cast at navigation property itself "$AnnotationPath" : "[email protected]" } }, { "$Type" : "UI.ReferenceFacet", "Target" : { // navigation property and term cast "$AnnotationPath" : "EMPLOYEE_2_TEAM/@UI.LineItem" } }, { "$Type" : "UI.ReferenceFacet", "Target" : { // type cast, navigation properties and term cast (at its type) "$AnnotationPath" : "tea_busi.TEAM/TEAM_2_EMPLOYEES/EMPLOYEE_2_TEAM/@UI.LineItem" } }], "@UI.LineItem" : [{ "$Type" : "UI.DataField", "Label" : "Team ID", "Value" : { "$Path" : "EMPLOYEE_2_TEAM/Team_Id" } }] }, "tea_busi.Worker/EMPLOYEE_2_TEAM" : { "@Common.Label" : "Employee's Team" } }, "$EntityContainer" : "tea_busi.DefaultContainer", "empty." : { "$kind" : "Schema" }, "name.space." : { "$kind" : "Schema" }, "tea_busi." : { "$kind" : "Schema", "@Schema" : {} }, "empty.Container" : { "$kind" : "EntityContainer" }, "name.space.BadContainer" : { "$kind" : "EntityContainer", "DanglingActionImport" : { "$kind" : "ActionImport", "$Action" : "not.Found" }, "DanglingFunctionImport" : { "$kind" : "FunctionImport", "$Function" : "not.Found" } }, "name.space.Broken" : { "$kind" : "Term", "$Type" : "not.Found" }, "name.space.BrokenFunction" : [{ "$kind" : "Function", "$ReturnType" : { "$Type" : "not.Found" } }], "name.space.BrokenOverloads" : [{ "$kind" : "Operation" }], "name.space.DerivedPrimitiveFunction" : [{ "$kind" : "Function", "$ReturnType" : { "$Type" : "name.space.Id" } }], "name.space.EmptyOverloads" : [], "name.space.Id" : { "$kind" : "TypeDefinition", "$UnderlyingType" : "Edm.String", "$MaxLength" : 10 }, "name.space.Term" : { // only case with a qualified name and a $Type "$kind" : "Term", "$Type" : "tea_busi.Worker" }, "name.space.OverloadedAction" : [{ "$kind" : "Action", "$IsBound" : true, "$Parameter" : [{ // "$Name" : "_it", "$Type" : "tea_busi.EQUIPMENT" }], "$ReturnType" : { "$Type" : "tea_busi.EQUIPMENT" } }, { "$kind" : "Action", "$IsBound" : true, "$Parameter" : [{ // "$Name" : "_it", "$Type" : "tea_busi.TEAM" }], "$ReturnType" : { "$Type" : "tea_busi.TEAM" } }, { // "An unbound action MAY have the same name as a bound action." "$kind" : "Action", "$ReturnType" : { "$Type" : "tea_busi.ComplexType_Salary" } }, { "$kind" : "Action", "$IsBound" : true, "$Parameter" : [{ // "$Name" : "_it", "$Type" : "tea_busi.Worker" }], "$ReturnType" : { "$Type" : "tea_busi.Worker" } }], "name.space.OverloadedFunction" : [{ "$kind" : "Function", "$ReturnType" : { "$Type" : "Edm.String" } }, { "$kind" : "Function", "$ReturnType" : { "$Type" : "Edm.String" } }], "name.space.VoidAction" : [{ "$kind" : "Action" }], "tea_busi.AcChangeManagerOfTeam" : [{ "$kind" : "Action", "$ReturnType" : { "$Type" : "tea_busi.TEAM", "@Common.Label" : "Hail to the Chief" } }], "tea_busi.ComplexType_Salary" : { "$kind" : "ComplexType", "AMOUNT" : { "$kind" : "Property", "$Type" : "Edm.Decimal" }, "CURRENCY" : { "$kind" : "Property", "$Type" : "Edm.String" } }, "tea_busi.ContainedC" : { "$kind" : "EntityType", "$Key" : ["Id"], "Id" : { "$kind" : "Property", "$Type" : "Edm.String" }, "C_2_EMPLOYEE" : { "$kind" : "NavigationProperty", "$Type" : "tea_busi.Worker" }, "C_2_S" : { "$ContainsTarget" : true, "$kind" : "NavigationProperty", "$Type" : "tea_busi.ContainedS" } }, "tea_busi.ContainedS" : { "$kind" : "EntityType", "$Key" : ["Id"], "Id" : { "$kind" : "Property", "$Type" : "Edm.String" }, "S_2_C" : { "$ContainsTarget" : true, "$kind" : "NavigationProperty", "$isCollection" : true, "$Type" : "tea_busi.ContainedC" }, "S_2_EMPLOYEE" : { "$kind" : "NavigationProperty", "$Type" : "tea_busi.Worker" } }, "tea_busi.DefaultContainer" : { "$kind" : "EntityContainer", "ChangeManagerOfTeam" : { "$kind" : "ActionImport", "$Action" : "tea_busi.AcChangeManagerOfTeam" }, "EMPLOYEES" : { "$kind" : "EntitySet", "$NavigationPropertyBinding" : { "EMPLOYEE_2_TEAM" : "T€AMS", "EMPLOYEE_2_EQUIPM€NTS" : "EQUIPM€NTS" }, "$Type" : "tea_busi.Worker" }, "EQUIPM€NTS" : { "$kind" : "EntitySet", "$Type" : "tea_busi.EQUIPMENT" }, "GetEmployeeMaxAge" : { "$kind" : "FunctionImport", "$Function" : "tea_busi.FuGetEmployeeMaxAge" }, "Me" : { "$kind" : "Singleton", "$NavigationPropertyBinding" : { "EMPLOYEE_2_TEAM" : "T€AMS", "EMPLOYEE_2_EQUIPM€NTS" : "EQUIPM€NTS" }, "$Type" : "tea_busi.Worker" }, "OverloadedAction" : { "$kind" : "ActionImport", "$Action" : "name.space.OverloadedAction" }, "TEAMS" : { "$kind" : "EntitySet", "$NavigationPropertyBinding" : { "TEAM_2_EMPLOYEES" : "EMPLOYEES", "TEAM_2_CONTAINED_S/S_2_EMPLOYEE" : "EMPLOYEES" }, "$Type" : "tea_busi.TEAM" }, "T€AMS" : { "$kind" : "EntitySet", "$NavigationPropertyBinding" : { "TEAM_2_EMPLOYEES" : "EMPLOYEES" }, "$Type" : "tea_busi.TEAM" }, "VoidAction" : { "$kind" : "ActionImport", "$Action" : "name.space.VoidAction" } }, "tea_busi.EQUIPMENT" : { "$kind" : "EntityType", "$Key" : ["ID"], "ID" : { "$kind" : "Property", "$Type" : "Edm.Int32", "$Nullable" : false } }, "tea_busi.FuGetEmployeeMaxAge" : [{ "$kind" : "Function", "$ReturnType" : { "$Type" : "Edm.Int16" } }], "tea_busi.TEAM" : { "$kind" : "EntityType", "$Key" : ["Team_Id"], "Team_Id" : { "$kind" : "Property", "$Type" : "name.space.Id", "$Nullable" : false, "$MaxLength" : 10 }, "Name" : { "$kind" : "Property", "$Type" : "Edm.String", "$Nullable" : false, "$MaxLength" : 40 }, "TEAM_2_EMPLOYEES" : { "$kind" : "NavigationProperty", "$isCollection" : true, "$OnDelete" : "None", "[email protected]" : "None of my business", "$ReferentialConstraint" : { "foo" : "bar", "[email protected]" : "Just a Gigolo" }, "$Type" : "tea_busi.Worker" }, "TEAM_2_CONTAINED_S" : { "$ContainsTarget" : true, "$kind" : "NavigationProperty", "$Type" : "tea_busi.ContainedS" }, "TEAM_2_CONTAINED_C" : { "$ContainsTarget" : true, "$kind" : "NavigationProperty", "$isCollection" : true, "$Type" : "tea_busi.ContainedC" }, // Note: "value" is a symbolic name for an operation's return type iff. it is // primitive "value" : { "$kind" : "Property", "$Type" : "Edm.String" } }, "tea_busi.Worker" : { "$kind" : "EntityType", "$Key" : ["ID"], "ID" : { "$kind" : "Property", "$Type" : "Edm.String", "$Nullable" : false, "$MaxLength" : 4 }, "AGE" : { "$kind" : "Property", "$Type" : "Edm.Int16", "$Nullable" : false }, "EMPLOYEE_2_CONTAINED_S" : { "$ContainsTarget" : true, "$kind" : "NavigationProperty", "$Type" : "tea_busi.ContainedS" }, "EMPLOYEE_2_EQUIPM€NTS" : { "$kind" : "NavigationProperty", "$isCollection" : true, "$Type" : "tea_busi.EQUIPMENT", "$Nullable" : false }, "EMPLOYEE_2_TEAM" : { "$kind" : "NavigationProperty", "$Type" : "tea_busi.TEAM", "$Nullable" : false }, "SALÃRY" : { "$kind" : "Property", "$Type" : "tea_busi.ComplexType_Salary" } }, "$$Loop" : "$$Loop/", // some endless loop "$$Term" : "name.space.Term" // replacement for any reference to the term }, oContainerData = mScope["tea_busi.DefaultContainer"], aOverloadedAction = mScope["name.space.OverloadedAction"], mSupplierScope = { "$Version" : "4.0", "tea_busi_supplier.v0001." : { "$kind" : "Schema" }, "tea_busi_supplier.v0001.Supplier" : { "$kind" : "EntityType", "Supplier_Name" : { "$kind" : "Property", "$Type" : "Edm.String" } } }, oTeamData = mScope["tea_busi.TEAM"], oTeamLineItem = mScope.$Annotations["tea_busi.TEAM"]["@UI.LineItem"], oWorkerData = mScope["tea_busi.Worker"], mXServiceScope = { "$Version" : "4.0", "$Annotations" : {}, // simulate ODataMetaModel#_mergeAnnotations "$EntityContainer" : "tea_busi.v0001.DefaultContainer", "$Reference" : { // Note: Do not reference tea_busi_supplier directly from here! We want to test the // special case that it is only indirectly referenced. "../../../../default/iwbep/tea_busi_foo/0001/$metadata" : { "$Include" : [ "tea_busi_foo.v0001." ] }, "../../../../default/iwbep/tea_busi_product/0001/$metadata" : { "$Include" : [ "ignore.me.", "tea_busi_product.v0001." ] }, "/empty/$metadata" : { "$Include" : [ "empty.", "I.still.haven't.found.what.I'm.looking.for." ] } }, "tea_busi.v0001." : { "$kind" : "Schema" }, "tea_busi.v0001.DefaultContainer" : { "$kind" : "EntityContainer", "EQUIPM€NTS" : { "$kind" : "EntitySet", "$Type" : "tea_busi.v0001.EQUIPMENT" } }, "tea_busi.v0001.EQUIPMENT" : { "$kind" : "EntityType", "EQUIPMENT_2_PRODUCT" : { "$kind" : "NavigationProperty", "$Type" : "tea_busi_product.v0001.Product" } } }, aAllScopes = [ mMostlyEmptyScope, mProductScope, mScope, mSupplierScope, mXServiceScope ]; /** * Checks the "get*" and "request*" methods corresponding to the named "fetch*" method, * using the given arguments. * * @param {object} oTestContext * the QUnit "this" object * @param {object} assert * the QUnit "assert" object * @param {string} sMethodName * method name "fetch*" * @param {object[]} aArguments * method arguments * @param {boolean} [bThrow=false] * whether the "get*" method throws if the promise is not fulfilled * @returns {Promise} * the "request*" method's promise */ function checkGetAndRequest(oTestContext, assert, sMethodName, aArguments, bThrow) { var oExpectation, sGetMethodName = sMethodName.replace("fetch", "get"), oMetaModel = oTestContext.oMetaModel, oReason = new Error("rejected"), oRejectedPromise = Promise.reject(oReason), sRequestMethodName = sMethodName.replace("fetch", "request"), oResult = {}, oSyncPromise = SyncPromise.resolve(oRejectedPromise); // resolve... oExpectation = oTestContext.mock(oMetaModel).expects(sMethodName).exactly(4); oExpectation = oExpectation.withExactArgs.apply(oExpectation, aArguments); oExpectation.returns(SyncPromise.resolve(oResult)); // get: fulfilled assert.strictEqual(oMetaModel[sGetMethodName].apply(oMetaModel, aArguments), oResult); // reject... oExpectation.returns(oSyncPromise); oTestContext.mock(Promise).expects("resolve") .withExactArgs(sinon.match.same(oSyncPromise)) .returns(oRejectedPromise); // return any promise (this is not unwrapping!) // request (promise still pending!) assert.strictEqual(oMetaModel[sRequestMethodName].apply(oMetaModel, aArguments), oRejectedPromise); // get: pending if (bThrow) { assert.throws(function () { oMetaModel[sGetMethodName].apply(oMetaModel, aArguments); }, new Error("Result pending")); } else { assert.strictEqual(oMetaModel[sGetMethodName].apply(oMetaModel, aArguments), undefined, "pending"); } return oSyncPromise.catch(function () { // get: rejected if (bThrow) { assert.throws(function () { oMetaModel[sGetMethodName].apply(oMetaModel, aArguments); }, oReason); } else { assert.strictEqual(oMetaModel[sGetMethodName].apply(oMetaModel, aArguments), undefined, "rejected"); } }); } /** * Returns a clone, that is a deep copy, of the given object. * * @param {object} o * any serializable object * @returns {object} * a deep copy of <code>o</code> */ function clone(o) { return JSON.parse(JSON.stringify(o)); } /** * Runs the given test for each name/value pair in the given fixture. The name is interpreted * as a path "[<sContextPath>'|']<sMetaPath>" and cut accordingly. The test is called with * an almost resolved sPath (just '|' replaced by '/'). * * @param {object} mFixture * map<string, any> * @param {function} fnTest * function(string sPath, any vResult, string sContextPath, string sMetaPath) */ function forEach(mFixture, fnTest) { var sPath; for (sPath in mFixture) { var i = sPath.indexOf("|"), sContextPath = "", sMetaPath = sPath.slice(i + 1), vValue = mFixture[sPath]; if (i >= 0) { sContextPath = sPath.slice(0, i); sPath = sContextPath + "/" + sMetaPath; } fnTest(sPath, vValue, sContextPath, sMetaPath); } } //********************************************************************************************* QUnit.module("sap.ui.model.odata.v4.ODataMetaModel", { // remember copy to ensure test isolation mOriginalScopes : clone(aAllScopes), afterEach : function (assert) { assert.deepEqual(aAllScopes, this.mOriginalScopes, "metadata unchanged"); }, /* * Allow warnings if told to; always suppress debug messages. */ allowWarnings : function (assert, bWarn) { this.mock(jQuery.sap.log).expects("isLoggable").atLeast(1) .withExactArgs(sinon.match.number, sODataMetaModel) .callsFake(function (iLogLevel) { switch (iLogLevel) { case jQuery.sap.log.Level.DEBUG: return false; case jQuery.sap.log.Level.WARNING: return bWarn; default: return true; } }); }, beforeEach : function () { var oMetadataRequestor = { read : function () { throw new Error(); } }, sUrl = "/a/b/c/d/e/$metadata"; this.oLogMock = this.mock(jQuery.sap.log); this.oLogMock.expects("warning").never(); this.oLogMock.expects("error").never(); this.oMetaModel = new ODataMetaModel(oMetadataRequestor, sUrl); this.oMetaModelMock = this.mock(this.oMetaModel); this.oModel = { reportError : function () { throw new Error("Unsupported operation"); }, resolve : ODataModel.prototype.resolve }; }, /* * Expect the given debug message with the given path, but only if debug level is on. */ expectDebug : function (bDebug, sMessage, sPath) { this.oLogMock.expects("isLoggable") .withExactArgs(jQuery.sap.log.Level.DEBUG, sODataMetaModel).returns(bDebug); this.oLogMock.expects("debug").exactly(bDebug ? 1 : 0) .withExactArgs(sMessage, sPath, sODataMetaModel); }, /* * Expects "fetchEntityContainer" to be called at least once on the current meta model, * returning a clone of the given scope. * * @param {object} mScope */ expectFetchEntityContainer : function (mScope) { mScope = clone(mScope); this.oMetaModel.validate("n/a", mScope); // fill mSchema2MetadataUrl! this.oMetaModelMock.expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(mScope)); } }); //********************************************************************************************* QUnit.test("basics", function (assert) { var sAnnotationUri = "my/annotation.xml", aAnnotationUris = [ sAnnotationUri, "uri2.xml"], oModel = {}, oMetadataRequestor = this.oMetaModel.oRequestor, sUrl = "/~/$metadata", oMetaModel; // code under test assert.strictEqual(ODataMetaModel.prototype.$$valueAsPromise, true); // code under test oMetaModel = new ODataMetaModel(oMetadataRequestor, sUrl); assert.ok(oMetaModel instanceof MetaModel); assert.strictEqual(oMetaModel.aAnnotationUris, undefined); assert.ok(oMetaModel.hasOwnProperty("aAnnotationUris"), "own property aAnnotationUris"); assert.strictEqual(oMetaModel.oRequestor, oMetadataRequestor); assert.strictEqual(oMetaModel.sUrl, sUrl); assert.strictEqual(oMetaModel.getDefaultBindingMode(), BindingMode.OneTime); assert.strictEqual(oMetaModel.toString(), "sap.ui.model.odata.v4.ODataMetaModel: /~/$metadata"); // code under test oMetaModel.setDefaultBindingMode(BindingMode.OneWay); assert.strictEqual(oMetaModel.getDefaultBindingMode(), BindingMode.OneWay); // code under test oMetaModel = new ODataMetaModel(oMetadataRequestor, sUrl, aAnnotationUris); assert.strictEqual(oMetaModel.aAnnotationUris, aAnnotationUris, "arrays are passed"); // code under test oMetaModel = new ODataMetaModel(oMetadataRequestor, sUrl, sAnnotationUri); assert.deepEqual(oMetaModel.aAnnotationUris, [sAnnotationUri], "single annotation is wrapped"); // code under test oMetaModel = new ODataMetaModel(null, null, null, oModel); // code under test assert.strictEqual(oMetaModel.getAdapterFactoryModulePath(), "sap/ui/model/odata/v4/meta/ODataAdapterFactory"); }); //********************************************************************************************* QUnit.test("forbidden", function (assert) { assert.throws(function () { //TODO implement this.oMetaModel.bindTree(); }, new Error("Unsupported operation: v4.ODataMetaModel#bindTree")); assert.throws(function () { this.oMetaModel.getOriginalProperty(); }, new Error("Unsupported operation: v4.ODataMetaModel#getOriginalProperty")); assert.throws(function () { //TODO implement this.oMetaModel.isList(); }, new Error("Unsupported operation: v4.ODataMetaModel#isList")); assert.throws(function () { this.oMetaModel.refresh(); }, new Error("Unsupported operation: v4.ODataMetaModel#refresh")); assert.throws(function () { this.oMetaModel.setLegacySyntax(); // argument does not matter! }, new Error("Unsupported operation: v4.ODataMetaModel#setLegacySyntax")); assert.throws(function () { this.oMetaModel.setDefaultBindingMode(BindingMode.TwoWay); }); }); //********************************************************************************************* [ undefined, ["/my/annotation.xml"], ["/my/annotation.xml", "/another/annotation.xml"] ].forEach(function (aAnnotationURI) { var title = "fetchEntityContainer - " + JSON.stringify(aAnnotationURI); QUnit.test(title, function (assert) { var oRequestorMock = this.mock(this.oMetaModel.oRequestor), aReadResults, mRootScope = {}, oSyncPromise, that = this; function expectReads(bPrefetch) { oRequestorMock.expects("read") .withExactArgs(that.oMetaModel.sUrl, false, bPrefetch) .returns(Promise.resolve(mRootScope)); aReadResults = []; (aAnnotationURI || []).forEach(function (sAnnotationUrl) { var oAnnotationResult = {}; aReadResults.push(oAnnotationResult); oRequestorMock.expects("read") .withExactArgs(sAnnotationUrl, true, bPrefetch) .returns(Promise.resolve(oAnnotationResult)); }); } this.oMetaModel.aAnnotationUris = aAnnotationURI; this.oMetaModelMock.expects("_mergeAnnotations").never(); expectReads(true); // code under test assert.strictEqual(this.oMetaModel.fetchEntityContainer(true), null); // bPrefetch => no caching expectReads(true); // code under test assert.strictEqual(this.oMetaModel.fetchEntityContainer(true), null); // now test [bPrefetch=false] expectReads(); this.oMetaModelMock.expects("_mergeAnnotations") .withExactArgs(mRootScope, aReadResults); // code under test oSyncPromise = this.oMetaModel.fetchEntityContainer(); // pending assert.strictEqual(oSyncPromise.isPending(), true); // already caching assert.strictEqual(this.oMetaModel.fetchEntityContainer(), oSyncPromise); assert.strictEqual(this.oMetaModel.fetchEntityContainer(true), oSyncPromise, "now bPrefetch makes no difference"); return oSyncPromise.then(function (mRootScope0) { assert.strictEqual(mRootScope0, mRootScope); // still caching assert.strictEqual(that.oMetaModel.fetchEntityContainer(), oSyncPromise); }); }); }); //TODO later support "$Extends" : "<13.1.2 EntityContainer Extends>" //********************************************************************************************* QUnit.test("fetchEntityContainer: _mergeAnnotations fails", function (assert) { var oError = new Error(); this.mock(this.oMetaModel.oRequestor).expects("read") .withExactArgs(this.oMetaModel.sUrl, false, undefined) .returns(Promise.resolve({})); this.oMetaModelMock.expects("_mergeAnnotations").throws(oError); return this.oMetaModel.fetchEntityContainer().then(function () { assert.ok(false, "unexpected success"); }, function (oError0) { assert.strictEqual(oError0, oError); }); }); //********************************************************************************************* QUnit.test("getMetaContext", function (assert) { var oMetaContext; this.oMetaModelMock.expects("getMetaPath") .withExactArgs("/Foo/-1/bar") .returns("/Foo/bar"); // code under test oMetaContext = this.oMetaModel.getMetaContext("/Foo/-1/bar"); assert.strictEqual(oMetaContext.getModel(), this.oMetaModel); assert.strictEqual(oMetaContext.getPath(), "/Foo/bar"); }); //********************************************************************************************* QUnit.test("getMetaPath", function (assert) { var sMetaPath = {}, sPath = {}; this.mock(_Helper).expects("getMetaPath") .withExactArgs(sinon.match.same(sPath)).returns(sMetaPath); assert.strictEqual(this.oMetaModel.getMetaPath(sPath), sMetaPath); }); //********************************************************************************************* forEach({ // absolute path "/" : "/", "/foo/bar|/" : "/", // context is ignored // relative path "" : undefined, // w/o context --> important for MetaModel#createBindingContext etc. "|foo/bar" : undefined, // w/o context "/|" : "/", "/|foo/bar" : "/foo/bar", "/foo|bar" : "/foo/bar", "/foo/bar|" : "/foo/bar", "/foo/|bar" : "/foo/bar", // trailing slash is preserved "/foo/bar/" : "/foo/bar/", "/foo|bar/" : "/foo/bar/", // relative path that starts with a dot "/foo/bar|./" : "/foo/bar/", "/foo|./bar/" : "/foo/bar/", "/foo/|./bar/" : "/foo/bar/", // annotations "/foo|@bar" : "/foo@bar", "/foo/|@bar" : "/foo/@bar", "/foo|./@bar" : "/foo/@bar", "/foo/|./@bar" : "/foo/@bar", // technical properties "/foo|$kind" : "/foo/$kind", "/foo/|$kind" : "/foo/$kind", "/foo|./$kind" : "/foo/$kind", "/foo/|./$kind" : "/foo/$kind" }, function (sPath, sResolvedPath, sContextPath, sMetaPath) { QUnit.test("resolve: " + sContextPath + " > " + sMetaPath, function (assert) { var oContext = sContextPath && this.oMetaModel.getContext(sContextPath); assert.strictEqual(this.oMetaModel.resolve(sMetaPath, oContext), sResolvedPath); }); }); //TODO make sure that Context objects are only created for absolute paths?! //********************************************************************************************* [".bar", ".@bar", ".$kind"].forEach(function (sPath) { QUnit.test("resolve: unsupported relative path " + sPath, function (assert) { var oContext = this.oMetaModel.getContext("/foo"); assert.raises(function () { this.oMetaModel.resolve(sPath, oContext); }, new Error("Unsupported relative path: " + sPath)); }); }); //********************************************************************************************* QUnit.test("resolve: undefined", function (assert) { assert.strictEqual( this.oMetaModel.resolve(undefined, this.oMetaModel.getContext("/")), "/"); }); //********************************************************************************************* //TODO better map meta model path to pure JSON path (look up inside JsonModel)? // what about @sapui.name then, which requires a literal as expected result? // --> we could distinguish "/<path>" from "<literal>" forEach({ // "JSON" drill-down ---------------------------------------------------------------------- "/$EntityContainer" : "tea_busi.DefaultContainer", "/tea_busi./$kind" : "Schema", "/tea_busi.DefaultContainer/$kind" : "EntityContainer", // trailing slash: object vs. name -------------------------------------------------------- "/" : oContainerData, "/$EntityContainer/" : oContainerData, "/T€AMS/" : oTeamData, "/T€AMS/$Type/" : oTeamData, // scope lookup ("17.3 QualifiedName") ---------------------------------------------------- "/$EntityContainer/$kind" : "EntityContainer", "/$EntityContainer/T€AMS/$Type" : "tea_busi.TEAM", "/$EntityContainer/T€AMS/$Type/Team_Id" : oTeamData.Team_Id, // "17.3 QualifiedName", e.g. type cast --------------------------------------------------- "/tea_busi." : mScope["tea_busi."], // access to schema "/tea_busi.DefaultContainer/EMPLOYEES/tea_busi.Worker/AGE" : oWorkerData.AGE, // implicit $Type insertion --------------------------------------------------------------- "/T€AMS/Team_Id" : oTeamData.Team_Id, "/T€AMS/TEAM_2_EMPLOYEES" : oTeamData.TEAM_2_EMPLOYEES, "/T€AMS/TEAM_2_EMPLOYEES/AGE" : oWorkerData.AGE, // scope lookup, then implicit $Type insertion! "/$$Term/AGE" : oWorkerData.AGE, // "17.2 SimpleIdentifier": lookup inside current schema child ---------------------------- "/T€AMS" : oContainerData["T€AMS"], "/T€AMS/$NavigationPropertyBinding/TEAM_2_EMPLOYEES/" : oWorkerData, "/T€AMS/$NavigationPropertyBinding/TEAM_2_EMPLOYEES/$Type" : "tea_busi.Worker", "/T€AMS/$NavigationPropertyBinding/TEAM_2_EMPLOYEES/AGE" : oWorkerData.AGE, // operations ----------------------------------------------------------------------------- "/OverloadedAction" : oContainerData["OverloadedAction"], "/OverloadedAction/$Action" : "name.space.OverloadedAction", "/ChangeManagerOfTeam/" : oTeamData, //TODO mScope[mScope["..."][0].$ReturnType.$Type] is where the next OData simple identifier // would live in case of entity/complex type, but we would like to avoid warnings for // primitive types - how to tell the difference? // "/GetEmployeeMaxAge/" : "Edm.Int16", // Note: "value" is a symbolic name for the whole return type iff. it is primitive "/GetEmployeeMaxAge/value" : mScope["tea_busi.FuGetEmployeeMaxAge"][0].$ReturnType, "/GetEmployeeMaxAge/value/$Type" : "Edm.Int16", // path may continue! "/tea_busi.FuGetEmployeeMaxAge/value" : mScope["tea_busi.FuGetEmployeeMaxAge"][0].$ReturnType, "/name.space.DerivedPrimitiveFunction/value" //TODO merge facets of return type and type definition?! : mScope["name.space.DerivedPrimitiveFunction"][0].$ReturnType, "/ChangeManagerOfTeam/value" : oTeamData.value, // action overloads ----------------------------------------------------------------------- //TODO @$ui5.overload: support for split segments? etc. "/OverloadedAction/@$ui5.overload" : sinon.match.array.deepEquals([aOverloadedAction[2]]), "/OverloadedAction/@$ui5.overload/0" : aOverloadedAction[2], // Note: trailing slash does not make a difference in "JSON" drill-down "/OverloadedAction/@$ui5.overload/0/$ReturnType/" : aOverloadedAction[2].$ReturnType, "/OverloadedAction/@$ui5.overload/0/$ReturnType/$Type" : "tea_busi.ComplexType_Salary", "/OverloadedAction/" : mScope["tea_busi.ComplexType_Salary"], "/name.space.OverloadedAction" : aOverloadedAction, "/T€AMS/NotFound/name.space.OverloadedAction" : aOverloadedAction, "/name.space.OverloadedAction/1" : aOverloadedAction[1], "/OverloadedAction/$Action/1" : aOverloadedAction[1], "/OverloadedAction/@$ui5.overload/AMOUNT" : mScope["tea_busi.ComplexType_Salary"].AMOUNT, "/OverloadedAction/AMOUNT" : mScope["tea_busi.ComplexType_Salary"].AMOUNT, "/T€AMS/name.space.OverloadedAction/Team_Id" : oTeamData.Team_Id, "/T€AMS/name.space.OverloadedAction/@$ui5.overload" : sinon.match.array.deepEquals([aOverloadedAction[1]]), "/name.space.OverloadedAction/@$ui5.overload" : sinon.match.array.deepEquals([]), // only "Action" and "Function" is expected as $kind, but others are not filtered out! "/name.space.BrokenOverloads" : sinon.match.array.deepEquals(mScope["name.space.BrokenOverloads"]), // annotations ---------------------------------------------------------------------------- "/@DefaultContainer" : mScope.$Annotations["tea_busi.DefaultContainer"]["@DefaultContainer"], "/tea_busi.DefaultContainer@DefaultContainer" : mScope.$Annotations["tea_busi.DefaultContainer"]["@DefaultContainer"], "/tea_busi.DefaultContainer/@DefaultContainer" // w/o $Type, slash makes no difference! : mScope.$Annotations["tea_busi.DefaultContainer"]["@DefaultContainer"], "/$EntityContainer@DefaultContainer" // Note: we could change this : mScope.$Annotations["tea_busi.DefaultContainer"]["@DefaultContainer"], "/$EntityContainer/@DefaultContainer" // w/o $Type, slash makes no difference! : mScope.$Annotations["tea_busi.DefaultContainer"]["@DefaultContainer"], "/T€AMS/$Type/@UI.LineItem" : oTeamLineItem, "/T€AMS/@UI.LineItem" : oTeamLineItem, "/T€AMS/@UI.LineItem/0/Label" : oTeamLineItem[0].Label, "/T€AMS/@UI.LineItem/0/@UI.Importance" : oTeamLineItem[0]["@UI.Importance"], "/T€AMS@T€AMS" : mScope.$Annotations["tea_busi.DefaultContainer/T€AMS"]["@T€AMS"], "/T€AMS/@Common.Text" : mScope.$Annotations["tea_busi.TEAM"]["@Common.Text"], "/T€AMS/@[email protected]" : mScope.$Annotations["tea_busi.TEAM"]["@[email protected]"], "/T€AMS/[email protected]" : mScope.$Annotations["tea_busi.TEAM/Team_Id"]["@Common.Text"], "/T€AMS/[email protected]@UI.TextArrangement" : mScope.$Annotations["tea_busi.TEAM/Team_Id"]["@[email protected]"], "/tea_busi./@Schema" : mScope["tea_busi."]["@Schema"], // inline annotations "/ChangeManagerOfTeam/$Action/0/$ReturnType/@Common.Label" : "Hail to the Chief", "/T€AMS/TEAM_2_EMPLOYEES/[email protected]" : "None of my business", "/T€AMS/TEAM_2_EMPLOYEES/$ReferentialConstraint/[email protected]" : "Just a Gigolo", "/T€AMS/@UI.LineItem/0/[email protected]" : "Team ID's Label", "/T€AMS/@[email protected]" : "Best Badge Ever!", // annotation of annotation "/T€AMS/@UI.Badge/@Common.Label" : "Label inside", // annotation of record // "@" to access to all annotations, e.g. for iteration "/T€AMS@" : mScope.$Annotations["tea_busi.DefaultContainer/T€AMS"], "/T€AMS/@" : mScope.$Annotations["tea_busi.TEAM"], "/T€AMS/Team_Id@" : mScope.$Annotations["tea_busi.TEAM/Team_Id"], // "14.5.12 Expression edm:Path" // Note: see integration test "{field>Value/[email protected]}" "/T€AMS/@UI.LineItem/0/Value/[email protected]" : mScope.$Annotations["tea_busi.TEAM/Team_Id"]["@Common.Text"], "/T€AMS/@UI.LineItem/0/Value/$Path/@Common.Label" : mScope.$Annotations["name.space.Id"]["@Common.Label"], "/EMPLOYEES/@UI.LineItem/0/Value/[email protected]" : mScope.$Annotations["tea_busi.TEAM/Team_Id"]["@Common.Text"], // "14.5.2 Expression edm:AnnotationPath" "/EMPLOYEES/@UI.Facets/0/Target/$AnnotationPath/" : mScope.$Annotations["tea_busi.Worker"]["@UI.LineItem"], "/EMPLOYEES/@UI.Facets/1/Target/$AnnotationPath/" : mScope.$Annotations["tea_busi.Worker/EMPLOYEE_2_TEAM"]["@Common.Label"], "/EMPLOYEES/@UI.Facets/2/Target/$AnnotationPath/" : mScope.$Annotations["tea_busi.TEAM"]["@UI.LineItem"], "/EMPLOYEES/@UI.Facets/3/Target/$AnnotationPath/" : mScope.$Annotations["tea_busi.TEAM"]["@UI.LineItem"], // @sapui.name ---------------------------------------------------------------------------- "/@sapui.name" : "tea_busi.DefaultContainer", "/[email protected]" : "tea_busi.DefaultContainer", "/tea_busi.DefaultContainer/@sapui.name" : "tea_busi.DefaultContainer", // no $Type here! "/$EntityContainer/@sapui.name" : "tea_busi.DefaultContainer", "/T€[email protected]" : "T€AMS", "/T€AMS/@sapui.name" : "tea_busi.TEAM", "/T€AMS/[email protected]" : "Team_Id", "/T€AMS/[email protected]" : "TEAM_2_EMPLOYEES", "/T€AMS/$NavigationPropertyBinding/TEAM_2_EMPLOYEES/@sapui.name" : "tea_busi.Worker", "/T€AMS/$NavigationPropertyBinding/TEAM_2_EMPLOYEES/[email protected]" : "AGE", "/T€AMS@T€[email protected]" : "@T€AMS", "/T€AMS@/@T€[email protected]" : "@T€AMS", "/T€AMS@T€AMS/@sapui.name" : "@T€AMS", // no $Type inside @T€AMS, / makes no difference! "/T€AMS@/@T€AMS/@sapui.name" : "@T€AMS", // dito "/T€AMS/@UI.LineItem/0/@UI.Importance/@sapui.name" : "@UI.Importance", // in "JSON" mode "/T€AMS/Team_Id@/@[email protected]" : "@Common.Label" // avoid indirection here! }, function (sPath, vResult) { QUnit.test("fetchObject: " + sPath, function (assert) { var oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mScope)); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath); assert.strictEqual(oSyncPromise.isFulfilled(), true); if (vResult && typeof vResult === "object" && "test" in vResult) { // Sinon.JS matcher assert.ok(vResult.test(oSyncPromise.getResult()), vResult); } else { assert.strictEqual(oSyncPromise.getResult(), vResult); } // self-guard to avoid that a complex right-hand side evaluates to undefined assert.notStrictEqual(vResult, undefined, "use this test for defined results only!"); }); }); //TODO annotations at enum member ".../<10.2.1 Member Name>@..." (Note: "<10.2.2 Member Value>" // might be a string! Avoid indirection!) //TODO special cases where inline and external targeting annotations need to be merged! //TODO support also external targeting from a different schema! //TODO MySchema.MyFunction/MyParameter --> requires search in array?! //TODO $count? //TODO "For annotations targeting a property of an entity type or complex type, the path // expression is evaluated starting at the outermost entity type or complex type named in the // Target of the enclosing edm:Annotations element, i.e. an empty path resolves to the // outermost type, and the first segment of a non-empty path MUST be a property or navigation // property of the outermost type, a type cast, or a term cast." --> consequences for us? //********************************************************************************************* [ // "JSON" drill-down ---------------------------------------------------------------------- "/$missing", "/tea_busi.DefaultContainer/$missing", "/tea_busi.DefaultContainer/missing", // "17.2 SimpleIdentifier" treated like any property "/tea_busi.FuGetEmployeeMaxAge/0/tea_busi.FuGetEmployeeMaxAge", // "0" switches to JSON "/tea_busi.TEAM/$Key/this.is.missing", "/tea_busi.Worker/missing", // entity container (see above) treated like any schema child // scope lookup ("17.3 QualifiedName") ---------------------------------------------------- "/$EntityContainer/$missing", "/$EntityContainer/missing", // implicit $Type insertion --------------------------------------------------------------- "/T€AMS/$Key", // avoid $Type insertion for following $ segments "/T€AMS/missing", "/T€AMS/$missing", // annotations ---------------------------------------------------------------------------- "/tea_busi.Worker@missing", "/tea_busi.Worker/@missing", // "@" to access to all annotations, e.g. for iteration "/tea_busi.Worker/@/@missing", // operations ----------------------------------------------------------------------------- "/VoidAction/" ].forEach(function (sPath) { QUnit.test("fetchObject: " + sPath + " --> undefined", function (assert) { var oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mScope)); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.strictEqual(oSyncPromise.getResult(), undefined); }); }); //********************************************************************************************* QUnit.test("fetchObject: Invalid relative path w/o context", function (assert) { var sMetaPath = "some/relative/path", oSyncPromise; this.oLogMock.expects("error").withExactArgs("Invalid relative path w/o context", sMetaPath, sODataMetaModel); // code under test oSyncPromise = this.oMetaModel.fetchObject(sMetaPath, null); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.strictEqual(oSyncPromise.getResult(), null); }); //********************************************************************************************* ["/empty.Container/@", "/T€AMS/Name@"].forEach(function (sPath) { QUnit.test("fetchObject returns {} (anonymous empty object): " + sPath, function (assert) { var oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mScope)); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.deepEqual(oSyncPromise.getResult(), {}); // strictEqual would not work! }); }); //********************************************************************************************* QUnit.test("fetchObject without $Annotations", function (assert) { var oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mMostlyEmptyScope)); // code under test oSyncPromise = this.oMetaModel.fetchObject("/@DefaultContainer"); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.deepEqual(oSyncPromise.getResult(), undefined); // strictEqual would not work! }); //TODO if no annotations exist for an external target, avoid {} internally unless "@" is used? //********************************************************************************************* [false, true].forEach(function (bWarn) { forEach({ "/$$Loop/" : "Invalid recursion at /$$Loop", // Invalid segment (warning) ---------------------------------------------------------- "//$Foo" : "Invalid empty segment", "/tea_busi./$Annotations" : "Invalid segment: $Annotations", // entrance forbidden! // Unknown ... ------------------------------------------------------------------------ "/not.Found" : "Unknown qualified name not.Found", "/Me/not.Found" : "Unknown qualified name not.Found", // no "at /.../undefined"! "/not.Found@missing" : "Unknown qualified name not.Found", "/." : "Unknown child . of tea_busi.DefaultContainer", "/Foo" : "Unknown child Foo of tea_busi.DefaultContainer", "/$EntityContainer/$kind/" : "Unknown child EntityContainer" + " of tea_busi.DefaultContainer at /$EntityContainer/$kind", // implicit $Action, $Function, $Type insertion "/name.space.BadContainer/DanglingActionImport/" : "Unknown qualified name not.Found" + " at /name.space.BadContainer/DanglingActionImport/$Action", "/name.space.BadContainer/DanglingFunctionImport/" : "Unknown qualified name not.Found" + " at /name.space.BadContainer/DanglingFunctionImport/$Function", "/name.space.Broken/" : "Unknown qualified name not.Found at /name.space.Broken/$Type", "/name.space.BrokenFunction/" : "Unknown qualified name not.Found" + " at /name.space.BrokenFunction/0/$ReturnType/$Type", //TODO align with "/GetEmployeeMaxAge/" : "Edm.Int16" "/GetEmployeeMaxAge/@sapui.name" : "Unknown qualified name Edm.Int16" + " at /tea_busi.FuGetEmployeeMaxAge/0/$ReturnType/$Type", "/GetEmployeeMaxAge/value/@sapui.name" : "Unknown qualified name Edm.Int16" + " at /tea_busi.FuGetEmployeeMaxAge/0/$ReturnType/$Type", // implicit scope lookup "/name.space.Broken/$Type/" : "Unknown qualified name not.Found at /name.space.Broken/$Type", "/tea_busi.DefaultContainer/$kind/@sapui.name" : "Unknown child EntityContainer" + " of tea_busi.DefaultContainer at /tea_busi.DefaultContainer/$kind", // Unsupported path before @sapui.name ------------------------------------------------ "/[email protected]" : "Unsupported path before @sapui.name", "/tea_busi.FuGetEmployeeMaxAge/[email protected]" : "Unsupported path before @sapui.name", "/tea_busi.TEAM/$Key/not.Found/@sapui.name" : "Unsupported path before @sapui.name", "/GetEmployeeMaxAge/[email protected]" : "Unsupported path before @sapui.name", // Unsupported path after @sapui.name ------------------------------------------------- "/@sapui.name/foo" : "Unsupported path after @sapui.name", "/$EntityContainer/T€AMS/@sapui.name/foo" : "Unsupported path after @sapui.name", // Unsupported path after @@... ------------------------------------------------------- "/EMPLOYEES/@UI.Facets/1/Target/$AnnotationPath@@this.is.ignored/foo" : "Unsupported path after @@this.is.ignored", "/EMPLOYEES/@UI.Facets/1/Target/$AnnotationPath/@@this.is.ignored@foo" : "Unsupported path after @@this.is.ignored", "/EMPLOYEES/@UI.Facets/1/Target/$AnnotationPath@@[email protected]" : "Unsupported path after @@this.is.ignored", // ...is not a function but... -------------------------------------------------------- "/@@sap.ui.model.odata.v4.AnnotationHelper.invalid" : "sap.ui.model.odata.v4.AnnotationHelper.invalid is not a function but: undefined", "/@@sap.ui.model.odata.v4.AnnotationHelper" : "sap.ui.model.odata.v4.AnnotationHelper is not a function but: " + sap.ui.model.odata.v4.AnnotationHelper, // Unsupported overloads -------------------------------------------------------------- "/name.space.EmptyOverloads/" : "Unsupported overloads", "/name.space.OverloadedAction/" : "Unsupported overloads", "/name.space.OverloadedFunction/" : "Unsupported overloads" }, function (sPath, sWarning) { QUnit.test("fetchObject fails: " + sPath + ", warn = " + bWarn, function (assert) { var oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mScope)); this.oLogMock.expects("isLoggable") .withExactArgs(jQuery.sap.log.Level.WARNING, sODataMetaModel).returns(bWarn); this.oLogMock.expects("warning").exactly(bWarn ? 1 : 0) .withExactArgs(sWarning, sPath, sODataMetaModel); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.deepEqual(oSyncPromise.getResult(), undefined); }); }); }); //********************************************************************************************* [false, true].forEach(function (bDebug) { forEach({ // Invalid segment (debug) ------------------------------------------------------------ "/$Foo/@bar" : "Invalid segment: @bar", "/$Foo/$Bar" : "Invalid segment: $Bar", "/$Foo/$Bar/$Baz" : "Invalid segment: $Bar", "/$EntityContainer/T€AMS/Team_Id/$MaxLength/." : "Invalid segment: .", "/$EntityContainer/T€AMS/Team_Id/$Nullable/." : "Invalid segment: .", "/$EntityContainer/T€AMS/Team_Id/NotFound/Invalid" : "Invalid segment: Invalid" }, function (sPath, sMessage) { QUnit.test("fetchObject fails: " + sPath + ", debug = " + bDebug, function (assert) { var oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mScope)); this.oLogMock.expects("isLoggable") .withExactArgs(jQuery.sap.log.Level.DEBUG, sODataMetaModel).returns(bDebug); this.oLogMock.expects("debug").exactly(bDebug ? 1 : 0) .withExactArgs(sMessage, sPath, sODataMetaModel); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.deepEqual(oSyncPromise.getResult(), undefined); }); }); }); //********************************************************************************************* [ "/EMPLOYEES/@UI.Facets/1/Target/$AnnotationPath", "/EMPLOYEES/@UI.Facets/1/Target/$AnnotationPath/" ].forEach(function (sPath) { QUnit.test("fetchObject: " + sPath + "@@...isMultiple", function (assert) { var oContext, oInput, fnIsMultiple = this.mock(AnnotationHelper).expects("isMultiple"), oResult = {}, oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer").atLeast(1) // see oInput .returns(SyncPromise.resolve(mScope)); oInput = this.oMetaModel.getObject(sPath); fnIsMultiple .withExactArgs(oInput, sinon.match({ context : sinon.match.object, schemaChildName : "tea_busi.Worker" })).returns(oResult); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath + "@@sap.ui.model.odata.v4.AnnotationHelper.isMultiple"); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.strictEqual(oSyncPromise.getResult(), oResult); oContext = fnIsMultiple.args[0][1].context; assert.ok(oContext instanceof BaseContext); assert.strictEqual(oContext.getModel(), this.oMetaModel); assert.strictEqual(oContext.getPath(), sPath); assert.strictEqual(oContext.getObject(), oInput); }); }); //********************************************************************************************* (function () { var sPath, sPathPrefix, mPathPrefix2SchemaChildName = { "/EMPLOYEES/@UI.Facets/1/Target/$AnnotationPath" : "tea_busi.Worker", "/T€AMS/@UI.LineItem/0/Value/[email protected]" : "tea_busi.TEAM", "/T€AMS/@UI.LineItem/0/Value/$Path/@Common.Label" : "name.space.Id" }, sSchemaChildName; for (sPathPrefix in mPathPrefix2SchemaChildName) { sPath = sPathPrefix + "@@.computedAnnotation"; sSchemaChildName = mPathPrefix2SchemaChildName[sPathPrefix]; QUnit.test("fetchObject: " + sPath, function (assert) { var fnComputedAnnotation, oContext, oInput, oResult = {}, oScope = { computedAnnotation : function () {} }, oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer").atLeast(1) // see oInput .returns(SyncPromise.resolve(mScope)); oInput = this.oMetaModel.getObject(sPathPrefix); fnComputedAnnotation = this.mock(oScope).expects("computedAnnotation"); fnComputedAnnotation .withExactArgs(oInput, sinon.match({ context : sinon.match.object, schemaChildName : sSchemaChildName })).returns(oResult); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath, null, {scope : oScope}); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.strictEqual(oSyncPromise.getResult(), oResult); oContext = fnComputedAnnotation.args[0][1].context; assert.ok(oContext instanceof BaseContext); assert.strictEqual(oContext.getModel(), this.oMetaModel); assert.strictEqual(oContext.getPath(), sPathPrefix); assert.strictEqual(oContext.getObject(), oInput); }); } }()); //********************************************************************************************* [false, true].forEach(function (bWarn) { QUnit.test("fetchObject: " + "...@@... throws", function (assert) { var oError = new Error("This call failed intentionally"), sPath = "/@@sap.ui.model.odata.v4.AnnotationHelper.isMultiple", oSyncPromise; this.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mScope)); this.mock(AnnotationHelper).expects("isMultiple") .throws(oError); this.oLogMock.expects("isLoggable") .withExactArgs(jQuery.sap.log.Level.WARNING, sODataMetaModel).returns(bWarn); this.oLogMock.expects("warning").exactly(bWarn ? 1 : 0).withExactArgs( "Error calling sap.ui.model.odata.v4.AnnotationHelper.isMultiple: " + oError, sPath, sODataMetaModel); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.strictEqual(oSyncPromise.getResult(), undefined); }); }); //********************************************************************************************* [false, true].forEach(function (bDebug) { QUnit.test("fetchObject: cross-service reference, bDebug = " + bDebug, function (assert) { var mClonedProductScope = clone(mProductScope), aPromises = [], oRequestorMock = this.mock(this.oMetaModel.oRequestor), that = this; /* * Expect the given debug message with the given path. */ function expectDebug(sMessage, sPath) { that.expectDebug(bDebug, sMessage, sPath); } /* * Code under test: ODataMetaModel#fetchObject with the given path should yield the * given expected result. */ function codeUnderTest(sPath, vExpectedResult) { aPromises.push(that.oMetaModel.fetchObject(sPath).then(function (vResult) { assert.strictEqual(vResult, vExpectedResult); })); } this.expectFetchEntityContainer(mXServiceScope); oRequestorMock.expects("read") .withExactArgs("/a/default/iwbep/tea_busi_product/0001/$metadata") .returns(Promise.resolve(mClonedProductScope)); oRequestorMock.expects("read") .withExactArgs("/a/default/iwbep/tea_busi_supplier/0001/$metadata") .returns(Promise.resolve(mSupplierScope)); oRequestorMock.expects("read") .withExactArgs("/empty/$metadata") .returns(Promise.resolve(mMostlyEmptyScope)); expectDebug("Namespace tea_busi_product.v0001. found in $Include" + " of /a/default/iwbep/tea_busi_product/0001/$metadata" + " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name"); expectDebug("Reading /a/default/iwbep/tea_busi_product/0001/$metadata" + " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name"); expectDebug("Waiting for tea_busi_product.v0001." + " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name"); codeUnderTest("/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name", mClonedProductScope["tea_busi_product.v0001.Product"].Name); expectDebug("Waiting for tea_busi_product.v0001." + " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_CATEGORY/CategoryName"); codeUnderTest("/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_CATEGORY/CategoryName", mClonedProductScope["tea_busi_product.v0001.Category"].CategoryName); expectDebug("Waiting for tea_busi_product.v0001.", "/tea_busi_product.v0001.Category/CategoryName"); codeUnderTest("/tea_busi_product.v0001.Category/CategoryName", mClonedProductScope["tea_busi_product.v0001.Category"].CategoryName); expectDebug("Waiting for tea_busi_product.v0001.", "/tea_busi_product.v0001.Category/[email protected]"); codeUnderTest("/tea_busi_product.v0001.Category/[email protected]", "CategoryName from tea_busi_product.v0001."); expectDebug("Waiting for tea_busi_product.v0001." + " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name"); codeUnderTest("/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name", mSupplierScope["tea_busi_supplier.v0001.Supplier"].Supplier_Name); expectDebug("Namespace empty. found in $Include of /empty/$metadata", "/empty.DefaultContainer"); expectDebug("Reading /empty/$metadata", "/empty.DefaultContainer"); expectDebug("Waiting for empty.", "/empty.DefaultContainer"); codeUnderTest("/empty.DefaultContainer", mMostlyEmptyScope["empty.DefaultContainer"]); // Note: these are logged asynchronously! expectDebug("Including tea_busi_product.v0001." + " from /a/default/iwbep/tea_busi_product/0001/$metadata" + " at /tea_busi.v0001.EQUIPMENT/EQUIPMENT_2_PRODUCT/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/Name"); expectDebug("Including empty. from /empty/$metadata", "/empty.DefaultContainer"); expectDebug("Namespace tea_busi_supplier.v0001. found in $Include" + " of /a/default/iwbep/tea_busi_supplier/0001/$metadata" + " at /tea_busi_product.v0001.Product/PRODUCT_2_SUPPLIER/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name"); expectDebug("Reading /a/default/iwbep/tea_busi_supplier/0001/$metadata" + " at /tea_busi_product.v0001.Product/PRODUCT_2_SUPPLIER/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name"); expectDebug("Waiting for tea_busi_supplier.v0001." + " at /tea_busi_product.v0001.Product/PRODUCT_2_SUPPLIER/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name"); expectDebug("Including tea_busi_supplier.v0001." + " from /a/default/iwbep/tea_busi_supplier/0001/$metadata" + " at /tea_busi_product.v0001.Product/PRODUCT_2_SUPPLIER/$Type", "/EQUIPM€NTS/EQUIPMENT_2_PRODUCT/PRODUCT_2_SUPPLIER/Supplier_Name"); return Promise.all(aPromises); }); }); //TODO Decision: It is an error if a namespace is referenced multiple times with different URIs. // This should be checked even when load-on-demand is used. // (It should not even be included multiple times with the same URI!) //TODO Check that no namespace is included which is already present! //TODO API to load "transitive closure" //TODO support for sync. XML Templating //********************************************************************************************* [false, true].forEach(function (bWarn) { var sTitle = "fetchObject: missing cross-service reference, bWarn = " + bWarn; QUnit.test(sTitle, function (assert) { var sPath = "/not.found", oSyncPromise; this.expectFetchEntityContainer(mMostlyEmptyScope); this.oLogMock.expects("isLoggable") .withExactArgs(jQuery.sap.log.Level.WARNING, sODataMetaModel).returns(bWarn); this.oLogMock.expects("warning").exactly(bWarn ? 1 : 0) .withExactArgs("Unknown qualified name not.found", sPath, sODataMetaModel); // code under test oSyncPromise = this.oMetaModel.fetchObject(sPath); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.deepEqual(oSyncPromise.getResult(), undefined); }); }); //********************************************************************************************* [false, true].forEach(function (bWarn) { var sTitle = "fetchObject: referenced metadata does not contain included schema, bWarn = " + bWarn; QUnit.test(sTitle, function (assert) { var sSchemaName = "I.still.haven't.found.what.I'm.looking.for.", sQualifiedName = sSchemaName + "Child", sPath = "/" + sQualifiedName; this.expectFetchEntityContainer(mXServiceScope); this.mock(this.oMetaModel.oRequestor).expects("read") .withExactArgs("/empty/$metadata") .returns(Promise.resolve(mMostlyEmptyScope)); this.allowWarnings(assert, bWarn); this.oLogMock.expects("warning").exactly(bWarn ? 1 : 0) .withExactArgs("/empty/$metadata does not contain " + sSchemaName, sPath, sODataMetaModel); this.oLogMock.expects("warning").exactly(bWarn ? 1 : 0) .withExactArgs("Unknown qualified name " + sQualifiedName, sPath, sODataMetaModel); // code under test return this.oMetaModel.fetchObject(sPath).then(function (vResult) { assert.deepEqual(vResult, undefined); }); }); }); //********************************************************************************************* [false, true].forEach(function (bWarn) { var sTitle = "fetchObject: cross-service reference, respect $Include; bWarn = " + bWarn; QUnit.test(sTitle, function (assert) { var mScope0 = { "$Version" : "4.0", "$Reference" : { "../../../../default/iwbep/tea_busi_product/0001/$metadata" : { "$Include" : [ "not.found.", "tea_busi_product.v0001.", "tea_busi_supplier.v0001." ] } } }, mReferencedScope = { "$Version" : "4.0", "must.not.be.included." : { "$kind" : "Schema" }, "tea_busi_product.v0001." : { "$kind" : "Schema" }, "tea_busi_supplier.v0001." : { "$kind" : "Schema" } }, oRequestorMock = this.mock(this.oMetaModel.oRequestor), that = this; this.expectFetchEntityContainer(mScope0); oRequestorMock.expects("read") .withExactArgs("/a/default/iwbep/tea_busi_product/0001/$metadata") .returns(Promise.resolve(mReferencedScope)); this.allowWarnings(assert, bWarn); // code under test return this.oMetaModel.fetchObject("/tea_busi_product.v0001.").then(function (vResult) { var oSyncPromise; assert.strictEqual(vResult, mReferencedScope["tea_busi_product.v0001."]); assert.ok(that.oMetaModel.mSchema2MetadataUrl["tea_busi_product.v0001."] ["/a/default/iwbep/tea_busi_product/0001/$metadata"], "document marked as read"); that.oLogMock.expects("warning").exactly(bWarn ? 1 : 0) .withExactArgs("Unknown qualified name must.not.be.included.", "/must.not.be.included.", sODataMetaModel); assert.strictEqual(that.oMetaModel.getObject("/must.not.be.included."), undefined, "must not include schemata which are not mentioned in edmx:Include"); assert.strictEqual(that.oMetaModel.getObject("/tea_busi_supplier.v0001."), mReferencedScope["tea_busi_supplier.v0001."]); // now check that "not.found." does not trigger another read(), // does finish synchronously and logs a warning that.oLogMock.expects("warning").exactly(bWarn ? 1 : 0) .withExactArgs("/a/default/iwbep/tea_busi_product/0001/$metadata" + " does not contain not.found.", "/not.found.", sODataMetaModel); that.oLogMock.expects("warning").exactly(bWarn ? 1 : 0) .withExactArgs("Unknown qualified name not.found.", "/not.found.", sODataMetaModel); // code under test oSyncPromise = that.oMetaModel.fetchObject("/not.found."); assert.strictEqual(oSyncPromise.isFulfilled(), true); assert.strictEqual(oSyncPromise.getResult(), undefined); }); }); }); //********************************************************************************************* QUnit.test("fetchObject: cross-service reference - validation failure", function (assert) { var oError = new Error(), mReferencedScope = {}, sUrl = "/a/default/iwbep/tea_busi_product/0001/$metadata"; this.expectFetchEntityContainer(mXServiceScope); this.mock(this.oMetaModel.oRequestor).expects("read").withExactArgs(sUrl) .returns(Promise.resolve(mReferencedScope)); this.oMetaModelMock.expects("validate") .withExactArgs(sUrl, mReferencedScope) .throws(oError); return this.oMetaModel.fetchObject("/tea_busi_product.v0001.Product").then(function () { assert.ok(false); }, function (oError0) { assert.strictEqual(oError0, oError); }); }); //********************************************************************************************* QUnit.test("fetchObject: cross-service reference - document loaded from different URI", function (assert) { var sMessage = "A schema cannot span more than one document: schema is referenced by" + " following URLs: /a/default/iwbep/tea_busi_product/0001/$metadata," + " /second/reference", sSchema = "tea_busi_product.v0001."; this.expectFetchEntityContainer(mXServiceScope); this.oLogMock.expects("error") .withExactArgs(sMessage, sSchema, sODataMetaModel); // simulate 2 references for a schema this.oMetaModel.mSchema2MetadataUrl["tea_busi_product.v0001."]["/second/reference"] = false; // code under test return this.oMetaModel.fetchObject("/tea_busi_product.v0001.Product").then(function () { assert.ok(false); }, function (oError0) { assert.strictEqual(oError0.message, sSchema + ": " + sMessage); }); }); //********************************************************************************************* QUnit.test("fetchObject: cross-service reference - duplicate include", function (assert) { var oRequestorMock = this.mock(this.oMetaModel.oRequestor), // root service includes both A and B, A also includes B mScope0 = { "$Version" : "4.0", "$Reference" : { "/A/$metadata" : { "$Include" : [ "A." ] }, "/B/$metadata" : { "$Include" : [ "B." ] } } }, mScopeA = { "$Version" : "4.0", "$Reference" : { "/B/$metadata" : { "$Include" : [ "B.", "B.B." // includes additional namespace from already read document ] } }, "A." : { "$kind" : "Schema" } }, mScopeB = { "$Version" : "4.0", "B." : { "$kind" : "Schema" }, "B.B." : { "$kind" : "Schema" } }, that = this; this.expectFetchEntityContainer(mScope0); oRequestorMock.expects("read").withExactArgs("/A/$metadata") .returns(Promise.resolve(mScopeA)); oRequestorMock.expects("read").withExactArgs("/B/$metadata") .returns(Promise.resolve(mScopeB)); return this.oMetaModel.fetchObject("/B.") .then(function (vResult) { assert.strictEqual(vResult, mScopeB["B."]); // code under test - we must not overwrite our "$ui5.read" promise! return that.oMetaModel.fetchObject("/A.") .then(function (vResult) { assert.strictEqual(vResult, mScopeA["A."]); // Note: must not trigger read() again! return that.oMetaModel.fetchObject("/B.B.") .then(function (vResult) { assert.strictEqual(vResult, mScopeB["B.B."]); }); }); }); }); //TODO Implement consistency checks that the same namespace is always included from the same // reference URI, no matter which referencing document. //********************************************************************************************* [undefined, false, true].forEach(function (bSupportReferences) { var sTitle = "fetchObject: cross-service reference - supportReferences: " + bSupportReferences; QUnit.test(sTitle, function (assert) { var mClonedProductScope = clone(mProductScope), oModel = new ODataModel({ // code under test serviceUrl : "/a/b/c/d/e/", supportReferences : bSupportReferences, synchronizationMode : "None" }), sPath = "/tea_busi_product.v0001.Product", sUrl = "/a/default/iwbep/tea_busi_product/0001/$metadata"; this.oMetaModel = oModel.getMetaModel(); this.oMetaModelMock = this.mock(this.oMetaModel); bSupportReferences = bSupportReferences !== false; // default is true! assert.strictEqual(this.oMetaModel.bSupportReferences, bSupportReferences); this.expectFetchEntityContainer(mXServiceScope); this.mock(this.oMetaModel.oRequestor).expects("read") .exactly(bSupportReferences ? 1 : 0) .withExactArgs(sUrl) .returns(Promise.resolve(mClonedProductScope)); this.allowWarnings(assert, true); this.oLogMock.expects("warning").exactly(bSupportReferences ? 0 : 1) .withExactArgs("Unknown qualified name " + sPath.slice(1), sPath, sODataMetaModel); // code under test return this.oMetaModel.fetchObject(sPath).then(function (vResult) { assert.strictEqual(vResult, bSupportReferences ? mClonedProductScope["tea_busi_product.v0001.Product"] : undefined); }); }); }); //********************************************************************************************* QUnit.test("getObject, requestObject", function (assert) { return checkGetAndRequest(this, assert, "fetchObject", ["sPath", {/*oContext*/}]); }); //********************************************************************************************* [{ $Type : "Edm.Boolean" },{ $Type : "Edm.Byte" }, { $Type : "Edm.Date" }, { $Type : "Edm.DateTimeOffset" },{ $Precision : 7, $Type : "Edm.DateTimeOffset", __constraints : {precision : 7} }, { $Type : "Edm.Decimal" }, { $Precision : 20, $Scale : 5, $Type : "Edm.Decimal", __constraints : {maximum : "100.00", maximumExclusive : true, minimum : "0.00", precision : 20, scale : 5} }, { $Precision : 20, $Scale : "variable", $Type : "Edm.Decimal", __constraints : {precision : 20, scale : Infinity} }, { $Type : "Edm.Double" }, { $Type : "Edm.Guid" }, { $Type : "Edm.Int16" }, { $Type : "Edm.Int32" }, { $Type : "Edm.Int64" }, { $Type : "Edm.SByte" }, { $Type : "Edm.Single" }, { $Type : "Edm.Stream" }, { $Type : "Edm.String" }, { $MaxLength : 255, $Type : "Edm.String", __constraints : {maxLength : 255} }, { $Type : "Edm.String", __constraints : {isDigitSequence : true} }, { $Type : "Edm.TimeOfDay" }, { $Precision : 3, $Type : "Edm.TimeOfDay", __constraints : {precision : 3} }].forEach(function (oProperty0) { // Note: take care not to modify oProperty0, clone it first! [false, true].forEach(function (bNullable) { // Note: JSON.parse(JSON.stringify(...)) cannot clone Infinity! var oProperty = jQuery.extend(true, {}, oProperty0), oConstraints = oProperty.__constraints; delete oProperty.__constraints; if (!bNullable) { oProperty.$Nullable = false; oConstraints = oConstraints || {}; oConstraints.nullable = false; } QUnit.test("fetchUI5Type: " + JSON.stringify(oProperty), function (assert) { // Note: just spy on fetchModule() to make sure that the real types are used // which check correctness of constraints var fnFetchModuleSpy = this.spy(this.oMetaModel, "fetchModule"), sPath = "/EMPLOYEES/0/ENTRYDATE", oMetaContext = this.oMetaModel.getMetaContext(sPath), that = this; this.oMetaModelMock.expects("fetchObject").twice() .withExactArgs(undefined, oMetaContext) .returns(SyncPromise.resolve(oProperty)); if (oProperty.$Type === "Edm.String") { // simulate annotation for strings this.oMetaModelMock.expects("fetchObject") .withExactArgs("@com.sap.vocabularies.Common.v1.IsDigitSequence", oMetaContext) .returns( SyncPromise.resolve(oConstraints && oConstraints.isDigitSequence)); } else if (oProperty.$Type === "Edm.Decimal") { // simulate annotation for decimals this.oMetaModelMock.expects("fetchObject") .withExactArgs("@Org.OData.Validation.V1.Minimum/$Decimal", oMetaContext) .returns( SyncPromise.resolve(oConstraints && oConstraints.minimum)); this.oMetaModelMock.expects("fetchObject") .withExactArgs( "@Org.OData.Validation.V1.Minimum@Org.OData.Validation.V1.Exclusive", oMetaContext) .returns( SyncPromise.resolve(oConstraints && oConstraints.minimumExlusive)); this.oMetaModelMock.expects("fetchObject") .withExactArgs("@Org.OData.Validation.V1.Maximum/$Decimal", oMetaContext) .returns( SyncPromise.resolve(oConstraints && oConstraints.maximum)); this.oMetaModelMock.expects("fetchObject") .withExactArgs( "@Org.OData.Validation.V1.Maximum@Org.OData.Validation.V1.Exclusive", oMetaContext) .returns( SyncPromise.resolve(oConstraints && oConstraints.maximumExclusive)); } // code under test return this.oMetaModel.fetchUI5Type(sPath).then(function (oType) { var sExpectedTypeName = "sap.ui.model.odata.type." + oProperty.$Type.slice(4)/*cut off "Edm."*/; assert.strictEqual(fnFetchModuleSpy.callCount, 1); assert.ok(fnFetchModuleSpy.calledOn(that.oMetaModel)); assert.ok(fnFetchModuleSpy.calledWithExactly(sExpectedTypeName), fnFetchModuleSpy.printf("%C")); assert.strictEqual(oType.getName(), sExpectedTypeName); assert.deepEqual(oType.oConstraints, oConstraints); assert.strictEqual(that.oMetaModel.getUI5Type(sPath), oType, "cached"); }); }); }); }); //TODO later: support for facet DefaultValue? //********************************************************************************************* QUnit.test("fetchUI5Type: $count", function (assert) { var sPath = "/T€AMS/$count", oType; // code under test oType = this.oMetaModel.fetchUI5Type(sPath).getResult(); assert.strictEqual(oType.getName(), "sap.ui.model.odata.type.Int64"); assert.strictEqual(this.oMetaModel.getUI5Type(sPath), oType, "cached"); }); //********************************************************************************************* QUnit.test("fetchUI5Type: collection", function (assert) { var sPath = "/EMPLOYEES/0/foo", that = this; this.oMetaModelMock.expects("fetchObject").thrice() .withExactArgs(undefined, this.oMetaModel.getMetaContext(sPath)) .returns(SyncPromise.resolve({ $isCollection : true, $Nullable : false, // must not be turned into a constraint for Raw! $Type : "Edm.String" })); this.oLogMock.expects("warning").withExactArgs( "Unsupported collection type, using sap.ui.model.odata.type.Raw", sPath, sODataMetaModel); return Promise.all([ // code under test this.oMetaModel.fetchUI5Type(sPath).then(function (oType) { assert.strictEqual(oType.getName(), "sap.ui.model.odata.type.Raw"); assert.strictEqual(that.oMetaModel.getUI5Type(sPath), oType, "cached"); }), // code under test this.oMetaModel.fetchUI5Type(sPath).then(function (oType) { assert.strictEqual(oType.getName(), "sap.ui.model.odata.type.Raw"); }) ]); }); //********************************************************************************************* //TODO make Edm.Duration work with OData V4 ["acme.Type", "Edm.Duration", "Edm.GeographyPoint"].forEach(function (sQualifiedName) { QUnit.test("fetchUI5Type: unsupported type " + sQualifiedName, function (assert) { var sPath = "/EMPLOYEES/0/foo", that = this; this.oMetaModelMock.expects("fetchObject").twice() .withExactArgs(undefined, this.oMetaModel.getMetaContext(sPath)) .returns(SyncPromise.resolve({ $Nullable : false, // must not be turned into a constraint for Raw! $Type : sQualifiedName })); this.oLogMock.expects("warning").withExactArgs( "Unsupported type '" + sQualifiedName + "', using sap.ui.model.odata.type.Raw", sPath, sODataMetaModel); // code under test return this.oMetaModel.fetchUI5Type(sPath).then(function (oType) { assert.strictEqual(oType.getName(), "sap.ui.model.odata.type.Raw"); assert.strictEqual(that.oMetaModel.getUI5Type(sPath), oType, "cached"); }); }); }); //********************************************************************************************* QUnit.test("fetchUI5Type: invalid path", function (assert) { var sPath = "/EMPLOYEES/0/invalid", that = this; this.oMetaModelMock.expects("fetchObject").twice() .withExactArgs(undefined, this.oMetaModel.getMetaContext(sPath)) .returns(SyncPromise.resolve(/*no property metadata for path*/)); this.oLogMock.expects("warning").twice().withExactArgs( "No metadata for path '" + sPath + "', using sap.ui.model.odata.type.Raw", undefined, sODataMetaModel); // code under test return this.oMetaModel.fetchUI5Type(sPath).then(function (oType) { assert.strictEqual(oType.getName(), "sap.ui.model.odata.type.Raw"); // code under test assert.strictEqual(that.oMetaModel.getUI5Type(sPath), oType, "Type is cached"); }); }); //********************************************************************************************* QUnit.test("getUI5Type, requestUI5Type", function (assert) { return checkGetAndRequest(this, assert, "fetchUI5Type", ["sPath"], true); }); //********************************************************************************************* [{ // simple entity from a set dataPath : "/TEAMS/0", canonicalUrl : "/TEAMS(~1)", requests : [{ entityType : "tea_busi.TEAM", predicate : "(~1)" }] }, { // simple entity in transient context dataPath : "/TEAMS/-1", canonicalUrl : "/TEAMS(~1)", requests : [{ entityType : "tea_busi.TEAM", // TODO a transient entity does not necessarily have all key properties, but this is // required to create a dependent cache predicate : "(~1)" }] }, { // simple entity by key predicate dataPath : "/TEAMS('4%3D2')", canonicalUrl : "/TEAMS('4%3D2')", requests : [] }, { // simple singleton dataPath : "/Me", canonicalUrl : "/Me", requests : [] }, { // navigation to root entity dataPath : "/TEAMS/0/TEAM_2_EMPLOYEES/1", canonicalUrl : "/EMPLOYEES(~1)", requests : [{ entityType : "tea_busi.Worker", predicate : "(~1)" }] }, { // navigation to root entity dataPath : "/TEAMS('42')/TEAM_2_EMPLOYEES/1", canonicalUrl : "/EMPLOYEES(~1)", requests : [{ entityType : "tea_busi.Worker", predicate : "(~1)" }] }, { // navigation to root entity with key predicate dataPath : "/TEAMS('42')/TEAM_2_EMPLOYEES('23')", canonicalUrl : "/EMPLOYEES('23')", requests : [] }, { // multiple navigation to root entity dataPath : "/TEAMS/0/TEAM_2_EMPLOYEES/1/EMPLOYEE_2_TEAM", canonicalUrl : "/T%E2%82%ACAMS(~1)", requests : [{ entityType : "tea_busi.TEAM", predicate : "(~1)" }] }, { // navigation from entity set to single contained entity dataPath : "/TEAMS/0/TEAM_2_CONTAINED_S", canonicalUrl : "/TEAMS(~1)/TEAM_2_CONTAINED_S", requests : [{ entityType : "tea_busi.TEAM", path : "/TEAMS/0", predicate : "(~1)" }] }, { // navigation from singleton to single contained entity dataPath : "/Me/EMPLOYEE_2_CONTAINED_S", canonicalUrl : "/Me/EMPLOYEE_2_CONTAINED_S", requests : [] }, { // navigation to contained entity within a collection dataPath : "/TEAMS/0/TEAM_2_CONTAINED_C/1", canonicalUrl : "/TEAMS(~1)/TEAM_2_CONTAINED_C(~2)", requests : [{ entityType : "tea_busi.TEAM", path : "/TEAMS/0", predicate : "(~1)" }, { entityType : "tea_busi.ContainedC", path : "/TEAMS/0/TEAM_2_CONTAINED_C/1", predicate : "(~2)" }] }, { // navigation to contained entity with a key predicate dataPath : "/TEAMS('42')/TEAM_2_CONTAINED_C('foo')", canonicalUrl : "/TEAMS('42')/TEAM_2_CONTAINED_C('foo')", requests : [] }, { // navigation from contained entity to contained entity dataPath : "/TEAMS/0/TEAM_2_CONTAINED_S/S_2_C/1", canonicalUrl : "/TEAMS(~1)/TEAM_2_CONTAINED_S/S_2_C(~2)", requests : [{ entityType : "tea_busi.TEAM", path : "/TEAMS/0", predicate : "(~1)" }, { entityType : "tea_busi.ContainedC", path : "/TEAMS/0/TEAM_2_CONTAINED_S/S_2_C/1", predicate : "(~2)" }] }, { // navigation from contained to root entity // must be appended nevertheless since we only have a type, but no set dataPath : "/TEAMS/0/TEAM_2_CONTAINED_C/5/C_2_EMPLOYEE", canonicalUrl : "/TEAMS(~1)/TEAM_2_CONTAINED_C(~2)/C_2_EMPLOYEE", requests : [{ entityType : "tea_busi.TEAM", path : "/TEAMS/0", predicate : "(~1)" }, { entityType : "tea_busi.ContainedC", path : "/TEAMS/0/TEAM_2_CONTAINED_C/5", predicate : "(~2)" }] }, { // navigation from entity w/ key predicate to contained to root entity dataPath : "/TEAMS('42')/TEAM_2_CONTAINED_C/5/C_2_EMPLOYEE", canonicalUrl : "/TEAMS('42')/TEAM_2_CONTAINED_C(~1)/C_2_EMPLOYEE", requests : [{ entityType : "tea_busi.ContainedC", path : "/TEAMS('42')/TEAM_2_CONTAINED_C/5", predicate : "(~1)" }] }, { // decode entity set initially, encode it finally dataPath : "/T%E2%82%ACAMS/0", canonicalUrl : "/T%E2%82%ACAMS(~1)", requests : [{ entityType : "tea_busi.TEAM", predicate : "(~1)" }] }, { // decode navigation property, encode entity set when building sCandidate dataPath : "/EMPLOYEES('7')/EMPLOYEE_2_EQUIPM%E2%82%ACNTS(42)", canonicalUrl : "/EQUIPM%E2%82%ACNTS(42)", requests : [] }].forEach(function (oFixture) { QUnit.test("fetchCanonicalPath: " + oFixture.dataPath, function (assert) { var oContext = Context.create(this.oModel, undefined, oFixture.dataPath), oContextMock = this.mock(oContext), oPromise; this.oMetaModelMock.expects("getMetaPath").withExactArgs(oFixture.dataPath) .returns("metapath"); this.oMetaModelMock.expects("fetchObject").withExactArgs("metapath") .returns(SyncPromise.resolve()); this.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mScope)); oFixture.requests.forEach(function (oRequest) { var oEntityInstance = {"@$ui5._" : {"predicate" : oRequest.predicate}}; oContextMock.expects("fetchValue") .withExactArgs(oRequest.path || oFixture.dataPath) .returns(SyncPromise.resolve(oEntityInstance)); }); // code under test oPromise = this.oMetaModel.fetchCanonicalPath(oContext); assert.ok(!oPromise.isRejected()); return oPromise.then(function (sCanonicalUrl) { assert.strictEqual(sCanonicalUrl, oFixture.canonicalUrl); }); }); }); //********************************************************************************************* [{ // simple singleton path : "/Me|ID", editUrl : "Me" }, { // simple entity by key predicate path : "/TEAMS('42')|Name", editUrl : "TEAMS('42')" }, { // simple entity from a set path : "/TEAMS/0|Name", fetchPredicates : { "/TEAMS/0" : "tea_busi.TEAM" }, editUrl : "TEAMS(~0)" }, { // simple entity from a set, complex property path : "/EMPLOYEES/0|SAL%C3%83RY/CURRENCY", fetchPredicates : { "/EMPLOYEES/0" : "tea_busi.Worker" }, editUrl : "EMPLOYEES(~0)" }, { // navigation to root entity path : "/TEAMS/0/TEAM_2_EMPLOYEES/1|ID", fetchPredicates : { "/TEAMS/0/TEAM_2_EMPLOYEES/1" : "tea_busi.Worker" }, editUrl : "EMPLOYEES(~0)" }, { // navigation to root entity path : "/TEAMS('42')/TEAM_2_EMPLOYEES/1|ID", fetchPredicates : { "/TEAMS('42')/TEAM_2_EMPLOYEES/1" : "tea_busi.Worker" }, editUrl : "EMPLOYEES(~0)" }, { // navigation to root entity with key predicate path : "/TEAMS('42')/TEAM_2_EMPLOYEES('23')|ID", editUrl : "EMPLOYEES('23')" }, { // multiple navigation to root entity path : "/TEAMS/0/TEAM_2_EMPLOYEES/1/EMPLOYEE_2_TEAM|Name", fetchPredicates : { "/TEAMS/0/TEAM_2_EMPLOYEES/1/EMPLOYEE_2_TEAM" : "tea_busi.TEAM" }, editUrl : "T%E2%82%ACAMS(~0)" }, { // navigation from entity set to single contained entity path : "/TEAMS/0/TEAM_2_CONTAINED_S|Id", fetchPredicates : { "/TEAMS/0" : "tea_busi.TEAM" }, editUrl : "TEAMS(~0)/TEAM_2_CONTAINED_S" }, { // navigation from singleton to single contained entity path : "/Me/EMPLOYEE_2_CONTAINED_S|Id", editUrl : "Me/EMPLOYEE_2_CONTAINED_S" }, { // navigation to contained entity within a collection path : "/TEAMS/0/TEAM_2_CONTAINED_C/1|Id", fetchPredicates : { "/TEAMS/0" : "tea_busi.TEAM", "/TEAMS/0/TEAM_2_CONTAINED_C/1" : "tea_busi.ContainedC" }, editUrl : "TEAMS(~0)/TEAM_2_CONTAINED_C(~1)" }, { // navigation to contained entity with a key predicate path : "/TEAMS('42')/TEAM_2_CONTAINED_C('foo')|Id", editUrl : "TEAMS('42')/TEAM_2_CONTAINED_C('foo')" }, { // navigation from contained entity to contained entity path : "/TEAMS/0/TEAM_2_CONTAINED_S/S_2_C/1|Id", fetchPredicates : { "/TEAMS/0" : "tea_busi.TEAM", "/TEAMS/0/TEAM_2_CONTAINED_S/S_2_C/1" : "tea_busi.ContainedC" }, editUrl : "TEAMS(~0)/TEAM_2_CONTAINED_S/S_2_C(~1)" }, { // navigation from contained to root entity, resolved via navigation property binding path path : "/TEAMS/0/TEAM_2_CONTAINED_S/S_2_EMPLOYEE|ID", fetchPredicates : { "/TEAMS/0/TEAM_2_CONTAINED_S/S_2_EMPLOYEE" : "tea_busi.Worker" }, editUrl : "EMPLOYEES(~0)" }, { // navigation from entity w/ key predicate to contained to root entity path : "/TEAMS('42')/TEAM_2_CONTAINED_C/5/C_2_EMPLOYEE|ID", fetchPredicates : { "/TEAMS('42')/TEAM_2_CONTAINED_C/5" : "tea_busi.ContainedC" }, editUrl : "TEAMS('42')/TEAM_2_CONTAINED_C(~0)/C_2_EMPLOYEE" }, { // decode entity set initially, encode it finally path : "/T%E2%82%ACAMS/0|Name", fetchPredicates : { "/T%E2%82%ACAMS/0" : "tea_busi.TEAM" }, editUrl : "T%E2%82%ACAMS(~0)" }, { // decode navigation property, encode entity set path : "/EMPLOYEES('7')/EMPLOYEE_2_EQUIPM%E2%82%ACNTS(42)|ID", editUrl : "EQUIPM%E2%82%ACNTS(42)" }].forEach(function (oFixture) { QUnit.test("fetchUpdateData: " + oFixture.path, function (assert) { var i = oFixture.path.indexOf("|"), sContextPath = oFixture.path.slice(0, i), sPropertyPath = oFixture.path.slice(i + 1), oContext = Context.create(this.oModel, undefined, sContextPath), oContextMock = this.mock(oContext), oPromise, that = this; this.oMetaModelMock.expects("getMetaPath") .withExactArgs(oFixture.path.replace("|", "/")).returns("~"); this.oMetaModelMock.expects("fetchObject").withExactArgs("~") .returns(SyncPromise.resolve(Promise.resolve()).then(function () { that.oMetaModelMock.expects("fetchEntityContainer") .returns(SyncPromise.resolve(mScope)); Object.keys(oFixture.fetchPredicates || {}).forEach(function (sPath, i) { var oEntityInstance = {"@$ui5._" : {"predicate" : "(~" + i + ")"}}; // Note: the entity instance is delivered asynchronously oContextMock.expects("fetchValue") .withExactArgs(sPath) .returns(SyncPromise.resolve(Promise.resolve(oEntityInstance))); }); })); // code under test oPromise = this.oMetaModel.fetchUpdateData(sPropertyPath, oContext); assert.ok(!oPromise.isRejected()); return oPromise.then(function (oResult) { assert.strictEqual(oResult.editUrl, oFixture.editUrl); assert.strictEqual(oResult.entityPath, sContextPath); assert.strictEqual(oResult.propertyPath, sPropertyPath); }); }); }); //TODO support collection properties (-> path containing index not leading to predicate) //TODO prefer instance annotation at payload for "odata.editLink"?! //TODO target URLs like "com.sap.gateway.default.iwbep.tea_busi_product.v0001.Container/Products(...)"? //TODO type casts, operations? //********************************************************************************************* QUnit.test("fetchUpdateData: transient entity", function(assert) { var oContext = Context.create(this.oModel, undefined, "/TEAMS/-1"), sPropertyPath = "Name"; this.oMetaModelMock.expects("fetchEntityContainer").twice() .returns(SyncPromise.resolve(mScope)); this.mock(oContext).expects("fetchValue").withExactArgs("/TEAMS/-1") .returns(SyncPromise.resolve({"@$ui5._" : {"transient" : "update"}})); // code under test return this.oMetaModel.fetchUpdateData(sPropertyPath, oContext).then(function (oResult) { assert.deepEqual(oResult, { entityPath : "/TEAMS/-1", editUrl : undefined, propertyPath : "Name" }); }); }); //********************************************************************************************* QUnit.test("fetchUpdateData: fetchObject fails", function(assert) { var oModel = this.oModel, oContext = { getModel : function () { return oModel; } }, oExpectedError = new Error(), oMetaModelMock = this.mock(this.oMetaModel), sPath = "some/invalid/path/to/a/property"; this.mock(oModel).expects("resolve") .withExactArgs(sPath, sinon.match.same(oContext)) .returns("~1"); oMetaModelMock.expects("getMetaPath").withExactArgs("~1").returns("~2"); oMetaModelMock.expects("fetchObject").withExactArgs("~2") .returns(Promise.reject(oExpectedError)); // code under test return this.oMetaModel.fetchUpdateData(sPath, oContext).then(function () { assert.ok(false); }, function (oError) { assert.strictEqual(oError, oExpectedError); }); }); //********************************************************************************************* [{ dataPath : "/Foo/Bar", message : "Not an entity set: Foo", warning : "Unknown child Foo of tea_busi.DefaultContainer" }, { dataPath : "/TEAMS/0/Foo/Bar", message : "Not a (navigation) property: Foo" }, { dataPath : "/TEAMS/0/TEAM_2_CONTAINED_S", instance : undefined, message : "No instance to calculate key predicate at /TEAMS/0" }, { dataPath : "/TEAMS/0/TEAM_2_CONTAINED_S", instance : {}, message : "No key predicate known at /TEAMS/0" }, { dataPath : "/TEAMS/0/TEAM_2_CONTAINED_S", instance : new Error("failed to load team"), message : "failed to load team at /TEAMS/0" }].forEach(function (oFixture) { QUnit.test("fetchUpdateData: " + oFixture.message, function (assert) { var oContext = Context.create(this.oModel, undefined, oFixture.dataPath), oPromise; this.oMetaModelMock.expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(mScope)); if ("instance" in oFixture) { this.mock(oContext).expects("fetchValue") .returns(oFixture.instance instanceof Error ? SyncPromise.reject(oFixture.instance) : SyncPromise.resolve(oFixture.instance)); } if (oFixture.warning) { this.oLogMock.expects("isLoggable") .withExactArgs(jQuery.sap.log.Level.WARNING, sODataMetaModel) .returns(true); this.oLogMock.expects("warning") .withExactArgs(oFixture.warning, oFixture.dataPath, sODataMetaModel); } this.mock(this.oModel).expects("reportError") .withExactArgs(oFixture.message, sODataMetaModel, sinon.match({ message : oFixture.dataPath + ": " + oFixture.message, name : "Error" })); oPromise = this.oMetaModel.fetchUpdateData("", oContext); assert.ok(oPromise.isRejected()); assert.strictEqual(oPromise.getResult().message, oFixture.dataPath + ": " + oFixture.message); oPromise.caught(); // avoid "Uncaught (in promise)" }); }); //********************************************************************************************* QUnit.test("fetchCanonicalPath: success", function(assert) { var oContext = {}; this.mock(this.oMetaModel).expects("fetchUpdateData") .withExactArgs("", sinon.match.same(oContext)) .returns(SyncPromise.resolve(Promise.resolve({ editUrl : "edit('URL')", propertyPath : "" }))); // code under test return this.oMetaModel.fetchCanonicalPath(oContext).then(function (oCanonicalPath) { assert.strictEqual(oCanonicalPath, "/edit('URL')"); }); }); //********************************************************************************************* QUnit.test("fetchCanonicalPath: not an entity", function(assert) { var oContext = { getPath : function () { return "/TEAMS('4711')/Name"; } }; this.mock(this.oMetaModel).expects("fetchUpdateData") .withExactArgs("", sinon.match.same(oContext)) .returns(SyncPromise.resolve(Promise.resolve({ entityPath : "/TEAMS('4711')", editUrl : "TEAMS('4711')", propertyPath : "Name" }))); // code under test return this.oMetaModel.fetchCanonicalPath(oContext).then(function () { assert.ok(false); }, function (oError) { assert.strictEqual(oError.message, "Context " + oContext.getPath() + " does not point to an entity. It should be " + "/TEAMS('4711')"); }); }); //********************************************************************************************* QUnit.test("fetchCanonicalPath: fetchUpdateData fails", function(assert) { var oContext = {}, oExpectedError = new Error(); this.mock(this.oMetaModel).expects("fetchUpdateData") .withExactArgs("", sinon.match.same(oContext)) .returns(SyncPromise.resolve(Promise.reject(oExpectedError))); // code under test return this.oMetaModel.fetchCanonicalPath(oContext).then(function () { assert.ok(false); }, function (oError) { assert.strictEqual(oError, oExpectedError); }); }); //********************************************************************************************* QUnit.test("getProperty = getObject", function (assert) { assert.strictEqual(this.oMetaModel.getProperty, this.oMetaModel.getObject); }); //********************************************************************************************* QUnit.test("bindProperty", function (assert) { var oBinding, oContext = {}, mParameters = {}, sPath = "foo"; // code under test oBinding = this.oMetaModel.bindProperty(sPath, oContext, mParameters); assert.ok(oBinding instanceof PropertyBinding); assert.ok(oBinding.hasOwnProperty("vValue")); assert.strictEqual(oBinding.getContext(), oContext); assert.strictEqual(oBinding.getModel(), this.oMetaModel); assert.strictEqual(oBinding.getPath(), sPath); assert.strictEqual(oBinding.mParameters, mParameters, "mParameters available internally"); assert.strictEqual(oBinding.getValue(), undefined); // code under test: must not call getProperty() again! assert.strictEqual(oBinding.getExternalValue(), undefined); // code under test assert.throws(function () { oBinding.setExternalValue("foo"); }, /Unsupported operation: ODataMetaPropertyBinding#setValue/); }); //********************************************************************************************* [undefined, {}, {$$valueAsPromise : false}].forEach(function (mParameters, i) { QUnit.test("ODataMetaPropertyBinding#checkUpdate: " + i, function (assert) { var oBinding, oContext = {}, sPath = "foo", oValue = {}, oPromise = SyncPromise.resolve(Promise.resolve(oValue)); oBinding = this.oMetaModel.bindProperty(sPath, oContext, mParameters); this.oMetaModelMock.expects("fetchObject") .withExactArgs(sPath, sinon.match.same(oContext), sinon.match.same(mParameters)) .returns(oPromise); this.mock(oBinding).expects("_fireChange") .withExactArgs({reason : ChangeReason.Change}); // code under test oBinding.checkUpdate(); assert.strictEqual(oBinding.getValue(), undefined); oPromise.then(function () { assert.strictEqual(oBinding.getValue(), oValue); }); return oPromise; }); }); //********************************************************************************************* QUnit.test("ODataMetaPropertyBinding#checkUpdate: $$valueAsPromise=true, sync", function (assert) { var oBinding, oContext = {}, mParameters = {$$valueAsPromise : true}, sPath = "foo", oValue = {}, oPromise = SyncPromise.resolve(oValue); oBinding = this.oMetaModel.bindProperty(sPath, oContext, mParameters); this.oMetaModelMock.expects("fetchObject") .withExactArgs(sPath, sinon.match.same(oContext), sinon.match.same(mParameters)) .returns(oPromise); this.mock(oBinding).expects("_fireChange").withExactArgs({reason : ChangeReason.Change}); // code under test oBinding.checkUpdate(); assert.strictEqual(oBinding.getValue(), oValue, "Value sync"); return oPromise; }); //********************************************************************************************* QUnit.test("ODataMetaPropertyBinding#checkUpdate: no event", function (assert) { var oBinding, oContext = {}, mParameters = {}, sPath = "foo", oValue = {}, oPromise = SyncPromise.resolve(Promise.resolve(oValue)); oBinding = this.oMetaModel.bindProperty(sPath, oContext, mParameters); oBinding.vValue = oValue; this.oMetaModelMock.expects("fetchObject") .withExactArgs(sPath, sinon.match.same(oContext), sinon.match.same(mParameters)) .returns(oPromise); this.mock(oBinding).expects("_fireChange").never(); // code under test oBinding.checkUpdate(); return oPromise; }); //********************************************************************************************* QUnit.test("ODataMetaPropertyBinding#checkUpdate: bForceUpdate, sChangeReason", function (assert) { var oBinding, oContext = {}, mParameters = {}, sPath = "foo", oValue = {}, oPromise = SyncPromise.resolve(Promise.resolve(oValue)); oBinding = this.oMetaModel.bindProperty(sPath, oContext, mParameters); oBinding.vValue = oValue; this.oMetaModelMock.expects("fetchObject") .withExactArgs(sPath, sinon.match.same(oContext), sinon.match.same(mParameters)) .returns(oPromise); this.mock(oBinding).expects("_fireChange").withExactArgs({reason : "Foo"}); // code under test oBinding.checkUpdate(true, "Foo"); return oPromise; }); //********************************************************************************************* QUnit.test("ODataMetaPropertyBinding#checkUpdate: $$valueAsPromise = true", function (assert) { var oBinding, oContext = {}, mParameters = { $$valueAsPromise : true }, sPath = "foo", oValue = {}, oPromise = SyncPromise.resolve(Promise.resolve(oValue)); oBinding = this.oMetaModel.bindProperty(sPath, oContext, mParameters); oBinding.vValue = oValue; this.oMetaModelMock.expects("fetchObject") .withExactArgs(sPath, sinon.match.same(oContext), sinon.match.same(mParameters)) .returns(oPromise); this.mock(oBinding).expects("_fireChange") .withExactArgs({reason : "Foo"}) .twice() .onFirstCall().callsFake(function () { assert.ok(oBinding.getValue().isPending(), "Value is still a pending SyncPromise"); }) .onSecondCall().callsFake(function () { assert.strictEqual(oBinding.getValue(), oValue, "Value resolved"); }); // code under test oBinding.checkUpdate(false, "Foo"); assert.ok(oBinding.getValue().isPending(), "Value is a pending SyncPromise"); return oBinding.getValue().then(function (oResult) { assert.strictEqual(oResult, oValue); assert.strictEqual(oBinding.getValue(), oValue); }); }); //********************************************************************************************* QUnit.test("ODataMetaPropertyBinding#setContext", function (assert) { var oBinding, oBindingMock, oContext = {}; oBinding = this.oMetaModel.bindProperty("Foo", oContext); oBindingMock = this.mock(oBinding); oBindingMock.expects("checkUpdate").never(); // code under test oBinding.setContext(oContext); oBindingMock.expects("checkUpdate").withExactArgs(false, ChangeReason.Context); // code under test oBinding.setContext(undefined); assert.strictEqual(oBinding.getContext(), undefined); oBinding = this.oMetaModel.bindProperty("/Foo"); this.mock(oBinding).expects("checkUpdate").never(); // code under test oBinding.setContext(oContext); }); //********************************************************************************************* ["ENTRYDATE", "/EMPLOYEES/ENTRYDATE"].forEach(function (sPath) { QUnit.test("bindContext: " + sPath, function (assert) { var bAbsolutePath = sPath[0] === "/", oBinding, oBoundContext, iChangeCount = 0, oContext = this.oMetaModel.getMetaContext("/EMPLOYEES"), oContextCopy = this.oMetaModel.getMetaContext("/EMPLOYEES"), oNewContext = this.oMetaModel.getMetaContext("/T€AMS"); // without context oBinding = this.oMetaModel.bindContext(sPath, null); assert.ok(oBinding instanceof ContextBinding); assert.strictEqual(oBinding.getModel(), this.oMetaModel); assert.strictEqual(oBinding.getPath(), sPath); assert.strictEqual(oBinding.getContext(), null); assert.strictEqual(oBinding.isInitial(), true); assert.strictEqual(oBinding.getBoundContext(), null); // with context oBinding = this.oMetaModel.bindContext(sPath, oContextCopy); assert.ok(oBinding instanceof ContextBinding); assert.strictEqual(oBinding.getModel(), this.oMetaModel); assert.strictEqual(oBinding.getPath(), sPath); assert.strictEqual(oBinding.getContext(), oContextCopy); assert.strictEqual(oBinding.isInitial(), true); assert.strictEqual(oBinding.getBoundContext(), null); // setContext ********** oBinding.attachChange(function (oEvent) { assert.strictEqual(oEvent.getId(), "change"); iChangeCount += 1; }); // code under test oBinding.setContext(oContext); assert.strictEqual(iChangeCount, 0, "still initial"); assert.strictEqual(oBinding.isInitial(), true); assert.strictEqual(oBinding.getBoundContext(), null); assert.strictEqual(oBinding.getContext(), oContext); // code under test oBinding.initialize(); assert.strictEqual(iChangeCount, 1, "ManagedObject relies on 'change' event!"); assert.strictEqual(oBinding.isInitial(), false); oBoundContext = oBinding.getBoundContext(); assert.strictEqual(oBoundContext.getModel(), this.oMetaModel); assert.strictEqual(oBoundContext.getPath(), bAbsolutePath ? sPath : oContext.getPath() + "/" + sPath); // code under test - same context oBinding.setContext(oContext); assert.strictEqual(iChangeCount, 1, "context unchanged"); assert.strictEqual(oBinding.getBoundContext(), oBoundContext); // code under test oBinding.setContext(oContextCopy); assert.strictEqual(iChangeCount, 1, "context unchanged"); assert.strictEqual(oBinding.getBoundContext(), oBoundContext); // code under test // Note: checks equality on resolved path, not simply object identity of context! oBinding.setContext(oNewContext); if (bAbsolutePath) { assert.strictEqual(iChangeCount, 1, "context unchanged"); assert.strictEqual(oBinding.getBoundContext(), oBoundContext); } else { assert.strictEqual(iChangeCount, 2, "context changed"); oBoundContext = oBinding.getBoundContext(); assert.strictEqual(oBoundContext.getModel(), this.oMetaModel); assert.strictEqual(oBoundContext.getPath(), oNewContext.getPath() + "/" + sPath); } // code under test oBinding.setContext(null); if (bAbsolutePath) { assert.strictEqual(iChangeCount, 1, "context unchanged"); assert.strictEqual(oBinding.getBoundContext(), oBoundContext); } else { assert.strictEqual(iChangeCount, 3, "context changed"); assert.strictEqual(oBinding.isInitial(), false); assert.strictEqual(oBinding.getBoundContext(), null); } }); }); //********************************************************************************************* QUnit.test("bindList", function (assert) { var oBinding, oContext = this.oMetaModel.getContext("/EMPLOYEES"), aFilters = [], sPath = "@", aSorters = []; // avoid request to backend during initialization this.oMetaModelMock.expects("fetchObject").returns(SyncPromise.resolve()); // code under test oBinding = this.oMetaModel.bindList(sPath, oContext, aSorters, aFilters); assert.ok(oBinding instanceof ClientListBinding); assert.strictEqual(oBinding.getModel(), this.oMetaModel); assert.strictEqual(oBinding.getPath(), sPath); assert.strictEqual(oBinding.getContext(), oContext); assert.strictEqual(oBinding.aSorters, aSorters); assert.strictEqual(oBinding.aApplicationFilters, aFilters); }); //********************************************************************************************* QUnit.test("ODataMetaListBinding#setContexts", function (assert) { var oBinding, oBindingMock, oContext = this.oMetaModel.getContext("/EMPLOYEES"), aContexts = [], sPath = "path"; // avoid request to backend during initialization this.oMetaModelMock.expects("fetchObject").returns(SyncPromise.resolve()); oBinding = this.oMetaModel.bindList(sPath, oContext); oBindingMock = this.mock(oBinding); oBindingMock.expects("updateIndices").withExactArgs(); oBindingMock.expects("applyFilter").withExactArgs(); oBindingMock.expects("applySort").withExactArgs(); oBindingMock.expects("_getLength").withExactArgs().returns(42); // code under test oBinding.setContexts(aContexts); assert.strictEqual(oBinding.oList, aContexts); assert.strictEqual(oBinding.iLength, 42); }); //********************************************************************************************* QUnit.test("ODataMetaListBinding#update (sync)", function (assert) { var oBinding, oBindingMock, oContext = this.oMetaModel.getContext("/EMPLOYEES"), aContexts = [{}], sPath = "path"; // avoid request to backend during initialization this.oMetaModelMock.expects("fetchObject").returns(SyncPromise.resolve()); oBinding = this.oMetaModel.bindList(sPath, oContext); oBindingMock = this.mock(oBinding); oBindingMock.expects("fetchContexts").withExactArgs() .returns(SyncPromise.resolve(aContexts)); oBindingMock.expects("setContexts").withExactArgs(sinon.match.same(aContexts)); oBindingMock.expects("_fireChange").never(); // code under test oBinding.update(); }); //********************************************************************************************* QUnit.test("ODataMetaListBinding#update (async)", function (assert) { var oBinding, oBindingMock, oContext = this.oMetaModel.getContext("/EMPLOYEES"), aContexts = [{}], sPath = "path", oFetchPromise = SyncPromise.resolve(Promise.resolve()).then(function () { // This is expected to happen after the promise is resolved oBindingMock.expects("setContexts").withExactArgs(sinon.match.same(aContexts)); oBindingMock.expects("_fireChange").withExactArgs({reason : ChangeReason.Change}); return aContexts; }); // avoid request to backend during initialization this.oMetaModelMock.expects("fetchObject").returns(SyncPromise.resolve()); oBinding = this.oMetaModel.bindList(sPath, oContext); oBindingMock = this.mock(oBinding); oBindingMock.expects("fetchContexts").withExactArgs().returns(oFetchPromise); oBindingMock.expects("setContexts").withExactArgs([]); oBindingMock.expects("_fireChange").never(); // initially // code under test oBinding.update(); return oFetchPromise; }); //********************************************************************************************* QUnit.test("ODataMetaListBinding#checkUpdate", function (assert) { var oBinding, oBindingMock, oContext = this.oMetaModel.getContext("/"), sPath = ""; // avoid request to backend during initialization this.oMetaModelMock.expects("fetchObject").returns(SyncPromise.resolve()); oBinding = this.oMetaModel.bindList(sPath, oContext); oBindingMock = this.mock(oBinding); this.mock(oBinding).expects("update").thrice().callsFake(function () { this.oList = [{/*a context*/}]; }); oBindingMock.expects("_fireChange").withExactArgs({reason : ChangeReason.Change}); // code under test oBinding.checkUpdate(); // code under test: The second call must call update, but not fire an event oBinding.checkUpdate(); oBindingMock.expects("_fireChange").withExactArgs({reason : ChangeReason.Change}); // code under test: Must fire a change event oBinding.checkUpdate(true); }); //********************************************************************************************* QUnit.test("ODataMetaListBinding#getContexts, getCurrentContexts", function (assert) { var oBinding, oMetaModel = this.oMetaModel, // instead of "that = this" oContext = oMetaModel.getMetaContext("/EMPLOYEES"), sPath = ""; function assertContextPaths(aContexts, aPaths) { assert.notOk("diff" in aContexts, "extended change detection is ignored"); assert.deepEqual(aContexts.map(function (oContext) { assert.strictEqual(oContext.getModel(), oMetaModel); return oContext.getPath().replace("/EMPLOYEES/", ""); }), aPaths); assert.deepEqual(oBinding.getCurrentContexts(), aContexts); } this.oMetaModelMock.expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(mScope)); oBinding = oMetaModel.bindList(sPath, oContext); // code under test: should be ignored oBinding.enableExtendedChangeDetection(); assertContextPaths(oBinding.getContexts(0, 2), ["ID", "AGE"]); assertContextPaths(oBinding.getContexts(1, 2), ["AGE", "EMPLOYEE_2_CONTAINED_S"]); assertContextPaths(oBinding.getContexts(), ["ID", "AGE", "EMPLOYEE_2_CONTAINED_S", "EMPLOYEE_2_EQUIPM€NTS", "EMPLOYEE_2_TEAM", "SALÃRY"]); assertContextPaths(oBinding.getContexts(0, 10), ["ID", "AGE", "EMPLOYEE_2_CONTAINED_S", "EMPLOYEE_2_EQUIPM€NTS", "EMPLOYEE_2_TEAM", "SALÃRY"]); oMetaModel.setSizeLimit(2); assertContextPaths(oBinding.getContexts(), ["ID", "AGE"]); oBinding.attachEvent("sort", function () { assert.ok(false, "unexpected sort event"); }); oMetaModel.setSizeLimit(100); oBinding.sort(new Sorter("@sapui.name")); assertContextPaths(oBinding.getContexts(), ["AGE", "EMPLOYEE_2_CONTAINED_S", "EMPLOYEE_2_EQUIPM€NTS", "EMPLOYEE_2_TEAM", "ID", "SALÃRY"]); oBinding.attachEvent("filter", function () { assert.ok(false, "unexpected filter event"); }); oBinding.filter(new Filter("$kind", "EQ", "Property")); assertContextPaths(oBinding.getContexts(), ["AGE", "ID", "SALÃRY"]); }); //********************************************************************************************* [{ contextPath : undefined, metaPath : "@", result : [] }, { // <template:repeat list="{entitySet>}" ...> // Iterate all OData path segments, i.e. (navigation) properties. // Implicit $Type insertion happens here! //TODO support for $BaseType contextPath : "/EMPLOYEES", metaPath : "", result : [ "/EMPLOYEES/ID", "/EMPLOYEES/AGE", "/EMPLOYEES/EMPLOYEE_2_CONTAINED_S", "/EMPLOYEES/EMPLOYEE_2_EQUIPM€NTS", "/EMPLOYEES/EMPLOYEE_2_TEAM", "/EMPLOYEES/SALÃRY" ] }, { // <template:repeat list="{meta>EMPLOYEES}" ...> // same as before, but with non-empty path contextPath : "/", metaPath : "EMPLOYEES", result : [ "/EMPLOYEES/ID", "/EMPLOYEES/AGE", "/EMPLOYEES/EMPLOYEE_2_CONTAINED_S", "/EMPLOYEES/EMPLOYEE_2_EQUIPM€NTS", "/EMPLOYEES/EMPLOYEE_2_TEAM", "/EMPLOYEES/SALÃRY" ] }, { // <template:repeat list="{meta>/}" ...> // Iterate all OData path segments, i.e. entity sets and imports. // Implicit scope lookup happens here! metaPath : "/", result :[ "/ChangeManagerOfTeam", "/EMPLOYEES", "/EQUIPM€NTS", "/GetEmployeeMaxAge", "/Me", "/OverloadedAction", "/TEAMS", "/T€AMS", "/VoidAction" ] }, { // <template:repeat list="{property>@}" ...> // Iterate all external targeting annotations. contextPath : "/T€AMS/Team_Id", metaPath : "@", result : [ "/T€AMS/[email protected]", "/T€AMS/[email protected]", "/T€AMS/[email protected]@UI.TextArrangement" ] }, { // <template:repeat list="{property>@}" ...> // Iterate all external targeting annotations. contextPath : "/T€AMS/Name", metaPath : "@", result : [] }, { // <template:repeat list="{field>./@}" ...> // Iterate all inline annotations. contextPath : "/T€AMS/$Type/@UI.LineItem/0", metaPath : "./@", result : [ "/T€AMS/$Type/@UI.LineItem/0/@UI.Importance" ] }, { // <template:repeat list="{at>}" ...> // Iterate all inline annotations (edge case with empty relative path). contextPath : "/T€AMS/$Type/@UI.LineItem/0/@", metaPath : "", result : [ "/T€AMS/$Type/@UI.LineItem/0/@UI.Importance" ] }, { contextPath : undefined, metaPath : "/Unknown", result : [], warning : ["Unknown child Unknown of tea_busi.DefaultContainer", "/Unknown/"] }].forEach(function (oFixture) { var sPath = oFixture.contextPath ? oFixture.contextPath + "|"/*make cut more visible*/ + oFixture.metaPath : oFixture.metaPath; QUnit.test("ODataMetaListBinding#fetchContexts (sync): " + sPath, function (assert) { var oBinding, oMetaModel = this.oMetaModel, // instead of "that = this" oContext = oFixture.contextPath && oMetaModel.getContext(oFixture.contextPath); if (oFixture.warning) { // Note that _getContexts is called twice in this test: once from bindList via the // constructor, once directly from the test this.oLogMock.expects("isLoggable").twice() .withExactArgs(jQuery.sap.log.Level.WARNING, sODataMetaModel) .returns(true); this.oLogMock.expects("warning").twice() .withExactArgs(oFixture.warning[0], oFixture.warning[1], sODataMetaModel); } this.oMetaModelMock.expects("fetchEntityContainer").atLeast(0) .returns(SyncPromise.resolve(mScope)); oBinding = this.oMetaModel.bindList(oFixture.metaPath, oContext); // code under test assert.deepEqual(oBinding.fetchContexts().getResult().map(function (oContext) { assert.strictEqual(oContext.getModel(), oMetaModel); return oContext.getPath(); }), oFixture.result); }); }); //********************************************************************************************* QUnit.test("ODataMetaListBinding#fetchContexts (async)", function (assert) { var oBinding, oMetaModel = this.oMetaModel, sPath = "/foo"; // Note that fetchObject is called twice in this test: once from bindList via the // constructor, once from fetchContexts this.oMetaModelMock.expects("fetchObject").twice() .withExactArgs(sPath + "/") .returns(SyncPromise.resolve(Promise.resolve({bar: "", baz: ""}))); oBinding = this.oMetaModel.bindList(sPath); return oBinding.fetchContexts().then(function (oResult) { assert.deepEqual(oResult.map(function (oContext) { assert.strictEqual(oContext.getModel(), oMetaModel); return oContext.getPath(); }), ["/foo/bar", "/foo/baz"]); }); }); //TODO iterate mix of inline and external targeting annotations //TODO iterate annotations like "foo@..." for our special cases, e.g. annotations of annotation //********************************************************************************************* QUnit.test("events", function (assert) { assert.throws(function () { this.oMetaModel.attachParseError(); }, new Error("Unsupported event 'parseError': v4.ODataMetaModel#attachEvent")); assert.throws(function () { this.oMetaModel.attachRequestCompleted(); }, new Error("Unsupported event 'requestCompleted': v4.ODataMetaModel#attachEvent")); assert.throws(function () { this.oMetaModel.attachRequestFailed(); }, new Error("Unsupported event 'requestFailed': v4.ODataMetaModel#attachEvent")); assert.throws(function () { this.oMetaModel.attachRequestSent(); }, new Error("Unsupported event 'requestSent': v4.ODataMetaModel#attachEvent")); }); //********************************************************************************************* QUnit.test("validate: mSchema2MetadataUrl", function (assert) { var mScope = { "$Version" : "4.0", "$Reference" : { "/A/$metadata" : { "$Include" : [ "A.", "A.A." ] }, "/B/$metadata" : { "$Include" : [ "B.", "B.B." ] }, "/C/$metadata" : { "$Include" : ["C."] }, "../../../../default/iwbep/tea_busi_product/0001/$metadata" : { "$Include" : [ "tea_busi_product." ] } } }, sUrl = "/~/$metadata"; assert.deepEqual(this.oMetaModel.mSchema2MetadataUrl, {}); // simulate a previous reference to a schema with the _same_ reference URI --> allowed! this.oMetaModel.mSchema2MetadataUrl["A."] = {"/A/$metadata" : false}; // simulate a previous reference to a schema with the _different_ reference URI // --> allowed as long as the document is not yet read (and will never be read) this.oMetaModel.mSchema2MetadataUrl["B.B."] = {"/B/V2/$metadata" : false}; // simulate a previous reference to a schema with the _same_ reference URI, already loaded this.oMetaModel.mSchema2MetadataUrl["C."] = {"/C/$metadata" : true}; // code under test assert.strictEqual(this.oMetaModel.validate(sUrl, mScope), mScope); assert.deepEqual(this.oMetaModel.mSchema2MetadataUrl, { "A." : {"/A/$metadata" : false}, "A.A." : {"/A/$metadata" : false}, "B." : {"/B/$metadata" : false}, "B.B." : { "/B/$metadata" : false, "/B/V2/$metadata" : false }, "C." : {"/C/$metadata" : true}, "tea_busi_product." : {"/a/default/iwbep/tea_busi_product/0001/$metadata" : false} }); }); //********************************************************************************************* QUnit.test("getLastModified", function (assert) { var mEmptyScope = { "$Version" : "4.0" }, mNewScope = { "$Version" : "4.0", "$Date" : "Tue, 18 Apr 2017 14:40:29 GMT" }, iNow = Date.now(), mOldScope = { "$Version" : "4.0", "$Date" : "Tue, 18 Apr 2017 14:40:29 GMT", // $LastModified wins! "$LastModified" : "Fri, 07 Apr 2017 11:21:50 GMT" }, mOldScopeClone = clone(mOldScope), sUrl = "/~/$metadata"; // Note: in real life, each URL is read at most once! // code under test (together with c'tor) assert.strictEqual(this.oMetaModel.getLastModified().getTime(), 0, "initial value"); // code under test assert.strictEqual(this.oMetaModel.validate(sUrl, mOldScope), mOldScope); assert.strictEqual(this.oMetaModel.getLastModified().toISOString(), "2017-04-07T11:21:50.000Z", "old $LastModified is used"); assert.notOk("$LastModified" in mOldScope); // code under test assert.strictEqual(this.oMetaModel.validate(sUrl, mNewScope), mNewScope); assert.strictEqual(this.oMetaModel.getLastModified().toISOString(), "2017-04-18T14:40:29.000Z", "new $Date is used"); assert.notOk("$Date" in mNewScope); // code under test assert.strictEqual(this.oMetaModel.validate(sUrl, mOldScopeClone), mOldScopeClone); assert.strictEqual(this.oMetaModel.getLastModified().toISOString(), "2017-04-18T14:40:29.000Z", "new $Date wins, old $LastModified is ignored"); assert.notOk("$LastModified" in mOldScopeClone); // code under test assert.strictEqual(this.oMetaModel.validate(sUrl, mEmptyScope), mEmptyScope); assert.ok(this.oMetaModel.getLastModified().getTime() >= iNow, "missing $Date/$LastModified is like 'now': " + this.oMetaModel.getLastModified()); }); //********************************************************************************************* QUnit.test("getETags", function (assert) { var sETag = 'W/"..."', mETags, that = this; function codeUnderTest(sUrl, mScope) { // code under test assert.strictEqual(that.oMetaModel.validate(sUrl, mScope), mScope); assert.notOk("$ETag" in mScope); assert.notOk("$LastModified" in mScope); } // code under test (together with c'tor) assert.deepEqual(this.oMetaModel.getETags(), {}, "initial value"); codeUnderTest("/~/A", { "$Version" : "4.0", "$LastModified" : "Fri, 07 Apr 2017 11:21:50 GMT" }); codeUnderTest("/~/B", { "$Version" : "4.0", "$LastModified" : "Tue, 18 Apr 2017 14:40:29 GMT" }); codeUnderTest("/~/C", { "$Version" : "4.0" }); codeUnderTest("/~/D", { "$Version" : "4.0", "$ETag" : sETag }); // code under test mETags = this.oMetaModel.getETags(); assert.deepEqual(mETags, { "/~/A" : new Date(Date.UTC(2017, 3, 7, 11, 21, 50)), "/~/B" : new Date(Date.UTC(2017, 3, 18, 14, 40, 29)), "/~/C" : null, "/~/D" : sETag // wins over null! }); }); //********************************************************************************************* [{ message : "Unsupported IncludeAnnotations", scope : { "$Version" : "4.0", "$Reference" : { "/A/$metadata" : { "$Include" : [ "A." ] }, "/B/$metadata" : { "$IncludeAnnotations" : [{ "$TermNamespace" : "com.sap.vocabularies.Common.v1" }] } } } }, { message : "A schema cannot span more than one document: tea_busi." + " - is both included and defined", scope : { "$Version" : "4.0", "$Reference" : { "/B/$metadata" : { "$Include" : [ "foo.", "tea_busi." ] } }, "tea_busi." : { "$kind" : "Schema" } } }, { message : "A schema cannot span more than one document: existing." + " - expected reference URI /B/v1/$metadata but instead saw /B/v2/$metadata", scope : { "$Version" : "4.0", "$Reference" : { "/A/$metadata" : { "$Include" : [ "foo.", "bar." ] }, "/B/v2/$metadata" : { "$Include" : [ "baz.", "existing." ] } } } }].forEach(function (oFixture) { [false, true].forEach(function (bSupportReferences) { var sMessage = oFixture.message, sTitle = "validate: " + sMessage + ", supportReferences: " + bSupportReferences; QUnit.test(sTitle, function (assert) { var sUrl = "/~/$metadata", that = this; function codeUnderTest() { var oResult = that.oMetaModel.validate(sUrl, oFixture.scope); assert.strictEqual(oResult, oFixture.scope); } this.oMetaModel.bSupportReferences = bSupportReferences; // simulate a schema that has been loaded or referenced before this.oMetaModel.mSchema2MetadataUrl = { // simulate schema that is already read "existing." : {"/B/v1/$metadata" : true} }; if (bSupportReferences) { this.oLogMock.expects("error") .withExactArgs(sMessage, sUrl, sODataMetaModel); } if (bSupportReferences) { assert.throws(codeUnderTest, new Error(sUrl + ": " + sMessage)); } else { codeUnderTest(); } }); }); }); //********************************************************************************************* QUnit.test("_mergeAnnotations: without annotation files", function (assert) { // Note: target elements have been omitted for brevity var mExpectedAnnotations = { "same.target" : { "@Common.Description" : "", "@Common.Label" : { "old" : true // Note: no aggregation of properties here! }, "@Common.Text" : "" }, "another.target" : { "@Common.Label" : "" } }, mScope = { "A." : { "$kind" : "Schema", "$Annotations" : { "same.target" : { "@Common.Label" : { "old" : true }, "@Common.Text" : "" } } }, "B." : { "$kind" : "Schema", "$Annotations" : { "same.target" : { "@Common.Description" : "", "@Common.Label" : { // illegal overwrite within $metadata, ignored! "new" : true } }, "another.target" : { "@Common.Label" : "" } } }, "B.B" : {} }; this.oMetaModelMock.expects("validate") .withExactArgs(this.oMetaModel.sUrl, mScope); assert.deepEqual(this.oMetaModel.mSchema2MetadataUrl, {}); // code under test this.oMetaModel._mergeAnnotations(mScope, []); assert.deepEqual(mScope.$Annotations, mExpectedAnnotations, "$Annotations have been shifted and merged from schemas to root"); assert.notOk("$Annotations" in mScope["A."], "$Annotations removed from schema"); assert.notOk("$Annotations" in mScope["B."], "$Annotations removed from schema"); assert.deepEqual(this.oMetaModel.mSchema2MetadataUrl, { "A." : {"/a/b/c/d/e/$metadata" : false}, "B." : {"/a/b/c/d/e/$metadata" : false} }); }); //********************************************************************************************* QUnit.test("_mergeAnnotations: validation failure for $metadata", function (assert) { var oError = new Error(), mScope = {}; this.oMetaModelMock.expects("validate") .withExactArgs(this.oMetaModel.sUrl, mScope) .throws(oError); assert.throws(function () { // code under test this.oMetaModel._mergeAnnotations(mScope, []); }, oError); }); //********************************************************************************************* QUnit.test("_mergeAnnotations: validation failure in annotation file", function (assert) { var oError = new Error(), mScope = {}, mAnnotationScope1 = {}, mAnnotationScope2 = {}; this.oMetaModel.aAnnotationUris = ["n/a", "/my/annotation.xml"]; this.oMetaModelMock.expects("validate") .withExactArgs(this.oMetaModel.sUrl, mScope); this.oMetaModelMock.expects("validate") .withExactArgs("n/a", mAnnotationScope1); this.oMetaModelMock.expects("validate") .withExactArgs("/my/annotation.xml", mAnnotationScope2) .throws(oError); assert.throws(function () { // code under test this.oMetaModel._mergeAnnotations(mScope, [mAnnotationScope1, mAnnotationScope2]); }, oError); }); //********************************************************************************************* QUnit.test("_mergeAnnotations: with annotation files (legacy)", function (assert) { var sNamespace = "com.sap.gateway.default.iwbep.tea_busi.v0001.", sWorker = sNamespace + "Worker/", sBasicSalaryCurr = sWorker + "SALARY/BASIC_SALARY_CURR", sBasicSalaryCurr2 = "another.schema.2.SALARY/BASIC_SALARY_CURR", sBonusCurr = sWorker + "SALARY/BONUS_CURR", sCommonLabel = "@com.sap.vocabularies.Common.v1.Label", sCommonQuickInfo = "@com.sap.vocabularies.Common.v1.QuickInfo", sCommonText = "@com.sap.vocabularies.Common.v1.Text", sBaseUrl = "/" + window.location.pathname.split("/")[1] + "/test-resources/sap/ui/core/qunit/odata/v4/data/", oMetadata = jQuery.sap.sjax({url : sBaseUrl + "metadata.json", dataType : 'json'}).data, oExpectedResult = clone(oMetadata), oAnnotation = jQuery.sap.sjax({ url : sBaseUrl + "legacy_annotations.json", dataType : 'json' }).data, oAnnotationCopy = clone(oAnnotation); // the examples are unrealistic and only need to work in 'legacy mode' this.oMetaModel.bSupportReferences = false; this.oMetaModel.aAnnotationUris = ["n/a"]; this.oMetaModelMock.expects("validate") .withExactArgs(this.oMetaModel.sUrl, oMetadata); this.oMetaModelMock.expects("validate") .withExactArgs("n/a", oAnnotation); oExpectedResult.$Annotations = oMetadata[sNamespace].$Annotations; delete oExpectedResult[sNamespace].$Annotations; // all entries with $kind are merged oExpectedResult["my.schema.2.FuGetEmployeeMaxAge"] = oAnnotationCopy["my.schema.2.FuGetEmployeeMaxAge"]; oExpectedResult["my.schema.2.Entity"] = oAnnotationCopy["my.schema.2.Entity"]; oExpectedResult["my.schema.2.DefaultContainer"] = oAnnotationCopy["my.schema.2.DefaultContainer"]; oExpectedResult["my.schema.2."] = oAnnotationCopy["my.schema.2."]; oExpectedResult["another.schema.2."] = oAnnotationCopy["another.schema.2."]; // update annotations oExpectedResult.$Annotations[sBasicSalaryCurr][sCommonLabel] = oAnnotationCopy["my.schema.2."].$Annotations[sBasicSalaryCurr][sCommonLabel]; oExpectedResult.$Annotations[sBasicSalaryCurr][sCommonQuickInfo] = oAnnotationCopy["my.schema.2."].$Annotations[sBasicSalaryCurr][sCommonQuickInfo]; oExpectedResult.$Annotations[sBonusCurr][sCommonText] = oAnnotationCopy["my.schema.2."].$Annotations[sBonusCurr][sCommonText]; oExpectedResult.$Annotations[sBasicSalaryCurr2] = oAnnotationCopy["another.schema.2."].$Annotations[sBasicSalaryCurr2]; delete oExpectedResult["my.schema.2."].$Annotations; delete oExpectedResult["another.schema.2."].$Annotations; // code under test this.oMetaModel._mergeAnnotations(oMetadata, [oAnnotation]); assert.deepEqual(oMetadata, oExpectedResult, "merged metadata as expected"); }); //********************************************************************************************* QUnit.test("_mergeAnnotations: with annotation files", function (assert) { var mScope0 = { "$EntityContainer" : "tea_busi.DefaultContainer", "$Reference" : { "../../../../default/iwbep/tea_busi_foo/0001/$metadata" : { "$Include" : [ "tea_busi_foo.v0001." ] } }, "$Version" : "4.0", "tea_busi." : { "$kind" : "Schema", "$Annotations" : { "tea_busi.DefaultContainer" : { "@A" : "from $metadata", "@B" : "from $metadata", "@C" : "from $metadata" }, "tea_busi.TEAM" : { "@D" : ["from $metadata"], "@E" : ["from $metadata"], "@F" : ["from $metadata"] } } }, "tea_busi.DefaultContainer" : { "$kind" : "EntityContainer" }, "tea_busi.EQUIPMENT" : { "$kind" : "EntityType" }, "tea_busi.TEAM" : { "$kind" : "EntityType" }, "tea_busi.Worker" : { "$kind" : "EntityType" } }, mScope1 = { "$Version" : "4.0", "tea_busi_foo.v0001." : { "$kind" : "Schema", "$Annotations" : { "tea_busi_foo.v0001.Product/Name" : { "@Common.Label" : "from $metadata" } } }, "tea_busi_foo.v0001.Product" : { "$kind" : "EntityType", "Name" : { "$kind" : "Property", "$Type" : "Edm.String" } } }, mAnnotationScope1 = { "$Version" : "4.0", "foo." : { "$kind" : "Schema", "$Annotations" : { "tea_busi.DefaultContainer" : { "@B" : "from annotation #1", "@C" : "from annotation #1" }, "tea_busi.TEAM" : { "@E" : ["from annotation #1"], "@F" : ["from annotation #1"] }, "tea_busi.Worker" : { "@From.Annotation" : { "$Type" : "some.Record", "Label" : "from annotation #1" }, "@From.Annotation1" : "from annotation #1" } } } }, mAnnotationScope2 = { "$Version" : "4.0", "bar." : { "$kind" : "Schema", "$Annotations" : { "tea_busi.DefaultContainer" : { "@C" : "from annotation #2" }, "tea_busi.EQUIPMENT" : { "@From.Annotation2" : "from annotation #2" }, "tea_busi.TEAM" : { "@F" : ["from annotation #2"] }, "tea_busi.Worker" : { "@From.Annotation" : { "$Type" : "some.Record", "Value" : "from annotation #2" } }, "tea_busi_foo.v0001.Product/Name" : { "@Common.Label" : "from annotation #2" } } } }, mExpectedScope = { "$Annotations" : { "tea_busi.DefaultContainer" : { "@A" : "from $metadata", "@B" : "from annotation #1", "@C" : "from annotation #2" }, "tea_busi.EQUIPMENT" : { "@From.Annotation2" : "from annotation #2" }, "tea_busi.TEAM" : { // Note: no aggregation of array elements here! "@D" : ["from $metadata"], "@E" : ["from annotation #1"], "@F" : ["from annotation #2"] }, "tea_busi.Worker" : { "@From.Annotation" : { "$Type" : "some.Record", // Note: no "Label" here! "Value" : "from annotation #2" }, "@From.Annotation1" : "from annotation #1" }, "tea_busi_foo.v0001.Product/Name" : { "@Common.Label" : "from annotation #2" } }, "$EntityContainer" : "tea_busi.DefaultContainer", "$Reference" : { "../../../../default/iwbep/tea_busi_foo/0001/$metadata" : { "$Include" : [ "tea_busi_foo.v0001." ] } }, "$Version" : "4.0", "bar." : { "$kind" : "Schema" }, "foo." : { "$kind" : "Schema" }, "tea_busi." : { "$kind" : "Schema" }, "tea_busi.DefaultContainer" : { "$kind" : "EntityContainer" }, "tea_busi.EQUIPMENT" : { "$kind" : "EntityType" }, "tea_busi.TEAM" : { "$kind" : "EntityType" }, "tea_busi.Worker" : { "$kind" : "EntityType" } }; this.oMetaModel.aAnnotationUris = ["/URI/1", "/URI/2"]; this.oMetaModelMock.expects("validate") .withExactArgs(this.oMetaModel.sUrl, mScope0); this.oMetaModelMock.expects("validate") .withExactArgs("/URI/1", mAnnotationScope1); this.oMetaModelMock.expects("validate") .withExactArgs("/URI/2", mAnnotationScope2); assert.deepEqual(this.oMetaModel.mSchema2MetadataUrl, {}); // code under test this.oMetaModel._mergeAnnotations(mScope0, [mAnnotationScope1, mAnnotationScope2]); assert.deepEqual(mScope0, mExpectedScope); assert.strictEqual(mScope0["tea_busi."].$Annotations, undefined); assert.strictEqual(mAnnotationScope1["foo."].$Annotations, undefined); assert.strictEqual(mAnnotationScope2["bar."].$Annotations, undefined); assert.deepEqual(this.oMetaModel.mSchema2MetadataUrl, { "bar." : {"/URI/2" : false}, "foo." : {"/URI/1" : false}, "tea_busi." : {"/a/b/c/d/e/$metadata" : false} }); // prepare to load "cross-service reference" // simulate #validate of mScope0 this.oMetaModel.mSchema2MetadataUrl["tea_busi_foo.v0001."] = {"/a/default/iwbep/tea_busi_foo/0001/$metadata" : false}; this.oMetaModelMock.expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(mScope0)); this.mock(this.oMetaModel.oRequestor).expects("read") .withExactArgs("/a/default/iwbep/tea_busi_foo/0001/$metadata") .returns(Promise.resolve(mScope1)); this.oMetaModelMock.expects("validate") .withExactArgs("/a/default/iwbep/tea_busi_foo/0001/$metadata", mScope1) .returns(mScope1); // code under test return this.oMetaModel.fetchObject("/tea_busi_foo.v0001.Product/[email protected]") .then(function (sLabel) { assert.strictEqual(sLabel, "from annotation #2", "not overwritten by $metadata"); }); }); //********************************************************************************************* QUnit.test("_mergeAnnotations - error (legacy)", function (assert) { var oAnnotation1 = { "tea_busi.NewType1" : { "$kind" : "EntityType" } }, oAnnotation2 = { "tea_busi.NewType2" : { "$kind" : "EntityType" }, "tea_busi.ExistingType" : { "$kind" : "EntityType" } }, sMessage = "A schema cannot span more than one document: tea_busi.ExistingType", oMetadata = { "tea_busi.ExistingType" : { "$kind" : "EntityType" } }; this.oMetaModel.aAnnotationUris = ["n/a", "/my/annotation.xml"]; // legacy behavior: $Version is not checked, tea_busi.NewType2 is allowed this.oMetaModel.bSupportReferences = false; this.oMetaModelMock.expects("validate") .withExactArgs(this.oMetaModel.sUrl, oMetadata); this.oMetaModelMock.expects("validate") .withExactArgs("n/a", oAnnotation1); this.oMetaModelMock.expects("validate") .withExactArgs("/my/annotation.xml", oAnnotation2); this.oLogMock.expects("error") .withExactArgs(sMessage, "/my/annotation.xml", sODataMetaModel); assert.throws(function () { // code under test this.oMetaModel._mergeAnnotations(oMetadata, [oAnnotation1, oAnnotation2]); }, new Error("/my/annotation.xml: " + sMessage)); }); //********************************************************************************************* QUnit.test("_mergeAnnotations - a schema cannot span more than one document", function (assert) { var oAnnotation = { "$Version" : "4.0", "tea_busi." : { "$kind" : "Schema" } }, sMessage = "A schema cannot span more than one document: tea_busi.", oMetadata = { "$Version" : "4.0", "tea_busi." : { "$kind" : "Schema" } }; this.oMetaModel.aAnnotationUris = ["n/a", "/my/annotation.xml"]; this.oLogMock.expects("error") .withExactArgs(sMessage, "/my/annotation.xml", sODataMetaModel); assert.throws(function () { // code under test this.oMetaModel._mergeAnnotations(oMetadata, [{"$Version" : "4.0"}, oAnnotation]); }, new Error("/my/annotation.xml: " + sMessage)); } ); //********************************************************************************************* QUnit.test("getOrCreateValueListModel", function (assert) { var oModel = new ODataModel({ serviceUrl : "/Foo/DataService/", synchronizationMode : "None" }), oMetaModel = oModel.getMetaModel(), oValueListModel; oModel.oRequestor.mHeaders["X-CSRF-Token"] = "xyz"; // code under test oValueListModel = oMetaModel.getOrCreateValueListModel("../ValueListService/$metadata"); assert.ok(oValueListModel instanceof ODataModel); assert.strictEqual(oValueListModel.sServiceUrl, "/Foo/ValueListService/"); assert.strictEqual(oValueListModel.getDefaultBindingMode(), BindingMode.OneWay); assert.strictEqual(oValueListModel.sOperationMode, OperationMode.Server); assert.strictEqual(oValueListModel.oRequestor.mHeaders["X-CSRF-Token"], "xyz"); // code under test assert.strictEqual(oMetaModel.getOrCreateValueListModel("/Foo/ValueListService/$metadata"), oValueListModel); // code under test assert.strictEqual(oValueListModel.getMetaModel() .getOrCreateValueListModel("/Foo/ValueListService/$metadata"), oValueListModel); // code under test assert.strictEqual(oValueListModel.getMetaModel().getOrCreateValueListModel("$metadata"), oValueListModel); oModel = new ODataModel({ serviceUrl : "/Foo/DataService2/", synchronizationMode : "None" }); // code under test - even a totally different model gets the very same value list model assert.strictEqual(oModel.getMetaModel() .getOrCreateValueListModel("../ValueListService/$metadata"), oValueListModel); }); //********************************************************************************************* QUnit.test("getOrCreateValueListModel: relative data service URL", function (assert) { var sRelativePath = "../../../DataService/", sAbsolutePath = new URI(sRelativePath).absoluteTo(document.baseURI).pathname().toString(), oModel = new ODataModel({ serviceUrl : sRelativePath, synchronizationMode : "None" }), oValueListModel; // code under test oValueListModel = oModel.getMetaModel() .getOrCreateValueListModel("../ValueListService/$metadata"); assert.strictEqual(oValueListModel.sServiceUrl, new URI("../ValueListService/").absoluteTo(sAbsolutePath).toString()); }); //********************************************************************************************* QUnit.test("fetchValueListType: unknown property", function (assert) { var oContext = {}, sPath = "/Products('HT-1000')/Foo"; this.oMetaModelMock.expects("getMetaContext").withExactArgs(sPath).returns(oContext); this.oMetaModelMock.expects("fetchObject") .withExactArgs(undefined, sinon.match.same(oContext)) .returns(Promise.resolve()); // code under test return this.oMetaModel.fetchValueListType(sPath).then(function () { assert.ok(false); }, function (oError) { assert.ok(oError.message, "No metadata for " + sPath); }); }); //********************************************************************************************* [{ mAnnotations : { "@some.other.Annotation" : true }, sValueListType : ValueListType.None }, { mAnnotations : { "@com.sap.vocabularies.Common.v1.ValueListReferences" : [], "@com.sap.vocabularies.Common.v1.ValueListWithFixedValues" : true }, sValueListType : ValueListType.Fixed }, { mAnnotations : { "@com.sap.vocabularies.Common.v1.ValueListReferences" : [] }, sValueListType : ValueListType.Standard }, { mAnnotations : { "@com.sap.vocabularies.Common.v1.ValueListReferences#foo" : [], "@com.sap.vocabularies.Common.v1.ValueListWithFixedValues" : false }, sValueListType : ValueListType.Standard }, { mAnnotations : { "@com.sap.vocabularies.Common.v1.ValueListMapping#foo" : {}, "@com.sap.vocabularies.Common.v1.ValueListWithFixedValues" : false }, sValueListType : ValueListType.Standard }].forEach(function (oFixture) { QUnit.test("fetchValueListType: " + oFixture.sValueListType, function (assert) { var oContext = {}, sPropertyPath = "/ProductList('HT-1000')/Status"; this.oMetaModelMock.expects("getMetaContext") .withExactArgs(sPropertyPath).returns(oContext); this.oMetaModelMock.expects("fetchObject") .withExactArgs(undefined, sinon.match.same(oContext)) .returns(SyncPromise.resolve({})); this.oMetaModelMock.expects("getObject") .withExactArgs("@", sinon.match.same(oContext)) .returns(oFixture.mAnnotations); // code under test this.oMetaModel.fetchValueListType(sPropertyPath).then(function (sValueListType) { assert.strictEqual(sValueListType, oFixture.sValueListType); }); }); }); //********************************************************************************************* QUnit.test("getValueListType, requestValueListType", function (assert) { return checkGetAndRequest(this, assert, "fetchValueListType", ["sPath"], true); }); //********************************************************************************************* QUnit.test("fetchValueListMappings: success", function (assert) { var oModel = new ODataModel({ serviceUrl : "/Foo/DataService/", synchronizationMode : "None" }), oMetaModelMock = this.mock(oModel.getMetaModel()), oDefaultMapping = { "CollectionPath" : "VH_Category1Set", "Parameters" : [{"p1" : "foo"}] }, oFooMapping = { "CollectionPath" : "VH_Category2Set", "Parameters" : [{"p2" : "bar"}] }, oProperty = {}, oValueListMetadata = { "$Annotations" : { "zui5_epm_sample.Product/Category" : { "@com.sap.vocabularies.Common.v1.ValueListMapping" : oDefaultMapping, "@com.sap.vocabularies.Common.v1.ValueListMapping#foo" : oFooMapping }, "some.other.Target" : {} } }, oValueListModel = { getMetaModel : function () { return { fetchEntityContainer : function () { return Promise.resolve(oValueListMetadata); } }; } }; oMetaModelMock.expects("getObject") .withExactArgs("/zui5_epm_sample.Product/Category") .returns(oProperty); // code under test return oModel.getMetaModel() .fetchValueListMappings(oValueListModel, "zui5_epm_sample", oProperty) .then(function (oValueListMappings) { assert.deepEqual(oValueListMappings, { "" : oDefaultMapping, "foo" : oFooMapping }); }); }); //********************************************************************************************* [{ annotations : { "zui5_epm_sample.Product/CurrencyCode/type.cast" : true }, error : "Unexpected annotation target 'zui5_epm_sample.Product/CurrencyCode/type.cast' " + "with namespace of data service in /Foo/ValueListService" }, { annotations : { "zui5_epm_sample.Product/Category" : { "@some.other.Term" : true } }, error : "Unexpected annotation 'some.other.Term' for target " + "'zui5_epm_sample.Product/Category' with namespace of data service " + "in /Foo/ValueListService" }, { annotations : {}, error : "No annotation 'com.sap.vocabularies.Common.v1.ValueListMapping' " + "in /Foo/ValueListService" }].forEach(function (oFixture) { QUnit.test("fetchValueListMappings: " + oFixture.error, function (assert) { var oModel = new ODataModel({ serviceUrl : "/Foo/DataService/", synchronizationMode : "None" }), oMetaModel = oModel.getMetaModel(), oMetaModelMock = this.mock(oMetaModel), oProperty = {}, oValueListMetadata = { "$Annotations" : oFixture.annotations }, oValueListModel = { getMetaModel : function () { return { fetchEntityContainer : function () { return Promise.resolve(oValueListMetadata); } }; }, sServiceUrl : "/Foo/ValueListService" }, sTarget = Object.keys(oFixture.annotations)[0]; oMetaModelMock.expects("getObject").atLeast(0) .withExactArgs("/" + sTarget) .returns(sTarget === "zui5_epm_sample.Product/Category" ? oProperty : undefined); // code under test return oMetaModel .fetchValueListMappings(oValueListModel, "zui5_epm_sample", oProperty) .then(function () { assert.ok(false); }, function (oError) { assert.strictEqual(oError.message, oFixture.error); }); }); }); //********************************************************************************************* QUnit.test("fetchValueListMappings: value list model is data model", function (assert) { var oModel = new ODataModel({ serviceUrl : "/Foo/DataService/", synchronizationMode : "None" }), oMetaModelMock = this.mock(oModel.getMetaModel()), oMapping = { "CollectionPath" : "VH_CountrySet", "Parameters" : [{"p1" : "foo"}] }, oProperty = { "$kind" : "Property" }, oMetadata = { "$EntityContainer" : "value_list.Container", "value_list.VH_BusinessPartner" : { "$kind" : "Entity", "Country" : oProperty }, "$Annotations" : { // value list on value list "value_list.VH_BusinessPartner/Country" : { "@com.sap.vocabularies.Common.v1.Label" : "Country", "@com.sap.vocabularies.Common.v1.ValueListMapping" : oMapping }, "value_list.VH_BusinessPartner/Foo" : {/* some other field w/ value list*/} } }; oMetaModelMock.expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(oMetadata)); // code under test return oModel.getMetaModel() .fetchValueListMappings(oModel, "value_list", oProperty) .then(function (oValueListMappings) { assert.deepEqual(oValueListMappings, { "" : oMapping }); }); }); //********************************************************************************************* [{ sPropertyPath : "/EMPLOYEES/unknown", sExpectedError : "No metadata" }, { sPropertyPath : "/EMPLOYEES/AGE", sExpectedError : "No annotation 'com.sap.vocabularies.Common.v1.ValueListReferences'" }].forEach(function (oFixture) { QUnit.test("requestValueListInfo: " + oFixture.sExpectedError, function (assert) { var oModel = new ODataModel({ serviceUrl : "/~/", synchronizationMode : "None" }); this.mock(oModel.getMetaModel()).expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(mScope)); // code under test return oModel.getMetaModel().requestValueListInfo(oFixture.sPropertyPath) .then(function () { assert.ok(false); }, function (oError) { assert.strictEqual(oError.message, oFixture.sExpectedError + " for " + oFixture.sPropertyPath); }); }); }); //********************************************************************************************* [false, true].forEach(function (bDuplicate) { QUnit.test("requestValueListInfo: duplicate=" + bDuplicate, function (assert) { var sMappingUrl1 = "../ValueListService1/$metadata", sMappingUrl2 = "../ValueListService2/$metadata", sMappingUrlBar = "../ValueListServiceBar/$metadata", oModel = new ODataModel({ serviceUrl : "/Foo/DataService/", synchronizationMode : "None" }), oMetaModelMock = this.mock(oModel.getMetaModel()), oProperty = { "$kind" : "Property" }, sPropertyPath = "/ProductList('HT-1000')/Category", oMetadata = { "$EntityContainer" : "zui5_epm_sample.Container", "zui5_epm_sample.Product" : { "$kind" : "Entity", "Category" : oProperty }, "$Annotations" : { "zui5_epm_sample.Product/Category" : { "@com.sap.vocabularies.Common.v1.ValueListReferences" : [sMappingUrl1, sMappingUrl2], "@com.sap.vocabularies.Common.v1.ValueListReferences#bar" : [sMappingUrlBar], "@com.sap.vocabularies.Common.v1.ValueListReferences#[email protected]" : true, "@some.other.Annotation" : true } }, "zui5_epm_sample.Container" : { "ProductList" : { "$kind" : "EntitySet", "$Type" : "zui5_epm_sample.Product" } } }, oValueListMappings1 = { "" : {CollectionPath : ""} }, oValueListMappings2 = { "foo" : {CollectionPath : "foo"} }, oValueListMappingsBar = {}, oValueListModel1 = {sServiceUrl : sMappingUrl1}, oValueListModel2 = {sServiceUrl : sMappingUrl2}, oValueListModelBar = {sServiceUrl : sMappingUrlBar}; oValueListMappingsBar[bDuplicate ? "" : "bar"] = {CollectionPath : "bar"}; oMetaModelMock.expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(oMetadata)); oMetaModelMock.expects("getOrCreateValueListModel") .withExactArgs(sMappingUrl1) .returns(oValueListModel1); oMetaModelMock.expects("fetchValueListMappings") .withExactArgs(sinon.match.same(oValueListModel1), "zui5_epm_sample", sinon.match.same(oProperty)) .returns(Promise.resolve(oValueListMappings1)); oMetaModelMock.expects("getOrCreateValueListModel") .withExactArgs(sMappingUrl2) .returns(oValueListModel2); oMetaModelMock.expects("fetchValueListMappings") .withExactArgs(sinon.match.same(oValueListModel2), "zui5_epm_sample", sinon.match.same(oProperty)) .returns(Promise.resolve(oValueListMappings2)); oMetaModelMock.expects("getOrCreateValueListModel") .withExactArgs(sMappingUrlBar) .returns(oValueListModelBar); oMetaModelMock.expects("fetchValueListMappings") .withExactArgs(sinon.match.same(oValueListModelBar), "zui5_epm_sample", sinon.match.same(oProperty)) .returns(SyncPromise.resolve(oValueListMappingsBar)); // code under test return oModel.getMetaModel() .requestValueListInfo(sPropertyPath) .then(function (oResult) { assert.ok(!bDuplicate); assert.deepEqual(oResult, { "" : { $model : oValueListModel1, CollectionPath : "" }, "foo" : { $model : oValueListModel2, CollectionPath : "foo" }, "bar" : { $model : oValueListModelBar, CollectionPath : "bar" } }); }, function (oError) { assert.ok(bDuplicate); assert.strictEqual(oError.message, "Annotations 'com.sap.vocabularies.Common.v1.ValueListMapping' with " + "identical qualifier '' for property " + sPropertyPath + " in " + sMappingUrlBar + " and " + sMappingUrl1); }); }); }); //********************************************************************************************* QUnit.test("requestValueListInfo: same model w/o reference", function (assert) { var oProperty = { "$kind" : "Property" }, oValueListMappingFoo = {CollectionPath : "foo"}, oMetadata = { "$EntityContainer" : "value_list.Container", "value_list.Container" : { "$kind" : "EntityContainer", "VH_BusinessPartnerSet" : { "$kind" : "EntitySet", "$Type" : "value_list.VH_BusinessPartner" } }, "value_list.VH_BusinessPartner" : { "$kind" : "Entity", "Country" : oProperty }, "$Annotations" : { "value_list.VH_BusinessPartner/Country" : { "@com.sap.vocabularies.Common.v1.ValueListMapping#foo" : oValueListMappingFoo, "@com.sap.vocabularies.Common.v1.ValueListMapping#bar" : {CollectionPath : "bar"} } } }, oModel = new ODataModel({ serviceUrl : "/Foo/ValueListService/", synchronizationMode : "None" }), oMetaModelMock = this.mock(oModel.getMetaModel()), sPropertyPath = "/VH_BusinessPartnerSet('0100000000')/Country"; oMetaModelMock.expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(oMetadata)); // code under test return oModel.getMetaModel().requestValueListInfo(sPropertyPath).then(function (oResult) { assert.strictEqual(oResult.foo.$model, oModel); assert.strictEqual(oResult.bar.$model, oModel); assert.notOk("$model" in oValueListMappingFoo); delete oResult.foo.$model; delete oResult.bar.$model; assert.deepEqual(oResult, { "foo" : {CollectionPath : "foo"}, "bar" : {CollectionPath : "bar"} }); }); }); //********************************************************************************************* [false, true].forEach(function (bDuplicate) { var sTitle = "requestValueListInfo: fixed values: duplicate=" + bDuplicate; QUnit.test(sTitle, function (assert) { var oValueListMapping = {CollectionPath : "foo"}, oAnnotations = { "@com.sap.vocabularies.Common.v1.ValueListWithFixedValues" : true, "@com.sap.vocabularies.Common.v1.ValueListMapping#foo" : oValueListMapping }, oMetadata = { "$EntityContainer" : "value_list.Container", "value_list.Container" : { "$kind" : "EntityContainer", "VH_BusinessPartnerSet" : { "$kind" : "EntitySet", "$Type" : "value_list.VH_BusinessPartner" } }, "value_list.VH_BusinessPartner" : { "$kind" : "Entity", "Country" : {} }, "$Annotations" : { "value_list.VH_BusinessPartner/Country" : oAnnotations } }, oModel = new ODataModel({ serviceUrl : "/Foo/ValueListService/", synchronizationMode : "None" }), sPropertyPath = "/VH_BusinessPartnerSet('42')/Country"; if (bDuplicate) { oAnnotations["@com.sap.vocabularies.Common.v1.ValueListMapping#bar"] = {}; } this.mock(oModel.getMetaModel()).expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(oMetadata)); // code under test return oModel.getMetaModel().requestValueListInfo(sPropertyPath) .then(function (oResult) { assert.notOk(bDuplicate); assert.strictEqual(oResult[""].$model, oModel); delete oResult[""].$model; assert.deepEqual(oResult, { "" : {CollectionPath : "foo"} }); }, function (oError) { assert.ok(bDuplicate); assert.strictEqual(oError.message, "Annotation " + "'com.sap.vocabularies.Common.v1.ValueListWithFixedValues' but multiple " + "'com.sap.vocabularies.Common.v1.ValueListMapping' for property " + sPropertyPath); }); }); }); // ********************************************************************************************* QUnit.test("requestValueListInfo: property in cross-service reference", function (assert) { var sMappingUrl = "../ValueListService/$metadata", oModel = new ODataModel({ serviceUrl : "/Foo/DataService/", synchronizationMode : "None" }), oMetaModelMock = this.mock(oModel.getMetaModel()), oProperty = { "$kind" : "Property" }, oMetadata = { "$Version" : "4.0", "$Reference" : { "/Foo/EpmSample/$metadata" : { "$Include" : ["zui5_epm_sample."] } }, "$EntityContainer" : "base.Container", "base.Container" : { "BusinessPartnerList" : { "$kind" : "EntitySet", "$Type" : "base.BusinessPartner" } }, "base.BusinessPartner" : { "$kind" : "EntityType", "BP_2_PRODUCT" : { "$kind" : "NavigationProperty", "$Type" : "zui5_epm_sample.Product" } } }, oMetadataProduct = { "$Version" : "4.0", "zui5_epm_sample.Product" : { "$kind" : "Entity", "Category" : oProperty }, "zui5_epm_sample." : { "$kind" : "Schema", "$Annotations" : { "zui5_epm_sample.Product/Category" : { "@com.sap.vocabularies.Common.v1.ValueListReferences" : [sMappingUrl] } } } }, sPropertyPath = "/BusinessPartnerList('0100000000')/BP_2_PRODUCT('HT-1000')/Category", oRequestorMock = this.mock(oModel.oMetaModel.oRequestor), oValueListMappings = { "" : {CollectionPath : ""} }, oValueListModel = {sServiceUrl : sMappingUrl}; oRequestorMock.expects("read").withExactArgs("/Foo/DataService/$metadata", false, undefined) .returns(Promise.resolve(oMetadata)); oRequestorMock.expects("read").withExactArgs("/Foo/EpmSample/$metadata") .returns(Promise.resolve(oMetadataProduct)); oMetaModelMock.expects("getOrCreateValueListModel") .withExactArgs(sMappingUrl) .returns(oValueListModel); oMetaModelMock.expects("fetchValueListMappings") .withExactArgs(sinon.match.same(oValueListModel), "zui5_epm_sample", sinon.match.same(oProperty)) .returns(Promise.resolve(oValueListMappings)); // code under test return oModel.getMetaModel().requestValueListInfo(sPropertyPath).then(function (oResult) { assert.deepEqual(oResult, { "" : { $model : oValueListModel, CollectionPath : "" } }); }); }); // ********************************************************************************************* QUnit.test("requestValueListInfo: same qualifier in reference and local", function (assert) { var sMappingUrl = "../ValueListService/$metadata", oProperty = { "$kind" : "Property" }, oMetadata = { "$EntityContainer" : "zui5_epm_sample.Container", "zui5_epm_sample.Container" : { "$kind" : "EntityContainer", "ProductList" : { "$kind" : "EntitySet", "$Type" : "zui5_epm_sample.Product" } }, "zui5_epm_sample.Product" : { "$kind" : "Entity", "Category" : oProperty }, "$Annotations" : { "zui5_epm_sample.Product/Category" : { "@com.sap.vocabularies.Common.v1.ValueListReferences" : [sMappingUrl], "@com.sap.vocabularies.Common.v1.ValueListMapping#foo" : {} } } }, oModel = new ODataModel({ serviceUrl : "/Foo/ValueListService/", synchronizationMode : "None" }), oMetaModelMock = this.mock(oModel.getMetaModel()), sPropertyPath = "/ProductList('HT-1000')/Category", oValueListModel = {}; oMetaModelMock.expects("fetchEntityContainer").atLeast(1) .returns(SyncPromise.resolve(oMetadata)); oMetaModelMock.expects("getOrCreateValueListModel") .withExactArgs(sMappingUrl) .returns(oValueListModel); oMetaModelMock.expects("fetchValueListMappings") .withExactArgs(sinon.match.same(oValueListModel), "zui5_epm_sample", sinon.match.same(oProperty)) .returns(Promise.resolve({"foo" : {}})); // code under test return oModel.getMetaModel().requestValueListInfo(sPropertyPath).then(function () { assert.ok(false); }, function (oError) { assert.strictEqual(oError.message, "Annotations 'com.sap.vocabularies.Common.v1.ValueListMapping' with identical " + "qualifier 'foo' for property " + sPropertyPath + " in " + oModel.sServiceUrl + "$metadata and " + sMappingUrl); }); }); // ********************************************************************************************* QUnit.test("fetchModule: synchronously", function (assert) { var vModule = {}; this.mock(sap.ui).expects("require") .withExactArgs("sap/ui/model/odata/type/Int") .returns(vModule); // requested module already loaded // code under test assert.strictEqual(this.oMetaModel.fetchModule("sap.ui.model.odata.type.Int").getResult(), vModule); }); // ********************************************************************************************* QUnit.test("fetchModule, asynchronous", function (assert) { var vModule = {}, sModuleName = "sap/ui/model/odata/type/Int64", oSapUiMock = this.mock(sap.ui); oSapUiMock.expects("require") .withExactArgs(sModuleName) .returns(undefined); // requested module not yet loaded oSapUiMock.expects("require") .withExactArgs([sModuleName], sinon.match.func) .callsArgWithAsync(1, vModule); // code under test return this.oMetaModel.fetchModule("sap.ui.model.odata.type.Int64") .then(function (oResult) { assert.strictEqual(oResult, vModule); }); }); //********************************************************************************************* if (TestUtils.isRealOData()) { //***************************************************************************************** QUnit.test("getValueListType, requestValueListInfo: realOData", function (assert) { var sPath = new URI(TestUtils.proxy(sSampleServiceUrl)) .absoluteTo(window.location.pathname).toString(), oModel = new ODataModel({ serviceUrl : sPath, synchronizationMode : "None" }), oMetaModel = oModel.getMetaModel(), sPropertyPath = "/ProductList('HT-1000')/Category"; return oMetaModel.requestObject("/ProductList/").then(function () { assert.strictEqual(oMetaModel.getValueListType( "/com.sap.gateway.default.zui5_epm_sample.v0002.Contact/Sex"), ValueListType.Fixed); assert.strictEqual(oMetaModel.getValueListType(sPropertyPath), ValueListType.Standard); return oMetaModel.requestValueListInfo(sPropertyPath).then(function (oResult) { var oValueListInfo = oResult[""]; assert.strictEqual(oValueListInfo.CollectionPath, "H_EPM_PD_CATS_SH_Set"); }); }); }); //***************************************************************************************** QUnit.test("requestValueListInfo: same model w/o reference, realOData", function (assert) { var oModel = new ODataModel({ serviceUrl : TestUtils.proxy(sSampleServiceUrl), synchronizationMode : "None" }), oMetaModel = oModel.getMetaModel(), sPropertyPath = "/ProductList/0/CurrencyCode", oValueListMetaModel; return oMetaModel.requestObject("/ProductList/").then(function () { // value list in the data service assert.strictEqual(oMetaModel.getValueListType(sPropertyPath), ValueListType.Standard); return oMetaModel.requestValueListInfo(sPropertyPath); }).then(function (oValueListInfo) { var sPropertyPath2 = "/H_TCURC_SH_Set/1/WAERS"; // value list in the value list service oValueListMetaModel = oValueListInfo[""].$model.getMetaModel(); assert.strictEqual(oValueListMetaModel.getValueListType(sPropertyPath2), ValueListType.Standard); assert.strictEqual(oValueListInfo[""].CollectionPath, "H_TCURC_SH_Set"); return oValueListMetaModel.requestValueListInfo(sPropertyPath2); }).then(function (oValueListInfo) { assert.strictEqual(oValueListInfo[""].$model.getMetaModel(), oValueListMetaModel); assert.strictEqual(oValueListInfo[""].CollectionPath, "TCURC_CT_Set"); }); }); } }); //TODO getContext vs. createBindingContext; map of "singletons" vs. memory leak
cschuff/openui5
src/sap.ui.core/test/sap/ui/core/qunit/odata/v4/ODataMetaModel.qunit.js
JavaScript
apache-2.0
161,426
export const removeWeight = (element) => { try { element.removeAttribute('data-weight'); } catch (e) { // We are now in IE11 territory if (!!element) { element.setAttribute('data-weight', null); } } };
OpenConext/OpenConext-engineblock
theme/base/javascripts/wayf/search/removeWeight.js
JavaScript
apache-2.0
230
'use strict'; module.exports = function (grunt) { grunt.config( 'a11y', { live: { options: { urls: ['www.google.com'] } } }); };
spolnik/javascript-workspace
grunt/TodoApp/tasks/a11y.js
JavaScript
apache-2.0
166
OC.L10N.register( "settings", { "Security & Setup Warnings" : "Säkerhets & Inställningsvarningar", "Cron" : "Cron", "Sharing" : "Dela", "Security" : "Säkerhet", "Email Server" : "E-postserver", "Log" : "Logg", "Authentication error" : "Fel vid autentisering", "Your full name has been changed." : "Hela ditt namn har ändrats", "Unable to change full name" : "Kunde inte ändra hela namnet", "Files decrypted successfully" : "Filerna dekrypterades utan fel", "Couldn't decrypt your files, please check your owncloud.log or ask your administrator" : "Det gick inte att dekryptera dina filer, kontrollera din owncloud.log eller fråga administratören", "Couldn't decrypt your files, check your password and try again" : "Det gick inte att dekryptera filerna, kontrollera ditt lösenord och försök igen", "Encryption keys deleted permanently" : "Krypteringsnycklar raderades permanent", "Couldn't permanently delete your encryption keys, please check your owncloud.log or ask your administrator" : "Det gick inte att permanent ta bort dina krypteringsnycklar, kontrollera din owncloud.log eller fråga din administratör", "Couldn't remove app." : "Kunde inte ta bort applikationen.", "Backups restored successfully" : "Återställning av säkerhetskopior lyckades", "Couldn't restore your encryption keys, please check your owncloud.log or ask your administrator" : "Kan inte återställa dina krypteringsnycklar, vänligen kontrollera din owncloud.log eller fråga din administratör.", "Language changed" : "Språk ändrades", "Invalid request" : "Ogiltig begäran", "Admins can't remove themself from the admin group" : "Administratörer kan inte ta bort sig själva från admingruppen", "Unable to add user to group %s" : "Kan inte lägga till användare i gruppen %s", "Unable to remove user from group %s" : "Kan inte radera användare från gruppen %s", "Couldn't update app." : "Kunde inte uppdatera appen.", "Wrong password" : "Fel lösenord", "No user supplied" : "Ingen användare angiven", "Please provide an admin recovery password, otherwise all user data will be lost" : "Ange ett återställningslösenord för administratören. Annars kommer all användardata förloras", "Wrong admin recovery password. Please check the password and try again." : "Felaktigt återställningslösenord för administratör. Kolla lösenordet och prova igen.", "Back-end doesn't support password change, but the users encryption key was successfully updated." : "Gränssnittet stödjer inte byte av lösenord, men användarnas krypteringsnyckel blev uppdaterad.", "Unable to change password" : "Kunde inte ändra lösenord", "Enabled" : "Aktiverad", "Not enabled" : "Inte aktiverad", "Recommended" : "Rekomenderad", "Group already exists." : "Gruppen finns redan.", "Unable to add group." : "Lyckades inte lägga till grupp.", "Unable to delete group." : "Lyckades inte radera grupp.", "log-level out of allowed range" : "logg-nivå utanför tillåtet område", "Saved" : "Sparad", "test email settings" : "testa e-post inställningar", "If you received this email, the settings seem to be correct." : "Om du mottog detta e-postmeddelande, verkar dina inställningar vara korrekta.", "A problem occurred while sending the email. Please revise your settings." : "Ett problem uppstod när e-postmeddelandet skickades. Vänligen se över dina inställningar.", "Email sent" : "E-post skickat", "You need to set your user email before being able to send test emails." : "Du behöver ställa in din användares e-postadress före du kan skicka test e-post.", "Invalid mail address" : "Ogiltig e-postadress", "Unable to create user." : "Kan inte skapa användare.", "Your %s account was created" : "Ditt %s konto skapades", "Unable to delete user." : "Kan inte radera användare.", "Forbidden" : "Förbjuden", "Invalid user" : "Ogiltig användare", "Unable to change mail address" : "Kan inte ändra e-postadress", "Email saved" : "E-post sparad", "Are you really sure you want add \"{domain}\" as trusted domain?" : "Är du verkligen säker på att du vill lägga till \"{domain}\" som en trusted domian?", "Add trusted domain" : "Lägg till betrodd domän", "Sending..." : "Skickar ...", "All" : "Alla", "Please wait...." : "Var god vänta ...", "Error while disabling app" : "Fel vid inaktivering av app", "Disable" : "Deaktivera", "Enable" : "Aktivera", "Error while enabling app" : "Fel vid aktivering av app", "Updating...." : "Uppdaterar ...", "Error while updating app" : "Fel uppstod vid uppdatering av appen", "Updated" : "Uppdaterad", "Uninstalling ...." : "Avinstallerar ...", "Error while uninstalling app" : "Ett fel inträffade när applikatonen avinstallerades", "Uninstall" : "Avinstallera", "Select a profile picture" : "Välj en profilbild", "Very weak password" : "Väldigt svagt lösenord", "Weak password" : "Svagt lösenord", "So-so password" : "Okej lösenord", "Good password" : "Bra lösenord", "Strong password" : "Starkt lösenord", "Valid until {date}" : "Giltig t.o.m. {date}", "Delete" : "Radera", "Decrypting files... Please wait, this can take some time." : "Dekrypterar filer ... Vänligen vänta, detta kan ta en stund.", "Delete encryption keys permanently." : "Radera krypteringsnycklar permanent", "Restore encryption keys." : "Återställ krypteringsnycklar", "Groups" : "Grupper", "Unable to delete {objName}" : "Kunde inte radera {objName}", "Error creating group" : "Fel vid skapande av grupp", "A valid group name must be provided" : "Ett giltigt gruppnamn måste anges", "deleted {groupName}" : "raderade {groupName} ", "undo" : "ångra", "no group" : "ingen grupp", "never" : "aldrig", "deleted {userName}" : "raderade {userName}", "add group" : "lägg till grupp", "A valid username must be provided" : "Ett giltigt användarnamn måste anges", "Error creating user" : "Fel vid skapande av användare", "A valid password must be provided" : "Ett giltigt lösenord måste anges", "A valid email must be provided" : "En giltig e-postadress måste anges", "__language_name__" : "__language_name__", "Personal Info" : "Personlig info", "SSL root certificates" : "SSL rotcertifikat", "Encryption" : "Kryptering", "Everything (fatal issues, errors, warnings, info, debug)" : "Allting (allvarliga fel, fel, varningar, info, debug)", "Info, warnings, errors and fatal issues" : "Info, varningar och allvarliga fel", "Warnings, errors and fatal issues" : "Varningar, fel och allvarliga fel", "Errors and fatal issues" : "Fel och allvarliga fel", "Fatal issues only" : "Endast allvarliga fel", "None" : "Ingen", "Login" : "Logga in", "Plain" : "Enkel", "NT LAN Manager" : "NT LAN Manager", "SSL" : "SSL", "TLS" : "TLS", "Security Warning" : "Säkerhetsvarning", "You are accessing %s via HTTP. We strongly suggest you configure your server to require using HTTPS instead." : "Du ansluter till %s via HTTP. Vi rekommenderar starkt att du konfigurerar din server att använda HTTPS istället.", "Read-Only config enabled" : "Skrivskyddad konfiguration påslagen", "The Read-Only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Lär-bara konfigureringen har blivit aktiv. Detta förhindrar att några konfigureringar kan sättas via web-gränssnittet.", "Setup Warning" : "Installationsvarning", "PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." : "PHP är tydligen inställd för att rensa inline doc block. Detta kommer att göra flera kärnapplikationer otillgängliga.", "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Detta orsakas troligtvis av en cache/accelerator som t ex Zend OPchache eller eAccelerator.", "Database Performance Info" : "Databasprestanda Information", "Microsoft Windows Platform" : "Microsoft Windows-platform", "Your server is running on Microsoft Windows. We highly recommend Linux for optimal user experience." : "Din server använder Microsoft Windows. Vi rekommenderar starkt Linux för en optimal användarerfarenhet.", "Module 'fileinfo' missing" : "Modulen \"fileinfo\" saknas", "The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "PHP-modulen 'fileinfo' saknas. Vi rekommenderar starkt att aktivera den här modulen för att kunna upptäcka korrekt mime-typ.", "PHP charset is not set to UTF-8" : "PHP-teckenuppsättning är inte satt till UTF-8", "PHP charset is not set to UTF-8. This can cause major issues with non-ASCII characters in file names. We highly recommend to change the value of 'default_charset' php.ini to 'UTF-8'." : "PHP-teckenuppsättning är inte satt till UTF-8. Detta kan orsaka stora problem med icke-ASCII-tecken i filnamn. Vi rekommenderar starkt att ändra värdet \"default_charset\" i php.ini till \"UTF-8\".", "Locale not working" : "\"Locale\" fungerar inte", "System locale can not be set to a one which supports UTF-8." : "Systemspråk kan inte ställas in till ett som stödjer UTF-8.", "This means that there might be problems with certain characters in file names." : "Detta betyder att där kan komma att uppstå problem med vissa tecken i filnamn.", "We strongly suggest installing the required packages on your system to support one of the following locales: %s." : "Vi rekommenderar starkt att installera de nödvändiga paketen på ditt system för att stödja en av följande språkversioner: %s.", "URL generation in notification emails" : "URL-generering i notifieringsmejl", "If your installation is not installed in the root of the domain and uses system cron, there can be issues with the URL generation. To avoid these problems, please set the \"overwrite.cli.url\" option in your config.php file to the webroot path of your installation (Suggested: \"%s\")" : "Om din installation inte installerades på roten av domänen och använder system cron så kan det uppstå problem med URL-genereringen. För att undvika dessa problem, var vänlig sätt \"overwrite.cli.url\"-inställningen i din config.php-fil till webbrotsökvägen av din installation (Föreslagen: \"%s\")", "Configuration Checks" : "Konfigurationskontroller", "No problems found" : "Inga problem hittades", "Please double check the <a href='%s'>installation guides</a>." : "Var god kontrollera <a href='%s'>installationsguiden</a>.", "Last cron was executed at %s." : "Sista cron kördes vid %s", "Last cron was executed at %s. This is more than an hour ago, something seems wrong." : "Sista cron kördes vid %s. Detta är mer än en timme sedan, något verkar fel.", "Cron was not executed yet!" : "Cron kördes inte ännu!", "Execute one task with each page loaded" : "Exekvera en uppgift vid varje sidladdning", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php är registrerad som en webcron service att ropa på cron.php varje 15 minuter över http.", "Use system's cron service to call the cron.php file every 15 minutes." : "Använd systemets cron-tjänst för att anropa cron.php var 15:e minut.", "Allow apps to use the Share API" : "Tillåt applikationer att använda delat API", "Allow users to share via link" : "Tillåt användare att dela via länk", "Enforce password protection" : "Tillämpa lösenordskydd", "Allow public uploads" : "Tillåt offentlig uppladdning", "Allow users to send mail notification for shared files" : "Tillåt användare att skicka mailnotifieringar för delade filer", "Set default expiration date" : "Ställ in standardutgångsdatum", "Expire after " : "Förfaller efter", "days" : "dagar", "Enforce expiration date" : "Tillämpa förfallodatum", "Allow resharing" : "Tillåt vidaredelning", "Restrict users to only share with users in their groups" : "Begränsa användare till att enbart kunna dela med användare i deras grupper", "Allow users to send mail notification for shared files to other users" : "Tillåt användare att skicka mejlnotifiering för delade filer till andra användare", "Exclude groups from sharing" : "Exkludera grupp från att dela", "These groups will still be able to receive shares, but not to initiate them." : "Dessa grupper kommer fortfarande kunna ta emot delningar, men inte skapa delningar.", "Enforce HTTPS" : "Kräv HTTPS", "Forces the clients to connect to %s via an encrypted connection." : "Tvingar klienterna att ansluta till %s via en krypterad anslutning.", "Enforce HTTPS for subdomains" : "Framtvinga HTTPS för underdomäner", "Forces the clients to connect to %s and subdomains via an encrypted connection." : "Tvingar klienter att ansluta till %s och underdomäner via en krypterad anslutning.", "Please connect to your %s via HTTPS to enable or disable the SSL enforcement." : "Anslut till din %s via HTTPS för att aktivera/deaktivera SSL", "This is used for sending out notifications." : "Detta används för att skicka ut notifieringar.", "Send mode" : "Sändningsläge", "From address" : "Från adress", "mail" : "mail", "Authentication method" : "Autentiseringsmetod", "Authentication required" : "Autentisering krävs", "Server address" : "Serveradress", "Port" : "Port", "Credentials" : "Inloggningsuppgifter", "SMTP Username" : "SMTP-användarnamn", "SMTP Password" : "SMTP-lösenord", "Store credentials" : "Lagra inloggningsuppgifter", "Test email settings" : "Testa e-postinställningar", "Send email" : "Skicka e-post", "Log level" : "Nivå på loggning", "Download logfile" : "Ladda ner loggfil", "More" : "Mer", "Less" : "Mindre", "The logfile is bigger than 100MB. Downloading it may take some time!" : "Loggfilen är större än 100MB. Att ladda ner den kan ta lite tid!", "Version" : "Version", "Developed by the <a href=\"http://ownCloud.org/contact\" target=\"_blank\">ownCloud community</a>, the <a href=\"https://github.com/owncloud\" target=\"_blank\">source code</a> is licensed under the <a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" target=\"_blank\"><abbr title=\"Affero General Public License\">AGPL</abbr></a>." : "Utvecklad av <a href=\"http://ownCloud.org/contact\" target=\"_blank\">ownCloud Community</a>, <a href=\"https://github.com/owncloud\" target=\"_blank\">källkoden</a> är licenserad under <a href=\"http://www.gnu.org/licenses/agpl-3.0.html\" target=\"_blank\"><abbr title=\"Affero General Public License\">AGPL</abbr></a>.", "More apps" : "Fler appar", "Add your app" : "Lägg till din app", "by" : "av", "licensed" : "licensierad", "Documentation:" : "Dokumentation:", "User Documentation" : "Användardokumentation", "Admin Documentation" : "Administratörsdokumentation", "This app cannot be installed because the following dependencies are not fulfilled:" : "Denna applikation kan inte installeras då följande beroenden inte är uppfyllda: %s", "Update to %s" : "Uppdatera till %s", "Enable only for specific groups" : "Aktivera endast för specifika grupper", "Uninstall App" : "Avinstallera applikation", "Hey there,<br><br>just letting you know that you now have an %s account.<br><br>Your username: %s<br>Access it: <a href=\"%s\">%s</a><br><br>" : "Hej där,<br><br>vill bara informera dig om att du nu har ett %s konto.<br><br>Ditt användarnamn: %s<br>Accessa det genom: <a href=\"%s\">%s</a><br><br>", "Cheers!" : "Ha de fint!", "Hey there,\n\njust letting you know that you now have an %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Hej där,\n\nvill bara informera dig om att du nu har ett %s konto.\n\nDitt användarnamn: %s\nAccessa det genom: %s\n", "Administrator Documentation" : "Administratörsdokumentation", "Online Documentation" : "Onlinedokumentation", "Forum" : "Forum", "Bugtracker" : "Bugtracker", "Commercial Support" : "Kommersiell support", "Get the apps to sync your files" : "Skaffa apparna för att synkronisera dina filer", "Desktop client" : "Skrivbordsklient", "Android app" : "Android-app", "iOS app" : "iOS-app", "If you want to support the project\n\t\t<a href=\"https://owncloud.org/contribute\"\n\t\t\ttarget=\"_blank\">join development</a>\n\t\tor\n\t\t<a href=\"https://owncloud.org/promote\"\n\t\t\ttarget=\"_blank\">spread the word</a>!" : "Om du vill stödja projektet\n<a href=\"https://owncloud.org/contribute\"\n\t\t\ttarget=\"_blank\">hjälp till med utvecklingen</a>\n\t\teller\n\t\t<a href=\"https://owncloud.org/promote\"\n\t\t\ttarget=\"_blank\">sprid budskapet vidare</a>!", "Show First Run Wizard again" : "Visa Första uppstarts-guiden igen", "You have used <strong>%s</strong> of the available <strong>%s</strong>" : "Du har använt <strong>%s</strong> av tillgängliga <strong>%s</strong>", "Password" : "Lösenord", "Your password was changed" : "Ditt lösenord har ändrats", "Unable to change your password" : "Kunde inte ändra ditt lösenord", "Current password" : "Nuvarande lösenord", "New password" : "Nytt lösenord", "Change password" : "Ändra lösenord", "Full Name" : "Hela namnet", "No display name set" : "Inget visningsnamn angivet", "Email" : "E-post", "Your email address" : "Din e-postadress", "Fill in an email address to enable password recovery and receive notifications" : "Fyll i en e-postadress för att aktivera återställning av lösenord och mottagande av notifieringar", "No email address set" : "Ingen e-postadress angiven", "Profile picture" : "Profilbild", "Upload new" : "Ladda upp ny", "Select new from Files" : "Välj ny från filer", "Remove image" : "Radera bild", "Either png or jpg. Ideally square but you will be able to crop it." : "Antingen png eller jpg. Helst fyrkantig, men du kommer att kunna beskära den.", "Your avatar is provided by your original account." : "Din avatar tillhandahålls av ditt ursprungliga konto.", "Cancel" : "Avbryt", "Choose as profile image" : "Välj som profilbild", "Language" : "Språk", "Help translate" : "Hjälp att översätta", "Common Name" : "Vanligt namn", "Valid until" : "Giltigt till", "Issued By" : "Utfärdat av", "Valid until %s" : "Giltigt till %s", "Import Root Certificate" : "Importera rotcertifikat", "The encryption app is no longer enabled, please decrypt all your files" : "Krypteringsapplikationen är inte längre aktiverad, vänligen dekryptera alla dina filer", "Log-in password" : "Inloggningslösenord", "Decrypt all Files" : "Dekryptera alla filer", "Your encryption keys are moved to a backup location. If something went wrong you can restore the keys. Only delete them permanently if you are sure that all files are decrypted correctly." : "Dina krypteringsnycklar flyttas till en backup. Om något gick fel kan du återställa nycklarna. Bara ta bort dem permanent om du är säker på att alla filer dekrypteras korrekt.", "Restore Encryption Keys" : "Återställ krypteringsnycklar", "Delete Encryption Keys" : "Radera krypteringsnycklar", "Show storage location" : "Visa lagringsplats", "Show last log in" : "Visa senaste inloggning", "Show user backend" : "Visa användar-back-end", "Send email to new user" : "Skicka e-post till ny användare", "Show email address" : "Visa e-postadress", "Username" : "Användarnamn", "E-Mail" : "E-post", "Create" : "Skapa", "Admin Recovery Password" : "Admin-återställningslösenord", "Enter the recovery password in order to recover the users files during password change" : "Ange återställningslösenordet för att återställa användarnas filer vid lösenordsbyte", "Search Users" : "Sök användare", "Add Group" : "Lägg till Grupp", "Group" : "Grupp", "Everyone" : "Alla", "Admins" : "Administratörer", "Default Quota" : "Förvald datakvot", "Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Var god skriv in lagringskvot (ex: \"512MB\" eller \"12 GB\")", "Unlimited" : "Obegränsad", "Other" : "Annat", "Group Admin for" : "Gruppadministratör för", "Quota" : "Kvot", "Storage Location" : "Lagringsplats", "User Backend" : "Användar-back-end", "Last Login" : "Senaste inloggning", "change full name" : "ändra hela namnet", "set new password" : "ange nytt lösenord", "change email address" : "ändra e-postadress", "Default" : "Förvald" }, "nplurals=2; plural=(n != 1);");
kebenxiaoming/owncloudRedis
settings/l10n/sv.js
JavaScript
apache-2.0
21,151
var config = require('./lib/config'); var FaceRec = require('./lib/facerec').FaceRec; var hfr = new FaceRec(config); // constant var threshold = 20; var prevX; var prevY; setInterval(function() { var result = hfr.detect(); console.log('result:' + JSON.stringify(result)); if (result && result.pos_x && result.pos_y) { var newX = result.pos_x; var newY = result.pos_y; var deltaX = newX - prevX; var deltaY = newY - prevY; if (Math.abs(deltaX) > threshold) { var direction = deltaX > 0 ? "right" : "left"; console.log("moving head to " + direction + " , distance" + Math.abs(deltaX)); } if (Math.abs(deltaY) > threshold) { var direction = deltaY > 0 ? "down" : "up"; console.log("moving head to " + direction + " , distance" + Math.abs(deltaY)); } console.log('updating x and y'); prevX = newX; prevY = newY; } }, 5000);
project-humix/humix-facerec-module
test.js
JavaScript
apache-2.0
992
var structCO__config__t = [ [ "CNT_NMT", "structCO__config__t.html#aeef814580eb5ece5156e63bfc1b490c9", null ], [ "ENTRY_H1017", "structCO__config__t.html#ad17f77b55de3d90ec983fcac49eeab6d", null ], [ "CNT_HB_CONS", "structCO__config__t.html#a0031fc8f80e95f8480c918dbf8289671", null ], [ "ENTRY_H1016", "structCO__config__t.html#a0af4cf7d0355861e7f60206d794d6a91", null ], [ "CNT_EM", "structCO__config__t.html#a515e08f68835f71a6f145be8f27b510a", null ], [ "ENTRY_H1001", "structCO__config__t.html#a6a6c19e816fb76882e85b2c07c0d8f42", null ], [ "ENTRY_H1014", "structCO__config__t.html#a4827d94f6152cc12d86bd21312ae86e4", null ], [ "ENTRY_H1015", "structCO__config__t.html#a141f21b4d1730206d1af823fd6b13a01", null ], [ "ENTRY_H1003", "structCO__config__t.html#a7e320b309714b7f623c2006d45fee929", null ], [ "CNT_SDO_SRV", "structCO__config__t.html#aac83faf556924515cc2aa8003753ab58", null ], [ "ENTRY_H1200", "structCO__config__t.html#a05ab8adad4517850e31e5542895f7cc5", null ], [ "CNT_SDO_CLI", "structCO__config__t.html#a2fc9606643a7fb4d4237f01812d3a6d2", null ], [ "ENTRY_H1280", "structCO__config__t.html#a9f871c4ec753e8414cdb47eb78c3e09d", null ], [ "CNT_TIME", "structCO__config__t.html#ada2a43384a544fa2f235de24a874b1e6", null ], [ "ENTRY_H1012", "structCO__config__t.html#abac6be7122af1a8a4f9ae3ff5912d490", null ], [ "CNT_SYNC", "structCO__config__t.html#af6dbc7d9f31b4cb050e23af8cff3df33", null ], [ "ENTRY_H1005", "structCO__config__t.html#a02a4992f47db72816753ff2aa1964318", null ], [ "ENTRY_H1006", "structCO__config__t.html#aa9befdebbaaa22f309b9a1b115612071", null ], [ "ENTRY_H1007", "structCO__config__t.html#ad51ab63ca8b5836bf0dd8543f02db544", null ], [ "ENTRY_H1019", "structCO__config__t.html#a468c82f6a0afd757a6b78ce33532c0d2", null ], [ "CNT_RPDO", "structCO__config__t.html#a7a75302ac077462b67d767b0a11c9f56", null ], [ "ENTRY_H1400", "structCO__config__t.html#a5e0984d93183493d587523888465eaa7", null ], [ "ENTRY_H1600", "structCO__config__t.html#ab2ddc9943fd8c89f3b852d7ac9508d21", null ], [ "CNT_TPDO", "structCO__config__t.html#a1d830617f50e3235de35a403a1513693", null ], [ "ENTRY_H1800", "structCO__config__t.html#a29b98c08edfe0fba2e46c7af7a9edf6f", null ], [ "ENTRY_H1A00", "structCO__config__t.html#a43fd6a448c91910c603f2c7756610432", null ], [ "CNT_LEDS", "structCO__config__t.html#a642809cc681792bca855906241d891cc", null ], [ "CNT_GFC", "structCO__config__t.html#ae282bab830810b61c0b0c3223654d674", null ], [ "ENTRY_H1300", "structCO__config__t.html#a91c9f3ddb67231854af39224a9597e20", null ], [ "CNT_SRDO", "structCO__config__t.html#ae58a44be57069709af3f6acbd10953e1", null ], [ "ENTRY_H1301", "structCO__config__t.html#a87076cb1f9282d9720c21d395ff4e541", null ], [ "ENTRY_H1381", "structCO__config__t.html#a7b3172b29ce8751adcab9e4351dcc31e", null ], [ "ENTRY_H13FE", "structCO__config__t.html#a03fcaca5a8e0e71b86086908cae75f3d", null ], [ "ENTRY_H13FF", "structCO__config__t.html#aa4cb9674209b83e7f0e48b01feaa04ef", null ], [ "CNT_LSS_SLV", "structCO__config__t.html#a00a7a598b946ed13e3af7696e9f92dcc", null ], [ "CNT_LSS_MST", "structCO__config__t.html#ac253cae7039090a6c04bc1e385f3ec21", null ], [ "CNT_GTWA", "structCO__config__t.html#a64725014ecce342843f14ffc4b57e2a2", null ], [ "CNT_TRACE", "structCO__config__t.html#aaafb8ffff236b51cd6d4ab16426d460f", null ] ];
CANopenNode/CANopenSocket
docs/structCO__config__t.js
JavaScript
apache-2.0
3,451
/** * Copyright 2013-present NightWorld. * * 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 error = require('./error'), runner = require('./runner'), Client = require('./client'); module.exports = Authorise; /** * This is the function order used by the runner * * @type {Array} */ var fns = [ checkAuthoriseType, checkScope ]; /** * Authorise * * @param {Object} config Instance of OAuth object * @param {Object} req * @param {Object} res * @param {Object} options * @param {Function} next */ function Authorise (config, req, res, options, next) { options = options || {}; this.config = config; this.model = config.model; this.req = req; this.res = res; this.options = options; runner(fns, this, next); } function checkAuthoriseType(done) { var client = Client.credsFromBasic(this.req) || Client.credsFromBody(this.req); if (this.options.implicit) { if (this.req.body.response_type === 'token') { if (client.clientId) { this.redirectUri = this.req.body.redirect_uri || this.req.query.redirect_uri; this.clientId = client.clientId; this.req.auth_type = 'implicit'; return checkImplicitClient.call(this, done); } } } if (this.options.client_credentials) { if (client.clientId && client.clientSecret) { this.client = client; this.req.auth_type = 'client_credentials'; return getUserFromClient.call(this, done); } } getBearerToken.call(this, done); } function getUserFromClient(done) { var self = this; this.model.getClient(this.client.clientId, this.client.clientSecret, function (err, client) { if (err) return done(error('server_error', false, err)); if (!client) { return done(error('invalid_client', 'Client credentials are invalid')); } self.model.getUserFromClient(client, function (err, user) { if (err) return done(error('server_error', false, err)); if (!user) { return done(error('invalid_grant', 'Client credentials are invalid')); } self.req.oauth = { bearerToken: user }; self.req.user = { id: user.id }; done(); }); }); } function checkImplicitClient (done) { var self = this; this.model.getClient(this.clientId, null, function (err, client) { if (err) return done(error('server_error', false, err)); if (!client) { return done(error('invalid_client', 'Invalid client credentials')); } else if (self.redirectUri && Array.isArray(client.redirectUri)) { if (client.redirectUri.indexOf(self.redirectUri) === -1) { return done(error('invalid_request', 'redirect_uri does not match')); } client.redirectUri = self.redirectUri; } else if (self.redirectUri && client.redirectUri !== self.redirectUri) { return done(error('invalid_request', 'redirect_uri does not match')); } self.model.getUserFromClient(client, function (err, user) { if (err) return done(error('server_error', false, err)); if (!user) { return done(error('invalid_grant', 'Client credentials are invalid')); } // The request contains valid params so any errors after this point // are redirected to the redirect_uri self.res.redirectUri = client.redirectUri; self.res.oauthRedirect = true; self.req.oauth = { bearerToken: user }; self.req.user = { id: user.id }; done(); }); }); } /** * Get bearer token * * Extract token from request according to RFC6750 * * @param {Function} done * @this OAuth */ function getBearerToken (done) { var headerToken = this.req.get('Authorization'), getToken = this.req.query.access_token, postToken = this.req.body ? this.req.body.access_token : undefined; // Check exactly one method was used var methodsUsed = (headerToken !== undefined) + (getToken !== undefined) + (postToken !== undefined); if (methodsUsed > 1) { return done(error('invalid_request', 'Only one method may be used to authenticate at a time (Auth header, ' + 'GET or POST).')); } else if (methodsUsed === 0) { return done(error('invalid_request', 'The access token was not found')); } // Header: http://tools.ietf.org/html/rfc6750#section-2.1 if (headerToken) { var matches = headerToken.match(/Bearer\s(\S+)/); if (!matches) { return done(error('invalid_request', 'Malformed auth header')); } headerToken = matches[1]; } // POST: http://tools.ietf.org/html/rfc6750#section-2.2 if (postToken) { if (this.req.method === 'GET') { return done(error('invalid_request', 'Method cannot be GET When putting the token in the body.')); } if (!this.req.is('application/x-www-form-urlencoded')) { return done(error('invalid_request', 'When putting the token in the ' + 'body, content type must be application/x-www-form-urlencoded.')); } } this.bearerToken = headerToken || postToken || getToken; checkToken.call(this, done); } /** * Check token * * Check it against model, ensure it's not expired * @param {Function} done * @this OAuth */ function checkToken (done) { var self = this; this.model.getAccessToken(this.bearerToken, function (err, token) { if (err) return done(error('server_error', false, err)); if (!token) { return done(error('invalid_token', 'The access token provided is invalid.')); } if (token.expires !== null && (!token.expires || token.expires < new Date())) { return done(error('invalid_token', 'The access token provided has expired.')); } // Expose params self.req.oauth = { bearerToken: token }; self.req.user = token.user ? token.user : { id: token.userId }; done(); }); } /** * Check scope * * @param {Function} done * @this OAuth */ function checkScope (done) { if (!this.model.authoriseScope) return done(); this.model.authoriseScope(this.req.oauth.bearerToken, this.options.scope, function (err, invalid) { if (err) return done(error('server_error', false, err)); if (invalid) return done(error('invalid_scope', invalid)); done(); }); }
zoltangbereczky/node-oauth2-server
lib/authorise.js
JavaScript
apache-2.0
6,699
//// [contextualTypeWithUnionTypeMembers.ts] //When used as a contextual type, a union type U has those members that are present in any of // its constituent types, with types that are unions of the respective members in the constituent types. interface I1<T> { commonMethodType(a: string): string; commonPropertyType: string; commonMethodWithTypeParameter(a: T): T; methodOnlyInI1(a: string): string; propertyOnlyInI1: string; } interface I2<T> { commonMethodType(a: string): string; commonPropertyType: string; commonMethodWithTypeParameter(a: T): T; methodOnlyInI2(a: string): string; propertyOnlyInI2: string; } // Let S be the set of types in U that has a property P. // If S is not empty, U has a property P of a union type of the types of P from each type in S. var i1: I1<number>; var i2: I2<number>; var i1Ori2: I1<number> | I2<number> = i1; var i1Ori2: I1<number> | I2<number> = i2; var i1Ori2: I1<number> | I2<number> = { // Like i1 commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI1: a => a, propertyOnlyInI1: "Hello", }; var i1Ori2: I1<number> | I2<number> = { // Like i2 commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI2: a => a, propertyOnlyInI2: "Hello", }; var i1Ori2: I1<number> | I2<number> = { // Like i1 and i2 both commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI1: a => a, propertyOnlyInI1: "Hello", methodOnlyInI2: a => a, propertyOnlyInI2: "Hello", }; var arrayI1OrI2: Array<I1<number> | I2<number>> = [i1, i2, { // Like i1 commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI1: a => a, propertyOnlyInI1: "Hello", }, { // Like i2 commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI2: a => a, propertyOnlyInI2: "Hello", }, { // Like i1 and i2 both commonPropertyType: "hello", commonMethodType: a=> a, commonMethodWithTypeParameter: a => a, methodOnlyInI1: a => a, propertyOnlyInI1: "Hello", methodOnlyInI2: a => a, propertyOnlyInI2: "Hello", }]; interface I11 { commonMethodDifferentReturnType(a: string, b: number): string; commonPropertyDifferentType: string; } interface I21 { commonMethodDifferentReturnType(a: string, b: number): number; commonPropertyDifferentType: number; } var i11: I11; var i21: I21; var i11Ori21: I11 | I21 = i11; var i11Ori21: I11 | I21 = i21; var i11Ori21: I11 | I21 = { // Like i1 commonMethodDifferentReturnType: (a, b) => { var z = a.charAt(b); return z; }, commonPropertyDifferentType: "hello", }; var i11Ori21: I11 | I21 = { // Like i2 commonMethodDifferentReturnType: (a, b) => { var z = a.charCodeAt(b); return z; }, commonPropertyDifferentType: 10, }; var arrayOrI11OrI21: Array<I11 | I21> = [i11, i21, i11 || i21, { // Like i1 commonMethodDifferentReturnType: (a, b) => { var z = a.charAt(b); return z; }, commonPropertyDifferentType: "hello", }, { // Like i2 commonMethodDifferentReturnType: (a, b) => { var z = a.charCodeAt(b); return z; }, commonPropertyDifferentType: 10, }]; //// [contextualTypeWithUnionTypeMembers.js] // Let S be the set of types in U that has a property P. // If S is not empty, U has a property P of a union type of the types of P from each type in S. var i1; var i2; var i1Ori2 = i1; var i1Ori2 = i2; var i1Ori2 = { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI1: function (a) { return a; }, propertyOnlyInI1: "Hello" }; var i1Ori2 = { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI2: function (a) { return a; }, propertyOnlyInI2: "Hello" }; var i1Ori2 = { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI1: function (a) { return a; }, propertyOnlyInI1: "Hello", methodOnlyInI2: function (a) { return a; }, propertyOnlyInI2: "Hello" }; var arrayI1OrI2 = [i1, i2, { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI1: function (a) { return a; }, propertyOnlyInI1: "Hello" }, { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI2: function (a) { return a; }, propertyOnlyInI2: "Hello" }, { commonPropertyType: "hello", commonMethodType: function (a) { return a; }, commonMethodWithTypeParameter: function (a) { return a; }, methodOnlyInI1: function (a) { return a; }, propertyOnlyInI1: "Hello", methodOnlyInI2: function (a) { return a; }, propertyOnlyInI2: "Hello" }]; var i11; var i21; var i11Ori21 = i11; var i11Ori21 = i21; var i11Ori21 = { // Like i1 commonMethodDifferentReturnType: function (a, b) { var z = a.charAt(b); return z; }, commonPropertyDifferentType: "hello" }; var i11Ori21 = { // Like i2 commonMethodDifferentReturnType: function (a, b) { var z = a.charCodeAt(b); return z; }, commonPropertyDifferentType: 10 }; var arrayOrI11OrI21 = [i11, i21, i11 || i21, { // Like i1 commonMethodDifferentReturnType: function (a, b) { var z = a.charAt(b); return z; }, commonPropertyDifferentType: "hello" }, { // Like i2 commonMethodDifferentReturnType: function (a, b) { var z = a.charCodeAt(b); return z; }, commonPropertyDifferentType: 10 }];
freedot/tstolua
tests/baselines/reference/contextualTypeWithUnionTypeMembers.js
JavaScript
apache-2.0
6,404
'use strict'; var path = require('path'); var util = require('util'); module.exports = function(grunt) { grunt.registerMultiTask('vjslanguages', 'A Grunt plugin for compiling VideoJS language assets.', function() { var createLanguageFile = function(languageName, languageData, jsFilePath) { var jsTemplate = 'videojs.addLanguage("' + languageName + '",' + JSON.stringify(languageData,null,' ') + ');'; grunt.file.write(jsFilePath, jsTemplate); grunt.log.writeln('- [' + languageName +'] Language Built. File "' + jsFilePath + '" created.'); }; this.files.forEach(function(f) { var languageName, languageData, jsFilePath; // Multiple Files Case if(util.isArray(f.src)){ for(var i =0; i < f.src.length; i++) { languageName = path.basename(f.src[i], '.json'); languageData = grunt.file.readJSON(f.src[i]); jsFilePath = path.join(f.dest, languageName + '.js'); createLanguageFile(languageName, languageData, jsFilePath); } } // Singular File Case else { languageName = path.basename(f.src, '.json'); languageData = grunt.file.readJSON(f.src); jsFilePath = path.join(f.dest, languageName + '.js'); createLanguageFile(languageName, languageData, jsFilePath); } }); }); };
videojs/grunt-videojs-languages
tasks/videojs_languages.js
JavaScript
apache-2.0
1,338
$(document).ready(function(){ $("#inc_tab #tb1").removeClass(); $("#inc_tab #tb4").addClass("active"); $("#user_name").blur(function(){ var user_name = $.trim($(this).val()); $(this).val(user_name); if (user_name.length==0){ $(this).parent().find("#user_name_null_warn").show(); $(this).parent().find("#user_name_exist_warn").hide(); return; } $(this).parent().find("#user_name_null_warn").hide(); var user_id = $(this).parent().find("#user_id").val(); var obj = $(this).parent().find("#user_name_exist_warn"); $.post(app.global.variable.base_path +"user/name/verify", {user_id:user_id, user_name:user_name}, function(data) { if(data.toString().length > 0){ obj.show(); }else{ obj.hide(); } }) }) $('#user_save_cancel').click(function(){ window.location.href=app.global.variable.base_path +'user/list'; }) selectRoleChange(); }) function selectRoleChange(){ var obj = $("#select_role_id"); var role_id_obj = obj.parent().find("#role_id"); $("#role_authority_"+role_id_obj.val()).hide(); $("#role_authority_"+obj.val()).show(); role_id_obj.val(obj.val()); } function user_sava_check(){ var obj = $("#user_editor_form"); var valid = true; obj.find(".functionWarn").each(function(){ if($(this).is(":visible")){ valid = false; } }) // 用户名 var user_name = obj.find("#user_name").val(); if(isSpace(user_name)){ obj.find("#user_name_null_warn").show(); valid = false; }else{ obj.find("#user_name_null_warn").hide(); } return valid; }
wxiwei/manage
src/main/webapp/WEB-INF/js/user/userEditor.js
JavaScript
apache-2.0
1,536
define( ['app/models/proto_model'], function(ProtoModel) { var Model = ProtoModel.extend({ // matches first part of method name in @remote.method urlRoot: '/cru_api.order_', must_be_floats: ['sub_total', 'actual_total'], }); return Model; } );
babybunny/rebuildingtogethercaptain
gae/js/app/models/order.js
JavaScript
apache-2.0
317
/* * ! ${copyright} */ sap.ui.define([ "delegates/odata/v4/TableDelegate", "sap/ui/core/Core" ], function( TableDelegate, Core ) { "use strict"; /** * Test delegate for OData V4. */ var ODataTableDelegate = Object.assign({}, TableDelegate); /** * Updates the binding info with the relevant path and model from the metadata. * * @param {Object} oTable The MDC table instance * @param {Object} oBindingInfo The bindingInfo of the table */ ODataTableDelegate.updateBindingInfo = function(oTable, oBindingInfo) { TableDelegate.updateBindingInfo.apply(this, arguments); var oFilterBar = Core.byId(oTable.getFilter()); if (oFilterBar) { // get the basic search var sSearchText = oFilterBar.getSearch instanceof Function ? oFilterBar.getSearch() : ""; if (sSearchText && sSearchText.indexOf(" ") === -1) { // to allow search for "("..... sSearchText = '"' + sSearchText + '"'; // TODO: escape " in string } // if it contains spaces allow opeartors like OR... oBindingInfo.parameters.$search = sSearchText || undefined; } }; return ODataTableDelegate; });
SAP/openui5
src/sap.ui.mdc/test/sap/ui/mdc/internal/TableWithFilterBar/delegate/GridTable.delegate.js
JavaScript
apache-2.0
1,110
var logger = require('../logging').getLogger(__LOGGER__); var {PAGE_CSS_NODE_ID} = require('../constants'); var Q = require('q'); var PageUtil = require('./PageUtil') var loadedCss = {}; module.exports = { registerPageLoad: function registerPageLoad() { if (SERVER_SIDE) { throw new Error("ClientCssHelper.registerPageLoad can't be called server-side"); } // for each css node in the head that the react-server server wrote to the response, note it down in the cache, so that // we can remove it on a page to page transition. var serverWrittenLinkNodes = document.head.querySelectorAll(`link[${PAGE_CSS_NODE_ID}],style[${PAGE_CSS_NODE_ID}]`); for (var i = 0; i < serverWrittenLinkNodes.length; i++) { var key, styleNode = serverWrittenLinkNodes[i]; if (styleNode.href) { key = normalizeLocalUrl(styleNode.href); } else { key = styleNode.innerHTML; } loadedCss[key] = styleNode; } }, ensureCss: function ensureCss(routeName, pageObject) { if (SERVER_SIDE) { throw new Error("ClientCssHelper.registerPageLoad can't be called server-side"); } return Q.all(PageUtil.standardizeStyles(pageObject.getHeadStylesheets())).then(newCss => { var newCssByKey = {}; newCss .filter(style => !!style) .forEach(style => {newCssByKey[this._keyFromStyleSheet(style)] = style}); // first, remove the unneeded CSS link elements. Object.keys(loadedCss).forEach(loadedCssKey => { if (!newCssByKey[loadedCssKey]) { // remove the corresponding node from the DOM. logger.debug("Removing stylesheet: " + loadedCssKey); var node = loadedCss[loadedCssKey]; node.parentNode.removeChild(node); delete loadedCss[loadedCssKey]; } }); // next add the style URLs that weren't already loaded. return Q.all(Object.keys(newCssByKey).map(newCssKey => { var retval; if (!loadedCss[newCssKey]) { // this means that the CSS is not currently present in the // document, so we need to add it. logger.debug("Adding stylesheet: " + newCssKey); var style = newCssByKey[newCssKey]; var styleTag; if (style.href) { styleTag = document.createElement('link'); styleTag.rel = 'stylesheet'; styleTag.href = style.href; // If we _can_ wait for the CSS to be loaded before // proceeding, let's do so. if ('onload' in styleTag) { var dfd = Q.defer(); styleTag.onload = dfd.resolve; retval = dfd.promise; } } else { styleTag = document.createElement('style'); styleTag.innerHTML = style.text; } styleTag.type = style.type; styleTag.media = style.media; loadedCss[newCssKey] = styleTag; document.head.appendChild(styleTag); } else { logger.debug(`Stylesheet already loaded (no-op): ${newCssKey}`); } return retval; })); }); }, _keyFromStyleSheet: function(style) { return normalizeLocalUrl(style.href) || style.text; }, } function normalizeLocalUrl(url) { // Step 1: make the url protocol less first. This helps recognizing http://0.0.0.0:3001/common.css // and //0.0.0.0:3001/common.css as the same file. // Step 2: The browser will give us a full URL even if we only put a // path in on the server. So, if we're comparing against just // a path here we need to strip the base off to avoid a flash // of unstyled content. if (typeof url === 'string') { url = url .replace(/^http[s]?:/, '') .replace(new RegExp("^//" + location.host), ''); } return url; }
redfin/react-server
packages/react-server/core/util/ClientCssHelper.js
JavaScript
apache-2.0
3,519
var child_process = require('child_process'), fs = require('fs'), path = require('path'); module.exports = function(context) { var IOS_DEPLOYMENT_TARGET = '8.0', SWIFT_VERSION = '3.0', COMMENT_KEY = /_comment$/, CORDOVA_VERSION = process.env.CORDOVA_VERSION; run(); function run() { var cordova_util = context.requireCordovaModule('cordova-lib/src/cordova/util'), ConfigParser = CORDOVA_VERSION >= 6.0 ? context.requireCordovaModule('cordova-common').ConfigParser : context.requireCordovaModule('cordova-lib/src/configparser/ConfigParser'), projectRoot = cordova_util.isCordova(), platform_ios, xml = cordova_util.projectConfig(projectRoot), cfg = new ConfigParser(xml), projectName = cfg.name(), iosPlatformPath = path.join(projectRoot, 'platforms', 'ios'), iosProjectFilesPath = path.join(iosPlatformPath, projectName), xcconfigPath = path.join(iosPlatformPath, 'cordova', 'build.xcconfig'), xcconfigContent, projectFile, xcodeProject, bridgingHeaderPath; if(CORDOVA_VERSION < 7.0) { platform_ios = CORDOVA_VERSION < 5.0 ? context.requireCordovaModule('cordova-lib/src/plugman/platforms')['ios'] : context.requireCordovaModule('cordova-lib/src/plugman/platforms/ios') projectFile = platform_ios.parseProjectFile(iosPlatformPath); } else { var project_files = context.requireCordovaModule('glob').sync(path.join(iosPlatformPath, '*.xcodeproj', 'project.pbxproj')); if (project_files.length === 0) { throw new Error('Can\'t found xcode project file'); } var pbxPath = project_files[0]; var xcodeproj = context.requireCordovaModule('xcode').project(pbxPath); xcodeproj.parseSync(); projectFile = { 'xcode': xcodeproj, write: function () { var fs = context.requireCordovaModule('fs'); var frameworks_file = path.join(iosPlatformPath, 'frameworks.json'); var frameworks = {}; try { frameworks = context.requireCordovaModule(frameworks_file); console.log(JSON.stringify(frameworks)); } catch(e) {} fs.writeFileSync(pbxPath, xcodeproj.writeSync()); fs.writeFileSync(frameworks_file, JSON.stringify(this.frameworks, null, 4)); } }; } xcodeProject = projectFile.xcode; if (fs.existsSync(xcconfigPath)) { xcconfigContent = fs.readFileSync(xcconfigPath, 'utf-8'); } bridgingHeaderPath = getBridgingHeader(projectName, xcconfigContent, xcodeProject); if(bridgingHeaderPath) { bridgingHeaderPath = path.join(iosPlatformPath, bridgingHeaderPath); } else { bridgingHeaderPath = createBridgingHeader(xcodeProject, projectName, iosProjectFilesPath); } getExistingBridgingHeaders(iosProjectFilesPath, function (headers) { importBridgingHeaders(bridgingHeaderPath, headers); var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection()), config, buildSettings; for (config in configurations) { buildSettings = configurations[config].buildSettings; buildSettings['IPHONEOS_DEPLOYMENT_TARGET'] = IOS_DEPLOYMENT_TARGET; buildSettings['SWIFT_VERSION'] = SWIFT_VERSION; buildSettings['EMBEDDED_CONTENT_CONTAINS_SWIFT'] = "YES"; buildSettings['LD_RUNPATH_SEARCH_PATHS'] = '"@executable_path/Frameworks"'; } console.log('IOS project now has deployment target set as:[' + IOS_DEPLOYMENT_TARGET + '] ...'); console.log('IOS project option EMBEDDED_CONTENT_CONTAINS_SWIFT set as:[YES] ...'); console.log('IOS project swift_objc Bridging-Header set to:[' + bridgingHeaderPath + '] ...'); console.log('IOS project Runpath Search Paths set to: @executable_path/Frameworks ...'); projectFile.write(); }); } function getBridgingHeader(projectName, xcconfigContent, xcodeProject) { var configurations, config, buildSettings, bridgingHeader; if (xcconfigContent) { var regex = /^SWIFT_OBJC_BRIDGING_HEADER *=(.*)$/m, match = xcconfigContent.match(regex); if (match) { bridgingHeader = match[1]; bridgingHeader = bridgingHeader .replace("$(PROJECT_DIR)/", "") .replace("$(PROJECT_NAME)", projectName) .trim(); return bridgingHeader; } } configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection()); for (config in configurations) { buildSettings = configurations[config].buildSettings; bridgingHeader = buildSettings['SWIFT_OBJC_BRIDGING_HEADER']; if (bridgingHeader) { return unquote(bridgingHeader); } } } function createBridgingHeader(xcodeProject, projectName, xcodeProjectRootPath) { var newBHPath = path.join(xcodeProjectRootPath, "Plugins", "Bridging-Header.h"), content = ["//", "// Use this file to import your target's public headers that you would like to expose to Swift.", "//", "#import <Cordova/CDV.h>"] //fs.openSync(newBHPath, 'w'); console.log('Creating new Bridging-Header.h at path: ', newBHPath); fs.writeFileSync(newBHPath, content.join("\n"), { encoding: 'utf-8', flag: 'w' }); xcodeProject.addHeaderFile("Bridging-Header.h"); setBridgingHeader(xcodeProject, path.join(projectName, "Plugins", "Bridging-Header.h")); return newBHPath; } function setBridgingHeader(xcodeProject, headerPath) { var configurations = nonComments(xcodeProject.pbxXCBuildConfigurationSection()), config, buildSettings, bridgingHeader; for (config in configurations) { buildSettings = configurations[config].buildSettings; buildSettings['SWIFT_OBJC_BRIDGING_HEADER'] = '"' + headerPath + '"'; } } function getExistingBridgingHeaders(xcodeProjectRootPath, callback) { var searchPath = path.join(xcodeProjectRootPath, 'Plugins'); child_process.exec('find . -name "*Bridging-Header*.h"', { cwd: searchPath }, function (error, stdout, stderr) { var headers = stdout.toString().split('\n').map(function (filePath) { return path.basename(filePath); }); callback(headers); }); } function importBridgingHeaders(mainBridgingHeader, headers) { var content = fs.readFileSync(mainBridgingHeader, 'utf-8'), mainHeaderName = path.basename(mainBridgingHeader); headers.forEach(function (header) { if(header !== mainHeaderName && content.indexOf(header) < 0) { if (content.charAt(content.length - 1) != '\n') { content += "\n"; } content += "#import \""+header+"\"\n" console.log('Importing ' + header + ' into main bridging-header at: ' + mainBridgingHeader); } }); fs.writeFileSync(mainBridgingHeader, content, 'utf-8'); } function nonComments(obj) { var keys = Object.keys(obj), newObj = {}, i = 0; for (i; i < keys.length; i++) { if (!COMMENT_KEY.test(keys[i])) { newObj[keys[i]] = obj[keys[i]]; } } return newObj; } function unquote(str) { if (str) return str.replace(/^"(.*)"$/, "$1"); } }
pmwisdom/cordova-background-geolocation-services
hooks/add_swift_support.js
JavaScript
apache-2.0
8,172
var activeElements = []; var sleepElements = []; var promises = []; $.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/assetdatabases/D0EgxEhIf8KUieOFdFcX1IWQZ8qIGYDdE0m5aJCwNb4x_gSlVQSVRFUjAwMVxQSUZJVE5FU1M/elements", { type : 'GET', headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")}, success: function(results){ for (var i = 0; i < results.Items.length; i++) { var item = results.Items[i]; getSubElements(item); } } }).done(function(){ $.when.apply($,promises).done(function(){ spinner.stop(target); var blackout = document.getElementById('blackout'); $('#blackout').css('opacity', '0'); $('#blackout').css('width', '0%'); $('#blackout').css('height', '0%'); }); }); var getSubElements = function(personElement){ promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + personElement.WebId + "/elements", { type : 'GET', headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")}, success: function(results){ for (var i = 0; i < results.Items.length; i++) { var innerItem = results.Items[i]; if (innerItem.TemplateName == "Fitbit Activity Template") { getFitbitActivityAttributes({ Person : personElement.Name, Child : "Fitbit Activity", ChildWebId : innerItem.WebId }); } else if (innerItem.TemplateName == "Fitbit Sleep Template") { getFitbitSleepAttributes({ Person : personElement.Name, Child : "Fitbit Sleep", ChildWebId : innerItem.WebId }); } }}})); } var getFitbitActivityAttributes = function(object) { promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + object.ChildWebId + "/attributes",{ type : 'GET', headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")}, success: function(results){ object.Attributes = []; activeElements.push(object); for (var i = 0; i < results.Items.length; i++) { var attribute = results.Items[i]; object.Attributes.push({ Attribute : attribute.Name, AttributeWebId : attribute.WebId }); }; } })); } var getFitbitSleepAttributes = function(object) { promises.push($.ajax("https://osiproghackuc2015.osisoft.com/piwebapi/elements/" + object.ChildWebId + "/attributes",{ type : 'GET', headers: { "Authorization" : "Basic " + btoa("osiproghack\\hackuser051:bO2rA53P2")}, success: function(results){ object.Attributes = []; sleepElements.push(object); for (var i = 0; i < results.Items.length; i++) { var attribute = results.Items[i]; object.Attributes.push({ Attribute : attribute.Name, AttributeWebId : attribute.WebId }); }; } })); }
dstcontrols/UnhandledException
customJS/piWebAPI.js
JavaScript
apache-2.0
2,755
(function(jQuery) { "use strict"; var control = Echo.Control.manifest("Echo.Tests.Controls.TestControl"); if (Echo.Control.isDefined(control)) return; control.init = function() { if (!Echo.Variables) { Echo.Variables = {}; } Echo.Variables.TestControl = "production"; this.ready(); }; control.config = {}; control.templates.main = ""; Echo.Control.create(control); })(Echo.jQuery);
EchoAppsTeam/js-sdk
tests/fixtures/resources/loader/scripts.prod.js
JavaScript
apache-2.0
395
exports.view = function() { this.render(); }; exports.async = function() { this.render(); };
alibaba/plover
packages/plover/test/fixtures/core/app/modules/helper/index.js
JavaScript
apache-2.0
99
module.exports = { readFiles: readFiles }; var filewalker = require('filewalker'); var _ = require('kling/kling.js'); var fs = require('fs'); function readFiles(directory, fileSuffix) { return new Promise(function(resolve, reject) { var files = []; filewalker(directory) .on('file', function(file) { if (file.endsWith(fileSuffix)) { files.push(file); } }) .on('done', function() { var addLazyReaderCurried = _.curry(addLazyReader); resolve(_.fmap(addLazyReaderCurried(directory), files)); }) .walk(); }); } function addLazyReader(directory, file) { return { name: directory+file, getContents: function() { return fs.readFileSync(directory+file, 'utf8'); } }; }
petercrona/latmask
src/reader/reader.js
JavaScript
apache-2.0
880
/** * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const invariant = require('invariant'); /** * @typedef {object} request * @property {string} method * @property {string} route - string like /abc/:abc * @property {string} params * @property {object} [body] * @property {object} headers */ /** * @typedef {object} reponse * @property {Error} error - an error which occured during req or res * @property {object} body - content received from server (parsed) * @property {object} headers - set additional request headers * @property {number} status - http status code; 0 on failure */ /** * XHR wrapper for same-domain requests with Content-Type: application/json * * @param {request} request * @return {Promise} */ export default function implore(request) { return new Promise(resolve => { const response = { error: null }; invariant( request, 'implore requires a `request` argument' ); invariant( typeof request.route === 'string', 'implore requires parameter `route` to be a string' ); invariant( typeof request.method === 'string', 'implore requires parameter `method` to be a string' ); const xhr = new XMLHttpRequest(); xhr.open(request.method, getURLFromRequest(request)); switch (request.method) { case 'POST': case 'PUT': case 'PATCH': xhr.setRequestHeader('Content-Type', 'application/json'); break; } if (request.headers) { invariant( typeof request.headers === 'object', 'implore requires parameter `headers` to be an object' ); Object.keys(request.headers).forEach((header) => { xhr.setRequestHeader(header, request.headers[header]); }); } xhr.onreadystatechange = function onreadystatechange() { let responseText; if (xhr.readyState === 4) { responseText = xhr.responseText; response.status = xhr.status; response.type = xhr.getResponseHeader('Content-Type'); if (response.type === 'application/json') { try { response.body = JSON.parse(responseText); } catch (err) { err.message = err.message + ' while parsing `' + responseText + '`'; response.body = {}; response.status = xhr.status || 0; response.error = err; } } else { response.body = responseText; } return resolve({ request, response }); } }; try { if (request.body) { xhr.send(JSON.stringify(request.body)); } else { xhr.send(); } } catch (err) { response.body = {}; response.status = 0; response.error = err; return resolve({ request, response }); } }); } implore.get = function get(options) { options.method = 'GET'; return implore(options); }; implore.post = function post(options) { options.method = 'POST'; return implore(options); }; implore.put = function put(options) { options.method = 'PUT'; return implore(options); }; implore.delete = function httpDelete(options) { options.method = 'DELETE'; return implore(options); }; /** * Combine the route/params/query of a request into a complete URL * * @param {request} request * @param {object|array} request.query * @return {string} url */ function getURLFromRequest(request) { const queryString = makeQueryString(request.query || {}); let formatted = request.route; let name; let value; let regexp; for (name in request.params) { if (request.params.hasOwnProperty(name)) { value = request.params[name]; regexp = new RegExp(':' + name + '(?=(\\\/|$))'); formatted = formatted.replace(regexp, value); } } return formatted + (queryString ? '?' + queryString : ''); } /** * Take a simple object and turn it into a queryString, recursively. * * @param {object} obj - query object * @param {string} prefix - used in recursive calls to keep track of the parent * @return {string} queryString without the '?'' */ function makeQueryString(obj, prefix='') { const str = []; let prop; let key; let value; for (prop in obj) { if (obj.hasOwnProperty(prop)) { key = prefix ? prefix + '[' + prop + ']' : prop; value = obj[prop]; str.push(typeof value === 'object' ? makeQueryString(value, key) : encodeURIComponent(key) + '=' + encodeURIComponent(value)); } } return str.join('&'); }
mdhgriffiths/fluxthis
lib/implore.es6.js
JavaScript
apache-2.0
4,808
/* * Copyright 2016 Amadeus s.a.s. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ "use strict"; const co = require("co"); const path = require("path"); const assertFilesEqual = require("../helpers/assertFilesEqual"); const exec = require("../helpers/exec"); module.exports = function (results) { const outDir = results.outDir; const atDiffExecutable = require.resolve("../../bin/at-diff"); const filesToCompare = [ // The .json extension is automatically added "version1.parse", "version2.parse", "user.parse", "at.parse", "version1to2.diff", "filteredVersion1to2.diff", "impactsOnUser.diff", "filteredImpactsOnUser.diff" ]; filesToCompare.forEach((fileName) => { const nonDeterministicFileName = `${fileName}.json`; it(nonDeterministicFileName, co.wrap(function *() { this.timeout(10000); const transformCommand = /\.parse$/.test(fileName) ? "reformat" : "reserialize"; const deterministicFileName = `${fileName}.deterministic.json`; yield exec(atDiffExecutable, [transformCommand, nonDeterministicFileName, "--json-output", deterministicFileName, "--deterministic-output", "--json-beautify"], { cwd: outDir }); yield assertFilesEqual(path.join(outDir, deterministicFileName), path.join(__dirname, "..", "expected-output", deterministicFileName)); })); }); };
ariatemplates/at-diff
test/checks/compareWithPreviousOutputs.check.js
JavaScript
apache-2.0
1,985
/* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. Initial implementation: * http://www.mudynamics.com * http://labs.mudynamics.com * http://www.pcapr.net */ (function($) { var now = new Date().getTime(); var millisInHHour = 1000*60*30; $.jscouch = $.jscouch || {}; $.jscouch.documents = $.jscouch.documents || {}; $.extend($.jscouch.documents, { load: function() { // popluate the DB with initial entries $.jscouch.couchdb.put({ name: 'fish.jpg', created_at: new Date(now + millisInHHour*Math.random()).toUTCString(), user: 'bob', type: 'jpeg', camera: 'nikon', info: { width: 100, height: 200, size: 12345 }, tags: [ 'tuna', 'shark' ] }); $.jscouch.couchdb.put({ name: 'trees.jpg', created_at: new Date(now + millisInHHour*Math.random()).toUTCString(), user: 'john', type: 'jpeg', camera: 'canon', info: { width: 30, height: 250, size: 32091 }, tags: [ 'oak' ] }); $.jscouch.couchdb.put({ name: 'snow.png', created_at: new Date(now + millisInHHour*Math.random()).toUTCString(), user: 'john', type: 'png', camera: 'canon', info: { width: 64, height: 64, size: 1253 }, tags: [ 'tahoe', 'powder' ] }); $.jscouch.couchdb.put({ name: 'hawaii.png', created_at: new Date(now + millisInHHour*Math.random()).toUTCString(), user: 'john', type: 'png', camera: 'nikon', info: { width: 128, height: 64, size: 92834 }, tags: [ 'maui', 'tuna' ] }); $.jscouch.couchdb.put({ name: 'hawaii.gif', created_at: new Date(now + millisInHHour*Math.random()).toUTCString(), user: 'bob', type: 'gif', camera: 'canon', info: { width: 320, height: 128, size: 49287 }, tags: [ 'maui' ] }); $.jscouch.couchdb.put({ name: 'island.gif', created_at: new Date(now + millisInHHour*Math.random()).toUTCString(), user: 'zztop', type: 'gif', camera: 'nikon', info: { width: 640, height: 480, size: 50398 }, tags: [ 'maui' ] }); } }); })(jQuery);
janl/jscouch
jscouch.documents.js
JavaScript
apache-2.0
3,006
define(function (require) { var SymbolDraw = require('../helper/SymbolDraw'); var LargeSymbolDraw = require('../helper/LargeSymbolDraw'); require('../../echarts').extendChartView({ type: 'scatter', init: function () { this._normalSymbolDraw = new SymbolDraw(); this._largeSymbolDraw = new LargeSymbolDraw(); }, render: function (seriesModel, ecModel, api) { var data = seriesModel.getData(); var largeSymbolDraw = this._largeSymbolDraw; var normalSymbolDraw = this._normalSymbolDraw; var group = this.group; var symbolDraw = seriesModel.get('large') && data.count() > seriesModel.get('largeThreshold') ? largeSymbolDraw : normalSymbolDraw; this._symbolDraw = symbolDraw; symbolDraw.updateData(data); group.add(symbolDraw.group); group.remove( symbolDraw === largeSymbolDraw ? normalSymbolDraw.group : largeSymbolDraw.group ); }, updateLayout: function (seriesModel) { this._symbolDraw.updateLayout(seriesModel); }, remove: function (ecModel, api) { this._symbolDraw && this._symbolDraw.remove(api, true); } }); });
aholake/hiringviet
src/main/webapp/resources/vendors/echarts/src/chart/scatter/ScatterView.js
JavaScript
apache-2.0
1,369
/** * @author fanguozhu */ $(function() { var tab = new TabPanel("tab",true); var f_tree = new Fieldset("f_tree","公司列表",{ state: Fieldset.OPEN_STATE, topdown: false }); var mytree = new PorTreeT("tree", "-1", "手机公司",{isDefaultClick:0} ); var dw = new DataWrapper(); dw.service("PRtree"); mytree.dataWrapper(dw); tab.dataWrapper(dw); tab.addChangeObserver(function(src, msg){ var dw = this.dataWrapper(); if (!dw) return; var label = msg.data.label; var name = msg.data.name; for (var i=1;i<=3;i++) { if (label) { this.setTitle(i,"["+name+"]公司产品["+i+"]"); } else { this.setTitle(i,"全部公司产品["+i+"]"); } } },PorMessage.MSG_TREE_ONCLICK); var dw1 = new DataWrapper(); dw1.service("PR02"); var dw2 = new DataWrapper(); dw2.service("PR02"); var dw3 = new DataWrapper(); dw3.service("PR02"); var dg1 = new DataGrid("grid_1",{autoDraw:true,readonly:true}); dg1.dataWrapper(dw1); var dg2 = new DataGrid("grid_2",{autoDraw:true,readonly:true}); dg2.dataWrapper(dw2); var dg3 = new DataGrid("grid_3",{autoDraw:true,readonly:true}); dg3.dataWrapper(dw3); var mapping = { master:["label"], sub:["company"] }; PorUtil.linkTreeAndGrid( dw,[{ sub:dw1, mapping:mapping, tabs:{ tab:[0,1] //配置在'tab'的第1个tab页需要加载 } },{ sub:dw2, mapping:mapping, tabs:{ tab:[2] //配置在'tab'的第2个tab页需要加载 } },{ sub:dw3, mapping:mapping, tabs:{ tab:[3] //配置在'tab'的第3个tab页需要加载 } }]); mytree.init(); });
stserp/erp1
source/web/por2/demo/Demo/TreeTabDemo.js
JavaScript
apache-2.0
1,666
module.exports = unbuild unbuild.usage = "npm unbuild <folder>\n(this is plumbing)" var readJson = require("read-package-json") , rm = require("./utils/gently-rm.js") , gentlyRm = require("./utils/gently-rm.js") , npm = require("./npm.js") , path = require("path") , fs = require("graceful-fs") , lifecycle = require("./utils/lifecycle.js") , asyncMap = require("slide").asyncMap , chain = require("slide").chain , log = require("npmlog") , build = require("./build.js") // args is a list of folders. // remove any bins/etc, and then DELETE the folder. function unbuild (args, silent, cb) { if (typeof silent === 'function') cb = silent, silent = false asyncMap(args, unbuild_(silent), cb) } function unbuild_ (silent) { return function (folder, cb_) { function cb (er) { cb_(er, path.relative(npm.root, folder)) } folder = path.resolve(folder) delete build._didBuild[folder] log.info(folder, "unbuild") readJson(path.resolve(folder, "package.json"), function (er, pkg) { // if no json, then just trash it, but no scripts or whatever. if (er) return rm(folder, cb) readJson.cache.del(folder) chain ( [ [lifecycle, pkg, "preuninstall", folder, false, true] , [lifecycle, pkg, "uninstall", folder, false, true] , !silent && function(cb) { console.log("unbuild " + pkg._id) cb() } , [rmStuff, pkg, folder] , [lifecycle, pkg, "postuninstall", folder, false, true] , [rm, folder] ] , cb ) }) }} function rmStuff (pkg, folder, cb) { // if it's global, and folder is in {prefix}/node_modules, // then bins are in {prefix}/bin // otherwise, then bins are in folder/../.bin var parent = path.dirname(folder) , gnm = npm.dir , top = gnm === parent readJson.cache.del(path.resolve(folder, "package.json")) log.verbose([top, gnm, parent], "unbuild " + pkg._id) asyncMap([rmBins, rmMans], function (fn, cb) { fn(pkg, folder, parent, top, cb) }, cb) } function rmBins (pkg, folder, parent, top, cb) { if (!pkg.bin) return cb() var binRoot = top ? npm.bin : path.resolve(parent, ".bin") log.verbose([binRoot, pkg.bin], "binRoot") asyncMap(Object.keys(pkg.bin), function (b, cb) { if (process.platform === "win32") { chain([ [rm, path.resolve(binRoot, b) + ".cmd"] , [rm, path.resolve(binRoot, b) ] ], cb) } else { gentlyRm( path.resolve(binRoot, b) , !npm.config.get("force") && folder , cb ) } }, cb) } function rmMans (pkg, folder, parent, top, cb) { if (!pkg.man || !top || process.platform === "win32" || !npm.config.get("global")) { return cb() } var manRoot = path.resolve(npm.config.get("prefix"), "share", "man") asyncMap(pkg.man, function (man, cb) { if (Array.isArray(man)) { man.forEach(rm) } else { rm(man) } function rm(man) { var parseMan = man.match(/(.*)\.([0-9]+)(\.gz)?$/) , stem = parseMan[1] , sxn = parseMan[2] , gz = parseMan[3] || "" , bn = path.basename(stem) , manDest = path.join( manRoot , "man"+sxn , (bn.indexOf(pkg.name) === 0 ? bn : pkg.name + "-" + bn) + "." + sxn + gz ) gentlyRm( manDest , !npm.config.get("force") && folder , cb ) } }, cb) }
fabm/BabyHelp
node_modules/npm/lib/unbuild.js
JavaScript
apache-2.0
3,505
var gplay = require('google-play-scraper'); var fs = require('fs') var Promise = require('promise'); var myArgs = process.argv.slice(2); var passed_appid = myArgs[0]; var passed_appcount = myArgs[1]; console.log(passed_appid); var read = Promise.denodeify(fs.readFile); var write = Promise.denodeify(fs.writeFile); var dir = './dataset/' + passed_appcount; gplay.app({appId: passed_appid}) .then(function (str) { if(JSON.stringify(str, null, ' ').indexOf("title") > -1) { if (!fs.existsSync(dir)){ fs.mkdirSync(dir); } return write(dir + '/meta.json', JSON.stringify(str, null, ' '), 'utf8') } else { console.log('app doesnt exist'); return false } }) .then(function (){process.exit()});
iresium/apprater
scraper.js
JavaScript
apache-2.0
764
// Models app.SearchModel = Backbone.Model.extend({ idAttribute: "session_token", urlRoot: function() { var u = '/search/' + this.id; return u; } }); // Collections app.SearchCollection = Backbone.Collection.extend({ model: app.SearchModel, url: function() { if (typeof this.id === 'undefined') return '/search'; else return '/search/' + this.id; }, initialize: function(options) { if (typeof options != 'undefined') this.id = options.session_token; } }); // Views app.cardList = Backbone.View.extend({ el: '#cardList' }); app.cardView = Backbone.View.extend({ tagName: 'div', initialize: function(card) { this.card = card; }, template: _.template($("#card-template").html()), render: function(cardList) { this.$el.html(this.template({ card: this.card })); this.$el.addClass('card'); cardList.$el.append(this.el); return this; } });
GOPINATH-GS4/stock
public/lib/cards.js
JavaScript
apache-2.0
1,119
function htmlEncode(value){ return $('<div/>').text(value).html(); } var app = angular.module("oasassets",[]).controller("snippetsController",function($scope){ $scope.snippet = function(item){ var elem = $("#"+item); var contents = elem.html().trim(); elem.html(htmlEncode(contents)); $('pre code').each(function(i, block) { hljs.highlightBlock(block); }); }; $scope.loadMenu = function(){ $('#side-menu').metisMenu(); }; });
bizoru/assets-oas
js/app.js
JavaScript
apache-2.0
510
(function (chaiJquery) { // Module systems magic dance. if (typeof require === "function" && typeof exports === "object" && typeof module === "object") { // NodeJS module.exports = chaiJquery; } else if (typeof define === "function" && define.amd) { // AMD define(function () { return chaiJquery; }); } else { // Other environment (usually <script> tag): pass into global chai var global = (false || eval)("this"); global.chai.use(chaiJquery); } }(function (chai, utils) { var inspect = utils.inspect, flag = utils.flag; jQuery.fn.inspect = function (depth) { var el = jQuery('<div />').append(this.clone()); if (depth) { var children = el.children(); while (depth-- > 0) children = children.children(); children.html('...'); } return el.html(); }; chai.Assertion.addMethod('attr', function (name, val) { var actual = flag(this, 'object').attr(name); if (!flag(this, 'negate') || undefined === val) { this.assert( undefined !== actual , 'expected #{this} to have a #{exp} attribute' , 'expected #{this} not to have a #{exp} attribute' , name ); } if (undefined !== val) { this.assert( val === actual , 'expected #{this} to have a ' + inspect(name) + ' attribute with the value #{exp}, but the value was #{act}' , 'expected #{this} not to have a ' + inspect(name) + ' attribute with the value #{act}' , val , actual ); } flag(this, 'object', actual); }); chai.Assertion.addMethod('data', function (name, val) { // Work around a chai bug (https://github.com/logicalparadox/chai/issues/16) if (flag(this, 'negate') && undefined !== val && undefined === flag(this, 'object').data(name)) { return; } var assertion = new chai.Assertion(flag(this, 'object').data()); if (flag(this, 'negate')) assertion = assertion.not; assertion.property(name, val); }); chai.Assertion.addMethod('class', function (className) { this.assert( flag(this, 'object').hasClass(className) , 'expected #{this} to have class #{exp}' , 'expected #{this} not to have class #{exp}' , className ); }); chai.Assertion.addMethod('id', function (id) { this.assert( flag(this, 'object').attr('id') === id , 'expected #{this} to have id #{exp}' , 'expected #{this} not to have id #{exp}' , id ); }); chai.Assertion.addMethod('html', function (html) { this.assert( flag(this, 'object').html() === html , 'expected #{this} to have HTML #{exp}' , 'expected #{this} not to have HTML #{exp}' , html ); }); chai.Assertion.addMethod('text', function (text) { this.assert( flag(this, 'object').text() === text , 'expected #{this} to have text #{exp}' , 'expected #{this} not to have text #{exp}' , text ); }); chai.Assertion.addMethod('value', function (value) { this.assert( flag(this, 'object').val() === value , 'expected #{this} to have value #{exp}' , 'expected #{this} not to have value #{exp}' , value ); }); jQuery.each(['visible', 'hidden', 'selected', 'checked', 'disabled'], function (i, attr) { chai.Assertion.addProperty(attr, function () { this.assert( flag(this, 'object').is(':' + attr) , 'expected #{this} to be ' + attr , 'expected #{this} not to be ' + attr); }); }); chai.Assertion.overwriteProperty('exist', function (_super) { return function () { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( obj.length > 0 , 'expected ' + inspect(obj.selector) + ' to exist' , 'expected ' + inspect(obj.selector) + ' not to exist'); } else { _super.apply(this, arguments); } }; }); chai.Assertion.overwriteProperty('be', function (_super) { return function () { var be = function (selector) { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( obj.is(selector) , 'expected #{this} to be #{exp}' , 'expected #{this} not to be #{exp}' , selector ); } else { _super.apply(this, arguments); } }; be.__proto__ = this; return be; } }); chai.Assertion.overwriteMethod('match', function (_super) { return function (selector) { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( obj.is(selector) , 'expected #{this} to match #{exp}' , 'expected #{this} not to match #{exp}' , selector ); } else { _super.apply(this, arguments); } } }); chai.Assertion.overwriteProperty('contain', function (_super) { return function () { _super.call(this); var contain = function (text) { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( obj.is(':contains(\'' + text + '\')') , 'expected #{this} to contain #{exp}' , 'expected #{this} not to contain #{exp}' , text ); } else { Function.prototype.apply.call(_super.call(this), this, arguments); } }; contain.__proto__ = this; return contain; } }); chai.Assertion.overwriteProperty('have', function (_super) { return function () { _super.call(this); var have = function (selector) { var obj = flag(this, 'object'); if (obj instanceof jQuery) { this.assert( // Using find() rather than has() to work around a jQuery bug: // http://bugs.jquery.com/ticket/11706 obj.find(selector).length > 0 , 'expected #{this} to have #{exp}' , 'expected #{this} not to have #{exp}' , selector ); } }; have.__proto__ = this; return have; } }); }));
reaktor/jquery.spinner
test/chai-jquery-1.0.0.js
JavaScript
apache-2.0
6,187
'use strict'; viewModel.MonitoringAlarm = new Object(); var ma = viewModel.MonitoringAlarm; ma.minDatetemp = new Date(); ma.maxDatetemp = new Date(); ma.minDateRet = new Date(); ma.maxDateRet = new Date(); vm.currentMenu('Alarm Data'); vm.currentTitle('Alarm Data'); vm.isShowDataAvailability(false); vm.breadcrumb([ { title: "Monitoring", href: '#' }, { title: 'Alarm Data', href: viewModel.appName + 'page/monitoringalarm' }]); var intervalTurbine = null; ma.UpdateProjectList = function(project) { setTimeout(function(){ $('#projectList').data('kendoDropDownList').value(project); $("#projectList").data("kendoDropDownList").trigger("change"); },1000) } ma.UpdateTurbineList = function(turbineList) { if(turbineList.length == 0){ $("#turbineList").multiselect('selectAll', false).multiselect("refresh"); }else{ $('#turbineList').multiselect("deselectAll", false).multiselect("refresh"); $('#turbineList').multiselect('select', turbineList); } } ma.CreateGrid = function(gridType) { app.loading(true); $.when(fa.LoadData()).done(function () { var COOKIES = {}; var cookieStr = document.cookie; var param = { period: fa.period, dateStart: fa.dateStart, dateEnd: fa.dateEnd, turbine: [], project: "", tipe: gridType, }; if(localStorage.getItem("projectname") !== null && localStorage.getItem("turbine") !== null) { var locTurbine = localStorage.getItem("turbine"); param.turbine = locTurbine == "" ? [] : [locTurbine]; param.project = localStorage.getItem("projectname"); var tabActive = localStorage.getItem("tabActive"); $.when(ma.UpdateProjectList(param.project)).done(function () { setTimeout(function(){ ma.UpdateTurbineList(param.turbine); setTimeout(function() { ma.LoadDataAvail(param.project, gridType); if(tabActive !== null){ if(tabActive == "alarmRaw" ){ $("#alarmrawTab a:first-child").trigger('click'); }else{ ma.CreateGridAlarm(gridType, param); } } },500); app.resetLocalStorage(); }, 1500); }); } else { param.turbine = fa.turbine(); param.project = fa.project; ma.CreateGridAlarm(gridType, param); } }); } ma.buildParentFilter = function(filters, additionalFilter) { $.each(filters, function(idx, val){ if(val.filter !== undefined) { ma.buildParentFilter(val.filter.filters, additionalFilter) } additionalFilter.push(val); }); } ma.CreateGridAlarm = function(gridType, param) { var gridName = "#alarmGrid" var dt = new Date(); var time = dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds(); var nameFile = "Monitoring Alarm Down_"+ moment(new Date()).format("Y-M-D")+"_"+time; var defaultsort = [ { field: "TimeStart", dir: "desc" }, { field: "TimeEnd", dir: "asc" } ] var url = viewModel.appName + "monitoringrealtime/getdataalarm"; if(gridType == "warning") { gridName = "#warningGrid" nameFile = "Monitoring Alarm Warning"; } if(gridType == "alarmraw"){ gridName = "#alarmRawGrid" nameFile = "Monitoring Alarm Raw"; defaultsort = [ { field: "TimeStamp", dir: "desc" } ] } var columns = [{ field: "turbine", title: "Turbine", attributes: { style: "text-align:center;" }, filterable: false, width: 90 }, { field: "timestart", title: "Time Start", width: 170, filterable: false, attributes: { style: "text-align:center;" }, template: "#= moment.utc(data.timestart).format('DD-MMM-YYYY') # &nbsp; &nbsp; &nbsp; #=moment.utc(data.timestart).format('HH:mm:ss')#" }, { field: "timeend", title: "Time End", width: 170, filterable: false, attributes: { style: "text-align:center;" }, template: "#= (moment.utc(data.timeend).format('DD-MM-YYYY') == '01-01-0001'?'Not yet finished' : (moment.utc(data.timeend).format('DD-MMM-YYYY') # &nbsp; &nbsp; &nbsp; #=moment.utc(data.timeend).format('HH:mm:ss')))#" }, { field: "duration", title: "Duration (hh:mm:ss)", width: 120, attributes: { style: "text-align:center;" }, filterable: false, //template: "#= time(data.duration) #" template: '#= kendo.toString(secondsToTime(data.duration)) #', }, { field: "alarmcode", title: "Alarm Code", attributes: { style: "text-align:center;" }, filterable: { operators: { string: { eq: "Is equal to" } }, ui: function(element) { var form = element.closest("form"); form.find(".k-filter-help-text:first").text("Show items equal to:"); form.find("select").remove(); $("form").find("[data-bind='value:filters[0].value']").addClass('k-textbox'); } }, width: 90, },{ field: "alarmdesc", title: "Description", width: 330, }]; if(gridType == "alarm"){ columns.push({ field: "reduceavailability", title: "Reduce Avail.", attributes: { style: "text-align:center;" }, filterable: false, width: 90, }); } if(gridType == "alarmraw"){ columns = [{ field: "turbine", title: "Turbine", attributes: { style: "text-align:center;" }, filterable: false, width: 70 }, { field: "timestamp", title: "Timestamp", width: 120, attributes: { style: "text-align:center;" }, filterable: false, template: "#= moment.utc(data.timestamp).format('DD-MMM-YYYY') # &nbsp; &nbsp; &nbsp; #=moment.utc(data.timestamp).format('HH:mm:ss')#" }, { field: "tag", title: "Tag", width: 120, filterable: false, attributes: { style: "text-align:center;" }, }, { field: "value", title: "Value", attributes: { style: "text-align:center;" }, filterable: false, width: 70, // template: "#= kendo.toString(data.Timestamp,'n2') #" }, { field: "description", title: "Description", width: 200 }, { field: "addinfo", title: "Note", filterable: false, width: 250 }]; } $(gridName).html(''); $(gridName).kendoGrid({ dataSource: { serverPaging: true, serverSorting: true, serverFiltering: true, transport: { read: { url: url, type: "POST", data: param, dataType: "json", contentType: "application/json; charset=utf-8", }, parameterMap: function(options) { var additionalFilter = []; if(options.filter !== undefined && options.filter != null) { ma.buildParentFilter(options.filter.filters, additionalFilter) } if (additionalFilter.length > 0) { options["filter"] = additionalFilter; } return JSON.stringify(options); } }, schema: { data: function data(res) { if (!app.isFine(res)) { return; } var totalFreq = res.data.Total; var totalHour = res.data.Duration; ma.minDateRet = new Date(res.data.mindate); ma.maxDateRet = new Date(res.data.maxdate); ma.checkCompleteDate() $('#alarm_duration').text((totalHour/3600).toFixed(2)); $('#alarm_frequency').text(totalFreq); setTimeout(function(){ app.loading(false); }, 300) return res.data.Data; }, total: function data(res) { return res.data.Total; } }, pageSize: 10, sort: defaultsort, }, // toolbar: ["excel"], excel: { fileName: nameFile+".xlsx", filterable: true, allPages: true }, // pdf: { // fileName: nameFile+".pdf", // }, sortable: true, pageable: { refresh: true, pageSizes: true, buttonCount: 5 }, filterable: { extra: false, operators: { string: { contains: "Contains", eq: "Is equal to" }, } }, columns: columns }); }; function secondsToTime(d) { d = Number(d); var h = Math.floor(d / 3600); var m = Math.floor(d % 3600 / 60); var s = Math.floor(d % 3600 % 60); var res = (h > 0 ? (h < 10 ? "0" + h : h) : "00") + ":" + (m > 0 ? (m < 10 ? "0" + m : m) : "00") + ":" + (s > 0 ? s : "00") return res; } function time(s) { return new Date(s * 1e3).toISOString().slice(-13, -5); } ma.InitDateValue = function () { var maxDateData = new Date(); var lastStartDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0)); var lastEndDate = new Date(Date.UTC(moment(maxDateData).get('year'), maxDateData.getMonth(), maxDateData.getDate(), 0, 0, 0, 0)); $('#dateStart').data('kendoDatePicker').value(lastStartDate); $('#dateEnd').data('kendoDatePicker').value(lastEndDate); } ma.LoadDataAvail = function(projectname, gridType){ //fa.LoadData(); var payload = { project: projectname, tipe: gridType }; toolkit.ajaxPost(viewModel.appName + "monitoringrealtime/getdataalarmavaildate", payload, function (res) { if (!app.isFine(res)) { return; } if (res.data.Data.length == 0) { res.data.Data = []; } else { if (res.data.Data.length > 0) { ma.minDatetemp = new Date(res.data.Data[0]); ma.maxDatetemp = new Date(res.data.Data[1]); app.currentDateData = new Date(res.data.Data[1]); $('#availabledatestart').html(kendo.toString(moment.utc(ma.minDatetemp).format('DD-MMMM-YYYY'))); $('#availabledateend').html(kendo.toString(moment.utc(ma.maxDatetemp).format('DD-MMMM-YYYY'))); // $('#dateStart').data('kendoDatePicker').value( new Date(Date.UTC(moment( ma.maxDatetemp).get('year'), ma.maxDatetemp.getMonth(), ma.maxDatetemp.getDate() - 7, 0, 0, 0, 0))); // $('#dateEnd').data('kendoDatePicker').value(kendo.toString(moment.utc(res.data.Data[1]).format('DD-MMM-YYYY'))); ma.checkCompleteDate(); } } }); } ma.checkCompleteDate = function () { var currentDateData = moment.utc(ma.maxDatetemp).format('YYYY-MM-DD'); var prevDateData = moment.utc(ma.minDatetemp).format('YYYY-MM-DD'); var dateStart = moment.utc(ma.minDateRet).format('YYYY-MM-DD'); var dateEnd = moment.utc(ma.maxDateRet).format('YYYY-MM-DD'); if ((dateEnd > currentDateData) || (dateStart > currentDateData)) { fa.infoPeriodIcon(true); } else if ((dateEnd < prevDateData) || (dateStart < prevDateData)) { fa.infoPeriodIcon(true); } else { fa.infoPeriodIcon(false); fa.infoPeriodRange(""); } } ma.ToByProject = function(){ setTimeout(function(){ app.loading(true); app.resetLocalStorage(); var project = $('#projectList').data('kendoDropDownList').value(); localStorage.setItem('projectname', project); if(localStorage.getItem("projectname")){ window.location = viewModel.appName + "page/monitoringbyproject"; } },1500); } ma.exportToExcel = function(id){ $("#"+id).getKendoGrid().saveAsExcel(); } $(document).ready(function(){ $('#btnRefresh').on('click', function () { fa.checkTurbine(); if($('.nav').find('li.active').find('a.tab-custom').text() == "Alarm Down") { ma.CreateGrid("alarm"); } else if($('.nav').find('li.active').find('a.tab-custom').text() == "Alarm Warning") { ma.CreateGrid("warning"); }else{ ma.CreateGrid("alarmraw"); } }); //setTimeout(function() { $.when(ma.InitDateValue()).done(function () { setTimeout(function() { ma.CreateGrid("alarm"); ma.LoadDataAvail(fa.project, "alarm"); }, 100); }); //}, 300); $('#projectList').kendoDropDownList({ change: function () { var project = $('#projectList').data("kendoDropDownList").value(); fa.populateTurbine(project); ma.LoadDataAvail(project, "alarm"); } }); });
eaciit/windapp
web/assets/core/js/page-monitoring/monitoring-alarm.js
JavaScript
apache-2.0
14,310
import React from 'react'; import { action } from '@storybook/addon-actions'; import { Action } from '../Actions'; import ActionBar from './ActionBar.component'; const primary = { label: 'Primary', icon: 'talend-cog', bsStyle: 'primary', 'data-feature': 'actionbar.primary', onClick: action('You clicked me'), }; const actions = { left: [ primary, { label: 'Secondary1', icon: 'talend-cog', 'data-feature': 'actionbar.secondary', onClick: action('You clicked me'), }, { displayMode: ActionBar.DISPLAY_MODES.SPLIT_DROPDOWN, label: 'Secondary3', icon: 'talend-cog', 'data-feature': 'actionbar.splitdropdown', onClick: action('on split button click'), items: [ { label: 'From Local', 'data-feature': 'actionbar.splitdropdown.items', onClick: action('From Local click'), }, { label: 'From Remote', 'data-feature': 'actionbar.splitdropdown.items', onClick: action('From Remote click'), }, ], emptyDropdownLabel: 'No option', }, { id: 'dropdown', displayMode: ActionBar.DISPLAY_MODES.DROPDOWN, label: 'Dropdown', icon: 'talend-cog', items: [ { label: 'From Local', onClick: action('From Local click'), }, { label: 'From Remote', onClick: action('From Remote click'), }, ], }, ], right: [ { label: 'Secondary4', icon: 'talend-upload', displayMode: 'file', onChange: action('You changed me'), }, { label: 'Secondary5', icon: 'talend-cog', onClick: action('You clicked me'), }, ], }; const multi3 = { label: 'multi3', icon: 'talend-cog', onClick: action('You clicked me'), }; const multiSelectActions = { left: [ { label: 'multi1', icon: 'talend-cog', onClick: action('You clicked me'), }, { label: 'multi2', icon: 'talend-cog', onClick: action('You clicked me'), }, ], center: [ { label: 'multi5', icon: 'talend-cog', onClick: action('You clicked me'), }, ], right: [ multi3, { label: 'multi4', icon: 'talend-cog', onClick: action('You clicked me'), }, ], }; const btnGroupActions = { left: [ { displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP, actions: [ { label: 'hidden mean tooltips', icon: 'talend-cog', hideLabel: true, onClick: action('cog'), }, { label: 'you are a super star', icon: 'talend-badge', hideLabel: true, onClick: action('badge'), }, { label: 'but don t click this', icon: 'talend-cross', hideLabel: true, onClick: action('boom'), }, { label: 'edit me', icon: 'talend-pencil', hideLabel: true, onClick: action('oh yes'), }, ], }, { displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP, actions: [ { label: 'you can also add', icon: 'talend-plus-circle', hideLabel: true, onClick: action('add !'), }, { label: 'search', icon: 'talend-search', hideLabel: true, onClick: action('search'), }, { label: 'star', icon: 'talend-star', hideLabel: true, onClick: action('star'), }, ], }, ], center: [ { displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP, actions: [ { label: 'go to dataprep', icon: 'talend-dataprep', hideLabel: true, onClick: action('dataprep'), }, { label: 'go to elastic', icon: 'talend-elastic', hideLabel: true, onClick: action('elastic'), }, { label: 'go to cloud engine', icon: 'talend-cloud-engine', hideLabel: true, onClick: action('cloud-engine'), }, ], }, ], right: [ { displayMode: ActionBar.DISPLAY_MODES.BTN_GROUP, actions: [ { label: 'table', icon: 'talend-table', hideLabel: true, onClick: action('table'), }, { label: 'trash', icon: 'talend-trash', hideLabel: true, onClick: action('trash'), }, ], }, ], }; const basicProps = { actions, multiSelectActions, }; const multiDelete = { label: 'Delete', icon: 'talend-trash', onClick: action('multiple delete'), className: 'btn-icon-text', }; const multiDuplicate = { label: 'Duplicate', icon: 'talend-files-o', onClick: action('multiple duplicate'), className: 'btn-icon-text', }; const multiUpdate = { label: 'Update', icon: 'talend-file-move', onClick: action('multiple update'), className: 'btn-icon-text', }; const multiFavorite = { label: 'Favorite', icon: 'talend-star', onClick: action('multiple favorite'), className: 'btn-icon-text', }; const multiCertify = { label: 'Certify', icon: 'talend-badge', onClick: action('multiple certify'), className: 'btn-icon-text', }; const massActions = { left: [multiDelete, multiDuplicate, multiUpdate], }; const appMassActions = { left: [multiFavorite, multiCertify], }; export default { title: 'Form/Controls/ActionBar', }; export const Default = () => ( <nav> <p>No Selected, Layout: Left Space Right</p> <div id="default"> <ActionBar {...basicProps} selected={0} /> </div> <p>1 Selected, Layout: Left Center Right</p> <div id="selected"> <ActionBar {...basicProps} selected={1} /> </div> <p>1 Selected, Layout: Right</p> <div id="right"> <ActionBar selected={1} actions={{ left: [primary] }} multiSelectActions={{ right: [multi3] }} /> </div> <p>Toolbar with btn-group and only icons/ Layout: left, center, right</p> <div id="btn-group"> <ActionBar actions={btnGroupActions} /> </div> <p>3 items selected, with mass/bulk Actions</p> <div id="mass-actions"> <ActionBar selected={3} multiSelectActions={massActions} appMultiSelectActions={appMassActions} /> </div> </nav> ); export const Custom = () => ( <nav> <div id="default"> <ActionBar> <ActionBar.Content tag="a" left href="#/foo/bar"> Hello anchor </ActionBar.Content> <ActionBar.Content tag="button" className="btn btn-default" left> Hello button </ActionBar.Content> <ActionBar.Content left> <Action label="hello Action" icon="talend-trash" onClick={action('onClick')} /> </ActionBar.Content> <ActionBar.Content tag="form" role="search" center> <div className="form-group"> <input type="text" className="form-control" placeholder="Search" /> </div> <button type="submit" className="btn btn-default"> Submit </button> </ActionBar.Content> <ActionBar.Content tag="p" right> Hello paragraph </ActionBar.Content> </ActionBar> </div> </nav> );
Talend/ui
packages/components/src/ActionBar/ActionBar.stories.js
JavaScript
apache-2.0
6,576
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const options_1 = require("./options"); class TslintFixTask { constructor(configOrPath, options) { if (options) { this._configOrPath = configOrPath; this._options = options; } else { this._options = configOrPath; this._configOrPath = null; } } toConfiguration() { const path = typeof this._configOrPath == 'string' ? { tslintPath: this._configOrPath } : {}; const config = typeof this._configOrPath == 'object' && this._configOrPath !== null ? { tslintConfig: this._configOrPath } : {}; const options = { ...this._options, ...path, ...config, }; return { name: options_1.TslintFixName, options }; } } exports.TslintFixTask = TslintFixTask;
cloudfoundry-community/asp.net5-buildpack
fixtures/node_apps/angular_dotnet/ClientApp/node_modules/@angular-devkit/schematics/tasks/tslint-fix/task.js
JavaScript
apache-2.0
913
'use strict'; var fs = require('fs'); var path = require('path'); var util = require('util'); var dbg = require('debug'); // process.env.TABTAB_DEBUG = process.env.TABTAB_DEBUG || '/tmp/tabtab.log'; var out = process.env.TABTAB_DEBUG ? fs.createWriteStream(process.env.TABTAB_DEBUG, { flags: 'a' }) : null; module.exports = debug; // Internal: Facade to debug module, which provides the exact same interface. // // The added benefit is with the TABTAB_DEBUG environment variable, which when // defined, will write debug output to the specified filename. // // Usefull when debugging tab completion, as logs on stdout / stderr are either // shallowed or used as tab completion results. // // namespace - The String namespace to use when TABTAB_DEBUG is not defined, // delegates to debug module. // // Examples // // // Use with following command to redirect output to file // // TABTAB_DEBUG="debug.log" tabtab ... // debug('Foo'); function debug(namespace) { var log = dbg(namespace); return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } args = args.map(function (arg) { if (typeof arg === 'string') return arg; return JSON.stringify(arg); }); out && out.write(util.format.apply(util, args) + '\n'); out || log.apply(null, args); }; }
bhav0904/netDelSolution
node_modules/tabtab/src/debug.js
JavaScript
apache-2.0
1,398
// Copyright (c) 2015-2016 Yuya Ochiai // Copyright (c) 2016-present Mattermost, Inc. All Rights Reserved. // See LICENSE.txt for license information. import AutoLaunch from 'auto-launch'; import {app} from 'electron'; function shouldQuitApp(cmd) { if (process.platform !== 'win32') { return false; } const squirrelCommands = ['--squirrel-install', '--squirrel-updated', '--squirrel-uninstall', '--squirrel-obsolete']; return squirrelCommands.includes(cmd); } async function setupAutoLaunch(cmd) { const appLauncher = new AutoLaunch({ name: app.getName(), isHidden: true, }); if (cmd === '--squirrel-uninstall') { // If we're uninstalling, make sure we also delete our auto launch registry key await appLauncher.disable(); } else if (cmd === '--squirrel-install' || cmd === '--squirrel-updated') { // If we're updating and already have an registry entry for auto launch, make sure to update the path const enabled = await appLauncher.isEnabled(); if (enabled) { await appLauncher.enable(); } } } export default function squirrelStartup(callback) { if (process.platform === 'win32') { const cmd = process.argv[1]; setupAutoLaunch(cmd).then(() => { if (require('electron-squirrel-startup') && callback) { // eslint-disable-line global-require callback(); } }); return shouldQuitApp(cmd); } return false; }
yuya-oc/desktop
src/main/squirrelStartup.js
JavaScript
apache-2.0
1,409
var nodes = new vis.DataSet([ /* {id: a, label: b, ...}, */ {id: '192', label: 'VALUE\n13.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 13.0<br>Type: CONSTANT_VALUE<br>Id: 192<br>Formula Expression: Formula String: VALUE; Formula Values: 13.0; Formula Ptg: 13.0; Ptgs: VALUE Index in Ptgs: 0 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '193', label: 'VALUE\n9.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 9.0<br>Type: CONSTANT_VALUE<br>Id: 193<br>Formula Expression: Formula String: VALUE; Formula Values: 9.0; Formula Ptg: 9.0; Ptgs: VALUE Index in Ptgs: 1 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '194', label: 'VALUE\n5.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 5.0<br>Type: CONSTANT_VALUE<br>Id: 194<br>Formula Expression: Formula String: VALUE; Formula Values: 5.0; Formula Ptg: 5.0; Ptgs: VALUE Index in Ptgs: 2 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '195', label: 'VALUE\n7.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 7.0<br>Type: CONSTANT_VALUE<br>Id: 195<br>Formula Expression: Formula String: VALUE; Formula Values: 7.0; Formula Ptg: 7.0; Ptgs: VALUE Index in Ptgs: 3 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '196', label: 'VALUE\n12.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 12.0<br>Type: CONSTANT_VALUE<br>Id: 196<br>Formula Expression: Formula String: VALUE; Formula Values: 12.0; Formula Ptg: 12.0; Ptgs: VALUE Index in Ptgs: 4 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '197', label: 'VALUE\n5.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 5.0<br>Type: CONSTANT_VALUE<br>Id: 197<br>Formula Expression: Formula String: VALUE; Formula Values: 5.0; Formula Ptg: 5.0; Ptgs: VALUE Index in Ptgs: 5 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '198', label: 'VALUE\n46.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 46.0<br>Type: CONSTANT_VALUE<br>Id: 198<br>Formula Expression: Formula String: VALUE; Formula Values: 46.0; Formula Ptg: 46.0; Ptgs: VALUE Index in Ptgs: 6 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '199', label: 'VALUE\n85.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 85.0<br>Type: CONSTANT_VALUE<br>Id: 199<br>Formula Expression: Formula String: VALUE; Formula Values: 85.0; Formula Ptg: 85.0; Ptgs: VALUE Index in Ptgs: 7 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '200', label: 'VALUE\n15.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 15.0<br>Type: CONSTANT_VALUE<br>Id: 200<br>Formula Expression: Formula String: VALUE; Formula Values: 15.0; Formula Ptg: 15.0; Ptgs: VALUE Index in Ptgs: 8 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '201', label: 'VALUE\n159.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 159.0<br>Type: CONSTANT_VALUE<br>Id: 201<br>Formula Expression: Formula String: VALUE; Formula Values: 159.0; Formula Ptg: 159.0; Ptgs: VALUE Index in Ptgs: 9 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '202', label: 'VALUE\n452.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 452.0<br>Type: CONSTANT_VALUE<br>Id: 202<br>Formula Expression: Formula String: VALUE; Formula Values: 452.0; Formula Ptg: 452.0; Ptgs: VALUE Index in Ptgs: 10 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '203', label: 'VALUE\n452.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 452.0<br>Type: CONSTANT_VALUE<br>Id: 203<br>Formula Expression: Formula String: VALUE; Formula Values: 452.0; Formula Ptg: 452.0; Ptgs: VALUE Index in Ptgs: 11 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '204', label: 'VALUE\n365.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 365.0<br>Type: CONSTANT_VALUE<br>Id: 204<br>Formula Expression: Formula String: VALUE; Formula Values: 365.0; Formula Ptg: 365.0; Ptgs: VALUE Index in Ptgs: 12 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '205', label: 'VALUE\n36.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 36.0<br>Type: CONSTANT_VALUE<br>Id: 205<br>Formula Expression: Formula String: VALUE; Formula Values: 36.0; Formula Ptg: 36.0; Ptgs: VALUE Index in Ptgs: 13 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '206', label: 'VALUE\n362.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 362.0<br>Type: CONSTANT_VALUE<br>Id: 206<br>Formula Expression: Formula String: VALUE; Formula Values: 362.0; Formula Ptg: 362.0; Ptgs: VALUE Index in Ptgs: 14 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '207', label: 'VALUE\n23.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 23.0<br>Type: CONSTANT_VALUE<br>Id: 207<br>Formula Expression: Formula String: VALUE; Formula Values: 23.0; Formula Ptg: 23.0; Ptgs: VALUE Index in Ptgs: 15 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '208', label: 'VALUE\n236.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 236.0<br>Type: CONSTANT_VALUE<br>Id: 208<br>Formula Expression: Formula String: VALUE; Formula Values: 236.0; Formula Ptg: 236.0; Ptgs: VALUE Index in Ptgs: 16 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '209', label: 'VALUE\n562.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 562.0<br>Type: CONSTANT_VALUE<br>Id: 209<br>Formula Expression: Formula String: VALUE; Formula Values: 562.0; Formula Ptg: 562.0; Ptgs: VALUE Index in Ptgs: 17 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '210', label: 'VALUE\n45.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 45.0<br>Type: CONSTANT_VALUE<br>Id: 210<br>Formula Expression: Formula String: VALUE; Formula Values: 45.0; Formula Ptg: 45.0; Ptgs: VALUE Index in Ptgs: 18 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '211', label: 'VALUE\n125.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 125.0<br>Type: CONSTANT_VALUE<br>Id: 211<br>Formula Expression: Formula String: VALUE; Formula Values: 125.0; Formula Ptg: 125.0; Ptgs: VALUE Index in Ptgs: 19 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '212', label: 'VALUE\n23.0', color: '#31b0d5', title: 'Name: VALUE<br>Alias: null<br>Value: 23.0<br>Type: CONSTANT_VALUE<br>Id: 212<br>Formula Expression: Formula String: VALUE; Formula Values: 23.0; Formula Ptg: 23.0; Ptgs: VALUE Index in Ptgs: 20 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '213', label: 'CHOOSE\n36.0', color: '#f0ad4e', title: 'Name: CHOOSE<br>Alias: null<br>Value: 36.0<br>Type: FUNCTION<br>Id: 213<br>Formula Expression: Formula String: CHOOSE(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE); Formula Values: CHOOSE(23.0, 125.0, 45.0, 562.0, 236.0, 23.0, 362.0, 36.0, 365.0, 452.0, 452.0, 159.0, 15.0, 85.0, 46.0, 5.0, 12.0, 7.0, 5.0, 9.0, 13.0); Formula Ptg: ; Ptgs: Index in Ptgs: 21 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'}, {id: '191', label: 'B2\n36.0', color: '#31b0d5', title: 'Name: B2<br>Alias: null<br>Value: 36.0<br>Type: CELL_WITH_FORMULA<br>Id: 191<br>Formula Expression: Formula String: CHOOSE(VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE, VALUE); Formula Values: CHOOSE(23.0, 125.0, 45.0, 562.0, 236.0, 23.0, 362.0, 36.0, 365.0, 452.0, 452.0, 159.0, 15.0, 85.0, 46.0, 5.0, 12.0, 7.0, 5.0, 9.0, 13.0); Formula Ptg: ; Ptgs: Index in Ptgs: 0 <br>Source Object Id: com.dataart.spreadsheetanalytics.engine.PoiProxyWorkbook@301eda63'} ]); var edges = new vis.DataSet([ /* {from: id_a, to: id_b}, */ {from: '212', to: '213'}, {from: '211', to: '213'}, {from: '210', to: '213'}, {from: '209', to: '213'}, {from: '208', to: '213'}, {from: '207', to: '213'}, {from: '206', to: '213'}, {from: '205', to: '213'}, {from: '204', to: '213'}, {from: '203', to: '213'}, {from: '213', to: '191'}, {from: '202', to: '213'}, {from: '201', to: '213'}, {from: '200', to: '213'}, {from: '199', to: '213'}, {from: '198', to: '213'}, {from: '197', to: '213'}, {from: '196', to: '213'}, {from: '195', to: '213'}, {from: '194', to: '213'}, {from: '193', to: '213'}, {from: '192', to: '213'} ]);
DataArt/CalculationEngine
calculation-engine/engine-tests/engine-it-graph/src/test/resources/standard_data_js_files/data_CHOOSE_Fx_cells_B2.js
JavaScript
apache-2.0
9,297
[ { "title": "Ventes véhicules", "url": "", "imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg", "language": "fr-FR", "order": "1", "workplace": "All", "department": "All", "categoryPro": "All", "status": "published", "children": [ { "title": "http://portail.inetpsa.com/sites/gpmobile/PublishingImages/car2.jpg", "url": "http://portail.inetpsa.com/sites/gpmobile/PublishingImages/car2.jpg", "imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg", "language": "fr-FR", "order": 0, "workplace": "All", "department": "All", "categoryPro": "All", "status": "published" }, { "title": "Ventes véhicules Peugeot", "url": "https://docinfogroupe.psa-peugeot-citroen.com/ead/dom/1000788899.fd", "imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg", "language": "fr-FR", "order": 1, "workplace": "All", "department": "All", "categoryPro": "All", "status": "edited" }, { "title": "Ventes véhicules DS", "url": "https://docinfogroupe.psa-peugeot-citroen.com/ead/dom/1000779116.fd", "imageUrl": "http://lim.local.inetpsa.com/application/images/service/car2.jpg", "language": "fr-FR", "order": 2, "workplace": "All", "department": "All", "categoryPro": "All", "status": "published" } ] }, { "title": "Webmail", "url": "https://webmail.mpsa.com/", "imageUrl": "http://lim.local.inetpsa.com/application/images/service/webmail.jpg", "language": "en-US", "order": "0", "workplace": "All", "department": "All", "categoryPro": "All", "status": "published", "children": [] }, { "title": "Net'RH congés", "url": "https://fr-rh.mpsa.com/rib00/ribdnins.nsf/fc583fb6947d633ac12569450031fbd2/755dcfb785421c6cc1256c7f003107c2?OpenDocument", "imageUrl": "http://lim.local.inetpsa.com/application/images/service/holiday.jpg", "language": "fr-FR", "order": "3", "workplace": "All", "department": "All", "categoryPro": "All", "status": "unpublished", "children": [] } ]
florentbruel/livein
services.js
JavaScript
apache-2.0
2,378
sap.ui.define(["sap/ui/integration/Designtime"], function ( Designtime ) { "use strict"; return function () { return new Designtime({ "form": { "items": { "validationGroup": { "type": "group", "label": "Validation" }, "OrderID": { "manifestpath": "/sap.card/configuration/parameters/OrderID/value", "label": "Order Id", "type": "integer", "required": true }, "stringphone": { "manifestpath": "/sap.card/configuration/parameters/string/value", "label": "String with Pattern validation", "type": "string", "translatable": false, "required": true, "placeholder": "555-4555", "validation": { "type": "error", "maxLength": 20, "minLength": 1, "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$", "message": "The string does not match a telefone number" } }, "stringphonenomessage": { "manifestpath": "/sap.card/configuration/parameters/string/value", "label": "String with default validation message", "type": "string", "translatable": false, "required": true, "placeholder": "555-4555", "validation": { "type": "warning", "maxLength": 20, "minLength": 1, "pattern": "^(\\([0-9]{3}\\))?[0-9]{3}-[0-9]{4}$" } }, "stringmaxmin": { "manifestpath": "/sap.card/configuration/parameters/string/value", "label": "String with Length Constrained", "type": "string", "translatable": false, "required": true, "placeholder": "MinMaxlength", "validation": { "type": "warning", "maxLength": 20, "minLength": 3 }, "hint": "Please refer to the <a href='https://www.sap.com'>documentation</a> lets see how this will behave if the text is wrapping to the next line and has <a href='https://www.sap.com'>two links</a>. good?" }, "integerrequired": { "manifestpath": "/sap.card/configuration/parameters/integerrequired/value", "label": "Integer with Required", "type": "integer", "translatable": false, "required": true }, "integervalidation": { "manifestpath": "/sap.card/configuration/parameters/integer/value", "label": "Integer with Min Max value", "type": "integer", "visualization": { "type": "Slider", "settings": { "value": "{currentSettings>value}", "min": 0, "max": 16, "width": "100%", "showAdvancedTooltip": true, "showHandleTooltip": false, "inputsAsTooltips": true, "enabled": "{currentSettings>editable}" } }, "validations": [ { "type": "warning", "minimum": 5, "message": "The minimum is 5." }, { "type": "error", "exclusiveMaximum": 16, "message": "The maximum is 15." }, { "type": "error", "multipleOf": 5, "message": "Has to be multiple of 5" } ] }, "numberrequired": { "manifestpath": "/sap.card/configuration/parameters/number/value", "label": "Number with validation", "type": "number", "translatable": false, "required": true, "validation": { "type": "error", "minimum": 0, "maximum": 100, "exclusiveMaximum": true, "message": "The value should be equal or greater than 0 and be less than 100." } } } }, "preview": { "modes": "AbstractLive" } }); }; });
SAP/openui5
src/sap.ui.integration/test/sap/ui/integration/demokit/cardExplorer/webapp/samples/designtimeValidation/dt/configuration.js
JavaScript
apache-2.0
3,586
/** * Created by Jacky.Gao on 2017-02-09. */ import {alert} from '../MsgBox.js'; export default class EditPropertyConditionDialog{ constructor(conditions){ this.conditions=conditions; this.dialog=$(`<div class="modal fade" role="dialog" aria-hidden="true" style="z-index: 11001"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h4 class="modal-title"> ${window.i18n.dialog.editPropCondition.title} </h4> </div> <div class="modal-body"></div> <div class="modal-footer"></div> </div> </div> </div>`); const body=this.dialog.find('.modal-body'),footer=this.dialog.find(".modal-footer"); this.init(body,footer); } init(body,footer){ const _this=this; this.joinGroup=$(`<div class="form-group"><label>${window.i18n.dialog.editPropCondition.relation}</label></div>`); this.joinSelect=$(`<select class="form-control" style="display: inline-block;width:430px;"> <option value="and">${window.i18n.dialog.editPropCondition.and}</option> <option value="or">${window.i18n.dialog.editPropCondition.or}</option> </select>`); this.joinGroup.append(this.joinSelect); body.append(this.joinGroup); const leftGroup=$(`<div class="form-group"><label>${window.i18n.dialog.editPropCondition.leftValue}</label></div>`); this.leftTypeSelect=$(`<select class="form-control" style="display: inline-block;width: inherit"> <option value="current">${window.i18n.dialog.editPropCondition.currentValue}</option> <option value="property">${window.i18n.dialog.editPropCondition.property}</option> <option value="expression">${window.i18n.dialog.editPropCondition.expression}</option> </select>`); leftGroup.append(this.leftTypeSelect); this.propertyGroup=$(`<span style="margin-left: 10px"><label>${window.i18n.dialog.editPropCondition.propName}</label></span>`); this.propertySelect=$(`<select class="form-control" style="display: inline-block;width:320px;"></select>`); this.propertyGroup.append(this.propertySelect); leftGroup.append(this.propertyGroup); body.append(leftGroup); this.exprGroup=$(`<span style="margin-left: 10px"><label>${window.i18n.dialog.editPropCondition.expr}</label></span>`); this.exprEditor=$(`<input type="text" style="display: inline-block;width:320px;" class="form-control">`); this.exprGroup.append(this.exprEditor); leftGroup.append(this.exprGroup); this.exprEditor.change(function(){ const val=$(this).val(); const url=window._server+'/designer/conditionScriptValidation'; $.ajax({ url, type:'POST', data:{content:val}, success:function(errors){ if(errors.length>0){ alert(`${val} ${window.i18n.dialog.editPropCondition.syntaxError}`); } } }); }); this.leftTypeSelect.change(function(){ const val=$(this).val(); if(val==='current'){ _this.exprGroup.hide(); _this.propertyGroup.hide(); }else if(val==='property'){ _this.exprGroup.hide(); _this.propertyGroup.show(); }else{ _this.propertyGroup.hide(); _this.exprGroup.show(); } }); const operatorGroup=$(`<div class="form-group"><label>${window.i18n.dialog.editPropCondition.operator}</label></div>`); this.operatorSelect=$(`<select class="form-control" style="display: inline-block;width:490px;"> <option value=">">${window.i18n.dialog.editPropCondition.greater}</option> <option value=">=">${window.i18n.dialog.editPropCondition.greaterEquals}</option> <option value="<">${window.i18n.dialog.editPropCondition.less}</option> <option value="<=">${window.i18n.dialog.editPropCondition.lessEquals}</option> <option value="==">${window.i18n.dialog.editPropCondition.equals}</option> <option value="!=">${window.i18n.dialog.editPropCondition.notEquals}</option> <option value="in">${window.i18n.dialog.editPropCondition.in}</option> <option value="like">${window.i18n.dialog.editPropCondition.like}</option> </select>`); operatorGroup.append(this.operatorSelect); body.append(operatorGroup); const valueGroup=$(`<div class="form-group"><label>${window.i18n.dialog.editPropCondition.valueExpr}</label></div>`); this.valueEditor=$(`<input type="text" class="form-control" style="display: inline-block;width:477px;">`); valueGroup.append(this.valueEditor); body.append(valueGroup); this.valueEditor.change(function(){ const val=$(this).val(); const url=window._server+'/designer/conditionScriptValidation'; $.ajax({ url, type:'POST', data:{content:val}, success:function(errors){ if(errors.length>0){ alert(`${val} ${window.i18n.dialog.editPropCondition.syntaxError}`); } } }); }); const button=$(`<button class="btn btn-default">${window.i18n.dialog.editPropCondition.ok}</button>`); button.click(function(){ let property=_this.propertySelect.val(),op=_this.operatorSelect.val(),value=_this.valueEditor.val(),join=_this.joinSelect.val(),type=_this.leftTypeSelect.val(),expr=_this.exprEditor.val(); if (type === 'property') { if (property === '') { alert(`${window.i18n.dialog.editPropCondition.selectProp}`); return; } } else if(type==='expression') { if(expr===''){ alert(`${window.i18n.dialog.editPropCondition.leftValueExpr}`); return; } property=expr; }else{ property = null; } if(type==='current'){ type="property"; } if (op === '') { alert(`${window.i18n.dialog.editPropCondition.selectOperator}`); return; } if (value === '') { alert(`${window.i18n.dialog.editPropCondition.inputExpr}`); return; } if (_this.condition) { if (_this.condition.join) { _this.callback.call(_this,type, property, op, value, join); } else { _this.callback.call(_this,type, property, op, value); } } else if (_this.conditions.length > 0) { _this.callback.call(_this,type, property, op, value, join); } else { _this.callback.call(_this,type, property, op, value); } _this.dialog.modal('hide'); }); footer.append(button); } show(callback,fields,condition){ this.callback=callback; this.condition=condition; this.type='current'; if(condition){ this.type=condition.type; if(condition.join){ this.joinGroup.show(); }else{ this.joinGroup.hide(); } }else{ if(this.conditions.length>0){ this.joinGroup.show(); }else{ this.joinGroup.hide(); } } this.propertySelect.empty(); for(let field of fields){ this.propertySelect.append(`<option>${field.name}</option>`); } if(condition){ if(this.type==='expression'){ this.leftTypeSelect.val("expression"); this.exprEditor.val(condition.left); this.propertyGroup.hide(); this.exprGroup.show(); }else{ if(condition.left && condition.left!==''){ this.propertySelect.val(condition.left); this.leftTypeSelect.val("property"); this.propertyGroup.show(); }else{ this.leftTypeSelect.val("current"); this.propertyGroup.hide(); } this.exprGroup.hide(); } this.operatorSelect.val(condition.operation || condition.op); this.valueEditor.val(condition.right); this.joinSelect.val(condition.join); }else{ this.leftTypeSelect.val("current"); this.propertyGroup.hide(); this.exprGroup.hide(); } this.dialog.modal('show'); } }
youseries/ureport
ureport2-js/src/dialog/EditPropertyConditionDialog.js
JavaScript
apache-2.0
9,326
//// [/lib/initial-buildOutput.txt] /lib/tsc --b /src/core --verbose 12:01:00 AM - Projects in this build: * src/core/tsconfig.json 12:01:00 AM - Project 'src/core/tsconfig.json' is out of date because output file 'src/core/anotherModule.js' does not exist 12:01:00 AM - Building project '/src/core/tsconfig.json'... exitCode:: ExitStatus.Success //// [/src/core/anotherModule.js] "use strict"; exports.__esModule = true; exports.World = "hello"; //// [/src/core/index.js] "use strict"; exports.__esModule = true; exports.someString = "HELLO WORLD"; function leftPad(s, n) { return s + n; } exports.leftPad = leftPad; function multiply(a, b) { return a * b; } exports.multiply = multiply; //// [/src/core/tsconfig.json] { "compilerOptions": { "incremental": true, "module": "commonjs" } } //// [/src/core/tsconfig.tsbuildinfo] { "program": { "fileInfos": { "../../lib/lib.d.ts": { "version": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };", "signature": "3858781397-/// <reference no-default-lib=\"true\"/>\ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array<T> { length: number; [n: number]: T; }\ninterface ReadonlyArray<T> {}\ndeclare const console: { log(msg: any): void; };" }, "./anothermodule.ts": { "version": "-2676574883-export const World = \"hello\";\r\n", "signature": "-8396256275-export declare const World = \"hello\";\r\n" }, "./index.ts": { "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", "signature": "1874987148-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n" }, "./some_decl.d.ts": { "version": "-9253692965-declare const dts: any;\r\n", "signature": "-9253692965-declare const dts: any;\r\n" } }, "options": { "incremental": true, "module": 1, "configFilePath": "./tsconfig.json" }, "referencedMap": {}, "exportedModulesMap": {}, "semanticDiagnosticsPerFile": [ "../../lib/lib.d.ts", "./anothermodule.ts", "./index.ts", "./some_decl.d.ts" ] }, "version": "FakeTSVersion" }
minestarks/TypeScript
tests/baselines/reference/tsbuild/sample1/initial-build/when-module-option-changes.js
JavaScript
apache-2.0
3,067
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2020, OpenNebula Project, OpenNebula Systems */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ define(function(require){ return 'acls-tab'; });
baby-gnu/one
src/sunstone/public/app/tabs/acls-tab/tabId.js
JavaScript
apache-2.0
1,267
'use strict'; module.exports = function(config) { config.set({ files: [ 'tests/main.js', {pattern: 'app/js/**/*.js', included: false}, {pattern: 'app/bower_components/**/*.js', included: false}, {pattern: 'tests/specs/**/*.js', included: false}, {pattern: 'tests/fixtures/**/*.js', included: false} ], basePath: '../', frameworks: ['jasmine', 'requirejs'], reporters: ['progress'], runnerPort: 9000, singleRun: true, browsers: ['PhantomJS', 'Chrome'], logLevel: 'ERROR' }); };
spolnik/javascript-workspace
grunt/TodoApp/tests/karma.conf.js
JavaScript
apache-2.0
619
// Copyright 2017 The Oppia Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS-IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @fileoverview Factory for creating new frontend instances of Interaction * domain objects. */ oppia.factory('InteractionObjectFactory', [ 'AnswerGroupObjectFactory', 'HintObjectFactory', 'OutcomeObjectFactory', 'SolutionObjectFactory', function( AnswerGroupObjectFactory, HintObjectFactory, OutcomeObjectFactory, SolutionObjectFactory) { var Interaction = function( answerGroups, confirmedUnclassifiedAnswers, customizationArgs, defaultOutcome, hints, id, solution) { this.answerGroups = answerGroups; this.confirmedUnclassifiedAnswers = confirmedUnclassifiedAnswers; this.customizationArgs = customizationArgs; this.defaultOutcome = defaultOutcome; this.hints = hints; this.id = id; this.solution = solution; }; Interaction.prototype.toBackendDict = function() { return { answer_groups: this.answerGroups.map(function(answerGroup) { return answerGroup.toBackendDict(); }), confirmed_unclassified_answers: this.confirmedUnclassifiedAnswers, customization_args: this.customizationArgs, default_outcome: this.defaultOutcome ? this.defaultOutcome.toBackendDict() : null, hints: this.hints.map(function(hint) { return hint.toBackendDict(); }), id: this.id, solution: this.solution ? this.solution.toBackendDict() : null }; }; Interaction.createFromBackendDict = function(interactionDict) { var defaultOutcome; if (interactionDict.default_outcome) { defaultOutcome = OutcomeObjectFactory.createFromBackendDict( interactionDict.default_outcome); } else { defaultOutcome = null; } return new Interaction( generateAnswerGroupsFromBackend(interactionDict.answer_groups), interactionDict.confirmed_unclassified_answers, interactionDict.customization_args, defaultOutcome, generateHintsFromBackend(interactionDict.hints), interactionDict.id, interactionDict.solution ? ( generateSolutionFromBackend(interactionDict.solution)) : null); }; var generateAnswerGroupsFromBackend = function(answerGroupBackendDicts) { return answerGroupBackendDicts.map(function( answerGroupBackendDict) { return AnswerGroupObjectFactory.createFromBackendDict( answerGroupBackendDict); }); }; var generateHintsFromBackend = function(hintBackendDicts) { return hintBackendDicts.map(function(hintBackendDict) { return HintObjectFactory.createFromBackendDict(hintBackendDict); }); }; var generateSolutionFromBackend = function(solutionBackendDict) { return SolutionObjectFactory.createFromBackendDict(solutionBackendDict); }; return Interaction; } ]);
AllanYangZhou/oppia
core/templates/dev/head/domain/exploration/InteractionObjectFactory.js
JavaScript
apache-2.0
3,481
"use strict"; import {Vector2, Vector3, Matrix4, Vector4} from 'vectormath'; /* NOTE: this was originally a WebGL UI library I wrote. it's gone through several transitions since then, and is now a canvas2d UI library (bleh). the code is quite horrible. */ #include "src/utils/utildefine.js" //we keep track of any canvases with non-GC managed data, //(gl objects, TriListAlloc, TA_Alloc, etc) to avoid reference leaks //g_app_state.reset calls .destroy() on all canvases inside this list. //(then resets it back to {}). window.active_canvases = {}; window._canvas_draw_id = 1; //disable use of theoretically faster typed array allocator, //for now. //#ifdef NOCACHE #define F32ALLOC(verts) new Float32Array(verts); #define F32FREE(verts) verts = undefined; /*#else -#define F32ALLOC(verts123) f32_alloc.from_array(verts123); -#define F32FREE(verts123) if (verts123 != undefined) { f32_alloc.free(verts123); verts123 = undefined;} #endif */ // // //stupid statics var _trilist_n0 = new Vector3(); var _trilist_n1 = new Vector3() var _trilist_n2 = new Vector3(); var _trilist_n3 = new Vector3() var _trilist_v1 = new Vector3(); var _trilist_v2 = new Vector3() var _trilist_v3 = new Vector3(); var _trilist_v4 = new Vector3() var _trilist_c1 = new Vector4(); var _trilist_c2 = new Vector4() var _trilist_c3 = new Vector4(); var _trilist_c4 = new Vector4() var _trilist_v5 = new Vector3(); var _trilist_v6 = new Vector3(); var _trilist_v7 = new Vector3(); var _trilist_v8 = new Vector3(); var _trilist_v9 = new Vector3(); #define TRILIST_CACHE_SIZE 8192 /*I hate garbage collected languages. Bleh! This class is necessary to avoid object allocations within draw frames. evil!*/ export class TriListAlloc { constructor() { this.freelist = []; this.freecount = 0; this.usedcount = 0; this.peakcount = 0; } alloc(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) : TriList { this.peakcount = Math.max(this.peakcount, this.usedcount+1); #ifdef NOCACHE return new TriList(canvas, transmat, use_small_icons); #endif if (this.freecount == 0) { //ensure a saturated cache if (this.usedcount == 0) { for (var i=0; i<TRILIST_CACHE_SIZE; i++) { var tl = new TriList(canvas, transmat, use_small_icons); tl.cache_destroy(); this.freelist.push(tl); this.freecount++; } } this.usedcount++; return new TriList(canvas, transmat, use_small_icons); } else { //console.log("using cached trilist", this.freecount, this.freelist.length); var ret = this.freelist.pop(); ret.cache_init(canvas, transmat, use_small_icons); this.freecount--; this.usedcount++; return ret; } } free(TriList trilist) { this.usedcount--; #ifdef NOCACHE trilist.cache_destroy(); return; #endif //abandon trilist to the GC if (this.freecount >= TRILIST_CACHE_SIZE) return; trilist.cache_destroy(); this.freelist.push(trilist); this.freecount++; } } var _talloc = new TriListAlloc(); /* TriList is being refactored to make it more usable. vertex buffers will be reused, and transformation matrices will be passed in at draw time, not applied at vertex generation time. */ export class TriListRef { constructor(gl, TriList trilist, Matrix4 mat, UICanvas canvas) { this.trilist = trilist; this.mat = mat; this.workmat = new Matrix4(); this.gl = gl; this.canvas = canvas; } destroy() { } on_draw(WebGLRenderingContext gl) { this.workmat.load(this.mat); this.workmat.multiply(this.canvas.global_matrix); this.trilist.global_matrix = this.workmat; this.trilist.on_draw(gl); } } export class TriListCache { constructor(limit=100) { this.cache = {}; this.length = 0; this.limit = limit; } get(String key) : TriList { return this.cache[key]; } has(String key) : Boolean { return key in this.cache; } set(String key, TriList trilist) { if (!(key in this.cache)) { this.length++; } this.cache[key] = trilist; } remove(String key) { if (key in this.cache) { this.cache[key].destroy(); this.length--; delete this.cache[key]; } } destroy() { for (var k in this.cache) { var tl = this.cache[k]; tl.destroy(); } this.cache = {}; this.length = 0; } on_gl_lost() { this.length = 0; this.cache = {}; } } export class TriList { cache_destroy() { this._free_typed(); this.verts.length = 0; this.texcos.length = 0; this.colors.length = 0; this.tottri = 0; //this.canvas = undefined; //this.iconsheet = undefined; //this.viewport = undefined; this._dead = true; } _free_typed() { //f32free sets vertbuf/colorbuf/texbuf to undefined F32FREE(this.vertbuf); F32FREE(this.colorbuf); F32FREE(this.texbuf); } cache_init(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) { this._dead = false; this.transmat = transmat; this.global_matrix = canvas.global_matrix; this.use_tex = 1; this.tex = 0 : WebGLTexture; this.iconsheet = use_small_icons ? g_app_state.raster.iconsheet16 : g_app_state.raster.iconsheet; this.small_icons = use_small_icons; this.verts.length = 0; this.colors.length = 0; this.texcos.length = 0; this.recalc = 1 this.tottri = 0; this.canvas = canvas this.spos = undefined : Array<float>; this.ssize = undefined : Array<float>; this.gl_spos = undefined : Array<float>; this.gl_ssize = undefined : Array<float>; this.viewport = canvas != undefined ? canvas.viewport : undefined; } constructor(UICanvas canvas, Matrix4 transmat, Boolean use_small_icons=false) { this._id = _canvas_draw_id++; this.transmat = transmat; this.global_matrix = canvas.global_matrix; this.verts = []; this.colors = []; this.texcos = []; this._dead = false; this.vertbuf = undefined; this.colorbuf = undefined; this.texbuf = undefined; this.use_tex = 1; this.tex = 0 : WebGLTexture; this.iconsheet = use_small_icons ? g_app_state.raster.iconsheet16 : g_app_state.raster.iconsheet; this.small_icons = use_small_icons; this.recalc = 1 this.tottri = 0; this.canvas = canvas this.spos = undefined : Array<float>; this.ssize = undefined : Array<float>; this.gl_spos = undefined : Array<float>; this.gl_ssize = undefined : Array<float>; this.viewport = canvas != undefined ? canvas.viewport : undefined; } add_tri(Array<float> v1, Array<float> v2, Array<float> v3, Array<float> c1, Array<float> c2, Array<float> c3, Array<float> t1, Array<float> t2, Array<float> t3) { var vs = this.verts; this.tottri++; static v12 = new Vector3(); static v22 = new Vector3(); static v32 = new Vector3(); v12.loadxy(v1); v22.loadxy(v2); v32.loadxy(v3); v1 = v12; v2 = v22; v3 = v32; this.transform(v1); this.transform(v2); this.transform(v3); vs.push(v1[0]); vs.push(v1[1]); vs.push(v1[2]); vs.push(v2[0]); vs.push(v2[1]); vs.push(v2[2]); vs.push(v3[0]); vs.push(v3[1]); vs.push(v3[2]); var cs = this.colors if (c2 == undefined) { c2 = c1; c3 = c1; } cs.push(c1[0]); cs.push(c1[1]); cs.push(c1[2]); cs.push(c1[3]); cs.push(c2[0]); cs.push(c2[1]); cs.push(c2[2]); cs.push(c2[3]); cs.push(c3[0]); cs.push(c3[1]); cs.push(c3[2]); cs.push(c3[3]); if (this.use_tex) { if (t1 == undefined) { static negone = [-1, -1]; t1 = t2 = t3 = negone; } var ts = this.texcos ts.push(t1[0]); ts.push(t1[1]); ts.push(t2[0]); ts.push(t2[1]); ts.push(t3[0]); ts.push(t3[1]) } } add_quad(Vector3 v1, Vector3 v2, Vector3 v3, Vector3 v4, Array<float> c1,Array<float> c2,Array<float> c3, Array<float> c4,Array<float> t1,Array<float> t2, Array<float> t3,Array<float> t4) { this.add_tri(v1, v2, v3, c1, c2, c3, t1, t2, t3); this.add_tri(v1, v3, v4, c1, c3, c4, t1, t3, t4); } icon_quad(int icon, Vector3 pos, Array<Array<float>> cs) { static tcos = new Array(0); //var clr = [1, 1, 1, 1]; //var cs = [clr, clr, clr, clr]; var cw = this.iconsheet.cellsize[0], ch = this.iconsheet.cellsize[1]; var v1 = new Vector3([pos[0], pos[1], 0.0]); var v2 = new Vector3([pos[0], pos[1]+ch, 0.0]); var v3 = new Vector3([pos[0]+cw, pos[1]+ch, 0.0]); var v4 = new Vector3([pos[0]+cw, pos[1], 0.0]); tcos.length = 0; this.iconsheet.gen_tile(icon, tcos); var t1 = new Vector3([tcos[0], tcos[1], 0]); var t2 = new Vector3([tcos[2], tcos[3], 0]); var t3 = new Vector3([tcos[4], tcos[5], 0]); var t4 = new Vector3([tcos[6], tcos[7], 0]); var t5 = new Vector3([tcos[8], tcos[9], 0]); var t6 = new Vector3([tcos[10], tcos[11], 0]); this.add_tri(v1, v2, v3, cs[0], cs[1], cs[2], t1, t2, t3); this.add_tri(v1, v3, v4, cs[0], cs[2], cs[3], t4, t5, t6); } transform(v) { static transvec = new Vector3(); transvec[0] = v[0]; transvec[1] = v[1]; transvec[2] = 0.0; transvec.multVecMatrix(this.transmat); v[0] = (transvec[0]/this.viewport[1][0])*2.0 - 1.0; v[1] = (transvec[1]/this.viewport[1][1])*2.0 - 1.0; } line(v1, v2, c1, c2=undefined, width=undefined) { //c2 and width are optional if (c2 == undefined) { c2 = c1; } if (v1.length == 2) v1.push(0); if (v2.length == 2) v2.push(0); this.line_strip(CACHEARR2(CACHEARR2(v1, v2), CACHEARR2(c1, c2)), undefined, width); //this.line_strip(objcache.getarr(objcache.getarr(v1, v2), objcache.getarr(c1, c2)), undefined, width); } line_strip(lines, colors, texcos=undefined, width=2.0, half=false) { static black = new Vector4([0.0, 0.0, 0.0, 1.0]); static v0 = new Vector3(), v1 = new Vector3(), v2 = new Vector3(); static v3 = new Vector3(), v4 = new Vector3(), n0 = new Vector3(); static n1 = new Vector3(), n2 = new Vector3(), c3 = new Vector3(); static c4 = new Vector3(); for (var i =0; i<lines.length; i++) { var lc1 = colors[i][0], lc2 = colors[i][1]; //if (lines[i][0].length == 2) lines[i][0].push(0); //if (lines[i][1].length == 2) lines[i][1].push(0); if (lc1 == undefined) lc1 = black; if (lc2 == undefined) lc2 = black; var z = 0.0; v1.loadxy(lines[i][0]) v2.loadxy(lines[i][1]) n0.zero(); n1.zero(); n2.zero(); v1.loadxy(lines[i][1]); v1.sub(lines[i][0]); v1.normalize(); n1[0] = v1[1]; n1[1] = -v1[0]; n1[2] = z; n1.normalize() if (i > 0) { v0.loadxy(lines[i-1][1]); v0.sub(lines[i-1][0]) v0.normalize(); n0[0] = v0[1]; n0[1] = -v0[0]; n0[2] = z; n0.normalize() } else { n0.load(n1); } v1.loadxy(lines[i][1]); v1.sub(lines[i][0]) if (i < lines.length-1) { v3.loadxy(lines[i+1][1]); v3.sub(lines[i+1][0]); v3.normalize(); n2[0] = v3[1]; n2[1] = -v3[0]; n2[2] = z; n2.normalize() } else { n2.load(n1); } /* n0.normalize(); n1.normalize(); n2.normalize(); n0.mulScalar(0.5); n1.mulScalar(0.5); n2.mulScalar(0.5); */ n2.add(n1).normalize(); n1.add(n0).normalize(); n1.mulScalar(width*0.5); n2.mulScalar(width*0.5); v0.loadxy(lines[i][0]); v1.loadxy(lines[i][1]); v2.loadxy(lines[i][1]); v2.add(n1); v3.loadxy(lines[i][0]); v3.add(n2); var c1 = _trilist_c1.load(lc1); var c2 = _trilist_c2.load(lc2); var c3 = _trilist_c3.load(lc2); var c4 = _trilist_c4.load(lc1); if (width >= 1.5) { c3[3] = 0.0; c4[3] = 0.0; } n1.mulScalar(2.0); n2.mulScalar(2.0); if (this.use_tex && texcos) { if (!half) this.add_quad(v0, v1, v2, v3, c1, c2, c3, c4, texcos[i][0], texcos[i][1], texcos[i][0], texcos[i][1]); this.add_quad(v1, v0, v3.sub(n1), v2.sub(n2), c2, c1, c3, c4, texcos[i][0], texcos[i][1], texcos[i][0], texcos[i][1]); } else { if (!half) this.add_quad(v0, v1, v2, v3, c1, c2, c3, c4); this.add_quad(v1, v0, v3.sub(n2), v2.sub(n1), c2, c1, c3, c4); } } } destroy(Boolean only_gl=false) { var gl = g_app_state.gl; if (this.vbuf) { gl.deleteBuffer(this.vbuf); gl.deleteBuffer(this.cbuf); } if (this.tbuf) { gl.deleteBuffer(this.tbuf); } this.vbuf = this.cbuf = this.tbuf = undefined; this.recalc = 1; this._free_typed(); if (!only_gl) { this._dead = true; _talloc.free(this); } } gen_buffers(gl) { if (this.verts.length == 0) return; this.destroy(true); this._free_typed(); this._dead = false; this.vertbuf = F32ALLOC(this.verts); //new Float32Array(this.verts) this.colorbuf = F32ALLOC(this.colors); //new Float32Array(this.colors) if (this.use_tex) this.texbuf = F32ALLOC(this.texcos); //new Float32Array(this.texcos); gl.enableVertexAttribArray(0); gl.enableVertexAttribArray(1); if (this.use_tex) gl.enableVertexAttribArray(2); else gl.disableVertexAttribArray(2); var vbuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, vbuf); gl.bufferData(gl.ARRAY_BUFFER, this.vertbuf, gl.STATIC_DRAW); gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, vbuf); var cbuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, cbuf); gl.bufferData(gl.ARRAY_BUFFER, this.colorbuf, gl.STATIC_DRAW); gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, cbuf); if (this.use_tex) { var tbuf = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, tbuf); gl.bufferData(gl.ARRAY_BUFFER, this.texbuf, gl.STATIC_DRAW); gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, tbuf); this.tbuf = tbuf } this.vbuf = vbuf; this.cbuf = cbuf; gl.disableVertexAttribArray(1); gl.disableVertexAttribArray(2); this.recalc = 0; } on_draw(gl) { if (!this.iconsheet.ready) return; //if (this._dead) // return; if (this.verts.length == 0) return; if (this.recalc || (this.tdrawbuf != undefined && this.tdrawbuf.is_dead)) { this.gen_buffers(gl); } if (this.ssize != undefined) { gl.enable(gl.SCISSOR_TEST); // g_app_state.raster.push_scissor(this.spos, this.ssize); } gl.disable(gl.DEPTH_TEST); gl.enable(gl.BLEND); gl_blend_func(gl); //gl.blendEquation(gl.BLEND_EQUATION); //gl.blendEquationSeparate(gl.BLEND_EQUATION, gl.BLEND_EQUATION); gl.enableVertexAttribArray(0); gl.enableVertexAttribArray(1); gl.disableVertexAttribArray(3); gl.disableVertexAttribArray(4); gl.bindBuffer(gl.ARRAY_BUFFER, this.vbuf); gl.vertexAttribPointer(0, 3, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.vbuf); gl.bindBuffer(gl.ARRAY_BUFFER, this.cbuf); gl.vertexAttribPointer(1, 4, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.cbuf); if (this.use_tex) { gl.enableVertexAttribArray(2); gl.bindBuffer(gl.ARRAY_BUFFER, this.tbuf); gl.vertexAttribPointer(2, 2, gl.FLOAT, false, 0, 0); gl.bindBuffer(gl.ARRAY_BUFFER, this.tbuf); } else { gl.disableVertexAttribArray(2); } gl.activeTexture(gl.TEXTURE4); gl.bindTexture(gl.TEXTURE_2D, this.iconsheet.tex); gl.useProgram(gl.basic2d.program); this.global_matrix.setUniform(gl, gl.basic2d.uniformloc(gl, "mat")); gl.uniform1i(gl.basic2d.uniformloc(gl, "iconsampler"), 4); //console.log(this.verts); //console.log(this.tottri*3, this.verts.length/3, this.colors.length/4, this.verts[0], this.verts[1], this.verts[2]) gl.drawArrays(gl.TRIANGLES, 0,this.tottri*3); gl.disableVertexAttribArray(1); gl.disableVertexAttribArray(2); gl.enable(gl.DEPTH_TEST); if (this.ssize != undefined) { //g_app_state.raster.pop_scissor(); } } } /* var MAX_TRILIST_CACHE = 512; var _trilist_frame_counter = 0; var _trilist_template = {obj : new TriList(undefined, undefined), cachesize : MAX_TRILIST_CACHE}; function _reset_trilist_frame_counter() { _trilist_frame_counter = 0; } function _new_trilist(UICanvas canvas) { if (_trilist_frame_counter = 0 >= MAX_TRILIST_CACHE) { return new TriList(canvas); } else { var list = objcache.fetch(_trilist_template) TriList.call(list, canvas); } } function _save_trilist(TriList trilist) { if (objcache.is_cache_obj(trilist)) { objcache.cache_remove(trilist); } } */ export class TextDraw { constructor(pos, text, color, spos, ssize, viewport, size, scale, global_matrix, rot=0) { this._id = _canvas_draw_id++; this.rot = rot; this.global_matrix = global_matrix; this.text = text; this.pos = [pos[0], pos[1], pos[2]]; this.color = color; this.tdrawbuf = undefined : TextDrawBuffer; this.spos = spos; this.ssize = ssize; this.asp = viewport[1][1] / viewport[1][0]; this.viewport = viewport; this.scale = [scale[0], scale[1], 0]; this.size = size; this.raster = g_app_state.raster; var mat = new Matrix4(); mat.translate(this.pos[0], this.pos[1], 0.0); //denormalize to avoid squashed rotations mat.scale(1, 1.0/this.asp, 1); mat.rotate(0, 0, rot); mat.scale(this.scale); //norrmalize again mat.scale(1, this.asp, 1); this.mat = mat; } destroy() { /*don't destroy the gl buffers here, since I'm now caching them*/ /* if (this.tdrawbuf != undefined) this.tdrawbuf.destroy(); this.tdrawbuf = undefined; */ } toString() : String { return "TD" + this._id; } gen_buffers(gl) { this.tdrawbuf = this.raster.get_font(this.size).gen_text_buffers(gl, this.text, this.color, this.viewport); return this.tdrawbuf; } on_draw(gl) { static identitymat = new Matrix4(); gl.disableVertexAttribArray(4); if (this.tdrawbuf == undefined) this.gen_buffers(gl); var spos, ssize; if (this.ssize != undefined) { spos = CACHEARR3(this.spos[0], this.spos[1], 0); ssize = CACHEARR3(this.ssize[0], this.ssize[1], 0); // g_app_state.raster.push_scissor(spos, ssize); } static mat = new Matrix4(); mat.load(this.global_matrix); mat.multiply(this.mat); this.tdrawbuf.on_draw(gl, mat); if (this.ssize != undefined) { //g_app_state.raster.pop_scissor(); } } } var _ls_static_colors = {reallength: 0, length: 0}; window._box_process_clr = function _box_process_clr(default_cs, clr) { var cs = default_cs; static arr4 = [0, 0, 0, 0]; if (clr != undefined) { if (typeof clr == "number") { var cs2 = arr4; for (var i=0; i<4; i++) { cs2[i] = CACHEARR4(cs[i][0], cs[i][1], cs[i][2], cs[i][3]); for (var j=0; j<4; j++) { cs2[i] *= clr; } } cs = cs2; } else if (typeof clr[0] == "number") { var cs = arr4; cs[0] = clr; cs[1] = clr; cs[2] = clr; cs[3] = clr; } else { cs = clr; } } return cs; } //XXX XXX! export class UICanvas_ { constructor(viewport) { static _id = 1; this._id = _id++; this.global_matrix = new Matrix4(); this.iconsheet = g_app_state.raster.iconsheet; this.iconsheet16 = g_app_state.raster.iconsheet16; this.viewport = viewport; this.raster = g_app_state.raster; this.trilist = _talloc.alloc(this, this.transmat); this.textcache = {}; this.textcachelen = 0; this.max_textcache = 64; this.boxcache = new TriListCache(); this.trans_stack = [] this.transmat = new Matrix4() this.drawlists = [this.trilist] this.textlist = []; this.stack = [] this.cache = new hashtable(); this.oldcache = new hashtable(); this.uncached = new Array(); this.uncached.push(this.trilist); this.scissor_stack = new Array(); this.flag = 0; } ensure_trilist() { if (this.drawlists.length == 0 || !(this.drawlists[this.drawlists.length-1] instanceof TriList)) { this.new_trilist(); } } set_viewport(viewport) { var bad = false; for (var i=0; i<3; i++) { if (viewport[1][i] != this.viewport[1][i]) bad = true; } this.viewport = viewport; if (bad) { this.on_resize(viewport[1], viewport[1]); } } on_gl_lost(WebGLRenderingContext new_gl) { this.boxcache.on_gl_lost(); if (this.gl === new_gl) { console.trace(); console.log("Warning: uicanvas.on_gl_lost() called multiple times"); return; } this.gl = new_gl; this.drawlists = new Array(); this.iconsheet = g_app_state.raster.iconsheet; this.iconsheet16 = g_app_state.raster.iconsheet16; this.textcache = {}; this.textcachelen = 0; this.stack = [] this.raster = g_app_state.raster; this.cache = new hashtable(); this.oldcache = new hashtable(); this.boxcache = UICanvas.boxcache; this.new_trilist(); //now that gl data is destroyed, //call .reset to maintain data structure integrity this.reset(); } push_scissor(pos, size) { var oldpos = pos; pos = new Vector3([pos[0], pos[1], 0]); size = new Vector3([size[0], size[1], 0]); pos.multVecMatrix(this.transmat); size.multVecMatrix(this.transmat); var vx=this.viewport[0][0], vy=this.viewport[0][1] pos[0] += vx; pos[1] += vy; var dx = pos[0]-oldpos[0]-vx, dy = pos[1]-oldpos[1]-vy; size[0] -= dx; size[1] -= dy; for (var i=0; i<3; i++) { pos[i] = Math.floor(pos[i]); size[i] = Math.ceil(size[i]); } this.scissor_stack.push([pos, size]); this.new_trilist(); } pop_scissor() { this.scissor_stack.pop(); this.new_trilist(); } new_trilist(Boolean use_small_icons=false) { //flag canvas for memory leak detection, see active_canvases's definition active_canvases[this._id] = this; this.trilist = _talloc.alloc(this, this.transmat, use_small_icons); //new TriList(this, use_small_icons); if (this.scissor_stack.length > 0) { this.trilist.spos = this.scissor_stack[this.scissor_stack.length-1][0]; this.trilist.ssize = this.scissor_stack[this.scissor_stack.length-1][1]; } this.drawlists.push(this.trilist); return this.trilist; } translate(Array<float> off) { this.transmat.translate(off[0], off[1], 0.0); } push_transform(mat=undefined) { this.trans_stack.push(new Matrix4(this.transmat)); if (mat != undefined) this.transmat.multiply(mat); } pop_transform() { this.transmat.load(this.trans_stack.pop()); } frame_begin(Object item) { return;//XXX if (DEBUG.ui_canvas) { console.log("canvas start, stack length: ", this.stack.length); } this.new_trilist(); this.stack.push(this.drawlists.length-1); } frame_end(Object item) { return;//XXX var arr = new Array() var start = this.stack[this.stack.length-1]; this.stack.pop(); if (DEBUG.ui_canvas) console.log(start); for (var i=start; i<this.drawlists.length; i++) { arr.push(this.drawlists[i]); } this.cache.set(item, arr); this.new_trilist(); if (DEBUG.ui_canvas) { console.log("canvas end, stack length: ", this.stack.length); } return arr; } begin(Object item) { //okay, individual leaf element caching may not have been a good //idea. . . //-XXX return; if (DEBUG.ui_canvas) { console.log("canvas start, stack length: ", this.stack.length); } this.new_trilist(); this.stack.push(this.drawlists.length-1); } end(Object item) { //-XXX; return; var arr = new Array() var start = this.stack.pop(this.stack.length-1); if (DEBUG.ui_canvas) console.log(start); for (var i=start; i<this.drawlists.length; i++) { arr.push(this.drawlists[i]); } this.stack.pop(); this.cache.set(item, arr); this.new_trilist(); if (DEBUG.ui_canvas) { console.log("canvas end, stack length: ", this.stack.length); } return arr; } use_cache(Object item) { if (this.oldcache.has(item)) { var arr = this.oldcache.get(item); for (var i=0; i<arr.length; i++) { this.drawlists.push(arr[i]); if (arr[i] instanceof TextDraw) this.textlist.push(arr[i]); } this.oldcache.remove(item); this.cache.set(item, arr); this.new_trilist(); } } has_cache(Object item) { return this.oldcache.has(item); } remove_cache(Object item) { if (this.oldcache.has(item)) this.oldcache.remove(item); } textsize(text, size=default_ui_font_size) { var box = this.raster.get_font(size).calcsize(text); return [box[0], box[1]]; } line(v1, v2, c1, c2=c1, width=2.0) { this.ensure_trilist(); this.line_strip([[v1, v2]], [[c1, c2]], undefined, width); } line_strip(lines, colors, texcos, width, half) {//colors,texcos,width are optional this.ensure_trilist(); if (colors == undefined) { colors = uicolors["DefaultLine"]; } if (typeof(colors[0]) == "number") { var clr = colors; colors =_ls_static_colors; for (var i=0; i<lines.length; i++) { if (colors[i] == undefined) { colors[i] = [clr, clr]; } else { colors[i][0] = clr; colors[i][1] = clr; } } colors.reallength = Math.max(colors.reallength, i); colors.length = i; } this.trilist.line_strip(lines, colors, texcos, width, half); } line_loop(points, colors, texcos, width, half) { //colors,texcos,width are optional var lines = [] this.ensure_trilist(); if (colors == undefined) { colors = uicolors["DefaultLine"]; } var lcolors; if (typeof colors[0] != "number") lcolors = [] else lcolors = [] for (var i=0; i<points.length; i++) { var i2 = (i+1)%points.length; lines.push([points[i], points[i2]]); if (typeof(colors[0]) != "number") { lcolors.push([colors[i], colors[i2]]); } else { lcolors.push([colors, colors]); } } this.line_strip(lines, lcolors, undefined, width, half); } quad(v1, v2, v3, v4, c1, c2, c3, c4) { this.ensure_trilist(); if (v1.length == 2) v1.push(0); if (v2.length == 2) v2.push(0); if (v3.length == 2) v3.push(0); if (v4.length == 2) v4.push(0); this.trilist.add_quad(v1, v2, v3, v4, c1, c2, c3, c4); } quad_aa(v1, v2, v3, v4, c1, c2, c3, c4) { this.ensure_trilist(); if (v1.length == 2) v1.push(0); if (v2.length == 2) v2.push(0); if (v3.length == 2) v3.push(0); if (v4.length == 2) v4.push(0); if (c2 == undefined) { c2 = c3 = c4 = c1; } this.trilist.add_quad(v1, v2, v3, v4, c1, c2, c3, c4); var lines = [[v1, v4], [v4, v3], [v3, v2], [v2, v1]]; var colors = [[c1, c4], [c4, c3], [c3, c2], [c2, c1]]; this.trilist.line_strip(lines, colors, undefined, undefined, true) } tri(v1, v2, v3, c1, c2, c3) { this.ensure_trilist(); if (v1.length == 2) v1.push(0); if (v2.length == 2) v2.push(0); if (v3.length == 2) v3.push(0); this.trilist.add_tri(v1, v2, v3, c1, c2, c3); } on_draw(gl) { //Set the viewport and projection matrix for the scene gl.viewport(this.viewport[0][0], this.viewport[0][1], this.viewport[1][0], this.viewport[1][1]); var len = this.drawlists.length; for (var i=0; i<len; i++) { if (DEBUG.canvas_sep_text && this.drawlists[i] instanceof TextDraw) continue; this.drawlists[i].on_draw(gl); } if (DEBUG.canvas_sep_text) { var len = this.textlist.length; for (var i=0; i<len; i++) { this.textlist[i].on_draw(gl); } } } arc_points(pos, start, arc, r, steps) {//steps is optional if (steps == undefined) { steps = Math.floor(6*arc/Math.PI); } var f, df; var f = start; var df = arc / steps; var points = []; for (var i=0; i<steps+1; i++) { var x = pos[0] + Math.sin(f)*r; var y = pos[1] + Math.cos(f)*r; points.push([x, y, 0]); f += df; } return points; } arc(pos, start, arc, r, clr, half) { if (clr == undefined) { clr = [0.9, 0.8, 0.7, 0.6]; } var steps = 18/(2.0 - arc/(Math.PI*2)); var f, df; var f = start; var df = arc / steps; var points = []; for (var i=0; i<steps+1; i++) { var x = pos[0] + Math.sin(f)*r; var y = pos[1] + Math.cos(f)*r; points.push([x, y, 0]); f += df; } var lines = []; var colors = []; for (var i=0; i<points.length-1; i++) { lines.push([points[i], points[i+1]]) colors.push([clr, clr]) } colors[0][0] = [1.0, 1.0, 0.0, 1.0] colors[0][1] = [1.0, 1.0, 0.0, 1.0] this.trilist.line_strip(lines, colors, undefined, undefined, half); } destroy() { this.reset(); //get rid of any cache data, too for (var k in this.cache) { var arr = this.cache.get(k); for (var i=0; i<arr.length; i++) { arr[i].destroy(); arr[i] = undefined; } } this.boxcache.destroy(); this.cache = new hashtable(); if (this._id in active_canvases) { delete active_canvases[this._id]; } } reset() { /* for (var i=0; i<this.uncached.length; i++) { this.uncached[i].destroy(); this.uncached[i] = undefined; }*/ var dmap = {}; for (var k in this.cache) { var item = this.cache.get(k); for (var i=0; i<item.length; i++) { dmap[item[i]._id] = item[i]; } } var dl = this.drawlists; for (var i=0; i<dl.length; i++) { if (!(dl[i]._id in dmap)) { dl[i].destroy(); } } if (DEBUG.canvas_sep_text) { var tl = this.textlist; for (var i=0; i<tl.length; i++) { tl[i].destroy(); } this.textlist.length = 0; } this.uncached.length = 0; this.scissor_stack.length = 0; /*destroy old cache that was used in last draw cycle, then swap it with the new cache that was *built* last cycle.*/ for (var k in this.oldcache) { var arr = this.oldcache.get(k) for (var i=0; i<arr.length; i++) { arr[i].destroy(); arr[i] = undefined; } } this.oldcache = this.cache; this.cache = new hashtable(); this.drawlists.length = 0; if (this.trans_stack.length > 0) { this.trans_stack[0].makeIdentity(); this.trans_stack.length = 1; } else { this.trans_stack.length = 0; this.trans_stack.push(new Matrix4()); } this.transmat = this.trans_stack[0]; this.stack.length = 0; this.new_trilist(); } invbox(pos, size, clr, r) { var cs = uicolors["InvBox"] cs = _box_process_clr(cs, clr); this.box(pos, size, cs, r); } simple_box(pos, size, clr=undefined, r=2.0) { //clr is optional var cs = uicolors["SimpleBox"] cs = _box_process_clr(cs, clr); this.box(pos, size, cs, r); } hlightbox(pos, size, clr_mul, r) { //clr_mul is optional var cs = uicolors["HLightBox"] /*if (clr != undefined) { cs = [clr, clr, clr, clr] }*/ if (clr_mul != undefined) { cs = [new Vector4(cs[0]), new Vector4(cs[1]), new Vector4(cs[2]), new Vector4(cs[3])] for (var i=0; i<4; i++) { for (var j=0; j<4; j++) { cs[i][j] *= clr_mul; } } } this.box(pos, size, cs, r); } box_outline(pos, size, clr, rfac) { this.box(pos, size, clr, rfac, true); } shadow_box(pos, size, steps=6, margin=[6, 6], clr=uicolors["ShadowBox"]) { static neg1 = [-2, -2]; //arg, can't remember the correct formula to use here //x**steps = 0.1 //x = 0.1**(1.0/steps) var fac = (1.0/steps)*0.4; var clr = [clr[0], clr[1], clr[2], clr[3]*fac] pos = new Vector2(pos); size = new Vector2(size); expand_rect2d(pos, size, margin); for (var i=0; i<steps; i++) { this.box(pos, size, clr); expand_rect2d(pos, size, neg1); } } box(pos, size, clr, rfac, outline_only) { if (IsMobile || rfac == 0.0) return this.box2(pos, size, clr, rfac, outline_only); else //XXX return this.box1(pos, size, clr, rfac, outline_only); } /* I think this word is Dutch. it comes from photography, it means to dim the screen around a rectangle of interest. need to look up the english word. and no, I'm not Dutch. */ passpart(pos, size, clr=[0,0,0,0.5]) { this.ensure_trilist(); var p = this.viewport[0]; var s = this.viewport[1]; this.box2([p[0], p[1]], [pos[0], s[1]], clr); this.box2([p[0]+pos[0]+size[0], p[1]], [s[0]-pos[0]-size[0], s[1]], clr); this.box2([pos[0]+p[0], pos[1]+p[1]+size[1]], [size[0], s[1]-size[1]-p[1]], clr); this.box2([pos[0]+p[0], p[1]], [size[0], pos[1]], clr) } icon(int icon, Array<float> pos, float alpha=1.0, Boolean small=false, Array<float> clr=undefined) { static white = [[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]]; var cs = _box_process_clr(white, clr); for (var i=0; i<4; i++) { cs[i][3] = alpha; } this.ensure_trilist(); if (this.trilist.small_icons != small) { this.new_trilist(small); } this.trilist.icon_quad(icon, pos, cs); } box2(Array<float> pos, Array<float> size, Array<float> clr=undefined, float rfac=undefined, Boolean outline_only=false) { this.ensure_trilist(); var cs = uicolors["Box"]; cs = _box_process_clr(cs, clr); var x = pos[0], y=pos[1]; var w=size[0], h=size[1]; if (outline_only) { this.line([pos[0], pos[1]], [pos[0], pos[1]+size[1]], clr, clr, 1.0); this.line([pos[0], pos[1]+size[1]], [pos[0]+size[0], pos[1]+size[1]], clr, clr, 1.0); this.line([pos[0]+size[0], pos[1]+size[1]], [pos[0]+size[0], pos[1]], clr, clr, 1.0); this.line([pos[0]+size[0], pos[1]], [pos[0], pos[1]], clr, clr, 1.0); } else { this.trilist.add_quad(CACHEARR3(x, y, 0), CACHEARR3(x+w, y, 0), CACHEARR3(x+w, y+h, 0), CACHEARR3(x, y+h, 0), cs[0], cs[1], cs[2], cs[3]); } } gen_box_trilist(Array<float> size, Array<float> clr=undefined, float rfac=1, Boolean outline_only=false) { var w=size[0], h=size[1]; var start = 0, ang = Math.PI/2, r = 4; var cs = _box_process_clr(uicolors["Box"], clr); var trilist = new TriList(this, new Matrix4(), false); r /= rfac; var p1 = this.arc_points(CACHEARR3(0+r+2, 0+r+2, 0), Math.PI, ang, r); var p2 = this.arc_points(CACHEARR3(0+w-r-2, 0+r+2, 0), Math.PI/2, ang, r); var p3 = this.arc_points(CACHEARR3(0+w-r-2, 0+h-r-2, 0), 0, ang, r); var p4 = this.arc_points(CACHEARR3(0+r+2, 0+h-r-2, 0), -Math.PI/2, ang, r); var plen = p1.length; p4.reverse(); p3.reverse(); p2.reverse(); p1.reverse(); var points = []; for (var i=0; i<p1.length; i++) { points.push(p1[i]); } for (var i=0; i<p2.length; i++) { points.push(p2[i]); p1.push(p2[i]); } for (var i=0; i<p3.length; i++) { points.push(p3[i]); } p2 = p3; for (var i=0; i<p4.length; i++) { p2.push(p4[i]); points.push(p4[i]); } p2.reverse(); var plen = p1.length; function color(i) { if (i < plen) return cs[0]; else if (i < plen*2) return cs[1]; else if (i < plen*3) return cs[2]; else if (i <= plen*4+1) return cs[3]; } static v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3(), v4 = new Vector3(); #define LOAD_CLR(a, b) a[0] = b[0]; a[1] = b[1]; a[2] = b[2]; if (!outline_only) { for (var i=0; i<p1.length-1; i++) { var i1 = i; var i2 = i+plen*2; var i3 = i + 1+plen*2; var i4 = i+1; LOAD_CLR(v1, p1[i]); LOAD_CLR(v2, p2[i]); LOAD_CLR(v3, p2[i+1]); LOAD_CLR(v4, p1[i+1]); trilist.add_quad(v1, v2, v3, v4, color(i1), color(i2), color(i3), color(i4)); } } var lines = []; var colors = []; static pairs = []; for (var i=0; i<points.length; i++) { LOAD_CLR(v1, points[(i+1)%points.length]); LOAD_CLR(v2, points[i]); if (pairs.length <= i) { pairs.push([[0, 0], [0, 0]]); } pairs[i][0][0] = CACHEARR3(v1[0], v1[1], 0); pairs[i][0][1] = CACHEARR3(v2[0], v2[1], 0); lines.push(pairs[i][0]); pairs[i][1][0] = color((i+1)%points.length); pairs[i][1][1] = color(i); colors.push(pairs[i][1]); } #undef LOAD_CLR trilist.line_strip(lines, colors, undefined, outline_only ? 1.4 : 1.5, !outline_only); return trilist; } box1(Array<float> pos, Array<float> size, Array<float> clr=[0, 0, 0, 1], float rfac=1, Boolean outline_only=false) { var sclr = clr==undefined ? "u" : clr.toString(); var hash = size.toString()+sclr+rfac.toString()+(outline_only ? "|1" : "|0"); var cache = this.boxcache; if (!cache.has(hash)) { cache.set(hash, this.gen_box_trilist(size, clr, rfac, outline_only)); } static co = new Vector3(); co.loadxy(pos); co[2] = 0.0; co.multVecMatrix(this.transmat); var viewport = g_app_state.raster.viewport; var sx = viewport[1][0]; var sy = viewport[1][1]; co[0] = (Math.floor(co[0])/sx)*2.0;// - 1.0; co[1] = (Math.floor(co[1])/sy)*2.0;// - 1.0; var mat = new Matrix4(); mat.translate(co[0], co[1], 0.0); var ret = new TriListRef(this.gl, cache.get(hash), mat, this); this.drawlists.push(ret); return ret; } box1_old(Array<float> pos, Array<float> size, Array<float> clr=undefined, float rfac=undefined, Boolean outline_only=false) { var c1, c2, c3, c4; var cs = uicolors["Box"]; static cache = {}; if (outline_only == undefined) outline_only = false; cs = _box_process_clr(cs, clr); var x = Math.floor(pos[0]), y=Math.floor(pos[1]); var w=size[0], h=size[1]; var start = 0; var ang = Math.PI/2; var r = 4 //Math.sqrt(size[0]*size[1]) if (rfac == undefined) rfac = 1; var hash = size[0].toString() + " " + size[1] + " " + rfac; if (!(hash in cache)) { r /= rfac; var p1 = this.arc_points(CACHEARR3(0+r+2, 0+r+2, 0), Math.PI, ang, r); var p2 = this.arc_points(CACHEARR3(0+w-r-2, 0+r+2, 0), Math.PI/2, ang, r); var p3 = this.arc_points(CACHEARR3(0+w-r-2, 0+h-r-2, 0), 0, ang, r); var p4 = this.arc_points(CACHEARR3(0+r+2, 0+h-r-2, 0), -Math.PI/2, ang, r); var plen = p1.length; p4.reverse(); p3.reverse(); p2.reverse(); p1.reverse(); var points = [] for (var i=0; i<p1.length; i++) { points.push(p1[i]); } for (var i=0; i<p2.length; i++) { points.push(p2[i]); p1.push(p2[i]); } for (var i=0; i<p3.length; i++) { points.push(p3[i]); } p2 = p3; for (var i=0; i<p4.length; i++) { p2.push(p4[i]); points.push(p4[i]); } p2.reverse(); cache[hash] = [p1, p2, points]; } var cp = cache[hash]; var p1 = cp[0]; var p2 = cp[1]; var points = cp[2]; var plen = p1.length; function color(i) { if (i < plen) return cs[0]; else if (i < plen*2) return cs[1]; else if (i < plen*3) return cs[2]; else if (i <= plen*4+1) return cs[3]; } static v1 = new Vector3(), v2 = new Vector3(), v3 = new Vector3(), v4 = new Vector3(); #define LOAD_CLR(a, b) a[0] = b[0]+x; a[1] = b[1]+y; a[2] = b[2]; if (!outline_only) { for (var i=0; i<p1.length-1; i++) { var i1 = i; var i2 = i+plen*2; var i3 = i + 1+plen*2; var i4 = i+1; LOAD_CLR(v1, p1[i]); LOAD_CLR(v2, p2[i]); LOAD_CLR(v3, p2[i+1]); LOAD_CLR(v4, p1[i+1]); this.trilist.add_quad(v1, v2, v3, v4, color(i1), color(i2), color(i3), color(i4)); } } var lines = [] var colors = [] static pairs = []; for (var i=0; i<points.length; i++) { LOAD_CLR(v1, points[(i+1)%points.length]); LOAD_CLR(v2, points[i]); if (pairs.length <= i) { pairs.push([[0, 0], [0, 0]]); } pairs[i][0][0] = CACHEARR3(v1[0], v1[1], 0); pairs[i][0][1] = CACHEARR3(v2[0], v2[1], 0); lines.push(pairs[i][0]); pairs[i][1][0] = color((i+1)%points.length); pairs[i][1][1] = color(i); colors.push(pairs[i][1]); } #undef LOAD_CLR this.trilist.line_strip(lines, colors, undefined, 4, true); //this.box2(pos, size, clr, rfac, outline_only); return this.trilist } on_resize(newsize, oldsize) { this.boxcache.destroy(); //all cache entries with old size are now bad for (var k in this.textcache) { if (!this.textcache.hasOwnProperty(k)) continue; this.textcache[k].destroy(); } this.textcache = {}; this.textcachelen = 0; //clear entire cache this.destroy(); this.reset(); } text(Array<float> pos, String text, Array<float> color, float size, float scale, float rot, Array<float> scissor_pos, Array<float> scissor_size) { static loc = new Vector3(); if (rot == undefined) rot = 0.0; if (size == undefined) size = default_ui_font_size; if (scale == undefined) { scale = CACHEARR3(1.0, 1.0, 1.0); } else if (typeof(scale) == "number") { scale = CACHEARR3(scale, scale, scale); } if (color == undefined) { color = uicolors["DefaultText"] } if (scissor_pos == undefined) { if (this.scissor_stack.length > 0) { scissor_pos = this.scissor_stack[this.scissor_stack.length-1][0]; scissor_size = this.scissor_stack[this.scissor_stack.length-1][1]; } } else { scissor_pos = new Vector3([scissor_pos[0], scissor_pos[1], 0]); scissor_size = new Vector3([scissor_size[0], scissor_size[1], 0]); scissor_pos.multVecMatrix(this.transmat); } loc[0] = 0; loc[1] = 0; loc[2] = 0; loc.multVecMatrix(this.transmat); loc[0] += pos[0] loc[1] += pos[1] //yes, raster is supposed to be a nasty global var port = g_app_state.raster.viewport var sx = port[1][0] var sy = port[1][1] loc[0] = (Math.floor(loc[0])/sx)*2.0; //*2.0-1.0; loc[1] = (Math.floor(loc[1])/sy)*2.0; //*2.0-1.0; var textdraw = new TextDraw(loc, text, color, scissor_pos, scissor_size, this.viewport, size, scale, this.global_matrix, rot); var hash = text.toString() + ">>" + size + "|" + color + "|" + JSON.stringify(this.viewport); //XXX // /* if (!(hash in this.textcache)) { if (this.textcachelen > this.max_textcache) { var keys = Object.getOwnPropertyNames(this.textcache) for (i=0; i<keys.length; i++) { var k = keys[i]; this.textcache[k].destroy(); var users = this.textcache[k].users; //possible evil! for (var j=0; j<users.length; j++) { users[j].recalc = true; users[j].tdrawbuf = undefined; } delete this.textcache[k]; this.textcachelen--; //amortize cache destruction calls if (this.textcachelen < this.max_textcache/3) break; } } this.textcache[hash] = textdraw.gen_buffers(g_app_state.gl); this.textcachelen++; } else { textdraw.tdrawbuf = this.textcache[hash]; } this.textcache[hash].users.push(textdraw); //-XXX if (DEBUG.canvas_sep_text) { this.textlist.push(textdraw); this.drawlists.push(textdraw); if (this.stack.length == 0) { this.uncached.push(textdraw); } return loc; } else { if (this.drawlists[this.drawlists.length-1] == this.trilist) { this.drawlists.push(textdraw); this.new_trilist(); if (this.stack.length == 0) { this.uncached.push(textdraw); this.uncached.push(this.trilist); } } else { this.drawlists.push(textdraw); if (this.stack.length == 0) { this.uncached.push(textdraw); } } // */ return loc; } } }
joeedh/webblender
src/editors/interface/UICanvas.js
JavaScript
apache-2.0
46,545
$.FAQ = function(){ $self = this; this.url = "/faq" this.send = function(inputs){ var params = new FormData(); // var csrf = $("#csrf").val(); // params.append("csrf_ID", csrf); $.each(inputs, function(key, val){ params.append(key,val); }); $.ajax({ url : $self.url, type: 'POST', async: true, processData: false, data: params, success: function(response){ response = JSON.parse(response); $self.fillQAs(response.qadata); $self.createPagination(response.metadata) }, }); }; this.fillQAs = function(data){ var qaBox = $("#faq-container .faq-item").clone(); $("#faq-container .faq-item").remove(); $.each(data, function(obj){ var $div = qaBox.clone(); $div.find(".faq-item-question h2").html(obj.question); $div.find(".faq-item-answer p").html(obj.answer); }); }; this.createPagination = function(metadata){ }; this.load = function(data){ var limit = (data.limit > 0) ? data.limit : 5; var offset = (data.page_num - 1)*limit; var inputs = { action : 'loadFaq', limit : limit, offset : offset }; $self.send(inputs); }; this.init = function(){ var inputs = { limit : 5, page_num : 1 }; $self.load(inputs); }; };
ajaykiet2/htdocs
assets/js/website/faq.js
JavaScript
apache-2.0
1,284
$(document).ready(function(){ $('#datepickerDay1').hide(); $('#datepickerDay2').hide(); $('#datepickerMnd1').hide(); $('#datepickerMnd2').hide(); $('#datepickerYear1').hide(); $('#datepickerYear2').hide(); $('select').change(function(){ var index = $('select').val(); if(index == 0){ //day $('#datepickerDay1').show(); $('#datepickerDay2').show(); $('#datepickerMnd1').hide(); $('#datepickerMnd2').hide(); $('#datepickerYear1').hide(); $('#datepickerYear2').hide(); localStorage.setItem('type','0'); } else if(index == 1){ //month $('#datepickerMnd1').show(); $('#datepickerMnd2').show(); $('#datepickerDay1').hide(); $('#datepickerDay2').hide(); $('#datepickerYear1').hide(); $('#datepickerYear2').hide(); localStorage.setItem('type','1'); } else if(index == 2){ //year $('#datepickerYear1').show(); $('#datepickerYear2').show(); $('#datepickerDay1').hide(); $('#datepickerDay2').hide(); $('#datepickerMnd1').hide(); $('#datepickerMnd2').hide(); localStorage.setItem('type','2'); } }); $('#datepickerDay1').datepicker({ format: "yyyy-mm-dd", weekStart: 1, language: "no", todayHighlight: true }); $('#datepickerDay1').on('changeDate', function(ev){ $(this).datepicker('hide'); day1(); if ($('input[name=date2]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerDay2').datepicker({ format: "yyyy-mm-dd", weekStart: 1, language: "no", todayHighlight: true }); $('#datepickerDay2').on('changeDate', function(ev){ $(this).datepicker('hide'); day2(); if ($('input[name=date]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerYear1').datepicker({ format: "yyyy", weekStart: 1, startView: 1, minViewMode: 2, language: "no", todayHighlight: true }); $('#datepickerYear1').on('changeDate', function(ev){ $(this).datepicker('hide'); year1(); if ($('input[name=date6]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerYear2').datepicker({ format: "yyyy", weekStart: 1, startView: 1, minViewMode: 2, language: "no", todayHighlight: true }); $('#datepickerYear2').on('changeDate', function(ev){ $(this).datepicker('hide'); year2(); if ($('input[name=date5]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerMnd1').datepicker({ format: "yyyy-mm", weekStart: 1, startView: 0, minViewMode: 1, language: "no", todayHighlight: true }); $('#datepickerMnd1').on('changeDate', function(ev){ $(this).datepicker('hide'); mnd1(); if ($('input[name=date4]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#datepickerMnd2').datepicker({ format: "yyyy-mm", weekStart: 1, startView: 0, minViewMode: 1, language: "no", todayHighlight: true }); $('#datepickerMnd2').on('changeDate', function(ev){ $(this).datepicker('hide'); mnd2(); if ($('input[name=date3]').val() != "") { showChart1(); showChart2(); showChart3(); showChart4(); showChart5(); showChart6(); } }); $('#backBtn').on('click', function(ev){ window.location.replace("../pages/stats.php"); }); function day1(){ var day = $('input[name=date]').val(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("firstDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/day.php?date=" + day, true); xmlhttp.send(); } function day2(){ var day = $('input[name=date2]').val(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("lastDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/day.php?date=" + day, true); xmlhttp.send(); } function mnd1(){ var day = $('input[name=date3]').val() + '-01'; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("firstDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/month.php?date=" + day, true); xmlhttp.send(); } function mnd2(){ var day = $('input[name=date4]').val() + '-01'; var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("lastDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/month.php?date=" + day, true); xmlhttp.send(); } function year1(){ var day = $('input[name=date5]').val(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("firstDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/year.php?date=" + day, true); xmlhttp.send(); } function year2(){ var day = $('input[name=date6]').val(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function(){ if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { document.getElementById("lastDate").innerHTML = xmlhttp.responseText; } } xmlhttp.open("GET", "../phpBackend/OrgStat/year.php?date=" + day, true); xmlhttp.send(); } function showChart1(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk1').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 1, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 1, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#followersFirstDate").text(res1); $("#followersLastDate").text(res2); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 2, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 2, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#followersFirstDate").text(res1); $("#followersLastDate").text(res2); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 3, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 3, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#followersFirstDate").text(res1); $("#followersLastDate").text(res2); }, }); }, }); } } function showChart2(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk2').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 4, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 4, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#donationsFirstDate").text(res1); $("#donationsLastDate").text(res2); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 5, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 5, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#donationsFirstDate").text(res1); $("#donationsLastDate").text(res2); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 6, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 6, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#donationsFirstDate").text(res1); $("#donationsLastDate").text(res2); }, }); }, }); } } function showChart3(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk3').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 7, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 7, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#moneyDonatedFirstDate").text(res1 + ",-"); $("#moneyDonatedLastDate").text(res2 + ",-"); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 8, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 8, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#moneyDonatedFirstDate").text(res1 + ",-"); $("#moneyDonatedLastDate").text(res2 + ",-"); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 9, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 9, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#moneyDonatedFirstDate").text(res1 + ",-"); $("#moneyDonatedLastDate").text(res2 + ",-"); }, }); }, }); } } function showChart4(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk4').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 10, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 10, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#averageDonationFirstDate").text(res1 + ",-"); $("#averageDonationLastDate").text(res2 + ",-"); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 11, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 11, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#averageDonationFirstDate").text(res1 + ",-"); $("#averageDonationLastDate").text(res2 + ",-"); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 12, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 12, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#averageDonationFirstDate").text(res1 + ",-"); $("#averageDonationLastDate").text(res2 + ",-"); }, }); }, }); } } function showChart5(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk5').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 13, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 13, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#newsFirstDate").text(res1); $("#newsLastDate").text(res2); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 14, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 14, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#newsFirstDate").text(res1); $("#newsLastDate").text(res2); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 15, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 15, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#newsFirstDate").text(res1); $("#newsLastDate").text(res2); }, }); }, }); } } function showChart6(){ var data = [ { value: 1, color:"#1AA24C", highlight: "#1AD24C", label: "Valg 2" }, { value: 1, color: "#000000", highlight: "#333333", label: "Valg 1" } ] var ctx = $('#statistikk6').get(0).getContext("2d"); var myDoughnut = new Chart(ctx).Doughnut(data,{ animation:true, showTooltips: true, percentageInnerCutout : 0, segmentShowStroke : true }); var res1; var res2; var x = localStorage.getItem('type'); if(x == 0){ //day var date1 = $('input[name=date]').val(); var date2 = $('input[name=date2]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 16, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 16, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#prosjectsFirstDate").text(res1); $("#prosjectsLastDate").text(res2); }, }); }, }); }else if(x == 1){ //month var date1 = $('input[name=date3]').val() + '-01'; var date2 = $('input[name=date4]').val() + '-01'; $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 17, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 17, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#prosjectsFirstDate").text(res1); $("#prosjectsLastDate").text(res2); }, }); }, }); }else if(x == 2){ //year var date1 = $('input[name=date5]').val(); var date2 = $('input[name=date6]').val(); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date1 + '&num=' + 18, success: function(data) { res1 = parseInt(data); $.ajax({ url: '../phpBackend/doughnut.php?date='+ date2 + '&num=' + 18, success: function(data) { res2 = parseInt(data); myDoughnut.segments[0].value = res2; myDoughnut.segments[1].value = res1; myDoughnut.update(); $("#prosjectsFirstDate").text(res1); $("#prosjectsLastDate").text(res2); }, }); }, }); } } });
lavhmrps/SharityCRM
js/comparison.js
JavaScript
apache-2.0
25,646
/* The all pages that do not require authentication */ function UnAuthenticatedHandler() { "use strict"; this.displayAboutPage = function(req, res, next) { return res.render("about"); }; this.displayContactPage = function(req, res, next) { return res.render("contact"); }; this.displayHomePage = function(req, res, next) { return res.render("home"); }; this.displayChatPage = function(req, res, next) { return res.render("chat"); }; } module.exports = UnAuthenticatedHandler;
bertonjulian/NodeGoat
app/routes/unauthenticated.js
JavaScript
apache-2.0
549
function $childNode(o) { return window.frames[o] } function animationHover(o, e) { o = $(o), o.hover(function () { o.addClass("animated " + e) }, function () { window.setTimeout(function () { o.removeClass("animated " + e) }, 2e3) }) } function WinMove() { var o = "[class*=col]", e = ".ibox-title", i = "[class*=col]"; $(o).sortable({ handle: e, connectWith: i, tolerance: "pointer", forcePlaceholderSize: !0, opacity: .8 }).disableSelection() } var $parentNode = window.parent.document; if ($(".tooltip-demo").tooltip({ selector: "[data-toggle=tooltip]", container: "body" }), $(".modal").appendTo("body"), $("[data-toggle=popover]").popover(), $(".collapse-link").click(function () { var o = $(this).closest("div.ibox"), e = $(this).find("i"), i = o.find("div.ibox-content"); i.slideToggle(200), e.toggleClass("fa-chevron-up").toggleClass("fa-chevron-down"), o.toggleClass("").toggleClass("border-bottom"), setTimeout(function () { o.resize(), o.find("[id^=map-]").resize() }, 50) }), $(".close-link").click(function () { var o = $(this).closest("div.ibox"); o.remove() }), top == this) { }
pantisocracy/live-report
src/main/resources/static/resource/js/content.min.js
JavaScript
apache-2.0
1,277
/*! * Module requirements */ var NeopreneError = require('../error') /** * Document Validation Error * * @api private * @param {Document} instance * @inherits NeopreneError */ function ValidationError (instance) { NeopreneError.call(this, "Validation failed"); Error.captureStackTrace(this, arguments.callee); this.name = 'ValidationError'; this.errors = instance.errors = {}; }; /** * Console.log helper * @api private */ ValidationError.prototype.toString = function () { return this.name + ': ' + Object.keys(this.errors).map(function (key) { return String(this.errors[key]); }, this).join(', '); }; /*! * Inherits from NeopreneError. */ ValidationError.prototype.__proto__ = NeopreneError.prototype; /*! * Module exports */ module.exports = exports = ValidationError;
rorymadden/neoprene
lib/errors/validation.js
JavaScript
apache-2.0
813
/** * App routes. */ var homepage = require('./homepage'); var user = require('./user'); var news = require('./news'); var test = require('./test'); var passport = require('passport'); function ensureAuthenticated(req, res, next) { if (req.isAuthenticated()) { return next(); } req.flash('error', '抱歉,您尚未登录。'); return res.redirect('/user/signin?redirect=' + req.path); } function ensureAdmin(req, res, next) { if (req.isAuthenticated() && req.user.isadmin) { return next(); } req.flash('error', '抱歉,您不是管理员。'); return res.redirect('/user/signin?redirect=' + req.path); } function ensurePermission(req, res, next) { if (req.isAuthenticated() && req.user.isadmin) { return next(); } if (req.isAuthenticated() && req.user.username == req.params.id) { return next(); } req.flash('error', '抱歉,您没有权限。'); return res.redirect('/user/signin?redirect=' + req.path); } module.exports = function(app) { app.get('/', homepage.index); app.get('/user', ensureAdmin, user.showList); app.get('/user/page/:page(\\d+)', ensureAdmin, user.showList); app.get('/user/register', user.showRegister); app.post('/user/register', user.doRegister); app.get('/user/signin', user.showSignin); app.post('/user/signin', passport.authenticate('local', { successRedirect: '/', successFlash: '登录成功,欢迎回来。', failureRedirect: 'back', failureFlash: '抱歉,手机号或密码错误。', })); app.get('/user/signout', user.doSignout); app.get('/user/:id(\\d{8,13})/edit', ensurePermission, user.showEditUser); app.post('/user/:id(\\d{8,13})/edit', ensurePermission, user.doEditUser); app.get('/user/:id(\\d{8,13})/setadmin', ensureAdmin, user.setAdmin); app.get('/news', news.showList); app.get('/news/page/:page(\\d+)', news.showList); app.get('/news/:id(\\d+)', news.showItem); app.get('/news/:id(\\d+)/edit', ensureAdmin, news.showEditItem); app.post('/news/:id(\\d+)/edit', ensureAdmin, news.doEditItem); app.get('/news/:id(\\d+)/delete', ensureAdmin, news.doDeleteItem); app.get('/news/post', ensureAdmin, news.showNewItem); app.post('/news/post', ensureAdmin, news.doNewItem); app.get('/test', test); app.get('*', function(req, res){ return res.render('homepage', {title: '404'}); }); }
dotkrnl/helium
routes/index.js
JavaScript
apache-2.0
2,456
jQuery("#simulation") .on("click", ".s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d .click", function(event, data) { var jEvent, jFirer, cases; if(data === undefined) { data = event; } jEvent = jimEvent(event); jFirer = jEvent.getEventFirer(); if(jFirer.is("#s-Label_58")) { cases = [ { "blocks": [ { "actions": [ { "action": "jimChangeStyle", "parameter": [ { "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_58": { "attributes": { "font-size": "12.0pt", "font-family": "Roboto-Regular,Arial" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_58 .valign": { "attributes": { "vertical-align": "middle", "text-align": "left" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_58 span": { "attributes": { "color": "#80B8F1", "text-align": "left", "text-decoration": "none", "font-family": "Roboto-Regular,Arial", "font-size": "12.0pt" } } } ], "exectype": "serial", "delay": 0 }, { "action": "jimChangeStyle", "parameter": [ { "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_59": { "attributes": { "font-size": "20.0pt", "font-family": "IOS8-Icons-Regular,Arial" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_59 .valign": { "attributes": { "vertical-align": "middle", "text-align": "left" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_59 span": { "attributes": { "color": "#80B8F1", "text-align": "left", "text-decoration": "none", "font-family": "IOS8-Icons-Regular,Arial", "font-size": "20.0pt" } } } ], "exectype": "serial", "delay": 0 }, { "action": "jimPause", "parameter": { "pause": 300 }, "exectype": "serial", "delay": 0 }, { "action": "jimChangeStyle", "parameter": [ { "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_58": { "attributes": { "font-size": "12.0pt", "font-family": "Roboto-Regular,Arial" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_58 .valign": { "attributes": { "vertical-align": "middle", "text-align": "left" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_58 span": { "attributes": { "color": "#007DFF", "text-align": "left", "text-decoration": "none", "font-family": "Roboto-Regular,Arial", "font-size": "12.0pt" } } } ], "exectype": "serial", "delay": 0 }, { "action": "jimChangeStyle", "parameter": [ { "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_59": { "attributes": { "font-size": "20.0pt", "font-family": "IOS8-Icons-Regular,Arial" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_59 .valign": { "attributes": { "vertical-align": "middle", "text-align": "left" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Label_59 span": { "attributes": { "color": "#157EFB", "text-align": "left", "text-decoration": "none", "font-family": "IOS8-Icons-Regular,Arial", "font-size": "20.0pt" } } } ], "exectype": "serial", "delay": 0 } ] } ], "exectype": "serial", "delay": 0 } ]; event.data = data; jEvent.launchCases(cases); } else if(jFirer.is("#s-cover")) { cases = [ { "blocks": [ { "actions": [ { "action": "jimChangeStyle", "parameter": [ { "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-cover": { "attributes": { "opacity": "0.75" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-cover": { "attributes-ie": { "-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)", "filter": "alpha(opacity=75)" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-cover": { "attributes-ie8lte": { "-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=75)", "filter": "alpha(opacity=75)" } } } ], "exectype": "serial", "delay": 0 }, { "action": "jimPause", "parameter": { "pause": 300 }, "exectype": "serial", "delay": 0 }, { "action": "jimChangeStyle", "parameter": [ { "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-cover": { "attributes": { "opacity": "1.0" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-cover": { "attributes-ie": { "-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)", "filter": "alpha(opacity=100)" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-cover": { "attributes-ie8lte": { "-ms-filter": "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)", "filter": "alpha(opacity=100)" } } } ], "exectype": "serial", "delay": 0 } ] } ], "exectype": "serial", "delay": 0 } ]; event.data = data; jEvent.launchCases(cases); } else if(jFirer.is("#s-Hotspot_1")) { cases = [ { "blocks": [ { "actions": [ { "action": "jimNavigation", "parameter": { "target": "screens/6709a53d-60b3-4498-bf73-977706fff4da" }, "exectype": "serial", "delay": 0 } ] } ], "exectype": "serial", "delay": 0 } ]; event.data = data; jEvent.launchCases(cases); } else if(jFirer.is("#s-Hotspot_3")) { cases = [ { "blocks": [ { "actions": [ { "action": "jimNavigation", "parameter": { "target": "screens/27852e19-fc20-4cac-8d96-13d00ac70f75" }, "exectype": "serial", "delay": 0 } ] } ], "exectype": "serial", "delay": 0 } ]; event.data = data; jEvent.launchCases(cases); } else if(jFirer.is("#s-Button_1")) { cases = [ { "blocks": [ { "actions": [ { "action": "jimChangeStyle", "parameter": [ { "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Button_1": { "attributes": { "font-size": "12.0pt", "font-family": "Roboto-Regular,Arial" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Button_1 .valign": { "attributes": { "vertical-align": "middle", "text-align": "center" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Button_1 span": { "attributes": { "color": "#80B8F1", "text-align": "center", "text-decoration": "none", "font-family": "Roboto-Regular,Arial", "font-size": "12.0pt" } } } ], "exectype": "serial", "delay": 0 }, { "action": "jimPause", "parameter": { "pause": 300 }, "exectype": "serial", "delay": 0 }, { "action": "jimChangeStyle", "parameter": [ { "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Button_1": { "attributes": { "font-size": "12.0pt", "font-family": "Roboto-Regular,Arial" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Button_1 .valign": { "attributes": { "vertical-align": "middle", "text-align": "center" } } },{ "#s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d #s-Button_1 span": { "attributes": { "color": "#007DFF", "text-align": "center", "text-decoration": "none", "font-family": "Roboto-Regular,Arial", "font-size": "12.0pt" } } } ], "exectype": "serial", "delay": 0 } ] } ], "exectype": "serial", "delay": 0 } ]; event.data = data; jEvent.launchCases(cases); } }) .on("pageload", ".s-cd8b0318-8942-4a64-b2c9-ee7c253d6b7d .pageload", function(event, data) { var jEvent, jFirer, cases; if(data === undefined) { data = event; } jEvent = jimEvent(event); jFirer = jEvent.getEventFirer(); if(jFirer.is("#s-Label_35")) { cases = [ { "blocks": [ { "actions": [ { "action": "jimSetValue", "parameter": { "target": "#s-Label_35", "value": { "action": "jimConcat", "parameter": [ { "action": "jimSubstring", "parameter": [ { "action": "jimSystemTime" },"0","5" ] }," PM" ] } }, "exectype": "serial", "delay": 0 } ] } ], "exectype": "serial", "delay": 0 } ]; event.data = data; jEvent.launchCases(cases); } });
yicold/axure-case
caiqu/财趣v1.5/resources/screens/cd8b0318-8942-4a64-b2c9-ee7c253d6b7d-1445822636718.js
JavaScript
apache-2.0
13,587
/* COPYRIGHT 2012 SUPERMAP * 本程序只能在有效的授权许可下使用。 * 未经许可,不得以任何手段擅自使用或传播。*/ /** * @requires SuperMap/Util.js * @requires SuperMap/REST.js */ /** * Class: SuperMap.REST.ChartQueryParameters * 海图查询参数类,该类用于设置海图查询时的相关参数,海图查询分为海图属性 * 查询和海图范围查询两类,通过属性queryMode指定查询模式。必设属性有: * queryMode、chartLayerNames、chartQueryFilterParameters。当进行海图范围查询时,必设属性还包括bounds。 */ SuperMap.REST.ChartQueryParameters = SuperMap.Class({ /** * APIProperty: queryMode * {String} 海图查询模式类型,SuperMap iClient for JavaScript对海图支持两种 * 查询方式:海图属性查询("ChartAttributeQuery")和海图空间查询 * ("ChartBoundsQuery") 。 */ queryMode:null, /** * APIProperty: bounds * {<SuperMap.Bounds>} 海图查询范围。 */ bounds:null, /** * APIProperty: chartLayerNames * {Array(String)} 查询的海图图层的名称。 */ chartLayerNames:null, /** * APIProperty: chartQueryFilterParameters * {Array <SuperMap.REST.ChartQueryFilterParameter>} 海图查询过滤参数。 * 包括:物标代码、物标可应用对象的选择(是否查询点、线或面)、属性字 * 段过滤条件。 */ chartQueryFilterParameters:null, /** * Property: returnContent * {Boolean} 获取或设置是返回查询结果记录集 recordsets,还是返回查询结果的 * 资源 resourceInfo。默认为 true,表示返回 recordsets。 * * note: Recordsets 和 ResourceInfo 都存储在查询结果类 QueryResult 中。 * 当 * (start code) * ReturnContent = true * (end) * 表示返回查询记录集,这时 * 查询结果存储在 * (start code) * QueryResult.Recordsets * (end) * 中,而 * (start code) * QueryResult.ResourceInfo * (end) * 为空;当 * (start code) * ReturnContent = false * (end) * 时,表示返回查询结果资源,这时查询结果存储在 * (start code) * QueryResult.ResourceInfo * (end) * 中,而 * (start code) * QueryResult.Recordsets * (end) * 为空。 */ returnContent:true, /** * APIProperty: startRecord * {Number} 查询起始记录位置,默认为0。 */ startRecord:0, /** * APIProperty: expectCount * {Number} 期望查询结果返回的记录数,该值大于0。 */ expectCount:null, /** * Constructor: SuperMap.REST.ChartQueryParameters * 初始化 ChartQueryParameters 类的新实例。 * * Parameters: * options - {Object} 参数。 * * Allowed options properties: * queryMode - {String} 海图查询模式类型,SuperMap iClient for JavaScript对 * 海图支持两种查询方式:海图属性查询("ChartAttributeQuery")和海图空 * 间查询("ChartBoundsQuery") 。 * bounds - {<SuperMap.Bounds>} 海图查询范围。 * chartLayerNames - {Array(String)} 查询的海图图层的名称。 * chartQueryFilterParameters - {Array <SuperMap.REST.ChartQueryFilterParameter>} * 海图查询过滤参数。包括:物标代码、物标可应用对象的选择(是否查询点、 * 线或面)、属性字段过滤条件。 * returnContent - {Boolean} 获取或设置是返回查询结果记录集 recordsets,还 * 是返回查询结果的资源 resourceInfo。默认为 true,表示返回 recordsets。 * startRecord - {Number} 查询起始记录位置,默认为0。 * expectCount - {Number} 期望查询结果返回的记录数,该值大于0。 */ initialize:function (options) { if (!options) { return; } SuperMap.Util.extend(this, options); }, /** * APIMethod: destroy * 释放资源,将引用资源的属性置空。 */ destroy:function () { var me = this; me.queryMode = null; me.bounds = null; me.chartLayerNames = null; me.chartQueryFilterParameters = null; me.returnContent = true; me.startRecord = 0; me.expectCount = null; }, /** * Method: getVariablesJson * 将属性信息转换成能够被服务识别的JSON格式字符串。 */ getVariablesJson:function () { var json=""; json += "\"queryMode\":\"" + this.queryMode + "\","; if (this.chartLayerNames && this.chartLayerNames.length) { var chartLayersArray = []; var layerLength = this.chartLayerNames.length; for (var i = 0; i < layerLength; i++) { chartLayersArray.push("\""+this.chartLayerNames[i]+"\""); } var layerNames = "[" + chartLayersArray.join(",") + "]"; json += "\"chartLayerNames\":" + layerNames + ","; } if (this.queryMode === "ChartBoundsQuery" && this.bounds) { json += "\"bounds\":" + "{" + "\"leftBottom\":" + "{" + "\"x\":" + this.bounds.left + "," + "\"y\":" + this.bounds.bottom + "}" + "," + "\"rightTop\":" + "{" + "\"x\":" + this.bounds.right + "," + "\"y\":" + this.bounds.top + "}" + "},"; } if (this.chartQueryFilterParameters && this.chartQueryFilterParameters.length) { var chartParamArray = []; var chartLength = this.chartQueryFilterParameters.length; for (var j = 0; j < chartLength; j++) { var chartQueryFilterParameter = new SuperMap.REST.ChartQueryFilterParameter(); chartQueryFilterParameter = this.chartQueryFilterParameters[j]; chartParamArray.push(chartQueryFilterParameter.toJson()); } var chartParamsJson = "[" + chartParamArray.join(",") + "]"; chartParamsJson = "\"chartQueryParams\":" + chartParamsJson + ","; chartParamsJson += "\"startRecord\":" + this.startRecord + ","; chartParamsJson += "\"expectCount\":" + this.expectCount; chartParamsJson = "{" + chartParamsJson + "}"; json += "\"chartQueryParameters\":" + chartParamsJson; } json = "{" + json + "}"; return json; }, CLASS_NAME:"SuperMap.REST.ChartQueryParameters" })
SuperMap/iClient-for-JavaScript
libs/SuperMap/REST/Query/ChartQueryParameters.js
JavaScript
apache-2.0
6,706
'use strict'; var chai = require('chai'); var promised = require('chai-as-promised'); chai.use(promised); global.expect = chai.expect; exports.config = { // The timeout for each script run on the browser. This should be longer // than the maximum time your application needs to stabilize between tasks. allScriptsTimeout: 15000, // Capabilities to be passed to the webdriver instance. capabilities: { 'browserName': 'chrome', 'loggingPrefs': { 'browser': 'ALL' } }, // ----- What tests to run ----- // // Spec patterns are relative to the location of the spec file. They may // include glob patterns. specs: [ 'admin/specs/admin-user-spec.js', 'admin/specs/users-spec.js', 'admin/specs/groups-spec.js', 'admin/specs/system-spec.js', 'admin/specs/authorizations-spec.js', 'cockpit/specs/dashboard-spec.js', 'cockpit/specs/process-definition-spec.js', 'cockpit/specs/decision-definition-spec.js', 'cockpit/specs/process-instance-spec.js', 'cockpit/specs/process-definition-filter-spec.js', 'cockpit/specs/variable-spec.js', 'cockpit/specs/suspension-spec.js', 'tasklist/specs/filter-basic-spec.js', 'tasklist/specs/filter-permissions-spec.js', 'tasklist/specs/filter-criteria-spec.js', 'tasklist/specs/filter-vg-spec.js', 'tasklist/specs/process-stariables-spec.js', 'tasklist/specs/task-claiminart-spec.js', 'tasklist/specs/tasklist-sorting-spec.js', 'tasklist/specs/tasklist-search-spec.js', 'tasklist/specs/task-detail-view-spec.js', 'tasklist/specs/task-dates-spec.js' ], // A base URL for your application under test. Calls to protractor.get() // with relative paths will be prepended with this. baseUrl: 'http://localhost:8080', // ----- The test framework ----- // // Jasmine is fully supported as a test and assertion framework. // Mocha has limited beta support. You will need to include your own // assertion framework if working with mocha. framework: 'mocha', // ----- Options to be passed to minijasminenode ----- // // Options to be passed to Mocha-node. // See the full list at https://github.com/juliemr/minijasminenode mochaOpts: { timeout: 15000, colors: false, reporter: 'xunit-file', slow: 3000 } };
jangalinski/camunda-bpm-webapp
webapp/src/test/js/e2e/ci.conf.js
JavaScript
apache-2.0
2,310
/* * @class TableExamplesService */ export default class TableExamplesService { constructor($http) { this.$http = $http; } static getClassName() { return 'TableExamplesService'; } getClassName() { return TableExamplesService.getClassName(); } /* * @func getColumns * @desc getes a list of columns representing the dataset that * allows data tables to map the array of data to the table */ getColumns() { return this.$http.get('http://localhost:3001/api/DataTable/Columns/People'); } /* * @func addColumn * @desc adds a col * allows data tables to map the array of data to the table */ addColumn(item) { return this.$http.post('http://localhost:3001/api/DataTable/Columns/People', item); } /* * @func getData * @desc gets a list of items from the api */ getData() { return this.$http.get('http://localhost:3001/api/People'); } /* * @func addData * @desc adds an item to the api * @param item */ addData(item) { return this.$http.post('http://localhost:3001/api/People', item); } }
garrettwong/GDashboard
client/app/components/tableExamples/tableExamples.service.js
JavaScript
apache-2.0
1,084
describe('app.components.SaveProfileModal', function() { beforeEach(function () { module('app.components', 'ui.bootstrap', 'gettext'); }); describe('service', function () { var callbackObject; var saveSpy; var doNotSaveSpy; var cancelSpy; beforeEach(function () { bard.inject('SaveProfileModal', '$rootScope', '$document'); callbackObject = { save: function () {}, doNotSave: function () {}, cancel: function () {}, } saveSpy = sinon.spy(callbackObject, "save"); doNotSaveSpy = sinon.spy(callbackObject, "doNotSave"); cancelSpy = sinon.spy(callbackObject, "cancel"); }); xit('should show the modal', function () { var modal = SaveProfileModal.showModal(callbackObject.save, callbackObject.doNotSave, callbackObject.cancel); $rootScope.$digest(); var saveDialog = $document.find('.save-profile-modal'); expect(saveDialog.length).to.eq(1); var saveButton = $document.find('.save-profile-modal .btn.btn-primary'); expect(saveButton.length).to.eq(1); eventFire(saveButton[0], 'click'); $rootScope.$digest(); expect(saveSpy).to.have.been.called; var closeButtons = $document.find('.save-profile-modal .btn.btn-default'); expect(closeButtons.length).to.eq(2); eventFire(closeButtons[0], 'click'); $rootScope.$digest(); expect(cancelSpy).to.have.been.called; eventFire(closeButtons[1], 'click'); $rootScope.$digest(); expect(doNotSaveSpy).to.have.been.called; }); }); });
dtaylor113/manageiq-ui-self_service
tests/profiles/save-profile-modal-service.spec.js
JavaScript
apache-2.0
1,584
/* * Copyright (c) 2012-2015 S-Core Co., Ltd. * * 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([ 'common', 'lodash', 'moment', 'async', 'text!resource/add_wsdlg.html', 'text!resource/remove_wsdlg.html' ], function (common, _, moment, async, addDlg, removeDlg) { 'use strict'; /* global webidaFs, webidaApp, webidaAuth, webidaHost: true */ var WORKSPACE_PATH = '.profile/workspace.json'; var WORKSPACE_INFO; //var _menuSettings = $('#menu-settings'); var _wsContents = $('.ws-body'); var _dimming = $('.dimming'); var _uniqId; function _dimmingOn() { _dimming.addClass('active'); } function _dimmingOff() { _dimming.removeClass('active'); } function _checkValidWSFile(cb) { webidaFs.readFile(WORKSPACE_PATH, function (err, data) { if (err) { cb('_checkValidWSFile() - readFile Error: ' + err); } else { var wsMeta = JSON.parse(data); var wsMetaCount = Object.keys(wsMeta).length; _getWSList(function (err, wslist) { if (err) { cb('_checkValidWSFile() - _getWSList Error: ' + err); } else { var wsCount = wslist.length; if (wsMetaCount === wsCount) { cb(null, true); } else { cb(null, false); } } }); } }); } function _launchIDE(domObj) { console.log($(domObj).attr('data-wsname')); var workspace = '?workspace=' + webidaFs.fsid + '/' + domObj.attr('data-wsname'); webidaApp.launchApp('devenv', true, workspace); } function _registerDefaultEvent() { // register dimming cancel event _dimming.on('click', function () { _dimming.removeClass('active'); var addWSDlg = $('.add_wsdlg'); var removeWSDlg = $('.remove_wsdlg'); if (addWSDlg) { addWSDlg.remove(); } if (removeWSDlg) { removeWSDlg.remove(); } }); $('#menu-logo').on('click', function () { webidaApp.launchApp('desktop', false, null); }); // register workspace event $('#menu-ws').on('click', function () { var wswrap = $('.ws-wrap'); var settingwrap = $('.settings-wrap'); if (wswrap.hasClass('acitve')) { settingwrap.removeClass('active'); } else { wswrap.addClass('active'); settingwrap.removeClass('active'); } }); // register setting event $('#menu-settings').on('click', function () { var wswrap = $('.ws-wrap'); var settingwrap = $('.settings-wrap'); if (settingwrap.hasClass('acitve')) { wswrap.removeClass('active'); } else { settingwrap.addClass('active'); wswrap.removeClass('active'); } }); // register logout event $('#menu-logout').on('click', function () { _setLogout(); }); // register workspace add event $('.ws-icon-add').on('click', function () { _addWSList(); }); } // WORKSPACE_PATH 파일이 있는지 없는지 여부 확인 후 없으면 생성. function _initialize() { _registerDefaultEvent(); webidaFs.exists(WORKSPACE_PATH, function (err, exist) { if (err) { console.log('_checkWSFile() - exists Error: ' + err); } if (!exist) { _setWorkspace(function (err) { if (err) { console.log(err); } _renderWSList(); }); } else { _checkValidWSFile(function (err, bool) { if (err) { console.log(err); } else { if (bool) { _renderWSList(); } else { console.log('workspace meta-info is invalid.'); _renderWSList(); } } }); } }); } // WORKSPACE 목록 생성 및 WORKSPACE_PATH에 정보 저장. function _setWorkspace(cb) { webidaFs.list('/', function (err, data) { if (err) { console.log('setWorkspace() - list Error: ' + err); cb(err); } else { var WSList = _.chain(data).filter(function (fileObj) { if (!fileObj.name.match(/^\./) && fileObj.isDirectory) { return true; } }).map(function (fileObj) { return '/' + fileObj.name; }).value(); webidaFs.stat(WSList, function (err, stats) { if (err) { console.log('setWorkspace() - stat Error: ' + err); cb(err); } else { var wsObj = {}; _.forEach(stats, function (fileObj) { fileObj.birth = ''; fileObj.desc = ''; wsObj[fileObj.name] = fileObj; }); webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(wsObj), function (err) { if (err) { console.log('setWorkspace() - writeFile Error: ' + err); cb(err); } else { cb(null, true); } }); } }); } }); } // 유니크 id 생성. function _genUniuqeId() { _uniqId = _.uniqueId(); return _uniqId; } // 로그아웃 function _setLogout() { webidaAuth.logout(function (err) { if (err) { alert('Failed to logout'); } else { location.href = '//' + webidaHost; } }); } function _getWSList(cb) { webidaFs.list('/', function (err, data) { if (err) { cb(err); } else { var WSList = _.chain(data).filter(function (fileObj) { if (!fileObj.name.match(/^\./) && fileObj.isDirectory) { return true; } }).map(function (fileObj) { return '/' + fileObj.name; }).value(); webidaFs.stat(WSList, function (err, stats) { if (err) { cb(err); } else { cb(null, stats); } }); } }); } // 프로젝트 목록 얻어오기 function _getPJListPath(WSPath, cb) { webidaFs.list(WSPath, function (err, pjList) { if (err) { cb(err); } else { var filteredPJList = _.chain(pjList).filter(function (file) { if (!file.name.match('.workspace') && file.isDirectory) { return true; } }).map(function (file) { return WSPath + '/' + file.name + '/.project/project.json'; }).value(); return cb(null, filteredPJList); } }); } // 프로젝트 목록 그리기 function _renderPJList(domObj) { var ws = domObj.attr('data-wspath'); var wsRow = domObj.parent(); if (wsRow.hasClass('ws-closed')) { wsRow.addClass('ws-opened'); wsRow.removeClass('ws-closed'); wsRow.after('<div class="pj-body" data-id="' + wsRow.attr('data-id') + '"></div>'); var proRow = wsRow.next(); _getPJListPath(ws, function (err, pjPathList) { if (err) { console.log('_renderPJList() - _getPJListPath Error: ' + err); } else { _.forEach(pjPathList, function (pjPath) { webidaFs.exists(pjPath, function (err, exist) { if (err) { console.log('_renderPJList() - exists Error: ' + err); } if (exist) { webidaFs.readFile(pjPath, function (err, data) { if (err) { console.log('_renderPJList() - read Error: ' + err); } else { var projInfo = JSON.parse(data); /* jshint maxlen : 200 */ var template = '<div class="pj-row"">' + '<div class="pj-content">' + '<div class="pj-item pj-arrow"></div>' + '<div class="pj-item pj-name">' + projInfo.name + '</div>' + '<div class="pj-item pj-ltime"></div>' + '<div class="pj-item pj-birth">' + moment(projInfo.created).fromNow() + '</div>' + '<div class="pj-item pj-desc">' + projInfo.description + '</div>' + '</div>' + '<div class="pj-content-icon">' + '</div>' + '</div>'; /* jshint maxlen:120 */ proRow.append(template); } }); } }); }); } }); } else { var projRow = wsRow.next(); if (projRow.hasClass('pj-body') && (projRow.attr('data-id') === wsRow.attr('data-id'))) { projRow.remove(); wsRow.removeClass('ws-opened'); wsRow.addClass('ws-closed'); } } } // 워크스페이스 목록 그리기 function _renderWSList() { if (_wsContents.children.length) { _wsContents.empty(); } webidaFs.readFile(WORKSPACE_PATH, function (err, data) { if (err) { console.log('_renderWSList() - readFile Error: ' + err); } else { var wsObj = JSON.parse(data); WORKSPACE_INFO = wsObj; _.forEach(wsObj, function (ws) { var id = _genUniuqeId(); var birth = ''; var desc = ''; if (ws.birth) { birth = moment(ws.birth).fromNow(); } if (ws.desc) { desc = ws.desc; } /* jshint maxlen : 200 */ var template = '<div class="ws-row ws-closed" data-id="' + id + '">' + '<div class="ws-content" data-wspath="' + ws.path + '">' + '<div class="ws-item ws-arrow"></div>' + '<div class="ws-item ws-name">' + ws.name + '</div>' + '<div class="ws-item ws-ltime">' + moment(ws.mtime).fromNow() + '</div>' + '<div class="ws-item ws-birth">' + birth + '</div>' + '<div class="ws-item ws-desc">' + desc + '</div>' + '</div>' + '<div class="ws-content-icon">' + '<div class="ws-launch">' + '<div class="ws-icon-launch" title="Launch IDE" data-wsname="' + ws.name + '"></div>' + '</div>' + '<div class="ws-delete">' + '<div class="ws-icon-delete" title="Delete Workspace" data-wsname="' + ws.name + '" data-id="' + id + '"></div>' + '</div>' + '</div>' + '</div>'; /* jshint maxlen : 120 */ _wsContents.append(template); }); // register get project event $('.ws-body .ws-content').on('click', function (evt) { var domObj = $(evt.target).parent(); _renderPJList(domObj); }); // register launch event $('.ws-icon-launch').on('click', function (evt) { var domObj = $(evt.target); _launchIDE(domObj); }); $('.ws-icon-delete').on('click', function (evt) { var domObj = $(evt.target); _removeWSList(domObj); }); } }); } function _addWSList() { _dimmingOn(); $('body').append(addDlg); // register dialog close event $('.adddlg_close').on('click', function () { $('.add_wsdlg').remove(); _dimmingOff(); }); // input에 포커스 $('#workspace_name').focus(); $('#workspace_name').on('keyup', function () { var wsname = this.value; if (wsname) { $('#adddlg_message').text(''); } }); // register create workspace event $('#adddlg_confirm').on('click', function (evt) { evt.preventDefault(); var wsname = $('#workspace_name').val(); var wsdesc = $('#workspace_desc').val(); var message = $('#adddlg_message'); if (!wsname) { message.text('Please enter workspace name.'); return; } _getWSList(function (err, wslist) { if (err) { console.log('_addWSList()' + err); } else { var isExist = _.find(wslist, { 'name' : wsname }); if (isExist) { message.text('\'' + wsname + '\' worskpace is already existed.'); return; } else { // create workspace var WS_META_PATH = wsname + '/.workspace'; var WS_META_FILE = WS_META_PATH + '/workspace.json'; async.waterfall([ function (next) { webidaFs.createDirectory(wsname, false, function (err) { if (err) { next('_addWSList() - 1st createDirectory Error:' + err); } else { next(); } }); }, function (next) { webidaFs.createDirectory(WS_META_PATH, false, function (err) { if (err) { next('_addWSList() - 2nd createDirectory Error:' + err); } else { next(); } }); }, function (next) { webidaFs.writeFile(WS_META_FILE, '', function (err) { if (err) { next('_addWSList() - 1st writeFile Error:' + err); } else { next(); } }); }, function (next) { webidaFs.stat([wsname], function (err, stats) { if (err) { next('_addWSList() - stat Error:' + err); } else { stats[0].birth = new Date().toJSON(); stats[0].desc = wsdesc; WORKSPACE_INFO[wsname] = stats[0]; next(); } }); }, function (next) { webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(WORKSPACE_INFO), function (err) { if (err) { next('_addWSList() - 2nd writeFile Error:' + err); } else { next(); } }); } ], function (err) { if (err) { console.log(err); } else { $('.add_wsdlg').remove(); _dimmingOff(); _renderWSList(); } }); } } }); }); } function _removeWSList(domObj) { _dimmingOn(); $('body').append(removeDlg); $('.removedlg_close').on('click', function () { $('.remove_wsdlg').remove(); _dimmingOff(); }); var deleteWSname = domObj.attr('data-wsname'); var msg = '<p>This action <strong style="color:#fff">CANNOT</strong> be undone. ' + 'This will delete the <span style="color:#fff; font-weight:bold;">' + deleteWSname + '</span> workspace and projects permanetly.</p>' + '<p>Please type in the name of the workspace to confirm.</p>'; $('.removedlg_warning_text').html(msg); // input에 포커스 $('#workspace_name').focus(); $('#workspace_name').on('keyup', function () { var wsname = this.value; if (wsname) { $('#removedlg_message').text(''); } }); $('#removedlg_confirm').on('click', function (evt) { evt.preventDefault(); var wsname = $('#workspace_name').val(); var message = $('#removedlg_message'); if (!wsname) { message.text('Please enter workspace name.'); return; } else if (wsname !== deleteWSname) { message.text('workspace name doesn\'t match.'); return; } if (WORKSPACE_INFO[deleteWSname]) { delete WORKSPACE_INFO[deleteWSname]; async.waterfall([ function (next) { webidaFs.writeFile(WORKSPACE_PATH, JSON.stringify(WORKSPACE_INFO), function (err) { if (err) { err('_removeWSList() - writeFile Error: ' + err); } else { next(); } }); }, function (next) { webidaFs.delete(deleteWSname, true, function (err) { if (err) { next('_removeWSList() - delete Error:' + err); } else { next(); } }); } ], function (err) { if (err) { console.log(err); } else { var id = domObj.attr('data-id'); var selectorWS = '.ws-row[data-id=' + id + ']'; var selectorProj = '.pj-body[data-id=' + id + ']'; $(selectorWS).remove(); if ($(selectorProj)) { $(selectorProj).remove(); } $('.remove_wsdlg').remove(); _dimmingOff(); } }); } }); } common.getFS(function (exist) { if (exist) { _initialize(); } else { location.href = '//' + webidaHost; } }); });
5hk/webida-client
apps/dashboard/src/js/main_bak.js
JavaScript
apache-2.0
22,004
"use strict"; var router_1 = require('@angular/router'); var authorize_component_1 = require('./authorize/authorize-component'); var user_component_1 = require('./User/user-component'); var welcome_component_1 = require('./welcome-component'); exports.routes = [ { path: '', component: welcome_component_1.welcome }, { path: 'login', component: authorize_component_1.AuthorizeComponent }, { path: 'dashboard', component: user_component_1.UserComponent }, ]; exports.APP_ROUTER_PROVIDERS = [ router_1.provideRouter(exports.routes) ]; //# sourceMappingURL=app.route.js.map
devilsuraj/openiddict-samples
Samples/resource-owner-password-credential/Angualar2-Client-ROPC/app/app.route.js
JavaScript
apache-2.0
586
ngDefine( 'cockpit.plugin.statistics-plugin.controllers', function(module) { module .controller( 'processDefinitionCtrl', [ '$scope', 'DataFactory', 'Uri', function($scope, DataFactory, Uri) { $scope.options = { chart : { type : 'pieChart', height : 500, x : function(d) { return d.key; }, y : function(d) { return d.y; }, showLabels : true, transitionDuration : 500, labelThreshold : 0.01, tooltips : true, tooltipContent : function(key, y, e, graph) { if (key == "finished") { return '<h3>' + key + '</h3>' + '<p>count:<b>' + y + '</b><br/>' + 'average Duration:<b>' + (e.point.avg / 1000 / 60).toFixed(2) + ' min</b><br/>minimal Duration:<b>' + (e.point.min / 1000 / 60).toFixed(2) + ' min</b><br/>maximal Duration:<b>' + (e.point.max / 1000 / 60).toFixed(2) + ' min</b></p>' } else { return '<h3>' + key + '</h3>' + '<p>' + y + '</p>' } }, noData : "No Processes met the requirements", legend : { margin : { top : 5, right : 5, bottom : 5, left : 5 } } } }; DataFactory .getAllProcessInstanceCountsByState( $scope.processDefinition.key) .then( function() { var processDefinitionCounts = DataFactory.allProcessInstanceCountsByState[$scope.processDefinition.key]; var counts = []; counts .push({ "key" : "running", "y" : processDefinitionCounts[0].runningInstanceCount }); counts .push({ "key" : "failed", "y" : processDefinitionCounts[0].failedInstanceCount }); counts .push({ "key" : "finished", "y" : processDefinitionCounts[0].endedInstanceCount, "avg" : processDefinitionCounts[0].duration, "min" : processDefinitionCounts[0].minDuration, "max" : processDefinitionCounts[0].maxDuration }); $scope.statesOfDefinition = counts; }); } ]); });
nagyistoce/camunda-cockpit-plugin-statistics
src/main/resources/plugin-webapp/statistics-plugin/app/controllers/processDefinitionCtrl.js
JavaScript
apache-2.0
3,679
/** * Red Hat Open Innovation Labs API * A generic model to support automation at all levels of the application and infrastructure lifecycle. * * OpenAPI spec version: 0.3.0-alpha * Contact: [email protected] * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['ApiClient', 'model/Port'], factory); } else if (typeof module === 'object' && module.exports) { // CommonJS-like environments that support module.exports, like Node. module.exports = factory(require('../ApiClient'), require('./Port')); } else { // Browser globals (root is window) if (!root.RedHatOpenInnovationLabsApi) { root.RedHatOpenInnovationLabsApi = {}; } root.RedHatOpenInnovationLabsApi.Service = factory(root.RedHatOpenInnovationLabsApi.ApiClient, root.RedHatOpenInnovationLabsApi.Port); } }(this, function(ApiClient, Port) { 'use strict'; /** * The Service model module. * @module model/Service * @version 0.3.0-alpha */ /** * Constructs a new <code>Service</code>. * @alias module:model/Service * @class */ var exports = function() { var _this = this; }; /** * Constructs a <code>Service</code> from a plain JavaScript object, optionally creating a new instance. * Copies all relevant properties from <code>data</code> to <code>obj</code> if supplied or a new instance if not. * @param {Object} data The plain JavaScript object bearing properties of interest. * @param {module:model/Service} obj Optional instance to populate. * @return {module:model/Service} The populated <code>Service</code> instance. */ exports.constructFromObject = function(data, obj) { if (data) { obj = obj || new exports(); if (data.hasOwnProperty('id')) { obj['id'] = ApiClient.convertToType(data['id'], 'Number'); } if (data.hasOwnProperty('name')) { obj['name'] = ApiClient.convertToType(data['name'], 'String'); } if (data.hasOwnProperty('ports')) { obj['ports'] = ApiClient.convertToType(data['ports'], [Port]); } } return obj; } /** * @member {Number} id */ exports.prototype['id'] = undefined; /** * @member {String} name */ exports.prototype['name'] = undefined; /** * @member {Array.<module:model/Port>} ports */ exports.prototype['ports'] = undefined; return exports; }));
priley86/labs-console
app/automation/model/Service.js
JavaScript
apache-2.0
3,193
(function($) { module("referenceReads1"); // Test case : Reference Reads 1 _asyncTest("Reference Reads 1", function() { expect(6); GitanaTest.authenticateFullOAuth().then(function() { var platform = this; // create a few things var repository = null; this.createRepository().then(function() { repository = this; }); var domain = null; this.createDomain().then(function() { domain = this; }); var registrar = null; this.createRegistrar().then(function() { registrar = this; }); var stack = null; this.createStack().then(function() { stack = this; }); var team = null; this.then(function() { this.subchain(stack).createTeam("abc-" + new Date().getTime()).then(function() { team = this; }); }); this.then(function() { var repositoryReference = "repository://" + platform.getId() + "/" + repository.getId(); var domainReference = "domain://" + platform.getId() + "/" + domain.getId(); var registrarReference = "registrar://" + platform.getId() + "/" + registrar.getId(); var stackReference = "stack://" + platform.getId() + "/" + stack.getId(); var teamReference = "team://stack/" + platform.getId() + "/" + stack.getId() + "/" + team.getKey(); var entries = [{ "ref": repositoryReference }, { "ref": domainReference }, { "ref": registrarReference }, { "ref": stackReference }, { "ref": teamReference }]; this.referenceReads(entries, function(results) { // check that they all came back ok(results.length == entries.length, "Found the right number of results"); for (var i = 0; i < results.length; i++) { ok(results[i].entry, "Found entry #" + i); } // done start(); }); }); }); }); }(jQuery) );
gitana/gitana-javascript-driver
tests/js/testReferenceReads1.js
JavaScript
apache-2.0
2,469
$(function () { var controller = new ScrollMagic.Controller({ globalSceneOptions: { triggerHook: 'onLeave', reverse: true } }); // $('.homepage .panel').each(function () { // var element = $(this); // console.log(element); // new ScrollMagic.Scene({triggerElement: element}) // .setPin(element) // .setClassToggle(element,'active') // .addTo(controller) // }) // var actual_positions = [0]; // var mid_points = []; // var all_scenes = []; // $('.services .panel').each(function (index) { // if($(this).hasClass('main')) { // new ScrollMagic.Scene({triggerElement: '.services .main'}) // .setPin('.services .main') // .setClassToggle('.services .main','active') // .addTo(controller) // } // else { // var element_id = $(this).attr('id'); // var element_id_with_hash = '#' + $(this).attr('id'); // var scene = new ScrollMagic.Scene({triggerElement: element_id_with_hash}) // .setPin(element_id_with_hash) // .setClassToggle(element_id_with_hash,'show-bottom-nav') // .addTo(controller) // all_scenes.push({ // id: element_id, // scene: scene // }); // actual_positions.push(Math.ceil(scene.triggerPosition())); // if(actual_positions.length > 1) { // mid_points.push((actual_positions[index] + actual_positions [index-1]) / 2) // } // } // }) // $('a[href*=#]:not([href=#])').click(function () { // var id = $(this).attr('href').replace('#',''); // if($(this).parent().parent().parent().hasClass('bottom-nav')) { // var index = $('.bottom-nav ul li a').index($(this)); // }else { // var index = $('ul.wrap li a').index($(this)); // } // if(id == 'down') { // setTimeout(function () { // $('.bottom-nav').addClass('fixed') // },1100) // } // else { // var targetted_scene = all_scenes[index]; // if(targetted_scene.id == id) { // $('html,body').animate({scrollTop: targetted_scene.scene.scrollOffset()},1000); // return false; // } // } // }) // var add_and_remove_active_class = function (index) { // $('.bottom-nav').addClass('fixed') // $('.bottom-nav ul li').removeClass('active'); // $('.bottom-nav ul li:nth-child(' + index + ')').children('a').parent().last().addClass('active'); // } // $(window).scroll(function () { // if ($(".show-bottom-nav")[0]){ // $('.bottom-nav').addClass('fixed') // }else{ // $('.bottom-nav').removeClass('fixed') // } // for(var index=0; index<mid_points.length; index++) { // var next_index = index+1; // var last_index = mid_points.length-1 // /* check between mid point ranges and set active class to the respective nav item. */ // if($(window).scrollTop() > mid_points[index] && $(window).scrollTop() < mid_points[next_index]) { // add_and_remove_active_class(next_index); // break; // /* if nothing matches and reaches to last index then set active active to last nav item. */ // }else if ($(window).scrollTop() > mid_points[last_index]) { // add_and_remove_active_class(mid_points.length); // /* remove from all if its rolled back to the top*/ // }else { // $('.bottom-nav ul li').removeClass('active'); // } // } // }); }); //change navigation color on scroll /* var offset_top_news_section = $('.color-light').offset().top; var offset_top_contact_section = $('.pattern').offset().top; console.log(offset_top_contact_section, offset_top_news_section); $(window).scroll(function (event) { var scroll = $(window).scrollTop(); console.log(scroll); if(scroll < offset_top_contact_section && scroll >= offset_top_news_section) { $('.homepage nav').addClass('change-color'); } else { $('.homepage nav').removeClass('change-color'); } }); */
shamroze/squarespace-gulp-scaffolding
sqs_template/scripts/parallax.js
JavaScript
apache-2.0
4,557
angular.module('aac.controllers.main', []) /** * Main layout controller * @param $scope */ .controller('MainCtrl', function($scope, $rootScope, $location, Data, Utils) { $scope.go = function(v) { $location.path(v); } $scope.activeView = function(view) { return view == $rootScope.currentView ? 'active' : ''; }; $scope.signOut = function() { window.document.location = "./logout"; }; Data.getProfile().then(function(data) { data.fullname = data.name + ' ' + data.surname; $rootScope.user = data; }).catch(function(err) { Utils.showError(err); }); }) .controller('HomeController', function($scope, $rootScope, $location) { }) .controller('AccountsController', function($scope, $rootScope, $location, Data, Utils) { Data.getAccounts().then(function(data) { Data.getProviders().then(function(providers) { providers.sort(function(a,b) { if (data.accounts[a] && !data.accounts[b]) return -1; if (data.accounts[b] && !data.accounts[a]) return 1; return a.localeCompare(b); }); $scope.providers = providers; var accounts = {}; for (var p in data.accounts) { var amap = {}; for (var k in data.accounts[p]) { if (k === 'it.smartcommunitylab.aac.surname') amap['surname'] = data.accounts[p][k]; else if (k === 'it.smartcommunitylab.aac.givenname') amap['givenname'] = data.accounts[p][k]; else if (k === 'it.smartcommunitylab.aac.username') amap['username'] = data.accounts[p][k]; else amap[k] = data.accounts[p][k]; } accounts[p] = amap; } $scope.accounts = accounts; }).catch(function(err) { Utils.showError(err); }); }).catch(function(err) { Utils.showError(err); }); $scope.confirmDeleteAccount = function() { $('#deleteConfirm').modal({keyboard: false}); } $scope.deleteAccount = function() { $('#deleteConfirm').modal('hide'); Data.deleteAccount().then(function() { window.location.href = './logout'; }).catch(function(err) { Utils.showError(err); }); } }) .controller('ConnectionsController', function($scope, $rootScope, $location, Data, Utils) { Data.getConnections().then(function(connections) { $scope.connections = connections; }).catch(function(err) { Utils.showError(err); }); $scope.confirmDeleteApp = function(app) { $scope.clientId = app.clientId; $('#deleteConfirm').modal({keyboard: false}); } $scope.deleteApp = function() { $('#deleteConfirm').modal('hide'); Data.removeConnection($scope.clientId).then(function(connections) { $scope.connections = connections; Utils.showSuccess(); }).catch(function(err) { Utils.showError(err); }); } }) .controller('ProfileController', function($scope, $rootScope, $location, Data, Utils) { $scope.profile = Object.assign($rootScope.user); Data.getAccounts().then(function(data) { if (!data.accounts.internal) { $scope.password_required = true; } }).catch(function(err) { Utils.showError(err); }); $scope.cancel = function() { window.history.back(); } $scope.save = function() { if (!$scope.profile.name || !$scope.profile.surname || !$scope.profile.username || $scope.profile.password && $scope.profile.password != $scope.profile.password2) { return; } Data.saveAccount($scope.profile).then(function(data) { data.fullname = data.name + ' ' + data.surname; $rootScope.user = data; $scope.profile = Object.assign($rootScope.user); $scope.password_required = false; Utils.showSuccess(); }).catch(function(err) { Utils.showError(err); }); } Utils.initUI(); }) ;
smartcommunitylab/AAC
src/main/resources/public/js/account/main.js
JavaScript
apache-2.0
3,561
jQuery(function($) { //smooth scroll $('.navbar-nav > li.anchor').click(function(event) { //event.preventDefault(); var target = $(this).find('>a').prop('hash'); $('#navbar .active').removeClass('active'); $(this).addClass('active'); $('html, body').animate({ scrollTop: $(target).offset().top }, 500); }); //scrollspy $('[data-spy="scroll"]').each(function () { var $spy = $(this).scrollspy('refresh') }); $(function() { $(".navbar-btn").click(function() { $("#options").toggle(); $(".navbar-btn .glyphicon").toggleClass("glyphicon-plus") .toggleClass("glyphicon-minus"); }); }); });
clinm/visu-regions-autonomes-france
js/main.js
JavaScript
apache-2.0
656
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = void 0; var STATIC_REG = /.*\.(png|jpe?g|gif|svg|woff2?|eot|ttf|otf)$/; var VER_REG = /[\W][\d\w]+(?=\.\w+$)/; var _default = function _default(req, res, next) { var filePaths = req.url.split('/'); if (STATIC_REG.test(req.path) && filePaths[2] === 'prd') { filePaths.splice(2, 1); req.url = filePaths.join('/').replace(VER_REG, ''); } next(); }; exports["default"] = _default;
angrytoro/fetool
lib/server/middlewares/webpackStatic.js
JavaScript
apache-2.0
497
System.register([], function (exports_1, context_1) { "use strict"; var __moduleName = context_1 && context_1.id; function toSnakeCase(camelCase) { if (!camelCase) { throw new Error("Please provide camelCase."); } return camelCase.replace(/([A-Z])/g, "-$1").toLowerCase(); } exports_1("toSnakeCase", toSnakeCase); return { setters: [], execute: function () { } }; }); //# sourceMappingURL=to.snake.case.js.map
roelvanlisdonk/dev
apps/sportersonline/www/libraries/am/common/text/to.snake.case.js
JavaScript
apache-2.0
497
import { createStore, applyMiddleware, compose } from 'redux' import logger from 'redux-logger' import thunkMiddleware from 'redux-thunk' import rootReducer from './reducers' const configureStore = () => { const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; return createStore(rootReducer, /* preloadedState, */ composeEnhancers( applyMiddleware(thunkMiddleware) // applyMiddleware(logger) )); } export default configureStore
AleksandrRogachev94/chat-vote-go-frontend
src/configureStore.js
JavaScript
apache-2.0
471
(function outer(modules, cache, entries){ /** * Global */ var global = (function(){ return this; })(); /** * Require `name`. * * @param {String} name * @param {Boolean} jumped * @api public */ function require(name, jumped){ if (cache[name]) return cache[name].exports; if (modules[name]) return call(name, require); throw new Error('cannot find module "' + name + '"'); } /** * Call module `id` and cache it. * * @param {Number} id * @param {Function} require * @return {Function} * @api private */ function call(id, require){ var m = cache[id] = { exports: {} }; var mod = modules[id]; var name = mod[2]; var fn = mod[0]; fn.call(m.exports, function(req){ var dep = modules[id][1][req]; return require(dep ? dep : req); }, m, m.exports, outer, modules, cache, entries); // expose as `name`. if (name) cache[name] = cache[id]; return cache[id].exports; } /** * Require all entries exposing them on global if needed. */ for (var id in entries) { if (entries[id]) { global[entries[id]] = require(id); } else { require(id); } } /** * Duo flag. */ require.duo = true; /** * Expose cache. */ require.cache = cache; /** * Expose modules */ require.modules = modules; /** * Return newest require. */ return require; })({ 1: [function(require, module, exports) { /** @jsx React.DOM */ React.renderComponent( React.DOM.h1(null, "Hello, world!"), document.getElementById('example') ); }, {}]}, {}, {"1":""})
wdamron/duo-jsx
test/exp_react.js
JavaScript
apache-2.0
1,625
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @fileoverview Embeds an instagram photo. The data-shortcode attribute can be * easily copied from a normal instagram URL. Example: <code> <amp-instagram * data-shortcode="fBwFP" data-captioned data-default-framing alt="Fastest page * in the west." width="320" height="392" layout="responsive"> </amp-instagram> * </code> * * For responsive embedding the width and height can be left unchanged from the * example above and should produce the correct aspect ratio. amp-instagram will * attempt to resize on load based on the height reported by the embedded frame. * If captions are specified (data-captioned) then a resize will be requested * every time due to the fact that it's not possible to know the height of the * caption in advance. * * If captions are included it is stringly reccomended that an overflow element * is also included. See description of overflow in amp-iframe. * * If data-default-framing is present will apply the default instagram frame * style without changing the layout/size. */ import {CSS} from '../../../build/amp-instagram-0.1.css'; import {getData, listen} from '../../../src/event-helper'; import {isLayoutSizeDefined} from '../../../src/layout'; import {isObject} from '../../../src/types'; import {removeElement} from '../../../src/dom'; import {setStyles} from '../../../src/style'; import {startsWith} from '../../../src/string'; import {tryParseJson} from '../../../src/json'; import {user} from '../../../src/log'; class AmpInstagram extends AMP.BaseElement { /** @param {!AmpElement} element */ constructor(element) { super(element); /** @private {?Element} */ this.iframe_ = null; /** @private {?string} */ this.shortcode_ = ''; /** @private {?Function} */ this.unlistenMessage_ = null; /** @private {string} */ this.captioned_ = ''; /** * @private {?Promise} * @visibleForTesting */ this.iframePromise_ = null; } /** * @param {boolean=} opt_onLayout * @override */ preconnectCallback(opt_onLayout) { // See // https://instagram.com/developer/embedding/?hl=en this.preconnect.url('https://www.instagram.com', opt_onLayout); // Host instagram used for image serving. While the host name is // funky this appears to be stable in the post-domain sharding era. this.preconnect.url('https://instagram.fsnc1-1.fna.fbcdn.net', opt_onLayout); } /** @override */ renderOutsideViewport() { return false; } /** @override */ buildCallback() { this.shortcode_ = user().assert( (this.element.getAttribute('data-shortcode') || this.element.getAttribute('shortcode')), 'The data-shortcode attribute is required for <amp-instagram> %s', this.element); this.captioned_ = this.element.hasAttribute('data-captioned') ? 'captioned/' : ''; } /** @override */ createPlaceholderCallback() { const placeholder = this.win.document.createElement('div'); placeholder.setAttribute('placeholder', ''); const image = this.win.document.createElement('amp-img'); image.setAttribute('noprerender', ''); // This will redirect to the image URL. By experimentation this is // always the same URL that is actually used inside of the embed. image.setAttribute('src', 'https://www.instagram.com/p/' + encodeURIComponent(this.shortcode_) + '/media/?size=l'); image.setAttribute('layout', 'fill'); image.setAttribute('referrerpolicy', 'origin'); this.propagateAttributes(['alt'], image); /* * Add instagram default styling */ if (this.element.hasAttribute('data-default-framing')) { this.element.classList.add('amp-instagram-default-framing'); } // This makes the non-iframe image appear in the exact same spot // where it will be inside of the iframe. setStyles(image, { 'top': '0 px', 'bottom': '0 px', 'left': '0 px', 'right': '0 px', }); placeholder.appendChild(image); return placeholder; } /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ layoutCallback() { const iframe = this.element.ownerDocument.createElement('iframe'); this.iframe_ = iframe; this.unlistenMessage_ = listen( this.win, 'message', this.handleInstagramMessages_.bind(this) ); iframe.setAttribute('scrolling', 'no'); iframe.setAttribute('frameborder', '0'); iframe.setAttribute('allowtransparency', 'true'); //Add title to the iframe for better accessibility. iframe.setAttribute('title', 'Instagram: ' + this.element.getAttribute('alt')); iframe.src = 'https://www.instagram.com/p/' + encodeURIComponent(this.shortcode_) + '/embed/' + this.captioned_ + '?cr=1&v=7'; this.applyFillContent(iframe); this.element.appendChild(iframe); setStyles(iframe, { 'opacity': 0, }); return this.iframePromise_ = this.loadPromise(iframe).then(() => { this.getVsync().mutate(() => { setStyles(iframe, { 'opacity': 1, }); }); }); } /** * @param {!Event} event * @private */ handleInstagramMessages_(event) { if (event.origin != 'https://www.instagram.com' || event.source != this.iframe_.contentWindow) { return; } const eventData = getData(event); if (!eventData || !(isObject(eventData) || startsWith(/** @type {string} */ (eventData), '{'))) { return; // Doesn't look like JSON. } const data = isObject(eventData) ? eventData : tryParseJson(eventData); if (data === undefined) { return; // We only process valid JSON. } if (data['type'] == 'MEASURE' && data['details']) { const height = data['details']['height']; this.getVsync().measure(() => { if (this.iframe_ && this.iframe_./*OK*/offsetHeight !== height) { this./*OK*/changeHeight(height); } }); } } /** @override */ unlayoutOnPause() { return true; } /** @override */ unlayoutCallback() { if (this.iframe_) { removeElement(this.iframe_); this.iframe_ = null; this.iframePromise_ = null; } if (this.unlistenMessage_) { this.unlistenMessage_(); } return true; // Call layoutCallback again. } } AMP.extension('amp-instagram', '0.1', AMP => { AMP.registerElement('amp-instagram', AmpInstagram, CSS); });
aghassemi/amphtml
extensions/amp-instagram/0.1/amp-instagram.js
JavaScript
apache-2.0
7,111
var addressBar = element(by.css("#addressBar")), url = 'http://www.example.com/base/ratingList.html#!/path?a=b#h'; it("should show fake browser info on load", function(){ expect(addressBar.getAttribute('value')).toBe(url); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/path'); expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}'); expect(element(by.binding('$location.hash()')).getText()).toBe('h'); }); it("should change $location accordingly", function(){ var navigation = element.all(by.css("#navigation a")); navigation.get(0).click(); expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/first?a=b"); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/first'); expect(element(by.binding('$location.search()')).getText()).toBe('{"a":"b"}'); expect(element(by.binding('$location.hash()')).getText()).toBe(''); navigation.get(1).click(); expect(addressBar.getAttribute('value')).toBe("http://www.example.com/base/ratingList.html#!/sec/ond?flag#hash"); expect(element(by.binding('$location.protocol()')).getText()).toBe('http'); expect(element(by.binding('$location.host()')).getText()).toBe('www.example.com'); expect(element(by.binding('$location.port()')).getText()).toBe('80'); expect(element(by.binding('$location.path()')).getText()).toBe('/sec/ond'); expect(element(by.binding('$location.search()')).getText()).toBe('{"flag":true}'); expect(element(by.binding('$location.hash()')).getText()).toBe('hash'); });
lvkklemo/shopApp
library/angular-1.4.9/docs/examples/example-location-hashbang-mode/protractor.js
JavaScript
apache-2.0
2,038
"use strict"; define(["lib/three.min"], function() { var Reality = function(sourceCanvas){ // Create a default camera and scene. var camera = new THREE.Camera(); var scene = new THREE.Scene(); // Create a plane geometry to hold the sourceCanvas texture var geometry = new THREE.PlaneGeometry(2, 2, 0); // Create a material textured with the contents of sourceCanvas. var texture = new THREE.Texture(sourceCanvas); var material = new THREE.MeshBasicMaterial({ map: texture, depthTest: false, depthWrite: false }); // Build a mesh and add it to the scene. var mesh = new THREE.Mesh( geometry, material ); scene.add(mesh); // We need to notify ThreeJS when the texture has changed. function update() { texture.needsUpdate = true; } return { camera: camera, scene: scene, update: update, } } var Scene = function() { var scene = new THREE.Scene(); var camera = new THREE.Camera(); function add(object) { scene.add(object); } function remove(object) { scene.remove(object); } function setProjectionMatrix(matrix) { camera.projectionMatrix.setFromArray( matrix ); } return { scene:scene, camera:camera, add:add, remove:remove, setProjectionMatrix:setProjectionMatrix, } } var create = function(dimensions, sourceCanvas) { // Create a canvas which will be used for WebGL var glCanvas = document.createElement('canvas'); // Initialize the renderer and attach it to the canvas var renderer = new THREE.WebGLRenderer({canvas:glCanvas}); renderer.setSize(dimensions.width, dimensions.height); renderer.autoClear = false; // Create a reality scene var reality = new Reality(sourceCanvas); var virtual = new Scene(); var light = new THREE.SpotLight(0xffffff); light.position.set(0, 0, 9000); light.lookAt( new THREE.Vector3(0,0,0) ); virtual.scene.add(light); function render() { // Render the reality scene renderer.render(reality.scene, reality.camera); // Render the augmented components on top of the reality scene. renderer.render(virtual.scene, virtual.camera); } function update() { // Notify the reality scene to update it's texture reality.update(); } function setCameraMatrix( matrix ) { virtual.setProjectionMatrix( matrix ); } function add( object ) { virtual.add( object.model ); } function remove( object ) { virtual.remove( object.model ); } return { add: add, remove: remove, update: update, render: render, glCanvas: glCanvas, setCameraMatrix: setCameraMatrix, } } return { create: create, } });
xsoh/3DKabah
arview.js
JavaScript
apache-2.0
3,251
const $ = require('jquery'); const { BagItProfile } = require('../../bagit/bagit_profile'); const { Job } = require('../../core/job'); const { JobRunController } = require('./job_run_controller'); const { PackageOperation } = require('../../core/package_operation'); const path = require('path'); const { StorageService } = require('../../core/storage_service'); const { TestUtil } = require('../../core/test_util'); const { UITestUtil } = require('../common/ui_test_util'); const { UploadOperation } = require('../../core/upload_operation'); const { Util } = require('../../core/util'); beforeEach(() => { TestUtil.deleteJsonFile('Job'); TestUtil.deleteJsonFile('StorageService'); }); afterAll(() => { TestUtil.deleteJsonFile('Job'); TestUtil.deleteJsonFile('StorageService'); }); function getStorageService(name, proto, host) { let ss = new StorageService({ name: name, protocol: proto, host: host }); ss.save(); return ss; } function getUploadOp(name, proto, host) { let ss = getStorageService(name, proto, host); let op = new UploadOperation(); op.sourceFiles = ['/dev/null']; op.storageServiceId = ss.id; return op; } function getJob() { var job = new Job(); job.packageOp = new PackageOperation('TestBag', '/dev/null'); job.packageOp.packageFormat = 'BagIt'; job.packageOp._trimLeadingPaths = false; job.packageOp.sourceFiles = [ __dirname, path.join(__dirname, '..', 'forms') ]; job.dirCount = 2; job.fileCount = 12; job.byteCount = 237174; job.uploadOps = [ getUploadOp('target1', 's3', 'target1.com'), getUploadOp('target2', 's3', 'target2.com') ]; job.bagItProfile = BagItProfile.load(path.join(__dirname, '..', '..', 'test', 'profiles', 'multi_manifest.json')); job.save(); return job; } function getController() { let job = getJob(); let params = new URLSearchParams({ id: job.id }); return new JobRunController(params); } test('constructor', () => { let controller = getController(); expect(controller.model).toEqual(Job); expect(controller.job).not.toBeNull(); }); test('show', () => { let controller = getController(); let response = controller.show() expect(response.container).toMatch(controller.job.packageOp.packageName); expect(response.container).toMatch(controller.job.packageOp.outputPath); expect(response.container).toMatch(controller.job.bagItProfile.name); expect(response.container).toMatch(controller.job.bagItProfile.description); expect(response.container).toMatch('2 Directories'); expect(response.container).toMatch('12 Files'); expect(response.container).toMatch('231.62 KB'); expect(response.container).toMatch(controller.job.packageOp.sourceFiles[0]); expect(response.container).toMatch(controller.job.packageOp.sourceFiles[1]); });
APTrust/easy-store
ui/controllers/job_run_controller.test.js
JavaScript
apache-2.0
2,913
/** * @license Apache-2.0 * * Copyright (c) 2020 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; // MODULES // var isPositiveInteger = require( '@stdlib/math/base/assert/is-positive-integer' ); var constantFunction = require( '@stdlib/utils/constant-function' ); var isfinite = require( '@stdlib/math/base/assert/is-finite' ); var round = require( '@stdlib/math/base/special/round' ); var isnan = require( '@stdlib/math/base/assert/is-nan' ); var exp = require( '@stdlib/math/base/special/exp' ); var LN2 = require( '@stdlib/constants/float64/ln-two' ); var weights = require( './weights.js' ); // MAIN // /** * Returns a function for evaluating the cumulative distribution function (CDF) for the distribution of the Wilcoxon signed rank test statistic with `n` observations. * * @param {PositiveInteger} n - number of observations * @returns {Function} CDF * * @example * var cdf = factory( 8 ); * var y = cdf( 3.9 ); * // returns ~0.027 * * y = cdf( 17.0 ); * // returns ~0.473 */ function factory( n ) { var mlim; var pui; if ( !isPositiveInteger( n ) || !isfinite( n ) ) { return constantFunction( NaN ); } pui = exp( -n * LN2 ); mlim = n * ( n + 1 ) / 2; return cdf; /** * Evaluates the cumulative distribution function (CDF) for the distribution of the Wilcoxon signed rank test statistic. * * @private * @param {number} x - input value * @returns {Probability} evaluated CDF * * @example * var y = cdf( 2 ); * // returns <number> */ function cdf( x ) { var i; var p; if ( isnan( x ) ) { return NaN; } if ( x < 0.0 ) { return 0.0; } x = round( x ); if ( x >= mlim ) { return 1.0; } p = 0; for ( i = 0; i <= x; i++ ) { p += weights( i, n ) * pui; } return p; } } // EXPORTS // module.exports = factory;
stdlib-js/stdlib
lib/node_modules/@stdlib/stats/base/dists/signrank/cdf/lib/factory.js
JavaScript
apache-2.0
2,313
/** * @license * Copyright The Closure Library Authors. * SPDX-License-Identifier: Apache-2.0 */ /** * @fileoverview Displays and edits the value of a cookie. * Intended only for debugging. */ goog.provide('goog.ui.CookieEditor'); goog.require('goog.asserts'); goog.require('goog.dom'); goog.require('goog.dom.TagName'); goog.require('goog.events.EventType'); goog.require('goog.net.Cookies'); goog.require('goog.string'); goog.require('goog.style'); goog.require('goog.ui.Component'); goog.requireType('goog.events.Event'); /** * Displays and edits the value of a cookie. * @final * @unrestricted */ goog.ui.CookieEditor = class extends goog.ui.Component { /** * @param {goog.dom.DomHelper=} opt_domHelper Optional DOM helper. */ constructor(opt_domHelper) { 'use strict'; super(opt_domHelper); } /** * Sets the cookie which this component will edit. * @param {string} cookieKey Cookie key. */ selectCookie(cookieKey) { 'use strict'; goog.asserts.assert(goog.net.Cookies.getInstance().isValidName(cookieKey)); this.cookieKey_ = cookieKey; if (this.textAreaElem_) { this.textAreaElem_.value = goog.net.Cookies.getInstance().get(cookieKey) || ''; } } /** @override */ canDecorate() { 'use strict'; return false; } /** @override */ createDom() { 'use strict'; // Debug-only, so we don't need i18n. this.clearButtonElem_ = goog.dom.createDom( goog.dom.TagName.BUTTON, /* attributes */ null, 'Clear'); this.updateButtonElem_ = goog.dom.createDom( goog.dom.TagName.BUTTON, /* attributes */ null, 'Update'); var value = this.cookieKey_ && goog.net.Cookies.getInstance().get(this.cookieKey_); this.textAreaElem_ = goog.dom.createDom( goog.dom.TagName.TEXTAREA, /* attibutes */ null, value || ''); this.valueWarningElem_ = goog.dom.createDom( goog.dom.TagName.SPAN, /* attibutes */ {'style': 'display:none;color:red'}, 'Invalid cookie value.'); this.setElementInternal(goog.dom.createDom( goog.dom.TagName.DIV, /* attibutes */ null, this.valueWarningElem_, goog.dom.createDom(goog.dom.TagName.BR), this.textAreaElem_, goog.dom.createDom(goog.dom.TagName.BR), this.clearButtonElem_, this.updateButtonElem_)); } /** @override */ enterDocument() { 'use strict'; super.enterDocument(); this.getHandler().listen( this.clearButtonElem_, goog.events.EventType.CLICK, this.handleClear_); this.getHandler().listen( this.updateButtonElem_, goog.events.EventType.CLICK, this.handleUpdate_); } /** * Handles user clicking clear button. * @param {!goog.events.Event} e The click event. * @private */ handleClear_(e) { 'use strict'; if (this.cookieKey_) { goog.net.Cookies.getInstance().remove(this.cookieKey_); } this.textAreaElem_.value = ''; } /** * Handles user clicking update button. * @param {!goog.events.Event} e The click event. * @private */ handleUpdate_(e) { 'use strict'; if (this.cookieKey_) { var value = this.textAreaElem_.value; if (value) { // Strip line breaks. value = goog.string.stripNewlines(value); } if (goog.net.Cookies.getInstance().isValidValue(value)) { goog.net.Cookies.getInstance().set(this.cookieKey_, value); goog.style.setElementShown(this.valueWarningElem_, false); } else { goog.style.setElementShown(this.valueWarningElem_, true); } } } /** @override */ disposeInternal() { 'use strict'; this.clearButtonElem_ = null; this.cookieKey_ = null; this.textAreaElem_ = null; this.updateButtonElem_ = null; this.valueWarningElem_ = null; } }; /** * Cookie key. * @type {?string} * @private */ goog.ui.CookieEditor.prototype.cookieKey_; /** * Text area. * @type {HTMLTextAreaElement} * @private */ goog.ui.CookieEditor.prototype.textAreaElem_; /** * Clear button. * @type {HTMLButtonElement} * @private */ goog.ui.CookieEditor.prototype.clearButtonElem_; /** * Invalid value warning text. * @type {HTMLSpanElement} * @private */ goog.ui.CookieEditor.prototype.valueWarningElem_; /** * Update button. * @type {HTMLButtonElement} * @private */ goog.ui.CookieEditor.prototype.updateButtonElem_; // TODO(user): add combobox for user to select different cookies
google/closure-library
closure/goog/ui/cookieeditor.js
JavaScript
apache-2.0
4,463