code
stringlengths
2
1.05M
import React, { PropTypes, Component } from 'react'; import PaymentAgentsList from './PaymentAgentsList'; import WithdrawalForm from './WithdrawalForm'; import M from '../_common/M'; import Tabs from '../_common/Tabs'; export default class DepositCard extends Component { static propTypes = { paymentAgent: PropTypes.object.isRequired, currency: PropTypes.string.isRequired, country: PropTypes.string.isRequired, }; constructor(props) { super(props); this.state = { activeTab: 0 }; } render() { const { paymentAgent, currency, country } = this.props; const paymentAgents = paymentAgent.toJS().paymentAgents; const paymentAgentOptions = paymentAgents.map(pa => ({ value: pa.paymentagent_loginid, text: pa.name })); const tabs = [ { text: 'Payment Agents', component: <PaymentAgentsList paymentAgents={paymentAgents} /> }, { text: 'Withdrawal', component: <WithdrawalForm paymentAgentOptions={paymentAgentOptions} currency={currency} {...paymentAgent.toJS()} {...this.props} />, }, ]; return ( paymentAgents.length === 0 ? <div> <M m="Sorry, we have no payment agents in" /> {country} </div> : <Tabs activeIndex={this.state.activeTab} onChange={idx => this.setState({ activeTab: idx })} id="pa-card" tabs={tabs} /> ); } }
let optionNames = [ 'Default', 'Lazy', ]; let isOptionName = (key, names = optionNames) => names.find(n => key.endsWith(n)); let AsyncDataMixin = { created () { }, mounted () { this.asyncReload(undefined, true); }, methods: { // name args optional asyncReload (propertyName, skipLazy = false) { let asyncData = this.$options.asyncData; if (asyncData) { let names = Object.keys(asyncData) .filter(s => !isOptionName(s)) .filter(s => propertyName === undefined || s === propertyName) .filter(s => skipLazy === false || !asyncData[`${s}Lazy`]); if (propertyName !== undefined && names.length === 0) { console.error(`asyncData.${propertyName} cannot find.`, this); return; } for (let prop of names) { // helper let setData = data => { this[prop] = data }; let setError = err => { this[`${prop}Error`] = err; if (err) this.asyncError = true; else this.asyncError = !!names.find(n => this[`${n}Error`]); }; let setLoading = flag => { this[`${prop}Loading`] = flag if (flag) this.asyncLoading = true; else this.asyncLoading = !!names.find(n => this[`${n}Loading`]); }; setLoading(true); setError(undefined); if (typeof asyncData[prop] !== 'function') { console.error(`asyncData.${prop} must be funtion. actual: ${asyncData[prop]}`, this); continue; } asyncData[prop].apply(this) .then(res => { this.$nextTick(() => { setData(res); setLoading(false); }); }) .catch(err => { this.$nextTick(() => { setError(err); setLoading(false); }); }); } } }, }, data () { let asyncData = this.$options.asyncData; if (asyncData) { let dataObj = { 'asyncLoading': false, 'asyncError': false, }; let names = Object.keys(asyncData) .filter(s => !isOptionName(s)); names.forEach(name => { dataObj[name] = asyncData[`${name}Default`]; }); names.forEach(name => { let loadingName = `${name}Loading` dataObj[loadingName] = !`${name}Lazy` }); let errorNames = names.map(s => `${s}Error`); errorNames.forEach(name => { dataObj[name] = undefined }); return dataObj; } return {} } } let AsyncDataPlugin = { install (Vue, options) { Vue.mixin(AsyncDataMixin) } } let api = { AsyncDataPlugin, AsyncDataMixin, } if (typeof exports === 'object' && typeof module === 'object') { module.exports = api } else if (typeof window !== 'undefined') { window.AsyncDataMixin = AsyncDataMixin; window.AsyncDataPlugin = AsyncDataPlugin; }
console.log('loading module ngUser') angular.module('ngUser', []).directive('ngUser',function(){ return{ templateUrl: 'ngapp/user/template.html' } }); console.log('loaded module ngUser')
import { deprecate } from 'ember-debug'; import calculateLocationDisplay from '../system/calculate-location-display'; /* * Remove after 3.4 once _ENABLE_RENDER_SUPPORT flag is no * longer needed. */ export default function deprecateRender(env) { let { moduleName } = env.meta; return { name: 'deprecate-render', visitor: { MustacheStatement(node) { if (node.path.original !== 'render') { return; } if (node.params.length !== 1) { return; } each(node.params, (param) => { if (param.type !== 'StringLiteral') { return; } deprecate(deprecationMessage(moduleName, node), false, { id: 'ember-template-compiler.deprecate-render', until: '3.0.0', url: 'https://emberjs.com/deprecations/v2.x#toc_code-render-code-helper' }); }); } } }; } function each(list, callback) { for (let i = 0, l = list.length; i < l; i++) { callback(list[i]); } } function deprecationMessage(moduleName, node) { let sourceInformation = calculateLocationDisplay(moduleName, node.loc); let componentName = node.params[0].original; let original = `{{render "${componentName}"}}`; let preferred = `{{${componentName}}}`; return `Please refactor \`${original}\` to a component and invoke via` + ` \`${preferred}\`. ${sourceInformation}`; }
'use strict'; var mean = require('meanio'); module.exports = function (System, app, auth, database) { app.route('/admin/menu/:name') .get(function (req, res) { var roles = req.user ? req.user.roles : ['anonymous']; var menu = req.params.name || 'main'; var defaultMenu = req.query.defaultMenu || []; if (!Array.isArray(defaultMenu)) defaultMenu = [defaultMenu]; var items = mean.menus.get({ roles: roles, menu: menu, defaultMenu: defaultMenu.map(function (item) { return JSON.parse(item); }) }); res.json(items); }); };
/* eslint react/prefer-es6-class: "off", max-len: "off" */ import React from 'react'; import PropTypes from 'prop-types'; import * as d3 from 'd3'; // import d3Drag from 'd3-drag'; import Faux from 'react-faux-dom'; // Can't use ES6 because Faux needs mixins too work. const Histogram = React.createClass({ propTypes: { name: PropTypes.string.isRequired, bars: PropTypes.array.isRequired, line: PropTypes.array.isRequired, manipulableLine: PropTypes.array.isRequired, width: PropTypes.number.isRequired, height: PropTypes.number.isRequired, onChange: PropTypes.func.isRequired, projectionTime: PropTypes.number, data: PropTypes.array, }, mixins: [ Faux.mixins.core, Faux.mixins.anim ], getInitialState() { return { chart: 'loading...' }; }, // componentWillMount() { // // this.props.init(); // }, componentDidMount() { this.componentWillReceiveProps(this.props); }, componentWillReceiveProps(nextProps) { const { gurka, width, height } = nextProps; const data = gurka[0]; const faux = this.connectFauxDOM('div.renderedD3', 'chart'); // set the dimensions and margins of the diagram const margin = { top: 20, right: 10, bottom: 0, left: 0 }; const svg = d3.select(faux).append('svg') .attr('width', width) .attr('height', height); const g = svg.append('g') .attr('transform', `translate(${margin.left},${margin.top})`); // var x = d3.scaleLinear().domain([0, bars.length]).range([0, width]); // var data = d3.range(1000).map(d3.randomBates(10)); var formatCount = d3.format(",.0f"); var x = d3.scaleLinear().domain([d3.min(data), d3.max(data)]).rangeRound([0, width]); console.log('x.domain()', x.domain()); const histogram = d3.histogram() .domain(x.domain()) .thresholds(x.ticks(20)); var bins = histogram(gurka[0]); var bins2 = histogram(gurka[1]); console.log('bins', bins); var y = d3.scaleLinear() .domain([0, d3.max(bins, d => d.length)]) .range([height, 0]); var bar = g.selectAll(".bar") .data(bins) .enter().append("g") .attr("class", "bar") .attr("fill", "#00ff00") .attr("opacity", 0.7) .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; }); var bar2 = g.selectAll(".bar2") .data(bins2) .enter().append("g") .attr("class", "bar2") .attr("fill", "#00ffff") .attr("opacity", 0.7) .attr("transform", function(d) { return "translate(" + x(d.x0) + "," + y(d.length) + ")"; }); bar.append("rect") .attr("x", 1) .attr("width", x(bins[0].x1) - x(bins[0].x0) - 1) .attr("height", function(d) { return height - y(d.length); }); bar2.append("rect") .attr("x", 1) .attr("width", x(bins[0].x1) - x(bins[0].x0) - 1) .attr("height", function(d) { return height - y(d.length); }); bar.append("text") .attr("dy", ".75em") .attr("y", 6) .attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2) .attr("text-anchor", "middle") .attr("fill", "#000000") .text(function(d) { return formatCount(d.length); }); // bar.append("text") // // .attr("dy", ".75em") // .attr("y", 0) // .attr("x", (x(bins[0].x1) - x(bins[0].x0)) / 2) // .attr("text-anchor", "middle") // .attr("fill", "#000000") // .text(d => d); g.append("g") .attr("class", "axis axis--x") .attr("transform", "translate(0," + height + ")") .call(d3.axisBottom(x)); }, render() { return ( <div className="renderedD3"> {this.state.chart} </div> ); } }); export default Histogram;
import React from 'react'; import firebase from 'firebase'; export default class CommentsForm extends React.Component { constructor(props) { super(props); this.state = { author: '', text: '', answer: { name: '', aText: '' } }; } setData = (e) => { e.preventDefault(); const {author, text, answer} = this.state; firebase.database().ref().child('comments').push({ author, text, answer }) }; render() { const {author, text, answer} = this.state; return ( <form className="comments-form" onSubmit={this.setData}> <label htmlFor="author">Author</label> <input type="text" id="author" name="author" value={ author } onChange={(e) => this.setState({author: e.target.value})}/> <label htmlFor="text">Comment</label> <textarea name="text" id="text" value={ text } onChange={(e) => this.setState({text: e.target.value})}/> <input id="postCommit" type="submit" value="post commit"/> </form> ) } }
#!/usr/bin/env node 'use strict'; var test = require('tape'); var path = require('path'); var fs = require('fs'); var existsSync = path.existsSync || fs.existsSync; var spawn = require('child_process').spawn; var args = process.argv.slice(2); // remove node, and script name var argEquals = function (argName) { return function (arg) { return arg === argName; }; }; var not = function (fn) { return function () { return !fn.apply(this, arguments); }; }; var isArg = function (x) { return x.slice(0, 2) === '--'; }; var isBound = args.some(argEquals('--bound')); var isProperty = args.some(argEquals('--property')); var skipShimPolyfill = args.some(argEquals('--skip-shim-returns-polyfill')); var skipAutoShim = args.some(argEquals('--skip-auto-shim')); var makeEntries = function (name) { return [name, name]; }; var moduleNames = args.filter(not(isArg)).map(makeEntries); if (moduleNames.length < 1) { var packagePath = path.join(process.cwd(), 'package.json'); if (!existsSync(packagePath)) { console.error('Error: No package.json found in the current directory'); console.error('at least one module name is required when not run in a directory with a package.json'); process.exit(1); } var pkg = require(packagePath); if (!pkg.name) { console.error('Error: No "name" found in package.json'); process.exit(2); } moduleNames.push([pkg.name + ' (current directory)', [path.join(process.cwd(), pkg.main || ''), process.cwd()]]); } var requireOrEvalError = function (name) { try { return require(name); } catch (e) { return new EvalError(e.message); } }; var validateModule = function validateAPIModule(t, nameOrFilePaths) { var name = nameOrFilePaths; var packageDir = nameOrFilePaths; if (Array.isArray(nameOrFilePaths)) { name = nameOrFilePaths[0]; packageDir = nameOrFilePaths[1]; } var module = requireOrEvalError(name); if (module instanceof EvalError) { return module; } var implementation = requireOrEvalError(packageDir + '/implementation'); var shim = requireOrEvalError(packageDir + '/shim'); var getPolyfill = requireOrEvalError(packageDir + '/polyfill'); t.test('export', function (st) { st.equal(typeof module, 'function', 'module is a function'); st.test('module is NOT bound (pass `--bound` to skip this test)', { skip: isBound }, function (st2) { st2.equal(module, getPolyfill(), 'module.exports === getPolyfill()'); st2.end(); }); st.end(); }); t.test('implementation', function (st) { st.equal(implementation, module.implementation, 'module.exports.implementation === implementation.js'); if (isProperty) { st.comment('# SKIP implementation that is a data property need not be a function'); } else { st.equal(typeof implementation, 'function', 'implementation is a function (pass `--property` to skip this test)'); } st.end(); }); t.test('polyfill', function (st) { st.equal(getPolyfill, module.getPolyfill, 'module.exports.getPolyfill === polyfill.js'); st.equal(typeof getPolyfill, 'function', 'getPolyfill is a function'); st.end(); }); t.test('shim', function (st) { st.equal(shim, module.shim, 'module.exports.shim === shim.js'); st.equal(typeof shim, 'function', 'shim is a function'); if (typeof shim === 'function') { var msg = 'shim returns polyfill (pass `--skip-shim-returns-polyfill` to skip this test)'; if (skipShimPolyfill) { st.comment('# SKIP ' + msg); } else { st.equal(shim(), getPolyfill(), msg); } } st.end(); }); t.test('auto', function (st) { var msg = 'auto is present'; if (skipAutoShim) { st.comment('# SKIP ' + msg); st.end(); } else { require(path.join(packageDir, '/auto')); st.comment(msg + ' (pass `--skip-auto-shim` to skip this test)'); var proc = spawn(path.join(__dirname, './autoTest.js'), [], { stdio: 'inherit' }); st.plan(1); proc.on('close', function (code) { st.equal(code, 0, 'auto invokes shim'); }); } }); return void 0; }; moduleNames.forEach(function (data) { var name = data[0]; var filePath = data[1]; test('es-shim API : testing module: ' + name, function (t) { t.comment('* ----------------------------- * #'); t.error(validateModule(t, filePath), 'expected no error'); t.end(); }); });
;(function(win, doc){ "use strict"; win.PngSprite = PngSprite; Implements(PngSprite, { getOriginalDimension: function(){ var img = this.image; if(img && img.nodeType == 1 && img.src){ var newImg = new Image(); newImg.src = img.src; this.image = newImg; this.width = newImg.width; this.height = newImg.height; } }, getBounds: function(){// var topBound = this.getTopBound(); var rightBound = this.getRightBound(); var bottomBound = this.getBottomBound(); var leftBound = this.getLeftBound(); console.log(topBound, rightBound, bottomBound, leftBound) if(topBound != null && rightBound != null && bottomBound != null && leftBound != null){ return { bounds:[leftBound, topBound, rightBound, bottomBound], originalWidth: this.imageWidth, originalHeight: this.imageHeight, width: rightBound - leftBound, height: bottomBound - topBound, url: this.image.src } } }, getTopBound: function(){ var imgData = this.imageData || ( this.imageData = this.getImageData()); if(!imgData) return var width = this.imageWidth || 0; var height = this.imageHeight || 0; var opaqueNumber = this.opaqueNumber || ( this.opaqueNumber = 100); var i,j, topBound,currentIndex,alphaIndex; for(j = 0; j < height; j++){ for(i = 0; i < width; i++){ topBound = j; currentIndex = j*width + i; //red, green, blue, alpha, just concein about alpha alphaIndex = currentIndex * 4 + 3; if(imgData[alphaIndex] && imgData[alphaIndex] >= opaqueNumber) return topBound - 1; } } }, getRightBound: function(){ var imgData = this.imageData || ( this.imageData = this.getImageData()); if(!imgData) return var width = this.imageWidth || 0; var height = this.imageHeight || 0; var opaqueNumber = this.opaqueNumber || ( this.opaqueNumber = 100); var i,j, rightBound,currentIndex,alphaIndex; for(i = width; i; i--){ for(j = 0; j < height; j++){ rightBound = i; currentIndex = j*width + i; //red, green, blue, alpha, just concein about alpha alphaIndex = currentIndex * 4 + 3; if(imgData[alphaIndex] && imgData[alphaIndex] >= opaqueNumber) return rightBound + 1; } } }, getBottomBound: function(){ var imgData = this.imageData || ( this.imageData = this.getImageData()); if(!imgData) return var width = this.imageWidth || 0; var height = this.imageHeight || 0; var opaqueNumber = this.opaqueNumber || ( this.opaqueNumber = 100); var i,j, bottomBound,currentIndex,alphaIndex; for(j = height; j; j--){ for(i = 0; i < width; i++){ bottomBound = j; currentIndex = j*width + i; //red, green, blue, alpha, just concein about alpha alphaIndex = currentIndex * 4 + 3; if(imgData[alphaIndex] && imgData[alphaIndex] >= opaqueNumber) return bottomBound + 1; } } }, getLeftBound: function(){ var imgData = this.imageData || ( this.imageData = this.getImageData()); if(!imgData) return var width = this.imageWidth || 0; var height = this.imageHeight || 0; var opaqueNumber = this.opaqueNumber || ( this.opaqueNumber = 100); var i,j, leftBound,currentIndex,alphaIndex; for(i = 0; i < width; i++){ for(j = 0; j < height; j++){ leftBound = i; currentIndex = j*width + i; //red, green, blue, alpha, just concein about alpha alphaIndex = currentIndex * 4 + 3; if(imgData[alphaIndex] && imgData[alphaIndex] >= opaqueNumber) return leftBound - 1; } } }, getImageData: function(){ var image = this.image; if(image && image.width && image.height){ var width = this.imageWidth || (this.imageWidth = image.width); var height = this.imageHeight || (this.imageHeight = image.height); var canvas = this.canvas || (this.canvas = doc.createElement('canvas')); var context = this.context || (this.context = canvas.getContext("2d")); canvas.width = width; canvas.height = height; context.drawImage(image, 0, 0, width, height); var imgData = context.getImageData(0,0,width,height); context.clearRect(0,0,width,height); if(imgData && imgData.data) return imgData.data; } return null; } }); function PngSprite(options){ if(!(this instanceof PngSprite)) return new PngSprite(options); options || ( options = {}); if(options.image && options.image.nodeType && options.image.nodeType == 1){ this.image = options.image; delete options.image; } for(var key in options){ if(Object.prototype.hasOwnProperty.call(options, key)) this[key] = options[key]; } this.getOriginalDimension(); } function Implements(obj,methods){ if(obj && typeof obj === "function"){ methods || ( methods = {}); for(var name in methods){ if(Object.prototype.hasOwnProperty.call(methods, name)) obj.prototype[name] = methods[name]; } } } })(window, document)
import { vec3 } from 'gl-matrix'; let tmpVec = vec3.create(); let tmpVec2 = vec3.create(); function sign(x) { if (x > 0) return 1; else return -1; } export default function collisionPush(engine) { this.looped = []; this.hooks = { 'external.update!': () => { this.looped = []; }, 'collision.collide!': ([entity, other, bounds]) => { if (this.looped[other.id]) return; this.looped[other.id] = true; // Test - pushing other object vec3.subtract(tmpVec2, bounds.max, bounds.min); // Choose biggest one let channel = 0; if (tmpVec2[channel] > tmpVec2[1]) channel = 1; if (tmpVec2[channel] > tmpVec2[2]) channel = 2; if (channel !== 0) tmpVec2[0] = 0; if (channel !== 1) tmpVec2[1] = 0; if (channel !== 2) tmpVec2[2] = 0; // Find direction to push vec3.subtract(tmpVec, engine.systems.collision.getCenter(other), engine.systems.collision.getCenter(entity)); // Sign tmpVec[0] = sign(tmpVec[0]); tmpVec[1] = sign(tmpVec[1]); tmpVec[2] = sign(tmpVec[2]); // Multiply sign vec3.multiply(tmpVec2, tmpVec2, tmpVec); engine.actions.transform.translate(other, tmpVec2, true); } }; }
var isLocal = document.location.hostname === 'localhost' || document.location.hostname === '127.0.0.1'; var pageName = isLocal ? getURLParameter('page') : decodeURI(location.pathname.substring(1, location.pathname.length)) var vue = new Vue({ el: '#app', data: { pageContent: '', isEditing: false, title: pageName }, filters: { marked: marked, maxLength: function (text, maxLength) { if (!maxLength) maxLength = 20; if (text.length > maxLength) { return text.substring(0, maxLength - 3) + '...' } else { return text; } } }, methods: { loadContent: function () { console.log('hre!'); setTimeout(function () { this.pageContent = 'sdfsdsdfsdf'; }, 400); }, onBodyKeydown: function(e) { // ctrl + e or ctrl + shift + e to edit if ((e.ctrlKey || (e.ctrlKey && e.shiftKey)) && e.keyCode === 69) { e.preventDefault(); this.edit(); return false; } // ctrl + s or ctrl + shift + s to save if ((e.ctrlKey || (e.ctrlKey && e.shiftKey)) && e.keyCode === 83) { e.preventDefault(); this.save(); return false; } if ((e.ctrlKey || (e.ctrlKey && e.shiftKey)) && e.keyCode === 83) { e.preventDefault(); this.new(); return false; } }, save: function () { this.isEditing = false; var self = this; $.ajax({ type: "POST", url: 'server/save-page.php', data: { pageName: pageName, pageContent: self.pageContent }, success: function (response) { console.log('Page "' + pageName + '" successfully saved.'); }, error: function (response) { console.error('Page "' + pageName + '" failed to save! Here\'s why: ' + response); }, dataType: 'text' }); }, edit: function () { this.isEditing = true; }, cancel: function() { this.isEditing = false; }, delete: function () { $.ajax({ type: "POST", url: 'server/delete-page.php', data: { pageName: pageName }, success: function (response) { console.log('Page "' + pageName + '" successfully deleted.'); vue.pageContent = '**Success.** "' + pageName + '" is now super gone.'; }, error: function (response) { console.error('Page "' + pageName + '" wasn\'t able to be deleted! Here\'s why: ' + response); }, dataType: 'text' }); }, new: function () { } } }); // initialize the page's content $.ajax({ type: "POST", url: 'server/get-page.php', data: { pageName: pageName }, success: function (response) { vue.pageContent = response; }, error: function (response) { vue.pageContent = '##Hmm. Seems something went wrong!\n A page named "' + pageName + '" wasn\'t found.'; }, dataType: 'text' }); // from http://stackoverflow.com/a/11582513/1063392 function getURLParameter(name) { console.log(location.search); return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [, ""])[1].replace(/\+/g, '%20')) || null }
export const EDIT_PAPER_FETCH = 'EDIT_PAPER_FETCH'; export const EDIT_PAPER_RECEIVE = 'EDIT_PAPER_RECEIVE'; export const EDIT_PAPER_RESET = 'EDIT_PAPER_RESET'; export const EDIT_PAPER_UPDATE = 'EDIT_PAPER_UPDATE'; export const EDIT_PAPER_SAVE = 'EDIT_PAPER_SAVE'; export const EDIT_PAPER_REQUIRE_DRIVE = 'EDIT_PAPER_REQUIRE_DRIVE'; export const EDIT_PAPER_LOGIN = 'EDIT_PAPER_LOGIN'; export const EDIT_PAPER_GOOGLE_DRIVE_HAS_ACCESS = 'EDIT_PAPER_GOOGLE_DRIVE_HAS_ACCESS';
import { intersectOf2Arr } from "./349.intersectOf2Arr"; describe("# Problem 349 - Given two arrays, write a function to compute their intersection.", () => { describe("Solution 1: use hash.", () => { it("return [] if nums is not array", () => { const foo = 42; const bar = "baz"; const wow = undefined; const much = {}; const fn = () => {}; const test = null; const nums2 = [1, 2, 3]; expect(intersectOf2Arr.hash(foo, nums2)).toEqual([]); expect(intersectOf2Arr.hash(bar, nums2)).toEqual([]); expect(intersectOf2Arr.hash(wow, nums2)).toEqual([]); expect(intersectOf2Arr.hash(much, nums2)).toEqual([]); expect(intersectOf2Arr.hash(fn, nums2)).toEqual([]); expect(intersectOf2Arr.hash(test, nums2)).toEqual([]); expect(intersectOf2Arr.hash(nums2, foo)).toEqual([]); expect(intersectOf2Arr.hash(nums2, bar)).toEqual([]); expect(intersectOf2Arr.hash(nums2, wow)).toEqual([]); expect(intersectOf2Arr.hash(nums2, much)).toEqual([]); expect(intersectOf2Arr.hash(nums2, fn)).toEqual([]); expect(intersectOf2Arr.hash(nums2, test)).toEqual([]); }); it("return [] if no desired result: [2, 7, 11, 15] & [3,1,4] => []", () => { const nums = [2, 7, 11, 15]; const nums2 = [3, 1, 4]; const result = intersectOf2Arr.hash(nums, nums2); expect(result).toEqual([]); }); it("return expected result for: [2, 7, 1] & [9, 2, 3, 4] => [2]", () => { const nums = [2, 7, 1]; const nums2 = [9, 2, 3, 4]; const result = intersectOf2Arr.hash(nums, nums2); expect(result).toEqual([2]); }); it("return expected result for: [2, 7, 1, 3, 4, 5] & [9, 2, 3, 4, 5, 1, 9, 8, 7] => [2, 7, 1, 3, 4, 5]", () => { const nums = [2, 7, 1, 3, 4, 5]; const nums2 = [9, 2, 3, 4, 5, 1, 9, 8, 7]; const result = intersectOf2Arr.hash(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 7]); }); it("return expected result for duplicated intersection: [2, 7, 1, 2, 3, 3] & [9, 2, 3, 3, 4] => [2]", () => { const nums = [2, 7, 1, 2, 3, 3]; const nums2 = [9, 2, 3, 3, 4]; const result = intersectOf2Arr.hash(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([2, 3]); }); it("return expected result for more duplicated intersection: [2, 7, 1, 1, 1, 2, 2, 3, 3] & [9, 2, 1, 1, 2, 1, 1, 2, 3, 3, 4] => [1, 2, 3]", () => { const nums = [2, 7, 1, 1, 1, 2, 2, 3, 3]; const nums2 = [9, 2, 1, 1, 2, 1, 1, 2, 3, 3, 4]; const result = intersectOf2Arr.hash(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([1, 2, 3]); }); it("return expected result for: [...] & [...] => [...]", () => { const nums = [ 61, 24, 20, 58, 95, 53, 17, 32, 45, 85, 70, 20, 83, 62, 35, 89, 5, 95, 12, 86, 58, 77, 30, 64, 46, 13, 5, 92, 67, 40, 20, 38, 31, 18, 89, 85, 7, 30, 67, 34, 62, 35, 47, 98, 3, 41, 53, 26, 66, 40, 54, 44, 57, 46, 70, 60, 4, 63, 82, 42, 65, 59, 17, 98, 29, 72, 1, 96, 82, 66, 98, 6, 92, 31, 43, 81, 88, 60, 10, 55, 66, 82, 0, 79, 11, 81, ]; const nums2 = [ 5, 25, 4, 39, 57, 49, 93, 79, 7, 8, 49, 89, 2, 7, 73, 88, 45, 15, 34, 92, 84, 38, 85, 34, 16, 6, 99, 0, 2, 36, 68, 52, 73, 50, 77, 44, 61, 48, ]; const result = intersectOf2Arr.hash(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual( [61, 45, 85, 89, 5, 77, 92, 38, 7, 34, 44, 57, 4, 6, 88, 0, 79].sort((a, b) => a - b), ); }); }); describe("Solution 2: sort the array, then use binary search.", () => { it("return [] if nums is not array", () => { const foo = 42; const bar = "baz"; const wow = undefined; const much = {}; const fn = () => {}; const test = null; const nums2 = [1, 2, 3]; expect(intersectOf2Arr.sortedBSearch(foo, nums2)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(bar, nums2)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(wow, nums2)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(much, nums2)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(fn, nums2)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(test, nums2)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(nums2, foo)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(nums2, bar)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(nums2, wow)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(nums2, much)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(nums2, fn)).toEqual([]); expect(intersectOf2Arr.sortedBSearch(nums2, test)).toEqual([]); }); it("return [] if no desired result: [2, 7, 11, 15] & [3,1,4] => []", () => { const nums = [2, 7, 11, 15]; const nums2 = [3, 1, 4]; const result = intersectOf2Arr.sortedBSearch(nums, nums2); expect(result).toEqual([]); }); it("return expected result for: [2, 7, 1] & [9, 2, 3, 4] => [2]", () => { const nums = [2, 7, 1]; const nums2 = [9, 2, 3, 4]; const result = intersectOf2Arr.sortedBSearch(nums, nums2); expect(result).toEqual([2]); }); it("return expected result for: [2, 7, 1, 3, 4, 5] & [9, 2, 3, 4, 5, 1, 9, 8, 7] => [2, 7, 1, 3, 4, 5]", () => { const nums = [2, 7, 1, 3, 4, 5]; const nums2 = [9, 2, 3, 4, 5, 1, 9, 8, 7]; const result = intersectOf2Arr.sortedBSearch(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 7]); }); it("return expected result for duplicated intersection: [2, 7, 1, 2, 3, 3] & [9, 2, 3, 3, 4] => [2, 3]", () => { const nums = [2, 7, 1, 2, 3, 3]; const nums2 = [9, 2, 3, 3, 4]; const result = intersectOf2Arr.sortedBSearch(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([2, 3]); }); it("return expected result for more duplicated intersection: [2, 7, 1, 1, 1, 2, 2, 3, 3] & [9, 2, 1, 1, 2, 1, 1, 2, 3, 3, 4] => [1, 2, 3]", () => { const nums = [2, 7, 1, 1, 1, 2, 2, 3, 3]; const nums2 = [9, 2, 1, 1, 2, 1, 1, 2, 3, 3, 4]; const result = intersectOf2Arr.sortedBSearch(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([1, 2, 3]); }); it("return expected result for: [...] & [...] => [...]", () => { const nums = [ 61, 24, 20, 58, 95, 53, 17, 32, 45, 85, 70, 20, 83, 62, 35, 89, 5, 95, 12, 86, 58, 77, 30, 64, 46, 13, 5, 92, 67, 40, 20, 38, 31, 18, 89, 85, 7, 30, 67, 34, 62, 35, 47, 98, 3, 41, 53, 26, 66, 40, 54, 44, 57, 46, 70, 60, 4, 63, 82, 42, 65, 59, 17, 98, 29, 72, 1, 96, 82, 66, 98, 6, 92, 31, 43, 81, 88, 60, 10, 55, 66, 82, 0, 79, 11, 81, ]; const nums2 = [ 5, 25, 4, 39, 57, 49, 93, 79, 7, 8, 49, 89, 2, 7, 73, 88, 45, 15, 34, 92, 84, 38, 85, 34, 16, 6, 99, 0, 2, 36, 68, 52, 73, 50, 77, 44, 61, 48, ]; const result = intersectOf2Arr.sortedBSearch(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual( [61, 45, 85, 89, 5, 77, 92, 38, 7, 34, 44, 57, 4, 6, 88, 0, 79].sort((a, b) => a - b), ); }); }); describe("Solution 3: sort the array, then use 2 pointer.", () => { it("return [] if nums is not array", () => { const foo = 42; const bar = "baz"; const wow = undefined; const much = {}; const fn = () => {}; const test = null; const nums2 = [1, 2, 3]; expect(intersectOf2Arr.sorted2Pointer(foo, nums2)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(bar, nums2)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(wow, nums2)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(much, nums2)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(fn, nums2)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(test, nums2)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(nums2, foo)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(nums2, bar)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(nums2, wow)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(nums2, much)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(nums2, fn)).toEqual([]); expect(intersectOf2Arr.sorted2Pointer(nums2, test)).toEqual([]); }); it("return [] if no desired result: [2, 7, 11, 15] & [3,1,4] => []", () => { const nums = [2, 7, 11, 15]; const nums2 = [3, 1, 4]; const result = intersectOf2Arr.sorted2Pointer(nums, nums2); expect(result).toEqual([]); }); it("return expected result for: [2, 7, 1] & [9, 2, 3, 4] => [2]", () => { const nums = [2, 7, 1]; const nums2 = [9, 2, 3, 4]; const result = intersectOf2Arr.sorted2Pointer(nums, nums2); expect(result).toEqual([2]); }); it("return expected result for: [2, 7, 1, 3, 4, 5] & [9, 2, 3, 4, 5, 1, 9, 8, 7] => [2, 7, 1, 3, 4, 5]", () => { const nums = [2, 7, 1, 3, 4, 5]; const nums2 = [9, 2, 3, 4, 5, 1, 9, 8, 7]; const result = intersectOf2Arr.sorted2Pointer(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([1, 2, 3, 4, 5, 7]); }); it("return expected result for duplicated intersection: [2, 7, 1, 2, 3, 3] & [9, 2, 3, 3, 4] => [2, 3]", () => { const nums = [2, 7, 1, 2, 3, 3]; const nums2 = [9, 2, 3, 3, 4]; const result = intersectOf2Arr.sorted2Pointer(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([2, 3]); }); it("return expected result for more duplicated intersection: [2, 7, 1, 1, 1, 2, 2, 3, 3] & [9, 2, 1, 1, 2, 1, 1, 2, 3, 3, 4] => [1, 2, 3]", () => { const nums = [2, 7, 1, 1, 1, 2, 2, 3, 3]; const nums2 = [9, 2, 1, 1, 2, 1, 1, 2, 3, 3, 4]; const result = intersectOf2Arr.sorted2Pointer(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual([1, 2, 3]); }); it("return expected result for: [...] & [...] => [...]", () => { const nums = [ 61, 24, 20, 58, 95, 53, 17, 32, 45, 85, 70, 20, 83, 62, 35, 89, 5, 95, 12, 86, 58, 77, 30, 64, 46, 13, 5, 92, 67, 40, 20, 38, 31, 18, 89, 85, 7, 30, 67, 34, 62, 35, 47, 98, 3, 41, 53, 26, 66, 40, 54, 44, 57, 46, 70, 60, 4, 63, 82, 42, 65, 59, 17, 98, 29, 72, 1, 96, 82, 66, 98, 6, 92, 31, 43, 81, 88, 60, 10, 55, 66, 82, 0, 79, 11, 81, ]; const nums2 = [ 5, 25, 4, 39, 57, 49, 93, 79, 7, 8, 49, 89, 2, 7, 73, 88, 45, 15, 34, 92, 84, 38, 85, 34, 16, 6, 99, 0, 2, 36, 68, 52, 73, 50, 77, 44, 61, 48, ]; const result = intersectOf2Arr.sorted2Pointer(nums, nums2); expect(result.sort((a, b) => a - b)).toEqual( [61, 45, 85, 89, 5, 77, 92, 38, 7, 34, 44, 57, 4, 6, 88, 0, 79].sort((a, b) => a - b), ); }); }); });
"use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; var core_1 = require('@angular/core'); var shoe_data_service_1 = require('../shared/shoe-data.service'); var ShoesComponent = (function () { function ShoesComponent(shoeDataService) { this.shoeDataService = shoeDataService; } ShoesComponent.prototype.ngOnInit = function () { this.shoes = this.shoeDataService.getShoeData(); }; ShoesComponent = __decorate([ core_1.Component({ selector: 'shoes', moduleId: module.id, templateUrl: 'shoes.component.html' }), __metadata('design:paramtypes', [shoe_data_service_1.ShoeDataService]) ], ShoesComponent); return ShoesComponent; }()); exports.ShoesComponent = ShoesComponent; //# sourceMappingURL=shoes.component.js.map
'use strict' const express = require('express') const router = express.Router() const path = require('path') const core = require('../core') const log = require('../libs/log') router.get('/', (req, res) => { res.json({ hello: 'world' }) }) router.get('/signup', (req, res) => { res.sendFile(path.join(__dirname, '..', 'tests', 'html') + '/signup.html') }) router.post('/signup', (req, res) => { log.debug(`${req.method} ${req.url}`) if (!req.body.name) { log.error('no name') return res.status(400) .send('missing name') } if (!req.body.email) { log.error('empty email') return res.status(400) .send('missing email') } if (!req.body.password || !req.body.passwordRepeat) { log.error('empty password') return res.status(400) .send('missing password') } if (req.body.password !== req.body.passwordRepeat) { log.error('password mismatch') return res.status(400) .send('password mismatch') } return core.signup(req.body) .then(user => { res.json(user) }) .catch(error => { res.status(400).send({ status: 400, text: error }) }) }) module.exports = router
'use strict'; var path = require('path'), policy = require('../policies/mago.server.policy'), vodSubtitles = require(path.resolve('./modules/mago/server/controllers/vod_subtitles.server.controller')); module.exports = function(app) { /* ===== vod subtitles===== */ app.route('/api/vodsubtitles') .all(policy.Authenticate) .all(policy.isAllowed) .get(vodSubtitles.list) .post(vodSubtitles.create); app.route('/api/vodsubtitles/:vodSubtitleId') .all(policy.Authenticate) .all(policy.isAllowed) .all(vodSubtitles.dataByID) .get(vodSubtitles.read) .put(vodSubtitles.update) .delete(vodSubtitles.delete); };
export const clock = {"viewBox":"0 0 24 24","children":[{"name":"circle","attribs":{"cx":"12","cy":"12","r":"10"},"children":[]},{"name":"polyline","attribs":{"points":"12 6 12 12 16 14"},"children":[]}],"attribs":{"fill":"none","stroke":"currentColor","stroke-width":"2","stroke-linecap":"round","stroke-linejoin":"round"}};
var data = {main: {}};
var Q = require('q'); // Q.Promise // 用于新建一个 Promise 对象 // 比如,我们新写一个模块,想让这个模块支持 Promise,则可以用 Q.Promise 方法实现 function promiseModule(status) { return Q.Promise(function (resolve, reject) { if (status) { resolve('success'); } else { reject(new Error('error')); } }); } promiseModule(true).then(function (value) { console.log(value); }).catch(function (err) { console.log(err); }); promiseModule(false).then(function (value) { console.log(value); }).catch(function (err) { console.log(err); });
if (!global.hasOwnProperty('db')) { var Sequelize = require('sequelize'); var sq = null; var fs = require('fs'); var path = require('path'); var PGPASS_FILE = path.join(__dirname, '../.pgpass'); if (process.env.DATABASE_URL) { /* Remote database Do `heroku config` for details. We will be parsing a connection string of the form: postgres://bucsqywelrjenr:ffGhjpe9dR13uL7anYjuk3qzXo@\ ec2-54-221-204-17.compute-1.amazonaws.com:5432/d4cftmgjmremg1 */ var pgregex = /postgres:\/\/([^:]+):([^@]+)@([^:]+):(\d+)\/(.+)/; var match = process.env.DATABASE_URL.match(pgregex); var user = match[1]; var password = match[2]; var host = match[3]; var port = match[4]; var dbname = match[5]; var config = { dialect: 'postgres', protocol: 'postgres', port: port, host: host, logging: true //false }; sq = new Sequelize(dbname, user, password, config); } else { /* Local database We parse the .pgpass file for the connection string parameters. */ var pgtokens = fs.readFileSync(PGPASS_FILE).toString().trimRight().split(':'); var host = pgtokens[0]; var port = pgtokens[1]; var dbname = pgtokens[2]; var user = pgtokens[3]; var password = pgtokens[4]; var config = { dialect: 'postgres', protocol: 'postgres', port: port, host: host, }; var sq = new Sequelize(dbname, user, password, config); } global.db = { Sequelize: Sequelize, sequelize: sq, Order: sq.import(__dirname + '/order') }; } module.exports = global.db;
import httpMocks from 'node-mocks-http' import HomeController from '../../src/controllers/home' describe('HomeController', () => { describe('#HomeController()', () => { it('should create a HomeController', () => { const homeController = HomeController() expect(homeController).toBeInstanceOf(Object) }) }) describe('#index()', () => { it('should respond 200 with user data', async () => { const req = httpMocks.createRequest({ method: 'GET', url: '/' }) const res = httpMocks.createResponse() const homeController = HomeController() await homeController.index(req, res) expect(res._getStatusCode()).toBe(200) expect(res._isJSON()).toBe(true) }) }) })
/** * Session Configuration * (sails.config.session) * * Sails session integration leans heavily on the great work already done by * Express, but also unifies Socket.io with the Connect session store. It uses * Connect's cookie parser to normalize configuration differences between Express * and Socket.io and hooks into Sails' middleware interpreter to allow you to access * and auto-save to `req.session` with Socket.io the same way you would with Express. * * For more information on configuring the session, check out: * http://sailsjs.org/#/documentation/reference/sails.config/sails.config.session.html */ module.exports.session = { /*************************************************************************** * * * Session secret is automatically generated when your new app is created * * Replace at your own risk in production-- you will invalidate the cookies * * of your users, forcing them to log in again. * * * ***************************************************************************/ secret: '43ad01e3d6534488fa2df600b769bd90', /*************************************************************************** * * * Set the session cookie expire time The maxAge is set by milliseconds, * * the example below is for 24 hours * * * ***************************************************************************/ // cookie: { // maxAge: 24 * 60 * 60 * 1000 // }, /*************************************************************************** * * * In production, uncomment the following lines to set up a shared redis * * session store that can be shared across multiple Sails.js servers * ***************************************************************************/ // adapter: 'redis', /*************************************************************************** * * * The following values are optional, if no options are set a redis * * instance running on localhost is expected. Read more about options at: * * https://github.com/visionmedia/connect-redis * * * * * ***************************************************************************/ // host: 'localhost', // port: 6379, // ttl: <redis session TTL in seconds>, // db: 0, // pass: <redis auth password>, // prefix: 'sess:', /*************************************************************************** * * * Uncomment the following lines to use your Mongo adapter as a session * * store * * * ***************************************************************************/ // adapter: 'mongo', // host: 'localhost', // port: 27017, // db: 'sails', // collection: 'sessions', /*************************************************************************** * * * Optional Values: * * * * # Note: url will override other connection settings url: * * 'mongodb://user:pass@host:port/database/collection', * * * ***************************************************************************/ // username: '', // password: '', // auto_reconnect: false, // ssl: false, // stringify: true };
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class AndroidStarOutline extends React.Component { render() { if(this.props.bare) { return <g> <path d="M458,210.409l-145.267-12.476L256,64l-56.743,133.934L54,210.409l110.192,95.524L131.161,448L256,372.686L380.83,448 l-33.021-142.066L458,210.409z M272.531,345.286L256,335.312l-16.53,9.973l-59.988,36.191l15.879-68.296l4.369-18.79l-14.577-12.637 l-52.994-45.939l69.836-5.998l19.206-1.65l7.521-17.75l27.276-64.381l27.27,64.379l7.52,17.751l19.208,1.65l69.846,5.998 l-52.993,45.939l-14.576,12.636l4.367,18.788l15.875,68.299L272.531,345.286z"></path> </g>; } return <IconBase> <path d="M458,210.409l-145.267-12.476L256,64l-56.743,133.934L54,210.409l110.192,95.524L131.161,448L256,372.686L380.83,448 l-33.021-142.066L458,210.409z M272.531,345.286L256,335.312l-16.53,9.973l-59.988,36.191l15.879-68.296l4.369-18.79l-14.577-12.637 l-52.994-45.939l69.836-5.998l19.206-1.65l7.521-17.75l27.276-64.381l27.27,64.379l7.52,17.751l19.208,1.65l69.846,5.998 l-52.993,45.939l-14.576,12.636l4.367,18.788l15.875,68.299L272.531,345.286z"></path> </IconBase>; } };AndroidStarOutline.defaultProps = {bare: false}
const authMiddleware = require('./authenticat'); module.exports = { authMiddleware };
import {Meteor} from 'meteor/meteor'; import {SimpleSchema} from 'meteor/aldeed:simple-schema'; // Helper for denying client code export const denyAll = { insert() { return true; }, update() { return true; }, remove() { return true; } }; // Field common to all collections export const defaultSchema = { ownerId: { type: String, regEx: SimpleSchema.RegEx.Id, autoValue: function () { if (this.isInsert && !this.isSet) { return Meteor.userId(); } }, denyUpdate: true }, createdAt: { type: Date, autoValue: function () { if (this.isInsert && !this.isSet) { return new Date(); } }, denyUpdate: true }, updatedAt: { type: Date, autoValue: function () { if (this.isUpdate) { return new Date(); } }, optional: true, denyInsert: true } }; // Default schema for denormalized "count" fields export const countSchema = { type: Number, min: 0, defaultValue: 0 };
/* * Searchbar Messages * * This contains all the text for the Searchbar component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.components.Searchbar.header', defaultMessage: 'This is the Searchbar component !', }, });
MediaPlayer.dependencies.Notifier = function () { "use strict"; var system, id = 0, getId = function() { if (!this.id) { id += 1; this.id = "_id_" + id; } return this.id; }, isEventSupported = function(eventName) { var event, events = this.eventList; for (event in events) { if (events[event] === eventName) return true; } return false; }; return { system : undefined, setup: function() { system = this.system; system.mapValue('notify', this.notify); system.mapValue('subscribe', this.subscribe); system.mapValue('unsubscribe', this.unsubscribe); }, notify: function (/*eventName[, args]*/) { var args = [].slice.call(arguments); args.splice(1, 0, this); args[0] += getId.call(this); system.notify.apply(system, args); }, subscribe: function(eventName, observer, handler, oneShot) { if (!handler && observer[eventName]) { handler = observer[eventName] = observer[eventName].bind(observer); } if(!isEventSupported.call(this, eventName)) throw ("object does not support given event " + eventName); if(!observer) throw "observer object cannot be null or undefined"; if(!handler) throw "event handler cannot be null or undefined"; eventName += getId.call(this); system.mapHandler(eventName, undefined, handler, oneShot); }, unsubscribe: function(eventName, observer, handler) { handler = handler || observer[eventName]; eventName += getId.call(this); system.unmapHandler(eventName, undefined, handler); } }; }; MediaPlayer.dependencies.Notifier.prototype = { constructor: MediaPlayer.dependencies.Notifier };
function Thermostat() { this.temperature = 20; this.powerSavingMode = true; } Thermostat.prototype.increaseTemperature = function() { if(this.temperature < this.maximumTemperature()) this.temperature += 1; } Thermostat.prototype.decreaseTemperature = function() { if(this.temperature > 10) this.temperature -= 1; } Thermostat.prototype.maximumTemperature = function() { return (this.powerSavingMode) ? 25 : 32; } Thermostat.prototype.reset = function() { this.temperature = 20; } Thermostat.prototype.energyUsage = function() { if(this.temperature < 18) return 'efficient'; if(this.temperature < 25) return 'average'; return 'inefficient' }
'use strict'; var React = require('react'); var mui = require('material-ui'); var SvgIcon = mui.SvgIcon; var createClass = require('create-react-class'); var DeviceBluetoothConnected = createClass({ displayName: 'DeviceBluetoothConnected', render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M7 12l-2-2-2 2 2 2 2-2zm10.71-4.29L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88zM19 10l-2 2 2 2 2-2-2-2z' }) ); } }); module.exports = DeviceBluetoothConnected;
define('summernote/module/Dialog', function () { /** * Dialog * * @class */ var Dialog = function () { /** * toggle button status * * @param {jQuery} $btn * @param {Boolean} bEnable */ var toggleBtn = function ($btn, bEnable) { $btn.toggleClass('disabled', !bEnable); $btn.attr('disabled', !bEnable); }; /** * show image dialog * * @param {jQuery} $editable * @param {jQuery} $dialog * @return {Promise} */ this.showImageDialog = function ($editable, $dialog) { return $.Deferred(function (deferred) { var $imageDialog = $dialog.find('.note-image-dialog'); var $imageInput = $dialog.find('.note-image-input'), $imageUrl = $dialog.find('.note-image-url'), $imageBtn = $dialog.find('.note-image-btn'); $imageDialog.one('shown.bs.modal', function () { // Cloning imageInput to clear element. $imageInput.replaceWith($imageInput.clone() .on('change', function () { deferred.resolve(this.files); $imageDialog.modal('hide'); }) ); $imageBtn.click(function (event) { event.preventDefault(); deferred.resolve($imageUrl.val()); $imageDialog.modal('hide'); }); $imageUrl.keyup(function () { toggleBtn($imageBtn, $imageUrl.val()); }).val('').trigger('focus'); }).one('hidden.bs.modal', function () { $imageInput.off('change'); $imageUrl.off('keyup'); $imageBtn.off('click'); if (deferred.state() === 'pending') { deferred.reject(); } }).modal('show'); }); }; /** * Show video dialog and set event handlers on dialog controls. * * @param {jQuery} $dialog * @param {Object} videoInfo * @return {Promise} */ this.showVideoDialog = function ($editable, $dialog, videoInfo) { return $.Deferred(function (deferred) { var $videoDialog = $dialog.find('.note-video-dialog'); var $videoUrl = $videoDialog.find('.note-video-url'), $videoBtn = $videoDialog.find('.note-video-btn'); $videoDialog.one('shown.bs.modal', function () { $videoUrl.val(videoInfo.text).keyup(function () { toggleBtn($videoBtn, $videoUrl.val()); }).trigger('keyup').trigger('focus'); $videoBtn.click(function (event) { event.preventDefault(); deferred.resolve($videoUrl.val()); $videoDialog.modal('hide'); }); }).one('hidden.bs.modal', function () { $videoUrl.off('keyup'); $videoBtn.off('click'); if (deferred.state() === 'pending') { deferred.reject(); } }).modal('show'); }); }; /** * Show link dialog and set event handlers on dialog controls. * * @param {jQuery} $dialog * @param {Object} linkInfo * @return {Promise} */ this.showLinkDialog = function ($editable, $dialog, linkInfo) { return $.Deferred(function (deferred) { var $linkDialog = $dialog.find('.note-link-dialog'); var $linkText = $linkDialog.find('.note-link-text'), $linkUrl = $linkDialog.find('.note-link-url'), $linkBtn = $linkDialog.find('.note-link-btn'), $openInNewWindow = $linkDialog.find('input[type=checkbox]'); $linkDialog.one('shown.bs.modal', function () { $linkText.val(linkInfo.text); $linkText.keyup(function () { // if linktext was modified by keyup, // stop cloning text from linkUrl linkInfo.text = $linkText.val(); }); // if no url was given, copy text to url if (!linkInfo.url) { linkInfo.url = linkInfo.text; toggleBtn($linkBtn, linkInfo.text); } $linkUrl.keyup(function () { toggleBtn($linkBtn, $linkUrl.val()); // display same link on `Text to display` input // when create a new link if (!linkInfo.text) { $linkText.val($linkUrl.val()); } }).val(linkInfo.url).trigger('focus').trigger('select'); $openInNewWindow.prop('checked', linkInfo.newWindow); $linkBtn.one('click', function (event) { event.preventDefault(); deferred.resolve($linkText.val(), $linkUrl.val(), $openInNewWindow.is(':checked')); $linkDialog.modal('hide'); }); }).one('hidden.bs.modal', function () { $linkUrl.off('keyup'); if (deferred.state() === 'pending') { deferred.reject(); } }).modal('show'); }).promise(); }; /** * show help dialog * * @param {jQuery} $dialog */ this.showHelpDialog = function ($editable, $dialog) { return $.Deferred(function (deferred) { var $helpDialog = $dialog.find('.note-help-dialog'); $helpDialog.one('hidden.bs.modal', function () { deferred.resolve(); }).modal('show'); }).promise(); }; }; return Dialog; });
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require turbolinks //= require_tree . //= require nprogress //= require nprogress-turbolinks
Ext.define('Ext.ux.DataView.DragSelector', { requires: ['Ext.dd.DragTracker', 'Ext.util.Region'], /** * Initializes the plugin by setting up the drag tracker */ init: function(dataview) { /** * @property dataview * @type Ext.view.View * The DataView bound to this instance */ this.dataview = dataview; dataview.mon(dataview, { beforecontainerclick: this.cancelClick, scope: this, render: { fn: this.onRender, scope: this, single: true } }); }, /** * @private * Called when the attached DataView is rendered. This sets up the DragTracker instance that will be used * to created a dragged selection area */ onRender: function() { /** * @property tracker * @type Ext.dd.DragTracker * The DragTracker attached to this instance. Note that the 4 on* functions are called in the scope of the * DragTracker ('this' refers to the DragTracker inside those functions), so we pass a reference to the * DragSelector so that we can call this class's functions. */ this.tracker = Ext.create('Ext.dd.DragTracker', { dataview: this.dataview, el: this.dataview.el, dragSelector: this, onBeforeStart: this.onBeforeStart, onStart: this.onStart, onDrag : this.onDrag, onEnd : this.onEnd }); /** * @property dragRegion * @type Ext.util.Region * Represents the region currently dragged out by the user. This is used to figure out which dataview nodes are * in the selected area and to set the size of the Proxy element used to highlight the current drag area */ this.dragRegion = Ext.create('Ext.util.Region'); }, /** * @private * Listener attached to the DragTracker's onBeforeStart event. Returns false if the drag didn't start within the * DataView's el */ onBeforeStart: function(e) { return e.target == this.dataview.getEl().dom; }, /** * @private * Listener attached to the DragTracker's onStart event. Cancel's the DataView's containerclick event from firing * and sets the start co-ordinates of the Proxy element. Clears any existing DataView selection * @param {Ext.EventObject} e The click event */ onStart: function(e) { var dragSelector = this.dragSelector, dataview = this.dataview; // Flag which controls whether the cancelClick method vetoes the processing of the DataView's containerclick event. // On IE (where else), this needs to remain set for a millisecond after mouseup because even though the mouse has // moved, the mouseup will still trigger a click event. this.dragging = true; //here we reset and show the selection proxy element and cache the regions each item in the dataview take up dragSelector.fillRegions(); dragSelector.getProxy().show(); dataview.getSelectionModel().deselectAll(); }, /** * @private * Reusable handler that's used to cancel the container click event when dragging on the dataview. See onStart for * details */ cancelClick: function() { return !this.tracker.dragging; }, /** * @private * Listener attached to the DragTracker's onDrag event. Figures out how large the drag selection area should be and * updates the proxy element's size to match. Then iterates over all of the rendered items and marks them selected * if the drag region touches them * @param {Ext.EventObject} e The drag event */ onDrag: function(e) { var dragSelector = this.dragSelector, selModel = dragSelector.dataview.getSelectionModel(), dragRegion = dragSelector.dragRegion, bodyRegion = dragSelector.bodyRegion, proxy = dragSelector.getProxy(), regions = dragSelector.regions, length = regions.length, startXY = this.startXY, currentXY = this.getXY(), minX = Math.min(startXY[0], currentXY[0]), minY = Math.min(startXY[1], currentXY[1]), width = Math.abs(startXY[0] - currentXY[0]), height = Math.abs(startXY[1] - currentXY[1]), region, selected, i; Ext.apply(dragRegion, { top: minY, left: minX, right: minX + width, bottom: minY + height }); dragRegion.constrainTo(bodyRegion); proxy.setRegion(dragRegion); for (i = 0; i < length; i++) { region = regions[i]; selected = dragRegion.intersect(region); if (selected) { selModel.select(i, true); } else { selModel.deselect(i); } } }, /** * @private * Listener attached to the DragTracker's onEnd event. This is a delayed function which executes 1 * millisecond after it has been called. This is because the dragging flag must remain active to cancel * the containerclick event which the mouseup event will trigger. * @param {Ext.EventObject} e The event object */ onEnd: Ext.Function.createDelayed(function(e) { var dataview = this.dataview, selModel = dataview.getSelectionModel(), dragSelector = this.dragSelector; this.dragging = false; dragSelector.getProxy().hide(); }, 1), /** * @private * Creates a Proxy element that will be used to highlight the drag selection region * @return {Ext.Element} The Proxy element */ getProxy: function() { if (!this.proxy) { this.proxy = this.dataview.getEl().createChild({ tag: 'div', cls: 'x-view-selector' }); } return this.proxy; }, /** * @private * Gets the region taken up by each rendered node in the DataView. We use these regions to figure out which nodes * to select based on the selector region the user has dragged out */ fillRegions: function() { var dataview = this.dataview, regions = this.regions = []; dataview.all.each(function(node) { regions.push(node.getRegion()); }); this.bodyRegion = dataview.getEl().getRegion(); } });
var fire = require('./ship_methods.js').fire; function checkGameStatus (players) { return false; } function takeTurn (opposingPlayer, guessFunction) { var coordinates = guessFunction(); fire(opposingPlayer, coordinates); var gameOver = checkGameStatus(); return gameOver; } module.exports.checkGameStatus = checkGameStatus; module.exports.takeTurn = takeTurn;
var util = require('util'); var Route = require('../routing/Route'); var errors = require('../errors'); var Result = require('../result/Result'); var List = require('../result/List'); var MountPoint = require('../routing/MountPoint'); function TransactionList (persistence) { Route.call(this); this._persistence = persistence; } util.inherits(TransactionList, Route); TransactionList.prototype.mountPoint = function () { return new MountPoint('get', '/user/:userId/transaction', ['UserId.get']); }; TransactionList.prototype.route = function (req, res, next) { var that = this; var orderStatement = req.strichliste.orderStatement; var limitStatement = req.strichliste.limitStatement; that._persistence.loadTransactionsByUserId(req.params.userId, limitStatement, orderStatement, function (error, transactions) { if (error) return next(new errors.InternalServerError(error.message)); if (!limitStatement) return end(transactions, transactions.length); that._persistence.loadTransactionsByUserId(req.params.userId, null, null, function (error, transactionsOverall) { if (error) return next(new errors.InternalServerError(error.message)); end(transactions, transactionsOverall.length); }); }); function end (list, overallNumber) { req.strichliste.result = new Result(new List(list, overallNumber, limitStatement), Result.CONTENT_TYPE_JSON); next(); } }; TransactionList.routeName = 'UserIdTransaction.get'; module.exports = TransactionList;
/************************************************************************************************ * * HTTP - Handle IO requests * * Description: This is used to handle all I/O requests from the client to our API * layer. Promises are used. * * (c) Sony Computer Entertainment Europe, 2017 * * Author: james.s.young@sony.com * ************************************************************************************************/ import axios from 'axios'; class HTTP { constructor() { console.log('HTTP.'); this._baseUrl = window.location.protocol + '//' + window.location.hostname + (location.port ? ':' + location.port : '/'); console.log( 'Base url is: ' + this._baseUrl ); } /** * Get */ get(url) { url = this._baseUrl + '/io?url=' + url; return new Promise((resolve, reject) => { axios.get(url, { }).then(res => { resolve(res); }).catch(err => { alert( 'http.' + err ); reject(err); return; }); }); } /** * Put */ put(url, putObject) { url = this._baseUrl + '/io?url=' + url; return new Promise((resolve, reject) => { // Note: Add auth header. axios.put(url, putObject) .then(res => { resolve(true); }).catch(err => { reject(err); }); }); } /** * POST */ post(url, postObject) { url = this._baseUrl + '/io?url=' + url; return new Promise((resolve, reject) => { // Note: Add auth header. axios.post(config.API_SERVICES_URL + '/partners/', partner) .then(res => { resolve(res.data.guid); }).catch(err => { reject(err); }); }); } delete(url) { url = this._baseUrl + '/io?url=' + url; return new Promise((resolve, reject) => { axios.delete( url, { }).then(res => { resolve(res.data) }).catch(err => { reject(err); } ) }); } } // end class export default HTTP;
'use babel'; // Java script preparation functions import os from 'os'; import path from 'path'; export default { // Public: Get atom temp file directory // // Returns {String} containing atom temp file directory tempFilesDir: path.join(os.tmpdir()), // Public: Get class name of file in context // // * `filePath` {String} containing file path // // Returns {String} containing class name of file getClassName(context) { return context.filename.replace(/\.java$/, ''); }, // Public: Get project path of context // // * `context` {Object} containing current context // // Returns {String} containing the matching project path getProjectPath(context) { const projectPaths = atom.project.getPaths(); return projectPaths.find(projectPath => context.filepath.includes(projectPath)); }, // Public: Get package of file in context // // * `context` {Object} containing current context // // Returns {String} containing class of contextual file getClassPackage(context) { const projectPath = module.exports.getProjectPath(context); const projectRemoved = (context.filepath.replace(`${projectPath}/`, '')); const filenameRemoved = projectRemoved.replace(`/${context.filename}`, ''); // File is in root of src directory - no package if (filenameRemoved === projectRemoved) { return ''; } return `${filenameRemoved}.`; }, };
class ModuleA { foo() { return 'foo'; } bar(x, y) { return 'x + y = ' + (x + y); } } export default ModuleA;
import { connect } from 'react-redux'; import { withRouter } from 'react-router'; import { load_search_results, prev_page, next_page, set_order_by } from './module.js'; import component from './component.js'; import './style.scss'; const map_dispatch_to_props = { load_search_results, prev_page, next_page, set_order_by, }; const map_state_to_props = state => ({ results: state.search.results, total: state.search.total, }); export default connect( map_state_to_props, map_dispatch_to_props )(withRouter(component));
require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ 'use strict'; var React = require('react'); var classes = require('classnames'); var Option = React.createClass({ displayName: 'Option', propTypes: { addLabelText: React.PropTypes.string, // string rendered in case of allowCreate option passed to ReactSelect className: React.PropTypes.string, // className (based on mouse position) mouseDown: React.PropTypes.func, // method to handle click on option element mouseEnter: React.PropTypes.func, // method to handle mouseEnter on option element mouseLeave: React.PropTypes.func, // method to handle mouseLeave on option element option: React.PropTypes.object.isRequired, // object that is base for that option renderFunc: React.PropTypes.func // method passed to ReactSelect component to render label text }, blockEvent: function blockEvent(event) { event.preventDefault(); if (event.target.tagName !== 'A' || !('href' in event.target)) { return; } if (event.target.target) { window.open(event.target.href); } else { window.location.href = event.target.href; } }, render: function render() { var obj = this.props.option; var renderedLabel = this.props.renderFunc(obj); var optionClasses = classes(this.props.className, obj.className); return obj.disabled ? React.createElement( 'div', { className: optionClasses, onMouseDown: this.blockEvent, onClick: this.blockEvent }, renderedLabel ) : React.createElement( 'div', { className: optionClasses, style: obj.style, onMouseEnter: this.props.mouseEnter, onMouseLeave: this.props.mouseLeave, onMouseDown: this.props.mouseDown, onClick: this.props.mouseDown, title: obj.title }, obj.create ? this.props.addLabelText.replace('{label}', obj.label) : renderedLabel ); } }); module.exports = Option; },{"classnames":undefined,"react":undefined}],2:[function(require,module,exports){ 'use strict'; var React = require('react'); var classes = require('classnames'); var SingleValue = React.createClass({ displayName: 'SingleValue', propTypes: { placeholder: React.PropTypes.string, // this is default value provided by React-Select based component value: React.PropTypes.object // selected option }, render: function render() { var classNames = classes('Select-placeholder', this.props.value && this.props.value.className); return React.createElement( 'div', { className: classNames, style: this.props.value && this.props.value.style, title: this.props.value && this.props.value.title }, this.props.placeholder ); } }); module.exports = SingleValue; },{"classnames":undefined,"react":undefined}],3:[function(require,module,exports){ 'use strict'; var React = require('react'); var classes = require('classnames'); var Value = React.createClass({ displayName: 'Value', propTypes: { disabled: React.PropTypes.bool, // disabled prop passed to ReactSelect onOptionLabelClick: React.PropTypes.func, // method to handle click on value label onRemove: React.PropTypes.func, // method to handle remove of that value option: React.PropTypes.object.isRequired, // option passed to component optionLabelClick: React.PropTypes.bool, // indicates if onOptionLabelClick should be handled renderer: React.PropTypes.func // method to render option label passed to ReactSelect }, blockEvent: function blockEvent(event) { event.stopPropagation(); }, handleOnRemove: function handleOnRemove(event) { if (!this.props.disabled) { this.props.onRemove(event); } }, render: function render() { var label = this.props.option.label; if (this.props.renderer) { label = this.props.renderer(this.props.option); } if (!this.props.onRemove && !this.props.optionLabelClick) { return React.createElement( 'div', { className: classes('Select-value', this.props.option.className), style: this.props.option.style, title: this.props.option.title }, label ); } if (this.props.optionLabelClick) { label = React.createElement( 'a', { className: classes('Select-item-label__a', this.props.option.className), onMouseDown: this.blockEvent, onTouchEnd: this.props.onOptionLabelClick, onClick: this.props.onOptionLabelClick, style: this.props.option.style, title: this.props.option.title }, label ); } return React.createElement( 'div', { className: classes('Select-item', this.props.option.className), style: this.props.option.style, title: this.props.option.title }, React.createElement( 'span', { className: 'Select-item-icon', onMouseDown: this.blockEvent, onClick: this.handleOnRemove, onTouchEnd: this.handleOnRemove }, '×' ), React.createElement( 'span', { className: 'Select-item-label' }, label ) ); } }); module.exports = Value; },{"classnames":undefined,"react":undefined}],"react-select":[function(require,module,exports){ /* disable some rules until we refactor more completely; fixing them now would cause conflicts with some open PRs unnecessarily. */ /* eslint react/jsx-sort-prop-types: 0, react/sort-comp: 0, react/prop-types: 0 */ 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = require('react'); var Input = require('react-input-autosize'); var classes = require('classnames'); var Value = require('./Value'); var SingleValue = require('./SingleValue'); var Option = require('./Option'); var requestId = 0; var Select = React.createClass({ displayName: 'Select', propTypes: { addLabelText: React.PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input allowCreate: React.PropTypes.bool, // whether to allow creation of new entries asyncOptions: React.PropTypes.func, // function to call to get options autoload: React.PropTypes.bool, // whether to auto-load the default async options set backspaceRemoves: React.PropTypes.bool, // whether backspace removes an item if there is no text input cacheAsyncResults: React.PropTypes.bool, // whether to allow cache className: React.PropTypes.string, // className for the outer element clearAllText: React.PropTypes.string, // title for the "clear" control when multi: true clearValueText: React.PropTypes.string, // title for the "clear" control clearable: React.PropTypes.bool, // should it be possible to reset value delimiter: React.PropTypes.string, // delimiter to use to join multiple values disabled: React.PropTypes.bool, // whether the Select is disabled or not filterOption: React.PropTypes.func, // method to filter a single option: function(option, filterString) filterOptions: React.PropTypes.func, // method to filter the options array: function([options], filterString, [values]) ignoreCase: React.PropTypes.bool, // whether to perform case-insensitive filtering inputProps: React.PropTypes.object, // custom attributes for the Input (in the Select-control) e.g: {'data-foo': 'bar'} matchPos: React.PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: React.PropTypes.string, // (any|label|value) which option property to filter on multi: React.PropTypes.bool, // multi-value input commaSplit: React.PropTypes.bool, // Split multi tags when comma is pressed name: React.PropTypes.string, // field name, for hidden <input /> tag newOptionCreator: React.PropTypes.func, // factory to create new options when allowCreate set noResultsText: React.PropTypes.string, // placeholder displayed when there are no matching search results onBlur: React.PropTypes.func, // onBlur handler: function(event) {} onChange: React.PropTypes.func, // onChange handler: function(newValue) {} onFocus: React.PropTypes.func, // onFocus handler: function(event) {} onInputChange: React.PropTypes.func, // onInputChange handler: function(inputValue) {} onOptionLabelClick: React.PropTypes.func, // onCLick handler for value labels: function (value, event) {} optionComponent: React.PropTypes.func, // option component to render in dropdown optionRenderer: React.PropTypes.func, // optionRenderer: function(option) {} options: React.PropTypes.array, // array of options placeholder: React.PropTypes.string, // field placeholder, displayed when there's no value searchable: React.PropTypes.bool, // whether to enable searching feature or not searchingText: React.PropTypes.string, // message to display whilst options are loading via asyncOptions searchPromptText: React.PropTypes.string, // label to prompt for search input singleValueComponent: React.PropTypes.func, // single value component when multiple is set to false value: React.PropTypes.any, // initial field value valueComponent: React.PropTypes.func, // value component to render in multiple mode valueRenderer: React.PropTypes.func // valueRenderer: function(option) {} }, getDefaultProps: function getDefaultProps() { return { addLabelText: 'Add "{label}"?', allowCreate: false, asyncOptions: undefined, autoload: true, backspaceRemoves: true, cacheAsyncResults: true, className: undefined, clearAllText: 'Clear all', clearValueText: 'Clear value', clearable: true, delimiter: ',', disabled: false, ignoreCase: true, inputProps: {}, matchPos: 'any', matchProp: 'any', name: undefined, newOptionCreator: undefined, noResultsText: 'No results found', onChange: undefined, onInputChange: undefined, onOptionLabelClick: undefined, optionComponent: Option, options: undefined, placeholder: 'Select...', searchable: true, commaSplit: true, searchingText: 'Searching...', searchPromptText: 'Type to search', singleValueComponent: SingleValue, value: undefined, valueComponent: Value }; }, getInitialState: function getInitialState() { return { /* * set by getStateFromValue on componentWillMount: * - value * - values * - filteredOptions * - inputValue * - placeholder * - focusedOption */ isFocused: false, isLoading: false, isOpen: false, options: this.props.options }; }, componentWillMount: function componentWillMount() { var _this = this; this._optionsCache = {}; this._optionsFilterString = ''; this._closeMenuIfClickedOutside = function (event) { if (!_this.state.isOpen) { return; } var menuElem = React.findDOMNode(_this.refs.selectMenuContainer); var controlElem = React.findDOMNode(_this.refs.control); var eventOccuredOutsideMenu = _this.clickedOutsideElement(menuElem, event); var eventOccuredOutsideControl = _this.clickedOutsideElement(controlElem, event); // Hide dropdown menu if click occurred outside of menu if (eventOccuredOutsideMenu && eventOccuredOutsideControl) { _this.setState({ isOpen: false }, _this._unbindCloseMenuIfClickedOutside); } }; this._bindCloseMenuIfClickedOutside = function () { if (!document.addEventListener && document.attachEvent) { document.attachEvent('onclick', this._closeMenuIfClickedOutside); } else { document.addEventListener('click', this._closeMenuIfClickedOutside); } }; this._unbindCloseMenuIfClickedOutside = function () { if (!document.removeEventListener && document.detachEvent) { document.detachEvent('onclick', this._closeMenuIfClickedOutside); } else { document.removeEventListener('click', this._closeMenuIfClickedOutside); } }; this.setState(this.getStateFromValue(this.props.value)); }, componentDidMount: function componentDidMount() { if (this.props.asyncOptions && this.props.autoload) { this.autoloadAsyncOptions(); } }, componentWillUnmount: function componentWillUnmount() { clearTimeout(this._blurTimeout); clearTimeout(this._focusTimeout); if (this.state.isOpen) { this._unbindCloseMenuIfClickedOutside(); } }, componentWillReceiveProps: function componentWillReceiveProps(newProps) { var _this2 = this; var optionsChanged = false; if (JSON.stringify(newProps.options) !== JSON.stringify(this.props.options)) { optionsChanged = true; this.setState({ options: newProps.options, filteredOptions: this.filterOptions(newProps.options) }); } if (newProps.value !== this.state.value || newProps.placeholder !== this.props.placeholder || optionsChanged) { var setState = function setState(newState) { _this2.setState(_this2.getStateFromValue(newProps.value, newState && newState.options || newProps.options, newProps.placeholder)); }; if (this.props.asyncOptions) { this.loadAsyncOptions(newProps.value, {}, setState); } else { setState(); } } }, componentDidUpdate: function componentDidUpdate() { var _this3 = this; if (!this.props.disabled && this._focusAfterUpdate) { clearTimeout(this._blurTimeout); this._focusTimeout = setTimeout(function () { _this3.getInputNode().focus(); _this3._focusAfterUpdate = false; }, 50); } if (this._focusedOptionReveal) { if (this.refs.focused && this.refs.menu) { var focusedDOM = React.findDOMNode(this.refs.focused); var menuDOM = React.findDOMNode(this.refs.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) { menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight; } } this._focusedOptionReveal = false; } }, focus: function focus() { this.getInputNode().focus(); }, clickedOutsideElement: function clickedOutsideElement(element, event) { var eventTarget = event.target ? event.target : event.srcElement; while (eventTarget != null) { if (eventTarget === element) return false; eventTarget = eventTarget.offsetParent; } return true; }, getStateFromValue: function getStateFromValue(value, options, placeholder) { if (!options) { options = this.state.options; } if (!placeholder) { placeholder = this.props.placeholder; } // reset internal filter string this._optionsFilterString = ''; var values = this.initValuesArray(value, options); var filteredOptions = this.filterOptions(options, values); var focusedOption; var valueForState = null; if (!this.props.multi && values.length) { focusedOption = values[0]; valueForState = values[0].value; } else { focusedOption = this.getFirstFocusableOption(filteredOptions); valueForState = values.map(function (v) { return v.value; }).join(this.props.delimiter); } return { value: valueForState, values: values, inputValue: '', filteredOptions: filteredOptions, placeholder: !this.props.multi && values.length ? values[0].label : placeholder, focusedOption: focusedOption }; }, getFirstFocusableOption: function getFirstFocusableOption(options) { for (var optionIndex = 0; optionIndex < options.length; ++optionIndex) { if (!options[optionIndex].disabled) { return options[optionIndex]; } } }, initValuesArray: function initValuesArray(values, options) { if (!Array.isArray(values)) { if (typeof values === 'string') { values = values === '' ? [] : this.props.multi ? values.split(this.props.delimiter) : [values]; } else { values = values !== undefined && values !== null ? [values] : []; } } return values.map(function (val) { if (typeof val === 'string' || typeof val === 'number') { for (var key in options) { if (options.hasOwnProperty(key) && options[key] && (options[key].value === val || typeof options[key].value === 'number' && options[key].value.toString() === val)) { return options[key]; } } return { value: val, label: val }; } else { return val; } }); }, setValue: function setValue(value, focusAfterUpdate) { if (focusAfterUpdate || focusAfterUpdate === undefined) { this._focusAfterUpdate = true; } var newState = this.getStateFromValue(value); newState.isOpen = false; this.fireChangeEvent(newState); this.setState(newState); }, selectValue: function selectValue(value) { if (!this.props.multi) { this.setValue(value); } else if (value) { this.addValue(value); } this._unbindCloseMenuIfClickedOutside(); }, addValue: function addValue(value) { this.setValue(this.state.values.concat(value)); }, popValue: function popValue() { this.setValue(this.state.values.slice(0, this.state.values.length - 1)); }, removeValue: function removeValue(valueToRemove) { this.setValue(this.state.values.filter(function (value) { return value !== valueToRemove; })); }, clearValue: function clearValue(event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this.setValue(null); }, resetValue: function resetValue() { this.setValue(this.state.value === '' ? null : this.state.value); }, getInputNode: function getInputNode() { var input = this.refs.input; return this.props.searchable ? input : React.findDOMNode(input); }, fireChangeEvent: function fireChangeEvent(newState) { if (newState.value !== this.state.value && this.props.onChange) { this.props.onChange(newState.value, newState.values); } }, handleMouseDown: function handleMouseDown(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); // for the non-searchable select, close the dropdown when button is clicked if (this.state.isOpen && !this.props.searchable) { this.setState({ isOpen: false }, this._unbindCloseMenuIfClickedOutside); return; } if (this.state.isFocused) { this.setState({ isOpen: true }, this._bindCloseMenuIfClickedOutside); } else { this._openAfterFocus = true; this.getInputNode().focus(); } }, handleMouseDownOnArrow: function handleMouseDownOnArrow(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } // If not focused, handleMouseDown will handle it if (!this.state.isOpen) { return; } event.stopPropagation(); event.preventDefault(); this.setState({ isOpen: false }, this._unbindCloseMenuIfClickedOutside); }, handleInputFocus: function handleInputFocus(event) { var newIsOpen = this.state.isOpen || this._openAfterFocus; this.setState({ isFocused: true, isOpen: newIsOpen }, function () { if (newIsOpen) { this._bindCloseMenuIfClickedOutside(); } else { this._unbindCloseMenuIfClickedOutside(); } }); this._openAfterFocus = false; if (this.props.onFocus) { this.props.onFocus(event); } }, handleInputBlur: function handleInputBlur(event) { var _this4 = this; this._blurTimeout = setTimeout(function () { if (_this4._focusAfterUpdate) return; _this4.setState({ isFocused: false, isOpen: false }); }, 50); if (this.props.onBlur) { this.props.onBlur(event); } }, handleKeyDown: function handleKeyDown(event) { if (this.props.disabled) return; switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { this.popValue(); } break; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.state.focusedOption) { return; } this.selectFocusedOption(); break; case 13: // enter if (!this.state.isOpen) return; this.selectFocusedOption(); break; case 27: // escape if (this.state.isOpen) { this.resetValue(); } else if (this.props.clearable) { this.clearValue(event); } break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; case 188: // , if (this.props.allowCreate && this.props.multi && this.props.commaSplit) { event.preventDefault(); event.stopPropagation(); this.selectFocusedOption(); } else { return; } break; default: return; } event.preventDefault(); }, // Ensures that the currently focused option is available in filteredOptions. // If not, returns the first available option. _getNewFocusedOption: function _getNewFocusedOption(filteredOptions) { for (var key in filteredOptions) { if (filteredOptions.hasOwnProperty(key) && filteredOptions[key] === this.state.focusedOption) { return filteredOptions[key]; } } return this.getFirstFocusableOption(filteredOptions); }, handleInputChange: function handleInputChange(event) { // assign an internal variable because we need to use // the latest value before setState() has completed. this._optionsFilterString = event.target.value; if (this.props.onInputChange) { this.props.onInputChange(event.target.value); } if (this.props.asyncOptions) { this.setState({ isLoading: true, inputValue: event.target.value }); this.loadAsyncOptions(event.target.value, { isLoading: false, isOpen: true }, this._bindCloseMenuIfClickedOutside); } else { var filteredOptions = this.filterOptions(this.state.options); this.setState({ isOpen: true, inputValue: event.target.value, filteredOptions: filteredOptions, focusedOption: this._getNewFocusedOption(filteredOptions) }, this._bindCloseMenuIfClickedOutside); } }, autoloadAsyncOptions: function autoloadAsyncOptions() { var _this5 = this; this.setState({ isLoading: true }); this.loadAsyncOptions(this.props.value || '', { isLoading: false }, function () { // update with fetched but don't focus _this5.setValue(_this5.props.value, false); }); }, loadAsyncOptions: function loadAsyncOptions(input, state, callback) { var _this6 = this; var thisRequestId = this._currentRequestId = requestId++; if (this.props.cacheAsyncResults) { for (var i = 0; i <= input.length; i++) { var cacheKey = input.slice(0, i); if (this._optionsCache[cacheKey] && (input === cacheKey || this._optionsCache[cacheKey].complete)) { var options = this._optionsCache[cacheKey].options; var filteredOptions = this.filterOptions(options); var newState = { options: options, filteredOptions: filteredOptions, focusedOption: this._getNewFocusedOption(filteredOptions) }; for (var key in state) { if (state.hasOwnProperty(key)) { newState[key] = state[key]; } } this.setState(newState); if (callback) callback.call(this, newState); return; } } } this.props.asyncOptions(input, function (err, data) { if (err) throw err; if (_this6.props.cacheAsyncResults) { _this6._optionsCache[input] = data; } if (thisRequestId !== _this6._currentRequestId) { return; } var filteredOptions = _this6.filterOptions(data.options); var newState = { options: data.options, filteredOptions: filteredOptions, focusedOption: _this6._getNewFocusedOption(filteredOptions) }; for (var key in state) { if (state.hasOwnProperty(key)) { newState[key] = state[key]; } } _this6.setState(newState); if (callback) callback.call(_this6, newState); }); }, filterOptions: function filterOptions(options, values) { var filterValue = this._optionsFilterString; var exclude = (values || this.state.values).map(function (i) { return i.value; }); if (this.props.filterOptions) { return this.props.filterOptions.call(this, options, filterValue, exclude); } else { var filterOption = function filterOption(op) { if (this.props.multi && exclude.indexOf(op.value) > -1) return false; if (this.props.filterOption) return this.props.filterOption.call(this, op, filterValue); var valueTest = String(op.value), labelTest = String(op.label); if (this.props.ignoreCase) { valueTest = valueTest.toLowerCase(); labelTest = labelTest.toLowerCase(); filterValue = filterValue.toLowerCase(); } return !filterValue || this.props.matchPos === 'start' ? this.props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || this.props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : this.props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || this.props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0; }; return (options || []).filter(filterOption, this); } }, selectFocusedOption: function selectFocusedOption() { if (this.props.allowCreate && !this.state.focusedOption) { return this.selectValue(this.state.inputValue); } if (this.state.focusedOption) { return this.selectValue(this.state.focusedOption); } }, focusOption: function focusOption(op) { this.setState({ focusedOption: op }); }, focusNextOption: function focusNextOption() { this.focusAdjacentOption('next'); }, focusPreviousOption: function focusPreviousOption() { this.focusAdjacentOption('previous'); }, focusAdjacentOption: function focusAdjacentOption(dir) { this._focusedOptionReveal = true; var ops = this.state.filteredOptions.filter(function (op) { return !op.disabled; }); if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this.state.focusedOption || ops[dir === 'next' ? 0 : ops.length - 1] }, this._bindCloseMenuIfClickedOutside); return; } if (!ops.length) { return; } var focusedIndex = -1; for (var i = 0; i < ops.length; i++) { if (this.state.focusedOption === ops[i]) { focusedIndex = i; break; } } var focusedOption = ops[0]; if (dir === 'next' && focusedIndex > -1 && focusedIndex < ops.length - 1) { focusedOption = ops[focusedIndex + 1]; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedOption = ops[focusedIndex - 1]; } else { focusedOption = ops[ops.length - 1]; } } this.setState({ focusedOption: focusedOption }); }, unfocusOption: function unfocusOption(op) { if (this.state.focusedOption === op) { this.setState({ focusedOption: null }); } }, buildMenu: function buildMenu() { var focusedValue = this.state.focusedOption ? this.state.focusedOption.value : null; var renderLabel = this.props.optionRenderer || function (op) { return op.label; }; if (this.state.filteredOptions.length > 0) { focusedValue = focusedValue == null ? this.state.filteredOptions[0] : focusedValue; } // Add the current value to the filtered options in last resort var options = this.state.filteredOptions; if (this.props.allowCreate && this.state.inputValue.trim()) { var inputValue = this.state.inputValue; options = options.slice(); var newOption = this.props.newOptionCreator ? this.props.newOptionCreator(inputValue) : { value: inputValue, label: inputValue, create: true }; options.unshift(newOption); } var ops = Object.keys(options).map(function (key) { var op = options[key]; var isSelected = this.state.value === op.value; var isFocused = focusedValue === op.value; var optionClass = classes({ 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': op.disabled }); var ref = isFocused ? 'focused' : null; var mouseEnter = this.focusOption.bind(this, op); var mouseLeave = this.unfocusOption.bind(this, op); var mouseDown = this.selectValue.bind(this, op); var optionResult = React.createElement(this.props.optionComponent, { key: 'option-' + op.value, className: optionClass, renderFunc: renderLabel, mouseEnter: mouseEnter, mouseLeave: mouseLeave, mouseDown: mouseDown, click: mouseDown, addLabelText: this.props.addLabelText, option: op, ref: ref }); return optionResult; }, this); if (ops.length) { return ops; } else { var noResultsText, promptClass; if (this.state.isLoading) { promptClass = 'Select-searching'; noResultsText = this.props.searchingText; } else if (this.state.inputValue || !this.props.asyncOptions) { promptClass = 'Select-noresults'; noResultsText = this.props.noResultsText; } else { promptClass = 'Select-search-prompt'; noResultsText = this.props.searchPromptText; } return React.createElement( 'div', { className: promptClass }, noResultsText ); } }, handleOptionLabelClick: function handleOptionLabelClick(value, event) { if (this.props.onOptionLabelClick) { this.props.onOptionLabelClick(value, event); } }, render: function render() { var selectClass = classes('Select', this.props.className, { 'is-multi': this.props.multi, 'is-searchable': this.props.searchable, 'is-open': this.state.isOpen, 'is-focused': this.state.isFocused, 'is-loading': this.state.isLoading, 'is-disabled': this.props.disabled, 'has-value': this.state.value }); var value = []; if (this.props.multi) { this.state.values.forEach(function (val) { var onOptionLabelClick = this.handleOptionLabelClick.bind(this, val); var onRemove = this.removeValue.bind(this, val); var valueComponent = React.createElement(this.props.valueComponent, { key: val.value, option: val, renderer: this.props.valueRenderer, optionLabelClick: !!this.props.onOptionLabelClick, onOptionLabelClick: onOptionLabelClick, onRemove: onRemove, disabled: this.props.disabled }); value.push(valueComponent); }, this); } if (!this.state.inputValue && (!this.props.multi || !value.length)) { var val = this.state.values[0] || null; if (this.props.valueRenderer && !!this.state.values.length) { value.push(React.createElement(Value, { key: 0, option: val, renderer: this.props.valueRenderer, disabled: this.props.disabled })); } else { var singleValueComponent = React.createElement(this.props.singleValueComponent, { key: 'placeholder', value: val, placeholder: this.state.placeholder }); value.push(singleValueComponent); } } var loading = this.state.isLoading ? React.createElement('span', { className: 'Select-loading', 'aria-hidden': 'true' }) : null; var clear = this.props.clearable && this.state.value && !this.props.disabled ? React.createElement('span', { className: 'Select-clear', title: this.props.multi ? this.props.clearAllText : this.props.clearValueText, 'aria-label': this.props.multi ? this.props.clearAllText : this.props.clearValueText, onMouseDown: this.clearValue, onTouchEnd: this.clearValue, onClick: this.clearValue, dangerouslySetInnerHTML: { __html: '&times;' } }) : null; var menu; var menuProps; if (this.state.isOpen) { menuProps = { ref: 'menu', className: 'Select-menu', onMouseDown: this.handleMouseDown }; menu = React.createElement( 'div', { ref: 'selectMenuContainer', className: 'Select-menu-outer' }, React.createElement( 'div', menuProps, this.buildMenu() ) ); } var input; var inputProps = { ref: 'input', className: 'Select-input ' + (this.props.inputProps.className || ''), tabIndex: this.props.tabIndex || 0, onFocus: this.handleInputFocus, onBlur: this.handleInputBlur }; for (var key in this.props.inputProps) { if (this.props.inputProps.hasOwnProperty(key) && key !== 'className') { inputProps[key] = this.props.inputProps[key]; } } if (!this.props.disabled) { if (this.props.searchable) { input = React.createElement(Input, _extends({ value: this.state.inputValue, onChange: this.handleInputChange, minWidth: '5' }, inputProps)); } else { input = React.createElement( 'div', inputProps, ' ' ); } } else if (!this.props.multi || !this.state.values.length) { input = React.createElement( 'div', { className: 'Select-input' }, ' ' ); } return React.createElement( 'div', { ref: 'wrapper', className: selectClass }, React.createElement('input', { type: 'hidden', ref: 'value', name: this.props.name, value: this.state.value, disabled: this.props.disabled }), React.createElement( 'div', { className: 'Select-control', ref: 'control', onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown }, value, input, React.createElement('span', { className: 'Select-arrow-zone', onMouseDown: this.handleMouseDownOnArrow }), React.createElement('span', { className: 'Select-arrow', onMouseDown: this.handleMouseDownOnArrow }), loading, clear ), menu ); } }); module.exports = Select; },{"./Option":1,"./SingleValue":2,"./Value":3,"classnames":undefined,"react":undefined,"react-input-autosize":undefined}]},{},[]);
import React, {PropTypes} from 'react'; import ReactCSSTransitionGroup from 'react-addons-css-transition-group'; import Round from './Round'; const Rounds = ({rounds, phase, player, actions}) => { var roundSet = []; for (var i = 0; i < rounds.total; i++) { roundSet.push(<Round number={i} current={rounds.current == i} score={rounds.score[i]} phase={phase} player={player.object} actions={actions} />) } return ( <div className="rounds"> {roundSet} </div> ); }; Rounds.propTypes = { rounds: PropTypes.object.isRequired, phase: PropTypes.string.isRequired, player: PropTypes.object.isRequired, actions: PropTypes.object.isRequired }; export default Rounds;
import React from 'react'; import cssModules from 'react-css-modules'; import styles from './index.module.scss'; import { LoginContainer } from 'containers'; // Pages map directly to Routes, i.e. one page equals on Route const LoginPage = () => ( <div className={styles.container}> <LoginContainer /> </div> ); export default cssModules(LoginPage, styles);
/** * Created by ramy on 10/29/2015. */ var Promise = require("js-promise"); var fse = require("fs-extra"); var homeDir = require("os").homedir(); var colors = require("colors"); var fs = require("fs"); var request = require("request"); var _ = require("lodash"); module.exports = { svnRoot: "https://sncsource1.corp.nai.org/svn/projects/ConsumerSVNSRC/users/ui-lib", currentFolderName:function(){// capture most child folder name return process.cwd().replace(/.*(\\|\/)/g, '');// capture most child folder name }, setupBower:function(comp_id){ if(!fse.existsSync(homeDir + "/.bowerrc")){ var config = { "analytics": false, "shorthand-resolver": "svn+https://sncsource1.corp.nai.org/svn/projects/ConsumerSVNSRC/users/{{owner}}/{{package}}" }; fse.outputFileSync(homeDir + "/.bowerrc", this.toJSON(config),"utf8"); } var comp_name = comp_id; var comp_folder = "app_components/" + comp_id; if(!comp_id || comp_id == ""){ comp_name = this.currentFolderName(); comp_folder = "."; } if(!fse.existsSync(comp_folder + "/bower.json")) { var bower_template = fse.readFileSync(__dirname + "/resources/bower_template.json","utf8"); fse.outputFileSync(comp_folder + "/bower.json", bower_template.replace(/\{comp_id\}/g, comp_name), "utf8"); fse.outputFileSync(comp_folder + "/.svnignore", fse.readFileSync(__dirname + "/resources/svn_ignore.txt","utf8"), "utf8"); } // }, componentFound:function(comp_id){ return this.exec("svn list " + this.svnRoot,new RegExp("(^|\n)" + comp_id + "\/","i")); }, publishComponent:function(comp_id){ var svnRoot = this.svnRoot; var self = this; var comment = ' -m "first commit" '; var silent = " -q "; console.log("Creating component on SVN..."); var localFolder; this.setupBower(comp_id); if(comp_id){ localFolder = "app_components/" + comp_id; //TODO: add this component as a dependency in base application ./bower.json }else { comp_id = this.currentFolderName(); localFolder = "."; } //TODO: verify that all components inside "includes" are listed as {local_folder}/bower.json dependencies var taskList = []; taskList.push( function(){ return self.exec("svn mkdir --parents " + svnRoot + "/" + comp_id + "/trunk " + comment + silent ); }, function(){ return self.exec("svn mkdir " + svnRoot + "/" + comp_id + "/tags " + comment + silent); }, function(){ return self.exec("svn mkdir " + svnRoot + "/" + comp_id + "/branches " + comment + silent); }, function(){ return self.exec("svn co " + svnRoot + "/" + comp_id + "/trunk " + localFolder + silent + silent); }, function(){// set ignored items return self.exec("svn propset svn:ignore -F " + localFolder + "/.svnignore " + localFolder + silent); }, function(){// add contents //TODO: fix .svn not added error return self.exec("svn add " + localFolder + "/* " + silent); }, function(){ return self.exec('svn ci ' + localFolder + comment + silent); } ); return Promise.series(taskList); }, quickBuildApp:function(params){ var app_id = this.currentFolderName(); var compList = []; var overrides = {}; var ignoreList = []; var headContent = []; var bodyContent = []; var contentsList = {}; var bodyTag = []; function processConfig(id, root){ if(-1!=compList.indexOf(id)||-1!=ignoreList.indexOf(id)){ return; } function readConfig(path, comp_id){ if(fs.existsSync(path)){ if(fs.existsSync(path + "/build.json")){ var configText = fs.readFileSync(path + "/build.json", "utf8"); configText = configText.replace(/\{\{comp_id\}\}/gi, comp_id); try { return JSON.parse(configText); }catch(e){ console.error(e.message); } } return {};//component exists without or with invalid build.json } return null;// component does not exist } if(overrides[id]){// override has been requested by a super container id = overrides[id]; } var build = readConfig(root + id, id ); if(!build){ root = "bower_components/"; build = readConfig(root + id , id); } if(!build){ console.warn("Couldn't find component %s".red, id); return; } if(build.override){ _.each(build.override,function(override, ovc){ overrides[ovc] = override; }); } if(build.exclude){ build.exclude.forEach(function(exclude){ if(!ignoreList.indexOf(exclude)){ ignoreList.push(exclude); } }); } _.each(build.include,function(component){ processConfig(component, "app_components/"); }); function injectList(from,to) { var list = []; if (Array.isArray(from)) { Array.prototype.push.apply(list, from); } else { list.push(from); } _.each(list, function (item) { var matchInclude = item.match(/^\#(.+)$/); if (matchInclude) { var includeText = fs.readFileSync(root + "/" + id + "/" + matchInclude[1], "utf8"); to.push(includeText); } else { to.push(item); } }); } if(build.head && build.head.default){ injectList(build.head.default,headContent); } if(build.body && build.body.default){ injectList(build.body.default,bodyContent); } if(build["body-tag"] && build["body-tag"].default){ injectList(build["body-tag"].default,bodyTag); } if(build.content){ _.each(build.content.parts,function(part_url, part_name){ var partInfo = {}; _.each(build.content.lang,function(lang, lang_folder){ partInfo[lang_folder] = true; contentsList["build/nls/" + lang_folder + "/" + part_name ] = part_url.replace("{{lang}}",lang); }); fse.outputFile("build/nls/" + part_name + ".js", "define(" + JSON.stringify(partInfo,undefined,2) + ");"); }); } if(id != ""){ compList.push(id); //Copy component folder to "build/" fse.copySync(root + id, "build/" + id); if(fs.existsSync(root + id + "/nls")){ fse.copySync(root + id + "/nls", "build/nls"); fse.remove("build/" + id + "/nls"); } } return build; } fse.removeSync("build"); fs.mkdirSync("build"); processConfig("",".");// will recursively process sub components console.log("\n---------- App components --------"); console.log("Excluded:" + JSON.stringify(ignoreList).red); console.log("Overrides:" + JSON.stringify(overrides).yellow); console.log("Components:" + JSON.stringify(compList).green); var html5 = fs.readFileSync(__dirname + "/resources/html5.html", "utf8").replace(/\{\{app_id\}\}/gi, app_id); var coloredHTML = html5.replace("{{headers}}",headContent.join("\n").cyan) .replace("{{body}}",bodyContent.join("\n").cyan) .replace("{{body-tag}}",bodyTag.join(" ").cyan); console.log("\n---------- build/index.html --------"); console.log( coloredHTML ); console.log("\n------------------------------------"); var outHTML = html5.replace("{{headers}}",headContent.join("\n")) .replace("{{body}}",bodyContent.join("\n")) .replace("{{body-tag}}",bodyTag.join(" ")); fs.writeFileSync( "build/index.html", outHTML, "utf8" ); if(_.keys(contentsList).length) { process.stdout.write("Installing contents".yellow); _.each(contentsList, function (url, partFile) { request.get(url, function(err, response, body){ process.stdout.write(".".yellow); var jsonText = JSON.stringify(JSON.parse(body).contentDictionary,undefined,2);//TODO: make contentDictionary optional //fse.outputFile(partFile + ".json", jsonText); fse.outputFile(partFile + ".js", "define(" + jsonText + ");"); }); }); } if(params && params.open){ require("open")("file://" + process.cwd() + "/build/index.html"); } }, buildApp:function(params) { var self = this; if( (params && params.quick) || !fs.existsSync("bower.json")) { this.quickBuildApp(params); } else { //TODO: clean Bower cache //this.setupBower("", "."); fse.removeSync("bower_components"); this.exec("bower install").then(function(){ self.quickBuildApp(params); }); } }, exec:function(command, findRegEx,bHideOutput) { var ret = new Promise(); var retVal = findRegEx ? false : ""; var child = require("child_process").exec(command); //spit stdout to screen child.stdout.on('data', function (data) { if(findRegEx) { retVal = retVal || findRegEx.test(data); //process.stdout.write(data.toString() + " " + retVal); }else{ retVal += data.toString(); if(!bHideOutput) { process.stdout.write(data.toString()); } } }); //spit stderr to screen child.stderr.on('data', function (data) { if(!bHideOutput) { process.stdout.write(data.toString().yellow); } }); child.on('close', function (code) { ret.resolve(retVal); }); return ret; }, listAllComponents:function(){ return this.exec("svn list " + this.svnRoot, undefined, true ).then(function(outText){ var ret = outText.split("\/\r\n"); ret.pop();//remove last element return ret; }); }, readJSON:function(path){ if(fse.existsSync(path)){ var text = fse.readFileSync(path, "utf8"); try { return JSON.parse(text); }catch(e){ return {__error:e}; } } return {_error:"not_found"}; }, toJSON:function(obj){ return JSON.stringify(obj,undefined,2); } };
import { GraphQLObjectType } from 'graphql'; import { types as collectiveTypes } from '../../../constants/collectives'; import { Account, AccountFields } from '../interface/Account'; import { AccountWithContributions, AccountWithContributionsFields } from '../interface/AccountWithContributions'; import { AccountWithHost, AccountWithHostFields } from '../interface/AccountWithHost'; export const Vendor = new GraphQLObjectType({ name: 'Vendor', description: 'This represents a Vendor account', interfaces: () => [Account, AccountWithHost, AccountWithContributions], isTypeOf: collective => collective.type === collectiveTypes.VENDOR, fields: () => { return { ...AccountFields, ...AccountWithHostFields, ...AccountWithContributionsFields, }; }, });
/** * Created by mosa on 2016/3/11. */ var requireDir = require('require-dir'); // Require all tasks in gulp/tasks, including subfolders requireDir('./gulp/tasks', {recurse: true});
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var FS = require("fs"); var Path = require("path"); var Request = require("request"); var ThenFail = require("../libs/thenfail"); var moment = require("moment"); var AdmZip = require("adm-zip"); var sizeOf = require("image-size"); var imagecolors = require('imagecolors'); var archiver = require('archiver'); var image_model_1 = require("./db-models/image-model"); var url_model_1 = require("./db-models/url-model"); var crawlerConfig = require("../../crawler-config"); var hop = Object.prototype.hasOwnProperty; var imageStatus; (function (imageStatus) { imageStatus[imageStatus["normal"] = 0] = "normal"; imageStatus[imageStatus["block"] = 1] = "block"; imageStatus[imageStatus["deleted"] = 2] = "deleted"; })(imageStatus = exports.imageStatus || (exports.imageStatus = {})); function createImage(imageData) { console.log("create image:"); console.log(imageData); return imageData && ThenFail .then(function () { return image_model_1.default.create({ name: imageData.name + "." + imageData.type, title: imageData.title || "", status: imageData.status || imageStatus.normal, type: imageData.type || "", url: imageData.url || "", farther_url: imageData.farther_url || "", width: imageData.width || 0, height: imageData.height || 0, size: imageData.size || 0, description: imageData.description || "", farther_description: imageData.farther_description || "", farther_keywords: imageData.farther_keywords || "", date: imageData.date || moment().format(crawlerConfig.timeDataFormat), }); }) .fail(function (error) { console.log("someting error in create image: "); console.log(error); }); } exports.createImage = createImage; function getImagesForCrawling(typeArray, limit) { var imageTypeArray = typeArray.length ? typeArray : ["png", "jpg", "jpeg", "gif"]; return ThenFail .then(function () { return new ThenFail(function (resolve, reject) { return image_model_1.default.find({ type: { $in: imageTypeArray } }) .sort({ 'date': -1 }) .limit(limit ? limit : Infinity) .exec(function (err, imageRecords) { resolve(imageRecords); }); }); }) .then(function (imageRecords) { return imageRecords; }); } exports.getImagesForCrawling = getImagesForCrawling; function getImagesForDisplay(typeArray, limit) { var imageTypeArray = typeArray.length ? typeArray : ["png", "jpg", "jpeg", "gif"]; var imageNameArray = []; var imagesData = []; return ThenFail .then(function () { return new ThenFail(function (resolve, reject) { return FS.readdir(crawlerConfig.imageDownLoadDestDir, function (err, result) { if (err) { console.log("get images error"); } console.log(result); resolve(result); }); }); }) .then(function (imageNameArray) { return imageNameArray && getImagesByNames(imageNameArray); }); } exports.getImagesForDisplay = getImagesForDisplay; function getImageByName(imageName) { return imageName && ThenFail .then(function () { return new ThenFail(function (resolve, reject) { return image_model_1.default.findOne({ name: imageName }) .exec(function (error, imageRecord) { if (error) { console.log('get image by name Error:' + error); } imageRecord ? resolve() : resolve(imageRecord); }); }); }) .then(function (imageRecord) { return imageRecord; }); } exports.getImageByName = getImageByName; function getImagesByNames(nameArray, limit) { console.log("in getImagesByNames"); console.log(nameArray); var imageNames = []; limit = nameArray.length; return nameArray && ThenFail .then(function () { return new ThenFail(function (resolve, reject) { return image_model_1.default.find({ name: { $in: nameArray } }) .sort({ 'date': -1 }) .limit(limit ? limit : Infinity) .exec(function (error, imageRecords) { if (error) { console.log('get images by name Error' + error); } resolve(imageRecords); }); }); }) .then(function (imageNames) { return imageNames; }); } exports.getImagesByNames = getImagesByNames; function downloadImagesFromUrl(url) { return url && ThenFail .delay(Math.floor(Math.random() * 1000)) .then(function () { return new ThenFail(function (resolve, reject) { console.log("image url:"); console.log(url); var imageTypeArray = ["png", "jpg", "jpeg", "gif"]; var imageUrlReg = /[\w\d@\-_%]+/ig; var imageUrlData = url.match(imageUrlReg); var length = imageUrlData.length; var imageName = imageUrlData[length - 2]; var imageType = imageUrlData[length - 1]; var imageSize = {}; if (imageTypeArray.indexOf(imageType) >= 0) { var downloadPath = Path.join(crawlerConfig.imageDownLoadDestDir, imageName + "." + imageType); var isSupport_1 = crawlerConfig.imageType.indexOf(imageType) > 0 ? true : false; Request .get({ url: url, encoding: null }, function (error, response, body) { if (error) { console.log("image download error 1:"); console.log(error); } if (isSupport_1) { var size = response && new sizeOf(response.body); if (size) { imageSize.height = size.height; imageSize.width = size.width; } imageSize.size = response ? response.headers['content-length'] : 0; return image_model_1.default .findOne({ url: url }) .exec(function (error, result) { if (error) { console.log("error in remove image: " + error); } result.width = imageSize.width; result.height = imageSize.height; result.size = imageSize.size; return result.save(); }); } }) .on('response', function (response) { console.log(response.statusCode); console.log(response.headers['content-type']); }) .pipe(FS.createWriteStream(downloadPath)); resolve(); } else { console.log("图片信息错误!"); } }); }) .fail(function (reason) { console.log("download image error: 2"); console.log(reason); }) .void; } exports.downloadImagesFromUrl = downloadImagesFromUrl; function removeImage(imageId) { return ThenFail .then(function () { return new ThenFail(function (resolve, reject) { return image_model_1.default.remove({ _id: imageId }) .exec(function (error, result) { if (error) { console.log("error in remove image: " + error); } resolve(result); }); }); }) .void; } exports.removeImage = removeImage; function removeImages(imageIds) { return ThenFail .map(imageIds, function (imageId) { return removeImage(imageId); }) .void; } exports.removeImages = removeImages; function zipImages(imageNames) { var zip = new AdmZip(); return ThenFail .then(function () { return ThenFail .map(imageNames, function (imageName) { var localFile = Path.join(crawlerConfig.imageDownLoadDestDir, imageName); console.log("add file:" + localFile); return zip.addFile(imageName, FS.readFileSync(localFile)); }); }) .then(function () { var zipPath = Path.join(crawlerConfig.imageZipDestDir, crawlerConfig.imageZipName); var willSendthis = zip.toBuffer(); console.log("write zip"); zip.writeZip(zipPath); return zipPath; }); } exports.zipImages = zipImages; function zipImagesByArchiver(imageNames) { var archive = archiver('zip'); var zipPath = Path.join(crawlerConfig.imageZipDestDir, crawlerConfig.imageZipName); return ThenFail .then(function () { return new ThenFail(function (resolve, reject) { var output = FS.createWriteStream(zipPath); output.on('close', function () { console.log(archive.pointer() + ' total bytes'); console.log('archiver has been finalized and the output file descriptor has closed.'); resolve(); }); archive.on('error', function (err) { console.log("archive error"); console.log(err); }); archive.pipe(output); for (var i = 0; i < imageNames.length; i++) { var localFile = Path.join(crawlerConfig.imageDownLoadDestDir, imageNames[i]); console.log("add file:" + localFile); archive.append(FS.createReadStream(localFile), { name: imageNames[i] }); } archive.finalize(); }); }).void; } exports.zipImagesByArchiver = zipImagesByArchiver; function imageRename(imageId, imageNewName) { console.log("in image rename model:"); console.log(imageId); console.log(imageNewName); var imageOldName = ""; return imageId && imageNewName && ThenFail .then(function () { return new ThenFail(function (resolve, reject) { return image_model_1.default.findOne({ _id: imageId }) .exec(function (error, result) { if (error) { console.log("error in remove image: " + error); } imageOldName = result.name; result.name = imageNewName; result.save(); resolve(); }); }); }) .then(function () { return new ThenFail(function (resolve, reject) { var oldPath = Path.join(crawlerConfig.imageDownLoadDestDir, imageOldName); var newPath = Path.join(crawlerConfig.imageDownLoadDestDir, imageNewName); return FS.rename(oldPath, newPath, function (error) { console.log(error); resolve(); }); }); }) .void; } exports.imageRename = imageRename; function deleteImages() { return ThenFail .then(function () { return new ThenFail(function (resolve, reject) { return FS.readdir(crawlerConfig.imageDownLoadDestDir, function (err, result) { if (err) { console.log("get images error"); } console.log(result); resolve(result); }); }); }) .then(function (imageNameArray) { return imageNameArray && imageNameArray.forEach(function (imageName) { return FS.unlink(Path.join(crawlerConfig.imageDownLoadDestDir, imageName), function (error) { error ? console.log(error) : null; }); }); }) .then(function () { return image_model_1.default.remove({}, function (error) { if (error) { console.log("error in deleteImaes while removing images in mongodb."); console.log(error); } }); }) .then(function () { return url_model_1.default.remove({}, function (error) { if (error) { console.log("error in deleteImaes while removing urls in mongodb."); console.log(error); } }); }) .void; } exports.deleteImages = deleteImages; //# sourceMappingURL=image.js.map
import has from './utils/has'; import cAbout from '../../views/components/about'; import cConsultationServices from '../../views/components/consultation-services'; import cCdnInAsiaAndChina from '../../views/components/features/cdn-in-asia-and-china'; import cJsdelivrCdnFeatures from '../../views/components/features/jsdelivr-cdn-features'; import cMultiCdnLoadBalancing from '../../views/components/features/multi-cdn-load-balancing'; import cNetworkMap from '../../views/components/features/network-map'; import cCustomCdn from '../../views/components/free-open-source-cdn/custom-cdn-for-open-source'; import cJavascriptCdn from '../../views/components/free-open-source-cdn/javascript-cdn'; // import cNpmCdn from '../../views/components/free-open-source-cdn/npm-cdn'; // import cWordPressCdn from '../../views/components/free-open-source-cdn/wordpress-cdn'; import cIndex from '../../views/components/index'; import cProjects from '../../views/components/projects'; import cBecomeASponsor from '../../views/components/sponsors/become-a-sponsor'; import cOurSponsors from '../../views/components/sponsors/our-sponsors'; import cStatistics from '../../views/components/statistics'; import cDebugTool from '../../views/components/tools/debug-tool'; Ractive.DEBUG = location.hostname === 'localhost'; Ractive.defaults.isolated = true; if (!window.Promise) { window.Promise = Ractive.Promise; } let app = { config: { animateScrolling: true, }, sriHashes: {}, usedCdn: '', }; app.router = new Ractive.Router({ el: '#page', data () { return { app, collection: has.localStorage() && localStorage.getItem('collection') ? JSON.parse(localStorage.getItem('collection')) : [], }; }, globals: [ 'query', 'collection' ], }); let routerDispatch = Ractive.Router.prototype.dispatch; Ractive.Router.prototype.dispatch = function () { routerDispatch.apply(this, arguments); document.title = app.router.route.view.get('title') || 'jsDelivr - A free super-fast CDN for developers and webmasters'; ga('set', 'page', this.getUri()); ga('send', 'pageview'); return this; }; app.router.addRoute('/', Ractive.extend(cIndex), { qs: [ 'query', 'limit' ] }); app.router.addRoute('/about', Ractive.extend(cAbout)); app.router.addRoute('/consultation-services', Ractive.extend(cConsultationServices)); app.router.addRoute('/features/multi-cdn-load-balancing', Ractive.extend(cMultiCdnLoadBalancing)); app.router.addRoute('/features/jsdelivr-cdn-features', Ractive.extend(cJsdelivrCdnFeatures)); app.router.addRoute('/features/network-map', Ractive.extend(cNetworkMap)); app.router.addRoute('/features/cdn-in-asia-and-china', Ractive.extend(cCdnInAsiaAndChina)); app.router.addRoute('/free-open-source-cdn/javascript-cdn', Ractive.extend(cJavascriptCdn)); // app.router.addRoute('/free-open-source-cdn/wordpress-cdn', Ractive.extend(cWordPressCdn)); // app.router.addRoute('/free-open-source-cdn/npm-cdn', Ractive.extend(cNpmCdn)); app.router.addRoute('/free-open-source-cdn/custom-cdn-for-open-source', Ractive.extend(cCustomCdn)); app.router.addRoute('/projects/:name', Ractive.extend(cProjects)); app.router.addRoute('/sponsors/become-a-sponsor', Ractive.extend(cBecomeASponsor)); app.router.addRoute('/sponsors/our-sponsors', Ractive.extend(cOurSponsors)); app.router.addRoute('/statistics', Ractive.extend(cStatistics)); app.router.addRoute('/tools/debug-tool', Ractive.extend(cDebugTool), { hash: [ 'resultsHash' ] }); app.router.addRoute('/(.*)', () => { location.pathname = '/'; }); $(() => { app.router .init() .watchLinks() .watchState(); // The affix plugin sometimes applies incorrect css on page load; scrolling fixes the problem. setTimeout(function () { scrollBy(0, 1); scrollBy(0, -1); }); }); $.fn.shuffle = function (selector) { return this.each(function () { $(this).find(selector) .sort(() => .5 - Math.random()) .detach() .appendTo(this); }); }; window.app = app;
var zther = zther || {}; zther.util = zther.util || {}; zther.util.NumberUtil = { /** Determines if the number is even. @param value: A number to determine if it is divisible by <code>2</code>. @return Returns <code>true</code> if the number is even; otherwise <code>false</code>. @example <code> console.log(NumberUtil.isEven(7)); // Traces false console.log(NumberUtil.isEven(12)); // Traces true </code> */ isEven : function(value) { "use strict"; return (value & 1) === 0; } };
export default class ColDefFactory { createColDefs() { const leftAlignStyle = { 'text-align': 'left' }; const centerAlignStyle = { 'text-align': 'center' } const makeAlignStyle = { 'border-left': '1px solid #808080', 'text-align': 'left' } const columnDefs = [ { headerName: 'MAKE', field: 'make', width: 100, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, cellStyle: makeAlignStyle }, { headerName: 'MODEL', field: 'model', width: 90, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, cellStyle: leftAlignStyle }, { headerName: 'YEAR', field: 'year', width: 60, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, cellStyle: centerAlignStyle }, { headerName: 'STATE', field: 'state', width: 60, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, cellStyle: centerAlignStyle, cellRenderer: stateCellRenderer }, { headerName: 'FAILED COMPONENT', field: 'component', width: 200, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, cellStyle: centerAlignStyle }, { headerName: 'CRASH', field: 'crashed', width: 30, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, headerClass: 'crashed', cellStyle: centerAlignStyle, cellRenderer: defaultMetricCellRenderer }, { headerName: 'FIRE', field: 'fire', width: 30, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, headerClass: 'fire', cellStyle: centerAlignStyle, cellRenderer: defaultMetricCellRenderer }, { headerName: 'INJURY', field: 'injured', width: 30, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, headerClass: 'injured', cellStyle: centerAlignStyle, cellRenderer: defaultMetricCellRenderer }, { headerName: 'MPH', field: 'speed', width: 40, suppressSorting: true, suppressSizeToFit: true, suppressMenu: true, headerClass: 'speed', cellStyle: centerAlignStyle, cellRenderer: speedCellRenderer }, { headerName: 'DESCRIPTION OF ISSUE', field: 'description', minWidth: 320, suppressSorting: true, suppressMenu: true, cellStyle: leftAlignStyle } ]; return columnDefs; } } function defaultMetricCellRenderer(params) { if (!params.value || params.value === "" || params.value === "0") { return '•'; } else { return 'Y'; } } function speedCellRenderer(params) { if (!params.value || params.value === "" || params.value === "0") { return 'n/a'; } else { return params.value; } } function stateCellRenderer(params) { const stateAbbreviationLookup = { 'Alabama': 'AL', 'Alaska': 'AK', 'Arizona': 'AZ', 'Arkansas': 'AR', 'California': 'CA', 'Colorado': 'CO', 'Connecticut': 'CT', 'Delaware': 'DE', 'Florida': 'FL', 'Georgia': 'GA', 'Hawaii': 'HI', 'Idaho': 'ID', 'Illinois': 'IL', 'Indiana': 'IN', 'Iowa': 'IA', 'Kansas': 'KS', 'Kentucky': 'KY', 'Louisiana': 'LA', 'Maine': 'ME', 'Maryland': 'MD', 'Massachusetts': 'MA', 'Michigan': 'MI', 'Minnesota': 'MN', 'Mississippi': 'MS', 'Missouri': 'MO', 'Montana': 'MT', 'Nebraska': 'NE', 'Nevada': 'NV', 'New Hampshire': 'NH', 'New Jersey': 'NJ', 'New Mexico': 'NM', 'New York': 'NY', 'North Carolina': 'NC', 'North Dakota': 'ND', 'Ohio': 'OH', 'Oklahoma': 'OK', 'Oregon': 'OR', 'Pennsylvania': 'PA', 'Rhode Island': 'RI', 'South Carolina': 'SC', 'South Dakota': 'SD', 'Tennessee': 'TN', 'Texas': 'TX', 'Utah': 'UT', 'Vermont': 'VT', 'Virginia': 'VA', 'Washington': 'WA', 'West Virginia': 'WV', 'Wisconsin': 'WI', 'Wyoming': 'WY' }; return stateAbbreviationLookup[params.value] }
T.registerModel(function (pane) { });
module.exports = function(){ var options=arguments; return function*(next){ yield less(this.req, this.res, options); yield next; }; }; function less(req, res, options){ return function(callback){ require('less-middleware').apply(this, options)(req, res, callback); }; }
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; jest.dontMock('../src'); var React = require('../src'); var ReactDOM = require('../src'); var ReactTestUtils = { renderIntoDocument: function(instance) { var div = document.createElement('div'); return ReactDOM.render(instance, div); } }; describe('Render Select with multiple values', function() { class Component extends React.Component { constructor(props, context) { super(props, context); this.state = {selectedValue: [1,3,4]}; } render() { return <div> <select value={this.state.selectedValue} ref="selectNode" id="selectNode" multiple> <option value={1}>1</option> <option value={2}>2</option> <option value={3}>3</option> <option value={4}>4</option> </select> {this.state.selectedValue} </div>; } } it('should mark correct option as selected', function() { var instance = ReactTestUtils.renderIntoDocument(<Component />); var root = ReactDOM.findDOMNode(instance); expect(root.childNodes[0].options[0].selected).toBe(true); expect(root.childNodes[0].options[1].selected).toBe(false); expect(root.childNodes[0].options[2].selected).toBe(true); expect(root.childNodes[0].options[3].selected).toBe(true); }); }); describe('Render Select with single value', function() { class Component extends React.Component { constructor(props, context) { super(props, context); this.state = {selectedValue: 2}; } render() { return <div> <select value={this.state.selectedValue} ref="selectNode" id="selectNode"> <option value={1}>1</option> <option value={2}>2</option> <option value={3}>3</option> <option value={4}>4</option> </select> {this.state.selectedValue} </div>; } } it('should mark correct option as selected', function() { var instance = ReactTestUtils.renderIntoDocument(<Component />); var root = ReactDOM.findDOMNode(instance); expect(root.childNodes[0].options[0].selected).toBe(false); expect(root.childNodes[0].options[1].selected).toBe(true); expect(root.childNodes[0].options[2].selected).toBe(false); expect(root.childNodes[0].options[3].selected).toBe(false); }); });
//////////////////////////////////////////////////////////////////////////////////// ////// Users //////////////////////////////////////////////////////////////////////////////////// 'use strict'; // DI var db, responseHandler; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.findAll = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); var errors = req.validationErrors(), appid; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; db.findAllUsers({'application_id': appid}, responseHandler(res, next)); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.findById = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('userid', '"userid": must be a valid identifier').notNull(); var errors = req.validationErrors(), appid, userid; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; userid = req.params.userid; db.findUserById({'application_id': appid, 'user_id': userid}, responseHandler(res, next)); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.findBadgesById = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('userid', '"userid": must be a valid identifier').notNull(); var errors = req.validationErrors(), appid, userid; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; userid = req.params.userid; db.findUserBadgesByUserId({'application_id': appid, 'user_id': userid}, responseHandler(res, next)); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.create = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('login', '"login": must be a valid string').notNull(); req.check('firstname', '"firstname": must be a valid string').notNull(); req.check('lastname', '"lastname": must be a valid string').notNull(); req.check('email', '"email": must be a valid Email adress').isEmail(); var errors = req.validationErrors(), appid, login, firstname, lastname, email; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; login = req.params.login; firstname = req.params.firstname; lastname = req.params.lastname; email = req.params.email; db.createUser( {'application_id': appid, 'login': login, 'firstname': firstname, 'lastname': lastname, 'email': email}, responseHandler(res, next) ); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.update = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('userid', '"userid": must be a valid identifier').notNull(); req.check('login', '"login": must be a valid string').notNull(); req.check('firstname', '"firstname": must be a valid string').notNull(); req.check('lastname', '"lastname": must be a valid string').notNull(); req.check('email', '"email": must be a valid Email adress').isEmail(); var errors = req.validationErrors(), appid, userid, login, firstname, lastname, email; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; userid = req.params.userid; login = req.params.login; firstname = req.params.firstname; lastname = req.params.lastname; email = req.params.email; db.updateUser( {'application_id': appid, 'user_id': userid, 'login': login, 'firstname': firstname, 'lastname': lastname, 'email': email}, responseHandler(res, next) ); }; /** * * @param req the HTTP requests, contains header and body parameters * @param res the callback to which send HTTP response * @param next facilitate restify function chaining */ exports.remove = function (req, res, next) { req.check('appid', '"appid": must be a valid identifier').notNull(); req.check('userid', '"userid": must be a valid identifier').notNull(); var errors = req.validationErrors(), appid, userid; if (errors) { responseHandler(res).error(400, errors); return; } appid = req.params.appid; userid = req.params.userid; db.deleteUser({'application_id': appid, 'user_id': userid}, responseHandler(res, next)); };
version https://git-lfs.github.com/spec/v1 oid sha256:c928791b0cde3d52edf0fffe39079fa656ef9c4ce1f16b7d4109a589e3e63740 size 6309
const path = require('path'); const webpack = require('webpack'); const UglifyJSPlugin = require('uglifyjs-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin'); const WebpackChunkHash = require('webpack-chunk-hash'); const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin'); const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin'); const plugins = [ new webpack.SourceMapDevToolPlugin(), // https://webpack.js.org/plugins/commons-chunk-plugin/ new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: function(module){ // @todo: do we want to include/exclude vendor CSS? if(module.resource && (/^.*\.(css|scss)$/).test(module.resource)) { return false; } return module.context && module.context.indexOf('node_modules') !== -1; }, }), new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity, // @todo: review }), new webpack.HashedModuleIdsPlugin(), new WebpackChunkHash(), new ChunkManifestPlugin({ filename: 'chunk-manifest.json', manifestVariable: 'webpackManifest', // inlineManifest: true, }), // https://github.com/jantimon/html-webpack-plugin new HtmlWebpackPlugin({ title: 'Demo Page', chunksSortMode: 'dependency', }), // https://github.com/numical/script-ext-html-webpack-plugin new ScriptExtHtmlWebpackPlugin({ sync: [ // @todo: figure out async vendor file D: /manifest\..*\.js$/, /vendor\..*\.js$/, /main\..*\.js$/, ], defaultAttribute: 'async', }), new HtmlWebpackHarddiskPlugin({ outputPath: path.resolve(__dirname, 'views'), }), ]; if (process.env.NODE_ENV === 'production') { plugins.push( new UglifyJSPlugin() ); } module.exports = { plugins, module: { rules: [ { include: [ /\/src\//, /\.js$/, ], loaders: [ 'babel-loader' ], }, { test: /\.(ico|eot|woff|woff2|ttf|svg|png|jpg)(\?.*)?$/, loaders: ['file-loader?name=[name].[ext]'], }, { test: /\.css$/, loaders: [ 'postcss-loader' ], }, { include: /\.tpl\.(pug|jade)$/, loaders: [ 'pug-loader' ], }, { include: /index\.(pug|jade)$/, loaders: [ 'file-loader?name=[name].html', 'extract-loader', 'html-loader', 'pug-html-loader?exports=false', ], }, { test: /index\.scss$/, loaders: [ 'file-loader?name=[name].css', 'postcss-loader', 'sass-loader', ], }, { test: /\.(sass|scss)$/, exclude: /index\.scss$/, loaders: [ 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader' ], }, { test: /allTest.js$/, loaders: ['mocha-loader'], }, ], }, context: path.resolve(process.cwd(), 'src'), entry: { app: [ './index.scss', './main.js', ], }, output: { filename: process.env.NODE_ENV === 'production' ? '[name].[chunkhash].bundle.js' : '[name].bundle.js', path: path.resolve(process.cwd(), 'bin'), }, };
module.exports = obj => new Promise((resolve, reject) => { if (typeof obj.email === "undefined") { const err = new Error("missingProperty"); err.details = { properties: { property: "email" } }; return reject(err); } else if (obj.email.indexOf("@") === -1) { const err = new Error("invalidProperty"); err.details = { properties: { property: "email" } }; return reject(err); } return resolve(true); });
version https://git-lfs.github.com/spec/v1 oid sha256:37d8a664534623015724da95816467e08fd4b8c2a24ff286d5705cf08d1e0b47 size 8106
const {app, BrowserWindow} = require("electron"); const path = require("path"); const url = require("url"); let win; function createWindow() { win = new BrowserWindow({ width: 800, height: 600 }); win.loadURL(url.format({ pathname: path.join(__dirname, "index.html"), protocol: "file:", slashes: true })); win.eval = global.eval = function() { throw new Error("eval() is overridden for security reasons."); } // win.webContents.openDevTools(); win.on("closed", () => { win = null; }); }; app.on("ready", createWindow); app.on("window-all-closed", () => { if (process.platform !== "darwin") { app.quit(); } }); app.on("activate", () => { if (win === null) { createWindow(); } });
const testEndpoint = require('./testEndpoint') const endpoints = require('./endpoints') async function runTests () { console.log('='.repeat(50)) console.log(`> Testing ${endpoints.length} API endpoints (${new Date().toISOString()})`) let results = [] for (let i = 0; i !== endpoints.length; i++) { results.push(await testEndpoint(endpoints[i])) } let possiblyBroken = results.filter(x => x.schemaValid === false) let definitelyBroken = results.filter(x => x.status >= 400) if (definitelyBroken.length > 0) { console.log(`❗ ERROR: ${definitelyBroken.length} API endpoint(s)`) } if (possiblyBroken.length > 0) { console.log(`⚠️ WARNING: ${possiblyBroken.length} API endpoint(s)`) } console.log(`✔️ OK: ${results.length - possiblyBroken.length - definitelyBroken.length} API endpoint(s)`) console.log('='.repeat(50)) console.log() return results } module.exports = runTests
(function(global) { // map tells the System loader where to look for things var map = { 'app': 'dist', // 'dist', 'rxjs': 'node_modules/rxjs', 'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api', '@angular': 'node_modules/@angular' }; // packages tells the System loader how to load when no filename and/or no extension var packages = { 'app': { main: 'main.js', defaultExtension: 'js' }, 'rxjs': { defaultExtension: 'js' }, 'angular2-in-memory-web-api': { defaultExtension: 'js' }, }; var packageNames = [ '@angular/common', '@angular/compiler', '@angular/core', '@angular/http', '@angular/platform-browser', '@angular/platform-browser-dynamic', '@angular/router', '@angular/router-deprecated', '@angular/testing', '@angular/upgrade', ]; // add package entries for angular packages in the form '@angular/common': { main: 'index.js', defaultExtension: 'js' } packageNames.forEach(function(pkgName) { packages[pkgName] = { main: 'index.js', defaultExtension: 'js' }; }); var config = { map: map, packages: packages } // filterSystemConfig - index.html's chance to modify config before we register it. if (global.filterSystemConfig) { global.filterSystemConfig(config); } System.config(config); })(this);
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M8 10.25c0 .41-.34.75-.75.75-.33 0-.6-.21-.71-.5H4.5v3h2.04c.1-.29.38-.5.71-.5.41 0 .75.34.75.75V14c0 .55-.45 1-1 1H4c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v.25zm5.04.25c.1.29.38.5.71.5.41 0 .75-.34.75-.75V10c0-.55-.45-1-1-1h-3c-.55 0-1 .45-1 1v1.5c0 .55.45 1 1 1H13v1h-2.04c-.1-.29-.38-.5-.71-.5-.41 0-.75.34-.75.75V14c0 .55.45 1 1 1h3c.55 0 1-.45 1-1v-1.5c0-.55-.45-1-1-1H11v-1h2.04zm6.5 0c.1.29.38.5.71.5.41 0 .75-.34.75-.75V10c0-.55-.45-1-1-1h-3c-.55 0-1 .45-1 1v1.5c0 .55.45 1 1 1h2.5v1h-2.04c-.1-.29-.38-.5-.71-.5-.41 0-.75.34-.75.75V14c0 .55.45 1 1 1h3c.55 0 1-.45 1-1v-1.5c0-.55-.45-1-1-1h-2.5v-1h2.04z" }), 'CssRounded');
/* eslint-disable no-unused-vars */ import coreJs from 'core-js'; import fetch from 'whatwg-fetch';
// this class creates our EnemyBaseEntity, which is our enemys tower, on the playscreen; game.EnemyBaseEntity = me.Entity.extend({ init : function(x, y, settings){ this._super(me.Entity, 'init', [x, y, { image: "tower", width: 100, height: 100, spritewidth: "100", spriteheight: "100", getShape: function(){ return (new me.Rect(0, 0, 100, 70)).toPolygon(); } }]); // says tower hasnt been destroyed this.broken = false; this.health = game.data.enemyBaseHealth; this.alwaysUpdate = true; this.body.onCollision = this.onCollision.bind(this); this.type = "EnemyBaseEntity"; // animation for when tower has full health this.renderable.addAnimation("idle", [0]); //animation when tower is broken this.renderable.addAnimation("broken", [1]); // animation tower starts with this.renderable.setCurrentAnimation("idle"); }, update: function(delta){ // if statement checks our is less than 0 and if we r declared dead if (this.health<=0) { this.broken = true; game.data.win =true; this.renderable.setCurrentAnimation("broken"); }; this.body.update(delta); this._super(me.Entity, "update", [delta]); return true; }, onCollision: function(){ }, loseHealth: function(){ this.health--; } });
const AuthorizationService = require('../../oauth/authorization-service').AuthorizationService; const BaseController = require('./base-controller'); const Promise = require('bluebird'); const code = "code"; const guid = require('../../tools/guid').guid; const errors = require('../../tools/errors'); const messages = require('../../oauth/messages').Messages; /** * Authorization API Controller * * @class AuthorizationController * @extends {BaseController} */ class AuthorizationController extends BaseController { /** * Creates an instance of AuthorizationController. * * * @memberOf AuthorizationController */ constructor() { super(); this.authorizationService = new AuthorizationService(); /** * Process get action on controller * * @param {any} req request content * @param {any} res response object * * @returns {undefined} * * @memberOf AuthorizationController */ this.get = (req, res) => { this.setJwtFromRequest(req, res) .then(() => { const requestPayload = { "response_type": req.swagger.params.response_type ? req.swagger.params.response_type.value : null, "client_id": req.swagger.params.client_id ? req.swagger.params.client_id.value : null, "state": req.swagger.params.state ? req.swagger.params.state.value : null, "redirect_uri": req.swagger.params.redirect_uri ? req.swagger.params.redirect_uri.value : null, "scope": req.swagger.params.scope ? req.swagger.params.scope.value : null }; if (requestPayload.response_type === code) { return this.codeFlow(req, res, requestPayload) .catch((error) => { if (error instanceof errors.ApplicationError) { // const redirectUrl = `${requestPayload.redirect_uri}?error=${error.message}&state=${requestPayload.state}`; // return this.sendRedirect(req, res, redirectUrl); return this.sendBadRequest(req, res, error.message); } return this.sendInternalServerError(req, res, error.message); }); } return this.sendBadRequest(req, res, messages.INVALID_RESPONSE_TYPE); }) .catch((error) => { return this.sendBadRequest(req, res, error.message); }); }; /** * Process code flow * * @param {any} req request content * @param {any} res response object * @param {any} requestPayload request payload * @returns {undefined} * * @memberOf AuthorizationController */ this.codeFlow = (req, res, requestPayload) => { const signinUrl = `${process.env.APPSETTING_APP_SIGN_IN_URL}?response_type=${requestPayload.response_type}&redirect_url=${requestPayload.redirect_uri}&client_id=${requestPayload.client_id}&scope=${requestPayload.scope}&state=${requestPayload.state}`; return this.authorizationService.clientAuthorizationRequestIsValid(requestPayload.client_id, requestPayload.redirect_uri, requestPayload.scope) .then((client) => { if (req.jwt) { return this.authorizationService.findAccount(req.jwt.body.sub) .then((account) => { if (account.hasApp(requestPayload.client_id)) { return this.authorizationService.getAuthorizationCode(req.token, client.redirectUrl, client.applicationKey) .then((authCode) => { const redirectUrl = `${requestPayload.redirect_uri}?authorization_code=${authCode}&state=${requestPayload.state}`; return this.sendRedirect(req, res, redirectUrl); }); } return this.sendRedirect(req, res, `${signinUrl}&signin_error=${messages.NO_CLIENT}`); }); } return this.sendRedirect(req, res, signinUrl); }); }; } } module.exports = new AuthorizationController();
invoker.print("Hello, invoker!");
'use strict'; /** * Offline Search Result contains the result of performing a scan of all the project layer files. */ var CsServerComp; (function (CsServerComp) { var Greeter = (function () { function Greeter() { } Greeter.prototype.sayHello = function () { return "Hello"; }; return Greeter; })(); CsServerComp.Greeter = Greeter; })(CsServerComp || (CsServerComp = {}));
module.exports = { INIT: 'init', STEP: 'step', // Bodies. ADD_BODY: 'add-body', REMOVE_BODY: 'remove-body', APPLY_BODY_METHOD: 'apply-body-method', UPDATE_BODY_PROPERTIES: 'update-body-properties', // Materials. ADD_MATERIAL: 'add-material', ADD_CONTACT_MATERIAL: 'add-contact-material', // Constraints. ADD_CONSTRAINT: 'add-constraint', REMOVE_CONSTRAINT: 'remove-constraint', // Events. COLLIDE: 'collide' };
import 'todomvc-app-css/index.css'; import React from 'react'; import ReactDOM from 'react-dom'; import { AppContainer } from 'react-hot-loader'; import configureStore from './store/configureStore'; import Root from './containers/Root'; const store = configureStore(); const rootEl = document.getElementById('root'); const render = () => { ReactDOM.render( <AppContainer> <Root store={store} /> </AppContainer>, rootEl ); }; render(Root); if (module.hot) { module.hot.accept('./containers/Root', render); }
/// <reference path="E:\Dropbox\Telerik Academy\5.JavaScript\2.JavaScript UI & DOM\2.Homework\10.jQuery-Plugins\10.jQuery-Plugins\libs/jquery-2.1.1.min.js" /> (function ($) { 'use strict' // I'm not sure I understood the task $.fn.makeDropdownList = function () { var $this = $(this); $this.css('display', 'none'); var $divContainer = $('<div />') .addClass('dropdown-list-container'); var $ul = $('<ul />') .addClass('dropdown-list-options') .css('list-style-type', 'none'); var $li = $('<li />') .addClass('dropdown-list-option') .css('width', '100px'); var $options = $this.find('option'); for (var i = 0, l = $options.length; i < l; i++) { var $currentOption = $($options[i]), $currentLi = $li.clone(true); $currentLi.css('display', 'none'); // Set first item as selected if (i === 0) { setSelectedCssAndClass($currentLi); $currentOption.attr('selected', 'selected'); } $currentLi.attr('data-value', i) .html($currentOption.html()) .css('border', '1px solid black'); $ul.append($currentLi); } $divContainer.append($ul); $this.after($divContainer); var isDivSlideDown = false; $divContainer.on('click', function (e) { var $that = $(e.target), $liOptions = $('.dropdown-list-option'); $('.dropdown-list-option').on('mouseover', function () { $(this).css('background-color', 'red'); }); $('.dropdown-list-option').on('mouseout', function () { $(this).css('background-color', 'white'); }); if (isDivSlideDown === false) { $liOptions.css('display', 'block'); } else { $liOptions.css('display', 'none'); $('.selected').removeClass('selected'); setSelectedCssAndClass($that); var curItemIndex = $that.attr('data-value'); $this.find(':selected').removeAttr('selected'); $($options[curItemIndex]).attr('selected', 'selected'); } isDivSlideDown = !isDivSlideDown; }); function setSelectedCssAndClass($selected) { $selected.addClass('selected') .css('display', 'block') //.css('border', '1px solid black'); } }; }(jQuery));
var Type = require("@kaoscript/runtime").Type; module.exports = function() { function foobar(__ks_class_1, __ks_default_1) { if(arguments.length < 1) { throw new SyntaxError("Wrong number of arguments (" + arguments.length + " for 1)"); } if(__ks_class_1 === void 0) { __ks_class_1 = null; } if(__ks_default_1 === void 0 || __ks_default_1 === null) { __ks_default_1 = 0; } else if(!Type.isNumber(__ks_default_1)) { throw new TypeError("'default' is not of type 'Number'"); } console.log(__ks_class_1, __ks_default_1); } };
const path = require('path'); const rrequire = /require\(\s*?(['"])(.+?)\1\s*?\)/g; const rexportsmodule = /\b(exports|module)\b/g; const rdefine = /^(define\(\s*)((?:\[.+\]\s*,\s*)?function\b)/m; const rdefineWithId = /^define\(\s*(['"]).+?\1\s*,\s*(?:\[.+\]\s*,\s*)?function\b/m; const rclosurewrapper = /^\(\s*function\b/m; const defaultConfig = { type: 'amd', idprefix: '', loadfunction: 'require', trimleading: 'src|dist' }; let wrapModular = function (filePath, fileContent, repoConfig) { let moduleConfig = Object.assign(defaultConfig, repoConfig.modular); if (rclosurewrapper.test(fileContent) || rdefineWithId.test(fileContent) || new RegExp(`^${moduleConfig.loadfunction}\\(`, 'm').test(fileContent)) { return fileContent; } let moduleId = filePath.slice(0, -path.extname(filePath).length).replace(new RegExp('^(?:' + moduleConfig.trimleading + ')/'), ''); if (moduleConfig.idprefix) { moduleId = moduleConfig.idprefix + '/' + moduleId; } let parseDependencies = true; fileContent = fileContent.replace(rdefine, function (str, p1, p2) { parseDependencies = false; return p1 + moduleId + ', ' + p2; }); if (parseDependencies) { let moduleIds = [], moduleExports = []; let require; while (require = rrequire.exec(fileContent)) {//eslint-disable-line moduleIds.push(require[2]); } if (moduleIds.length > 0) { if (moduleConfig.type === 'amd') { moduleIds.push('require'); } moduleExports.push('require'); } let exportsmodule = fileContent.match(rexportsmodule); if (exportsmodule) { exportsmodule = Array.from(new Set(exportsmodule)).sort(); if (moduleConfig.type === 'amd') { moduleIds.push(...exportsmodule); } moduleExports.push(...exportsmodule); } if (moduleIds.length > 0) { fileContent = `define('${moduleId}', ['${moduleIds.join("','")}'], function(${moduleExports.join(",")}) {\n${fileContent}\n});`; } else { fileContent = `define('${moduleId}', function() {\n${fileContent}\n});`; } } return fileContent; }; module.exports = function (file, callback) { let filedata = wrapModular(file.get('filename'), file.get('filedata'), file.get('config')); file.set('filedata', filedata); callback(); };
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is nsINarwhal. * * The Initial Developer of the Original Code is * Irakli Gozalishvili <rfobic@gmail.com>. * Portions created by the Initial Developer are Copyright (C) 2009 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Irakli Gozalishvili <rfobic@gmail.com> * Atul Varma <atul@mozilla.com> * Drew Willcoxon <adw@mozilla.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ const {Cc,Ci,Cr} = require("chrome"); const byteStreams = require("byte-streams"); const textStreams = require("text-streams"); // Flags passed when opening a file. See nsprpub/pr/include/prio.h. const OPEN_FLAGS = { RDONLY: 0x01, WRONLY: 0x02, CREATE_FILE: 0x08, APPEND: 0x10, TRUNCATE: 0x20, EXCL: 0x80 }; var dirsvc = Cc["@mozilla.org/file/directory_service;1"] .getService(Ci.nsIProperties); function MozFile(path) { var file = Cc['@mozilla.org/file/local;1'] .createInstance(Ci.nsILocalFile); file.initWithPath(path); return file; } function ensureReadable(file) { if (!file.isReadable()) throw new Error("path is not readable: " + file.path); } function ensureDir(file) { ensureExists(file); if (!file.isDirectory()) throw new Error("path is not a directory: " + file.path); } function ensureFile(file) { ensureExists(file); if (!file.isFile()) throw new Error("path is not a file: " + file.path); } function ensureExists(file) { if (!file.exists()) throw friendlyError(Cr.NS_ERROR_FILE_NOT_FOUND, file.path); } function friendlyError(errOrResult, filename) { var isResult = typeof(errOrResult) === "number"; var result = isResult ? errOrResult : errOrResult.result; switch (result) { case Cr.NS_ERROR_FILE_NOT_FOUND: return new Error("path does not exist: " + filename); } return isResult ? new Error("XPCOM error code: " + errOrResult) : errOrResult; } exports.exists = function exists(filename) { return MozFile(filename).exists(); }; exports.isFile = function isFile(filename) { return MozFile(filename).isFile(); }; exports.read = function read(filename, mode) { if (typeof(mode) !== "string") mode = ""; // Ensure mode is read-only. mode = /b/.test(mode) ? "b" : ""; var stream = exports.open(filename, mode); try { var str = stream.read(); } finally { stream.close(); } return str; }; exports.join = function join(base) { if (arguments.length < 2) throw new Error("need at least 2 args"); base = MozFile(base); for (var i = 1; i < arguments.length; i++) base.append(arguments[i]); return base.path; }; exports.dirname = function dirname(path) { var parent = MozFile(path).parent; return parent ? parent.path : ""; }; exports.basename = function basename(path) { var leafName = MozFile(path).leafName; // On Windows, leafName when the path is a volume letter and colon ("c:") is // the path itself. But such a path has no basename, so we want the empty // string. return leafName == path ? "" : leafName; }; exports.list = function list(path) { var file = MozFile(path); ensureDir(file); ensureReadable(file); var entries = file.directoryEntries; var entryNames = []; while(entries.hasMoreElements()) { var entry = entries.getNext(); entry.QueryInterface(Ci.nsIFile); entryNames.push(entry.leafName); } return entryNames; }; exports.open = function open(filename, mode) { var file = MozFile(filename); if (typeof(mode) !== "string") mode = ""; // File opened for write only. if (/w/.test(mode)) { if (file.exists()) ensureFile(file); var stream = Cc['@mozilla.org/network/file-output-stream;1']. createInstance(Ci.nsIFileOutputStream); var openFlags = OPEN_FLAGS.WRONLY | OPEN_FLAGS.CREATE_FILE | OPEN_FLAGS.TRUNCATE; var permFlags = 0644; // u+rw go+r try { stream.init(file, openFlags, permFlags, 0); } catch (err) { throw friendlyError(err, filename); } return /b/.test(mode) ? new byteStreams.ByteWriter(stream) : new textStreams.TextWriter(stream); } // File opened for read only, the default. ensureFile(file); stream = Cc['@mozilla.org/network/file-input-stream;1']. createInstance(Ci.nsIFileInputStream); try { stream.init(file, OPEN_FLAGS.RDONLY, 0, 0); } catch (err) { throw friendlyError(err, filename); } return /b/.test(mode) ? new byteStreams.ByteReader(stream) : new textStreams.TextReader(stream); }; exports.remove = function remove(path) { var file = MozFile(path); ensureFile(file); file.remove(false); }; exports.mkpath = function mkpath(path) { var file = MozFile(path); if (!file.exists()) file.create(Ci.nsIFile.DIRECTORY_TYPE, 0755); // u+rwx go+rx else if (!file.isDirectory()) throw new Error("The path already exists and is not a directory: " + path); }; exports.rmdir = function rmdir(path) { var file = MozFile(path); ensureDir(file); try { file.remove(false); } catch (err) { // Bug 566950 explains why we're not catching a specific exception here. throw new Error("The directory is not empty: " + path); } };
// Devices module.exports.mouse = require('./devices/mouse.js'); module.exports.keyboard = require('./devices/keyboard.js'); module.exports.tactile = require('./devices/tactile.js'); module.exports.pointers = require('./devices/pointers.js'); // UI module.exports.focus = require('./ui/focus.js'); // DSL module.exports.element = require('./dsl/element.js'); module.exports.input = require('./dsl/input.js');
'use strict'; /** * @ngdoc function * @name jkefWebApp.controller:AcceptorListCtrl * @description * # AcceptorListCtrl * Controller of the jkefWebApp */ angular.module('jkefWebApp') .controller('AcceptorListCtrl', function (auth, $scope, $rootScope, acceptor) { $rootScope.manage = true; // 自动登录 var autoSignIn = function () { // 生成登录按钮链接 auth.getAuthorizeUrl().then(function (data) { window.location = data; }, function (err) { alert(err.msg); }); } if($rootScope.promises.getMe) $rootScope.promises.getMe.then(function (me) { acceptor.list(function (acceptors) { $scope.acceptors = acceptors; }, function (err) { alert(err); }); }, function (err) { // 如果用户未登录,自动使用微信登录 if(err.ret === -2){ autoSignIn(); } }); else autoSignIn(); });
// Write a script that compares two char arrays lexicographically (letter by letter). var firstString = "adaneokdarazdakhiq"; var secondString = "adanefxajixakdadka"; var firstArray = firstString.split(''); var secondArray = secondString.split(''); var areEqual = false; if (firstArray.length === secondArray.length) { for (var i = 0; i < firstArray.length; i++) { if (firstArray[i] == secondArray[i]) { areEqual = true; continue; } else if (firstArray[i] < secondArray[i]) { console.log("First array is lexicographically first"); areEqual = false; break; } else { console.log("Second array is lexicographically first"); areEqual = false; break; } } if (areEqual == true) { console.log("Both arrays are lexicographically equal"); } } else { if (firstArray.length > secondArray.length) { console.log("Second array is lexicographically first"); } else { console.log("First array is lexicographically first"); } }
import forSelect from "../utils/for-select"; import h from "../utils/html"; export default function (node = document.body) { forSelect(node, ".box-header-groups", node => { if (node.textContent.replace(/^\s+|\s+$/g, '') === "Groups") { node.appendChild(h("a.box-header-right", { target: "_blank", href: "https://davidmz.me/frfrfr/all-groups/" }, "Show all")); } }); }
module.exports = function(grunt) { grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), copy: { main: { files: [{ src: 'bower_components/jquery/jquery.js', dest: 'public/js/jquery.js' }, { src: 'bower_components/lodash/dist/lodash.compat.js', dest: 'public/js/lodash.compat.js' }, { src: 'bower_components/backbone/backbone.js', dest: 'public/js/backbone.js' }, { src: 'bower_components/backbone.paginator/dist/backbone.paginator.js', dest: 'public/js/backbone.paginator.js' }, { src: 'bower_components/backbone.marionette/lib/backbone.marionette.js', dest: 'public/js/backbone.marionette.js' }] } } }); grunt.loadNpmTasks('grunt-contrib-copy'); grunt.registerTask('default', ['copy']); };
'use strict'; /** * Module dependencies. */ var should = require('chai').should(); /** * Test helpers */ var rewire = require('rewire'); var httpMocks = require('node-mocks-http'); var fs = require('fs'); var request = require('supertest'); /* jshint ignore:start */ var sinon = require('sinon'); /* jshint ignore:end */ /** * Module under test */ var controller; /** * Helper modules */ var config = require('../../../config/config'); var path = require('path'); /** * Globals */ var req, res; /** * Unit tests */ describe('Trial Controller', function() { before(function() { request = request('localhost:' + config.port); }); beforeEach(function() { controller = rewire('../../controllers/trial.server.controller'); req = httpMocks.createRequest(); res = httpMocks.createResponse(); }); describe('create()', function() { it('should require metadata', function() { controller.create(req, res); var data = JSON.parse(res._getData()); res.statusCode.should.equal(500); data.error.should.equal('No metadata.session_number property' + ' found.'); data.request_body.should.eql({}); }); it('should require a session number', function() { req.body = { metadata: {} }; controller.create(req, res); var data = JSON.parse(res._getData()); res.statusCode.should.equal(500); data.error.should.equal('No metadata.session_number property' + ' found.'); data.request_body.should.eql({ metadata: {} }); }); it('should require the session number to be a string', function() { req.body = { metadata: { session_number: 14 } }; controller.create(req, res); var data = JSON.parse(res._getData()); res.statusCode.should.equal(500); data.error.should.equal('No metadata.session_number property' + ' found.'); data.request_body.should.eql({ metadata: { session_number: 14 } }); }); it('should return a JSON error if there was an error while writing' + ' the file', function() { // Create body req.body = { metadata: { session_number: 'B42' } }; // Mock fs.writeFile() var errorMessage = 'Error in writeFile()'; var revert = controller.__set__('fs.writeFile', function(path, data, callback) { callback(new Error(errorMessage)); }); // Fire the request controller.create(req, res); // Check expectations res.statusCode.should.equal(500); var data = JSON.parse(res._getData()); console.log(data); data.error.should.equal(errorMessage); // Revert changes to controller revert(); }); it('should return JSON success if the write was successful', function(done) { // I don't think Travis allows us to write files if (process.env.NODE_ENV === 'travis') { return done(); } else { var filePath = path.resolve(__dirname, '../../../trials', 'B42.trial.json'); var reqJSON = {metadata: {session_number: 'B42'}}; //noinspection JSUnresolvedFunction request.post('/api/trials') .send(reqJSON) .end(function(err, response) { response.headers['content-type'].should.match(/application\/json/); response.statusCode.should.equal(200); fs.unlink(filePath, done); }); } }); it('should write the stringified body to the correct location', function(done) { // I don't think Travis allows us to write files if (process.env.NODE_ENV === 'travis') { return done(); } else { var filePath = path.resolve(__dirname, '../../../trials', 'B42.trial.json'); var reqJSON = {metadata: {session_number: 'B42'}}; //noinspection JSUnresolvedFunction request.post('/api/trials') .send(reqJSON) .end(function() { //noinspection JSUnresolvedFunction var contents = fs.readFileSync(filePath); var contentsJSON = JSON.parse(contents.toString()); contentsJSON.should.eql(reqJSON); fs.unlink(filePath, done); }); } }); }); });
$('.info dd').each(function() { $(this).css({width: $(this).text()+'%'}); });
var qsocks = require('qsocks'); var Promise = require('bluebird'); /** * Manages object removal in a blueprint. * Sheets & stories are refreshed on sync so no need to manage individual item removal. * * @param {Object} app qsocks app connection * @param {Object} blueprint Blueprint definition * @returns {Object} Returns Promise */ function removeBlueprintItems(childId, blueprintId, config) { config.appname = childId; var $ = {}; return qsocks.Connect(config).then(function(global) { return $.global = global; }).then(function(global) { return $.global.openDoc(childId, '', '', '', true) }) .then(function(app) { return $.app = app; }) .then(function() { return $.app.getAllInfos().then(function(infos) { return infos.qInfos.filter(function(d) { return d.qId === 'BlueprintManagedItems' }) }) .then(function(o) { if (o.length === 0) { throw new Error('App has no blueprint items') } return $.app.getObject('BlueprintManagedItems'); }) .then(function(handle) { return handle.getLayout().then(function(layout) { if (!layout[blueprintId]) { throw new Error('App is not assoicated with blueprint ' + blueprintId) } return Promise.all(layout[blueprintId].map(function(d) { if(d.qType === 'measure') { return $.app.destroyMeasure(d.qId) } if(d.qType === 'dimension') { return $.app.destroyDimension(d.qId) } if(d.qType === 'snapshot') { return $.app.destroyBookmark(d.qId) } if(d.qType === 'variable') { return $.app.destroyVariableById(d.qId); } // Generic Obects return $.app.destroyObject(d.qId) })) .then(function() { return handle.getProperties().then(function(props) { delete props[blueprintId]; return handle.setProperties(props); }) }) }) }) .then(function() { return $.app.saveObjects(); }) }).then(function() { $.global.connection.ws.terminate() return $ = null; }) }; module.exports = removeBlueprintItems;
version https://git-lfs.github.com/spec/v1 oid sha256:dfc1fe00375ed86590b0f77f34f01f190460075e5672257913ac053d88e67568 size 32578
/* eslint-disable no-console */ import React, { Component, PropTypes as T } from 'react'; class CarouselNode { next; prev; el; constructor() { this.next = null; this.prev = null; this.el = null; } } /** * Carousel Container Component: Provide initial carousel components as * children, with the first component to be displayed provided as the first * child. * * @class Carousel * @extends {Component} * * @property {Object} state - Carousel component's state */ class Carousel extends Component { static propTypes = { children: T.arrayOf(T.node), style: T.object }; /** * Append node to DLL as new tail * @memberOf Carousel * * @static * @param {...JSX.Element} els - Carousel component's elements * @param {CarouselNode} h - Current 'Head' node of Carousel * @param {CarouselNode} t - Current 'Tail' node of Carousel * * @return {object} New 'head' and 'tail' node of Carousel */ static appendNode = (els, h, t) => { els.forEach(el => { const newNode = new CarouselNode(); newNode.el = el; if (h) { let curr = h; while (curr && curr.next) { curr = curr.next; } curr.next = newNode; newNode.prev = curr; t = newNode; } else { h = t = newNode; } }); return { head: h, tail: t }; }; constructor(props) { super(props); const { children: nodes } = props; this.state = { head: null, tail: null, curr: null, nodes: [...nodes] }; } /** * Called before the component is mounted to the DOM * * @return {void} * @memberOf Carousel */ componentWillMount() { const { head, tail, nodes } = this.state; const newState = Carousel.appendNode([...nodes], head, tail), { head: curr } = newState; this.setState(prev => ({ ...prev, ...newState, curr })); } /* Component Lifecycle Methods componentDidMount() { } componentWillReceiveProps(nextProps) { } */ shouldComponentUpdate(_, { curr: el, nodes: newNodes }) { const { curr: nEl, nodes } = this.state; return (el !== nEl || nodes.length !== newNodes.length); } /* componentWillUpdate(nextProps, nextState) { } componentDidUpdate(prevProps, prevState) { } componentWillUnmount() { } */ handleLeft = () => { this.setState(({ tail, curr, ...rest }) => ({ ...rest, tail, curr: curr.prev || tail })); }; handleRight = () => { this.setState(({ head, curr, ...rest }) => ({ ...rest, head, curr: curr.next || head })); }; render() { const { curr: displayElem } = this.state; const { style } = this.props; return ( <div style={style}> <button onClick={this.handleLeft}>{'<'}</button> <span style={{ alignSelf: 'center' }}> {displayElem && displayElem.el} </span> <button onClick={this.handleRight}>{'>'}</button> </div> ); } } export { Carousel };
module.exports.BaseCronJob = require('./lib/baseCronJob.js'); module.exports.CronJobManagerJob = require('./lib/cronJobManagerJob.js'); module.exports.CronJobExecutionModel = require('./lib/cronJobExecutionModel.js'); module.exports.CronJobHeartbeatModel = require('./lib/cronServerHeartbeatModel.js');
Clazz.declarePackage ("JS"); Clazz.load (null, "JS.MathExt", ["java.lang.Float", "$.Number", "java.util.Date", "$.Hashtable", "$.Random", "JU.AU", "$.BS", "$.CU", "$.Lst", "$.M4", "$.Measure", "$.P3", "$.P4", "$.PT", "$.Quat", "$.SB", "$.V3", "J.api.Interface", "J.atomdata.RadiusData", "J.bspt.Bspt", "J.c.VDW", "J.i18n.GT", "JM.BondSet", "JS.SV", "$.ScriptParam", "$.T", "JU.BSUtil", "$.Escape", "$.JmolMolecule", "$.Logger", "$.Parser", "$.Point3fi", "$.SimpleUnitCell", "JV.FileManager", "$.JC"], function () { c$ = Clazz.decorateAsClass (function () { this.vwr = null; this.e = null; this.rand = null; this.pm = null; Clazz.instantialize (this, arguments); }, JS, "MathExt"); Clazz.makeConstructor (c$, function () { }); Clazz.defineMethod (c$, "init", function (se) { this.e = se; this.vwr = this.e.vwr; return this; }, "~O"); Clazz.defineMethod (c$, "evaluate", function (mp, op, args, tok) { switch (tok) { case 134218250: case 134218242: case 134218245: case 134217749: case 134218244: case 134218246: return this.evaluateMath (mp, args, tok); case 1275069441: case 1275068928: case 1275068929: case 1275068930: case 1275068931: case 1275335685: case 1275334681: return this.evaluateList (mp, op.intValue, args); case 268435520: if (args.length == 0) mp.wasX = false; case 1275068418: return this.evaluateArray (mp, args, tok == 1275068418 && op.tok == 268435665); case 134217731: case 134221850: return this.evaluateQuaternion (mp, args, tok); case 1275068420: return this.evaluateBin (mp, args); case 134221829: return this.evaluateCache (mp, args); case 1275068934: case 1275068935: return this.evaluateRowCol (mp, args, tok); case 1765808134: return this.evaluateColor (mp, args); case 134221831: return this.evaluateCompare (mp, args); case 1228931587: case 134217736: case 1275203608: return this.evaluateConnected (mp, args, tok, op.intValue); case 1814695966: return this.evaluateUnitCell (mp, args, op.tok == 268435665); case 134353926: return this.evaluateContact (mp, args); case 134221834: return this.evaluateData (mp, args); case 1275069444: case 1275069442: return this.evaluateDotDist (mp, args, tok, op.intValue); case 1275069443: if (op.tok == 268435665) return this.evaluateDotDist (mp, args, tok, op.intValue); case 134217729: case 1745489939: return this.evaluateMeasure (mp, args, op.tok); case 1228935687: case 134222849: return this.evaluateLoad (mp, args, tok == 1228935687); case 1275068427: return this.evaluateFind (mp, args); case 1287653388: case 1825200146: return this.evaluateFormat (mp, op.intValue, args, tok == 1825200146); case 134320141: return this.evaluateUserFunction (mp, op.value, args, op.intValue, op.tok == 268435665); case 1275068449: case 1275082245: case 1275072526: return this.evaluateGetProperty (mp, args, tok, op.tok == 268435665); case 136314895: return this.evaluateHelix (mp, args); case 134219265: case 134217750: case 134219266: return this.evaluatePlane (mp, args, tok); case 134218759: case 134238732: case 134222850: case 134222350: return this.evaluateScript (mp, args, tok); case 1275069446: case 1275069447: case 1275068932: return this.evaluateString (mp, op.intValue, args); case 134217751: return this.evaluatePoint (mp, args); case 134217762: return this.evaluatePointGroup (mp, args); case 134256131: return this.evaluatePrompt (mp, args); case 134219268: return this.evaluateRandom (mp, args); case 1275068432: return this.evaluateIn (mp, args); case 1275072532: return this.evaluateModulation (mp, args); case 1275068443: return this.evaluateReplace (mp, args); case 134218756: case 134218757: case 1237320707: return this.evaluateSubstructure (mp, args, tok, op.tok == 268435665); case 1275068444: case 1275068425: return this.evaluateSort (mp, args, tok); case 1296041986: return this.evaluateSymop (mp, args, op.tok == 268435665); case 1275068445: return this.evaluateTensor (mp, args); case 134217759: return this.evaluateWithin (mp, args); case 134221856: return this.evaluateWrite (mp, args); } return false; }, "JS.ScriptMathProcessor,JS.T,~A,~N"); Clazz.defineMethod (c$, "evaluatePointGroup", function (mp, args) { var pts = null; var center = null; var distanceTolerance = NaN; var linearTolerance = NaN; var bsAtoms; switch (args.length) { case 4: linearTolerance = args[3].asFloat (); case 3: distanceTolerance = args[2].asFloat (); case 2: switch (args[1].tok) { case 8: center = JS.SV.ptValue (args[1]); break; case 10: bsAtoms = JS.SV.getBitSet (args[1], false); var iatom = bsAtoms.nextSetBit (0); if (iatom < 0 || iatom >= this.vwr.ms.ac || bsAtoms.cardinality () != 1) return false; if (JS.SV.sValue (args[0]).equalsIgnoreCase ("spaceGroup")) { var lst = this.vwr.ms.generateCrystalClass (iatom, JU.P3.new3 (NaN, NaN, NaN)); pts = new Array (lst.size ()); for (var i = pts.length; --i >= 0; ) pts[i] = lst.get (i); center = new JU.P3 (); if (args.length == 2) distanceTolerance = 0; } else { center = this.vwr.ms.at[iatom]; }} if (pts != null) break; case 1: switch (args[0].tok) { case 7: var points = args[0].getList (); pts = new Array (points.size ()); for (var i = pts.length; --i >= 0; ) pts[i] = JS.SV.ptValue (points.get (i)); break; case 10: bsAtoms = JS.SV.getBitSet (args[0], false); var atoms = this.vwr.ms.getAtomPointVector (bsAtoms); pts = new Array (atoms.size ()); for (var i = pts.length; --i >= 0; ) pts[i] = atoms.get (i); break; default: return false; } break; default: return false; } var pointGroup = this.vwr.getSymTemp ().setPointGroup (null, center, pts, null, false, Float.isNaN (distanceTolerance) ? this.vwr.getFloat (570425382) : distanceTolerance, Float.isNaN (linearTolerance) ? this.vwr.getFloat (570425384) : linearTolerance, true); return mp.addXMap (pointGroup.getPointGroupInfo (-1, null, true, null, 0, 1)); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateUnitCell", function (mp, args, isSelector) { var x1 = (isSelector ? JS.SV.getBitSet (mp.getX (), true) : null); var iatom = ((x1 == null ? this.vwr.getAllAtoms () : x1).nextSetBit (0)); var lastParam = args.length - 1; var scale = 1; switch (lastParam < 0 ? 0 : args[lastParam].tok) { case 2: case 3: scale = args[lastParam].asFloat (); lastParam--; break; } var tok0 = (lastParam < 0 ? 0 : args[0].tok); var ucnew = null; var uc = null; switch (tok0) { case 7: uc = args[0].getList (); break; case 4: var s = args[0].asString (); if (s.indexOf ("a=") == 0) { ucnew = new Array (4); for (var i = 0; i < 4; i++) ucnew[i] = new JU.P3 (); JU.SimpleUnitCell.setOabc (s, null, ucnew); }break; } var u = null; var haveUC = (uc != null); if (ucnew == null && haveUC && uc.size () < 4) return false; var ptParam = (haveUC ? 1 : 0); if (ucnew == null && !haveUC && tok0 != 8) { u = (iatom < 0 ? null : this.vwr.ms.getUnitCell (this.vwr.ms.at[iatom].mi)); ucnew = (u == null ? Clazz.newArray (-1, [JU.P3.new3 (0, 0, 0), JU.P3.new3 (1, 0, 0), JU.P3.new3 (0, 1, 0), JU.P3.new3 (0, 0, 1)]) : u.getUnitCellVectors ()); }if (ucnew == null) { ucnew = new Array (4); if (haveUC) { switch (uc.size ()) { case 3: ucnew[0] = new JU.P3 (); for (var i = 0; i < 3; i++) ucnew[i + 1] = JU.P3.newP (JS.SV.ptValue (uc.get (i))); break; case 4: for (var i = 0; i < 4; i++) ucnew[i] = JU.P3.newP (JS.SV.ptValue (uc.get (i))); break; case 6: var params = Clazz.newFloatArray (6, 0); for (var i = 0; i < 6; i++) params[i] = uc.get (i).asFloat (); JU.SimpleUnitCell.setOabc (null, params, ucnew); break; default: return false; } } else { ucnew[0] = JS.SV.ptValue (args[0]); switch (lastParam) { case 3: for (var i = 1; i < 4; i++) (ucnew[i] = JU.P3.newP (JS.SV.ptValue (args[i]))).sub (ucnew[0]); break; case 1: var l = args[1].getList (); if (l != null && l.size () == 3) { for (var i = 0; i < 3; i++) ucnew[i + 1] = JS.SV.ptValue (l.get (i)); break; }default: return false; } }}var op = (ptParam <= lastParam ? args[ptParam].asString () : null); var toPrimitive = "primitive".equalsIgnoreCase (op); if (toPrimitive || "conventional".equalsIgnoreCase (op)) { var stype = (++ptParam > lastParam ? "" : args[ptParam].asString ().toUpperCase ()); if (stype.equals ("BCC")) stype = "I"; else if (stype.length == 0) stype = this.vwr.getSymTemp ().getSymmetryInfoAtom (this.vwr.ms, iatom, null, 0, null, null, null, 1073741994, 0, -1); if (stype == null || stype.length == 0 || !(u == null ? this.vwr.getSymTemp () : u).toFromPrimitive (toPrimitive, stype.charAt (0), ucnew)) return false; } else if ("reciprocal".equalsIgnoreCase (op)) { ucnew = JU.SimpleUnitCell.getReciprocal (ucnew, null, scale); scale = 1; }if (scale != 1) for (var i = 1; i < 4; i++) ucnew[i].scale (scale); return mp.addXObj (ucnew); }, "JS.ScriptMathProcessor,~A,~B"); Clazz.defineMethod (c$, "evaluateArray", function (mp, args, isSelector) { if (isSelector) { var x1 = mp.getX (); switch (args.length == 1 ? x1.tok : 0) { case 6: var lst = new JU.Lst (); var id = args[0].asString (); var map = x1.getMap (); var keys = x1.getKeys (false); for (var i = 0, n = keys.length; i < n; i++) if (map.get (keys[i]).getMap () == null) return false; for (var i = 0, n = keys.length; i < n; i++) { var m = map.get (keys[i]); var m1 = m.getMap (); var m2 = JS.SV.deepCopy (m1, true, false); m2.put (id, JS.SV.newS (keys[i])); lst.addLast (JS.SV.newV (6, m2)); } return mp.addXList (lst); case 7: var map1 = new java.util.Hashtable (); var lst1 = x1.getList (); var id1 = args[0].asString (); for (var i = 0, n = lst1.size (); i < n; i++) { var m0 = lst1.get (i).getMap (); if (m0 == null || m0.get (id1) == null) return false; } for (var i = 0, n = lst1.size (); i < n; i++) { var m = lst1.get (i); var m1 = JS.SV.deepCopy (m.getMap (), true, false); var mid = m1.remove (id1); map1.put (mid.asString (), JS.SV.newV (6, m1)); } return mp.addXObj (map1); } return false; }var a = new Array (args.length); for (var i = a.length; --i >= 0; ) a[i] = JS.SV.newT (args[i]); return mp.addXAV (a); }, "JS.ScriptMathProcessor,~A,~B"); Clazz.defineMethod (c$, "evaluateBin", function (mp, args) { var n = args.length; if (n < 3 || n > 5) return false; var x1 = mp.getX (); var isListf = (x1.tok == 13); if (!isListf && x1.tok != 7) return mp.addX (x1); var f0 = JS.SV.fValue (args[0]); var f1 = JS.SV.fValue (args[1]); var df = JS.SV.fValue (args[2]); var addBins = (n >= 4 && args[n - 1].tok == 1073742335); var key = ((n == 5 || n == 4 && !addBins) && args[3].tok != 1073742334 ? JS.SV.sValue (args[3]) : null); var data; var maps = null; if (isListf) { data = x1.value; } else { var list = x1.getList (); data = Clazz.newFloatArray (list.size (), 0); if (key != null) maps = JU.AU.createArrayOfHashtable (list.size ()); try { for (var i = list.size (); --i >= 0; ) data[i] = JS.SV.fValue (key == null ? list.get (i) : (maps[i] = list.get (i).getMap ()).get (key)); } catch (e) { if (Clazz.exceptionOf (e, Exception)) { return false; } else { throw e; } } }var nbins = Math.max (Clazz.doubleToInt (Math.floor ((f1 - f0) / df + 0.01)), 1); var array = Clazz.newIntArray (nbins, 0); var nPoints = data.length; for (var i = 0; i < nPoints; i++) { var v = data[i]; var bin = Clazz.doubleToInt (Math.floor ((v - f0) / df)); if (bin < 0 || bin >= nbins) continue; array[bin]++; if (key != null) { var map = maps[i]; if (map == null) continue; map.put ("_bin", JS.SV.newI (bin)); var v1 = f0 + df * bin; var v2 = v1 + df; map.put ("_binMin", JS.SV.newF (bin == 0 ? -3.4028235E38 : v1)); map.put ("_binMax", JS.SV.newF (bin == nbins - 1 ? 3.4028235E38 : v2)); }} if (addBins) { var lst = new JU.Lst (); for (var i = 0; i < nbins; i++) lst.addLast ( Clazz.newFloatArray (-1, [f0 + df * i, array[i]])); return mp.addXList (lst); }return mp.addXAI (array); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateCache", function (mp, args) { if (args.length > 0) return false; return mp.addXMap (this.vwr.fm.cacheList ()); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateColor", function (mp, args) { var colorScheme = (args.length > 0 ? JS.SV.sValue (args[0]) : ""); var isIsosurface = colorScheme.startsWith ("$"); if (args.length == 2 && colorScheme.equalsIgnoreCase ("TOHSL")) return mp.addXPt (JU.CU.rgbToHSL (JU.P3.newP (args[1].tok == 8 ? JS.SV.ptValue (args[1]) : JU.CU.colorPtFromString (args[1].asString ())), true)); if (args.length == 2 && colorScheme.equalsIgnoreCase ("TORGB")) { var pt = JU.P3.newP (args[1].tok == 8 ? JS.SV.ptValue (args[1]) : JU.CU.colorPtFromString (args[1].asString ())); return mp.addXPt (args[1].tok == 8 ? JU.CU.hslToRGB (pt) : pt); }if (args.length == 4 && (args[3].tok == 1073742335 || args[3].tok == 1073742334)) { var pt1 = JU.P3.newP (args[0].tok == 8 ? JS.SV.ptValue (args[0]) : JU.CU.colorPtFromString (args[0].asString ())); var pt2 = JU.P3.newP (args[1].tok == 8 ? JS.SV.ptValue (args[1]) : JU.CU.colorPtFromString (args[1].asString ())); var usingHSL = (args[3].tok == 1073742335); if (usingHSL) { pt1 = JU.CU.rgbToHSL (pt1, false); pt2 = JU.CU.rgbToHSL (pt2, false); }var sb = new JU.SB (); var vd = JU.V3.newVsub (pt2, pt1); var n = args[2].asInt (); if (n < 2) n = 20; vd.scale (1 / (n - 1)); for (var i = 0; i < n; i++) { sb.append (JU.Escape.escapeColor (JU.CU.colorPtToFFRGB (usingHSL ? JU.CU.hslToRGB (pt1) : pt1))); pt1.add (vd); } return mp.addXStr (sb.toString ()); }var ce = (isIsosurface ? null : this.vwr.cm.getColorEncoder (colorScheme)); if (!isIsosurface && ce == null) return mp.addXStr (""); var lo = (args.length > 1 ? JS.SV.fValue (args[1]) : 3.4028235E38); var hi = (args.length > 2 ? JS.SV.fValue (args[2]) : 3.4028235E38); var value = (args.length > 3 ? JS.SV.fValue (args[3]) : 3.4028235E38); var getValue = (value != 3.4028235E38 || lo != 3.4028235E38 && hi == 3.4028235E38); var haveRange = (hi != 3.4028235E38); if (!haveRange && colorScheme.length == 0) { value = lo; var range = this.vwr.getCurrentColorRange (); lo = range[0]; hi = range[1]; }if (isIsosurface) { var id = colorScheme.substring (1); var data = Clazz.newArray (-1, [id, null]); if (!this.vwr.shm.getShapePropertyData (24, "colorEncoder", data)) return mp.addXStr (""); ce = data[1]; } else { ce.setRange (lo, hi, lo > hi); }var key = ce.getColorKey (); if (getValue) return mp.addXPt (JU.CU.colorPtFromInt (ce.getArgb (hi == 3.4028235E38 ? lo : value), null)); return mp.addX (JS.SV.getVariableMap (key)); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateCompare", function (mp, args) { if (args.length < 2 || args.length > 5) return false; var stddev; var sOpt = JS.SV.sValue (args[args.length - 1]); var isStdDev = sOpt.equalsIgnoreCase ("stddev"); var isIsomer = sOpt.equalsIgnoreCase ("ISOMER"); var isBonds = sOpt.equalsIgnoreCase ("BONDS"); var isSmiles = (!isIsomer && args.length > (isStdDev ? 3 : 2)); var bs1 = (args[0].tok == 10 ? args[0].value : null); var bs2 = (args[1].tok == 10 ? args[1].value : null); var smiles1 = (bs1 == null ? JS.SV.sValue (args[0]) : ""); var smiles2 = (bs2 == null ? JS.SV.sValue (args[1]) : ""); var m = new JU.M4 (); stddev = NaN; var ptsA; var ptsB; try { if (isSmiles) { if (bs1 == null || bs2 == null) return false; }if (isBonds) { if (args.length != 4) return false; smiles1 = JS.SV.sValue (args[2]); isSmiles = smiles1.equalsIgnoreCase ("SMILES"); try { if (isSmiles) smiles1 = this.vwr.getSmiles (bs1); } catch (ex) { if (Clazz.exceptionOf (ex, Exception)) { this.e.evalError (ex.getMessage (), null); } else { throw ex; } } var data = this.e.getSmilesExt ().getFlexFitList (bs1, bs2, smiles1, !isSmiles); return (data == null ? mp.addXStr ("") : mp.addXAF (data)); }if (isIsomer) { if (args.length != 3) return false; if (bs1 == null && bs2 == null) return mp.addXStr (this.vwr.getSmilesMatcher ().getRelationship (smiles1, smiles2).toUpperCase ()); var mf1 = (bs1 == null ? this.vwr.getSmilesMatcher ().getMolecularFormula (smiles1, false) : JU.JmolMolecule.getMolecularFormulaAtoms (this.vwr.ms.at, bs1, null, false)); var mf2 = (bs2 == null ? this.vwr.getSmilesMatcher ().getMolecularFormula (smiles2, false) : JU.JmolMolecule.getMolecularFormulaAtoms (this.vwr.ms.at, bs2, null, false)); if (!mf1.equals (mf2)) return mp.addXStr ("NONE"); if (bs1 != null) smiles1 = this.e.getSmilesExt ().getSmilesMatches ("/strict///", null, bs1, null, 1, true, false); var check; if (bs2 == null) { check = (this.vwr.getSmilesMatcher ().areEqual (smiles2, smiles1) > 0); } else { smiles2 = this.e.getSmilesExt ().getSmilesMatches ("/strict///", null, bs2, null, 1, true, false); check = ((this.e.getSmilesExt ().getSmilesMatches ("/strict///" + smiles1, null, bs2, null, 1, true, false)).nextSetBit (0) >= 0); }if (!check) { var s = smiles1 + smiles2; if (s.indexOf ("/") >= 0 || s.indexOf ("\\") >= 0 || s.indexOf ("@") >= 0) { if (smiles1.indexOf ("@") >= 0 && (bs2 != null || smiles2.indexOf ("@") >= 0) && smiles1.indexOf ("@SP") < 0) { var pt = smiles1.toLowerCase ().indexOf ("invertstereo"); smiles1 = (pt >= 0 ? "/strict/" + smiles1.substring (0, pt) + smiles1.substring (pt + 12) : "/invertstereo strict/" + smiles1); if (bs2 == null) { check = (this.vwr.getSmilesMatcher ().areEqual (smiles1, smiles2) > 0); } else { check = ((this.e.getSmilesExt ().getSmilesMatches (smiles1, null, bs2, null, 1, true, false)).nextSetBit (0) >= 0); }if (check) return mp.addXStr ("ENANTIOMERS"); }if (bs2 == null) { check = (this.vwr.getSmilesMatcher ().areEqual ("/nostereo/" + smiles2, smiles1) > 0); } else { var ret = this.e.getSmilesExt ().getSmilesMatches ("/nostereo/" + smiles1, null, bs2, null, 1, true, false); check = ((ret).nextSetBit (0) >= 0); }if (check) return mp.addXStr ("DIASTEREOMERS"); }return mp.addXStr ("CONSTITUTIONAL ISOMERS"); }if (bs1 == null || bs2 == null) return mp.addXStr ("IDENTICAL"); stddev = this.e.getSmilesExt ().getSmilesCorrelation (bs1, bs2, smiles1, null, null, null, null, false, null, null, false, 1); return mp.addXStr (stddev < 0.2 ? "IDENTICAL" : "IDENTICAL or CONFORMATIONAL ISOMERS (RMSD=" + stddev + ")"); }if (isSmiles) { ptsA = new JU.Lst (); ptsB = new JU.Lst (); sOpt = JS.SV.sValue (args[2]); var isMap = sOpt.equalsIgnoreCase ("MAP"); isSmiles = sOpt.equalsIgnoreCase ("SMILES"); var isSearch = (isMap || sOpt.equalsIgnoreCase ("SMARTS")); if (isSmiles || isSearch) sOpt = (args.length > (isStdDev ? 4 : 3) ? JS.SV.sValue (args[3]) : null); var hMaps = (("H".equalsIgnoreCase (sOpt) || "allH".equalsIgnoreCase (sOpt) || "bestH".equalsIgnoreCase (sOpt))); var isPolyhedron = ("polyhedra".equalsIgnoreCase (sOpt)); if (isPolyhedron) sOpt = (args.length > (isStdDev ? 5 : 4) ? JS.SV.sValue (args[4]) : null); var allMaps = (("all".equalsIgnoreCase (sOpt) || "allH".equalsIgnoreCase (sOpt))); var bestMap = (("best".equalsIgnoreCase (sOpt) || "bestH".equalsIgnoreCase (sOpt))); if ("stddev".equals (sOpt)) sOpt = null; var pattern = sOpt; if (sOpt == null || hMaps || allMaps || bestMap) { if (!isMap && !isSmiles || hMaps && isPolyhedron) return false; pattern = "/noaromatic" + (allMaps || bestMap ? "/" : " nostereo/") + this.e.getSmilesExt ().getSmilesMatches ((hMaps ? "H" : ""), null, bs1, null, 1, true, false); } else { allMaps = true; }stddev = this.e.getSmilesExt ().getSmilesCorrelation (bs1, bs2, pattern, ptsA, ptsB, m, null, isMap, null, null, bestMap, (isSmiles ? 1 : 2) | (!allMaps && !bestMap ? 8 : 0)); if (isMap) { var nAtoms = ptsA.size (); if (nAtoms == 0) return mp.addXStr (""); var nMatch = Clazz.doubleToInt (ptsB.size () / nAtoms); var ret = new JU.Lst (); for (var i = 0, pt = 0; i < nMatch; i++) { var a = JU.AU.newInt2 (nAtoms); ret.addLast (a); for (var j = 0; j < nAtoms; j++, pt++) a[j] = Clazz.newIntArray (-1, [(ptsA.get (j)).i, (ptsB.get (pt)).i]); } return (allMaps ? mp.addXList (ret) : ret.size () > 0 ? mp.addXAII (ret.get (0)) : mp.addXStr ("")); }} else { switch (args.length) { case 2: break; case 3: if (isStdDev) break; default: return false; } ptsA = this.e.getPointVector (args[0], 0); ptsB = this.e.getPointVector (args[1], 0); if (ptsA != null && ptsB != null) { J.api.Interface.getInterface ("JU.Eigen", this.vwr, "script"); stddev = JU.Measure.getTransformMatrix4 (ptsA, ptsB, m, null); }}return (isStdDev || Float.isNaN (stddev) ? mp.addXFloat (stddev) : mp.addXM4 (m.round (1e-7))); } catch (ex) { if (Clazz.exceptionOf (ex, Exception)) { this.e.evalError (ex.getMessage () == null ? ex.toString () : ex.getMessage (), null); return false; } else { throw ex; } } }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateConnected", function (mp, args, tok, intValue) { if (args.length > 5) return false; var min = -2147483648; var max = 2147483647; var fmin = 0; var fmax = 3.4028235E38; var order = 65535; var atoms1 = null; var atoms2 = null; var haveDecimal = false; var isBonds = false; switch (tok) { case 1275203608: var nv = -2147483648; var smiles = null; if (args.length > 0) { switch (args[0].tok) { case 2: nv = args[0].intValue; break; case 4: smiles = JS.SV.sValue (args[0]); break; } }if (intValue == 1275203608) atoms1 = JS.SV.getBitSet (mp.getX (), true); var data = Clazz.newArray (-1, [Integer.$valueOf (nv), smiles, atoms1]); if (!this.vwr.shm.getShapePropertyData (21, "getCenters", data)) data[1] = null; return mp.addXBs (data[1] == null ? new JU.BS () : data[1]); case 1228931587: var x1 = mp.getX (); if (x1.tok != 10 || args.length != 1 || args[0].tok != 10) return false; atoms1 = x1.value; atoms2 = args[0].value; var list = new JU.Lst (); var atoms = this.vwr.ms.at; for (var i = atoms1.nextSetBit (0); i >= 0; i = atoms1.nextSetBit (i + 1)) { var n = 0; var b = atoms[i].bonds; for (var j = b.length; --j >= 0; ) if (atoms2.get (b[j].getOtherAtom (atoms[i]).i)) n++; list.addLast (Integer.$valueOf (n)); } return mp.addXList (list); } for (var i = 0; i < args.length; i++) { var $var = args[i]; switch ($var.tok) { case 10: isBonds = (Clazz.instanceOf ($var.value, JM.BondSet)); if (isBonds && atoms1 != null) return false; if (atoms1 == null) atoms1 = $var.value; else if (atoms2 == null) atoms2 = $var.value; else return false; break; case 4: var type = JS.SV.sValue ($var); if (type.equalsIgnoreCase ("hbond")) order = 30720; else order = JS.ScriptParam.getBondOrderFromString (type); if (order == 131071) return false; break; case 3: haveDecimal = true; default: var n = $var.asInt (); var f = $var.asFloat (); if (max != 2147483647) return false; if (min == -2147483648) { min = Math.max (n, 0); fmin = f; } else { max = n; fmax = f; }} } if (min == -2147483648) { min = 1; max = 100; fmin = 0.1; fmax = 1.0E8; } else if (max == 2147483647) { max = min; fmax = fmin; fmin = 0.1; }if (atoms1 == null) atoms1 = this.vwr.getAllAtoms (); if (haveDecimal && atoms2 == null) atoms2 = atoms1; if (atoms2 != null) { var bsBonds = new JU.BS (); this.vwr.makeConnections (fmin, fmax, order, 1086324745, atoms1, atoms2, bsBonds, isBonds, false, 0); return mp.addX (JS.SV.newV (10, JM.BondSet.newBS (bsBonds, this.vwr.ms.getAtomIndices (this.vwr.ms.getAtoms (1677721602, bsBonds))))); }return mp.addXBs (this.vwr.ms.getAtomsConnected (min, max, order, atoms1)); }, "JS.ScriptMathProcessor,~A,~N,~N"); Clazz.defineMethod (c$, "evaluateContact", function (mp, args) { if (args.length < 1 || args.length > 3) return false; var i = 0; var distance = 100; var tok = args[0].tok; switch (tok) { case 3: case 2: distance = JS.SV.fValue (args[i++]); break; case 10: break; default: return false; } if (i == args.length || !(Clazz.instanceOf (args[i].value, JU.BS))) return false; var bsA = JU.BSUtil.copy (args[i++].value); var bsB = (i < args.length ? JU.BSUtil.copy (args[i].value) : null); var rd = new J.atomdata.RadiusData (null, (distance > 10 ? distance / 100 : distance), (distance > 10 ? J.atomdata.RadiusData.EnumType.FACTOR : J.atomdata.RadiusData.EnumType.OFFSET), J.c.VDW.AUTO); bsB = this.setContactBitSets (bsA, bsB, true, NaN, rd, false); bsB.or (bsA); return mp.addXBs (bsB); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateData", function (mp, args) { var selected = (args.length == 0 ? "" : JS.SV.sValue (args[0])); var type = ""; switch (args.length) { case 0: case 1: break; case 2: case 3: if (args[0].tok == 10) return mp.addXStr (this.vwr.getModelFileData (selected, JS.SV.sValue (args[1]), args.length == 3 && JS.SV.bValue (args[2]))); break; case 4: var iField = args[1].asInt (); var nBytes = args[2].asInt (); var firstLine = args[3].asInt (); var f = JU.Parser.parseFloatArrayFromMatchAndField (JS.SV.sValue (args[0]), null, 0, 0, null, iField, nBytes, null, firstLine); return mp.addXStr (JU.Escape.escapeFloatA (f, false)); default: return false; } if (selected.indexOf ("data2d_") == 0) { var f1 = this.vwr.getDataObj (selected, null, 2); if (f1 == null) return mp.addXStr (""); if (args.length == 2 && args[1].tok == 2) { var pt = args[1].intValue; if (pt < 0) pt += f1.length; if (pt >= 0 && pt < f1.length) return mp.addXStr (JU.Escape.escapeFloatA (f1[pt], false)); return mp.addXStr (""); }return mp.addXStr (JU.Escape.escapeFloatAA (f1, false)); }if (selected.indexOf ("property_") == 0) { var f1 = this.vwr.getDataObj (selected, null, 1); if (f1 == null) return mp.addXStr (""); var f2 = (type.indexOf ("property_") == 0 ? this.vwr.getDataObj (selected, null, 1) : null); if (f2 != null) { f1 = JU.AU.arrayCopyF (f1, -1); for (var i = Math.min (f1.length, f2.length); --i >= 0; ) f1[i] += f2[i]; }return mp.addXStr (JU.Escape.escapeFloatA (f1, false)); }var data = this.vwr.getDataObj (selected, null, -1); return mp.addXStr (data == null ? "" : "" + data[1]); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateDotDist", function (mp, args, tok, op) { var isDist = (tok == 1275069443); var x1; var x2; var x3 = null; switch (args.length) { case 2: if (op == 2147483647) { x1 = args[0]; x2 = args[1]; break; }x3 = args[1]; case 1: x1 = mp.getX (); x2 = args[0]; break; default: return false; } if (tok == 1275069442) { var a = JU.P3.newP (mp.ptValue (x1, null)); a.cross (a, mp.ptValue (x2, null)); return mp.addXPt (a); }var pt2 = (x2.tok == 7 ? null : mp.ptValue (x2, null)); var plane2 = mp.planeValue (x2); if (isDist) { var minMax = (op == -2147483648 ? 0 : op & 480); var isMinMax = (minMax == 32 || minMax == 64); var isAll = minMax == 480; switch (x1.tok) { case 10: var bs = x1.value; var bs2 = null; var returnAtom = (isMinMax && x3 != null && x3.asBoolean ()); switch (x2.tok) { case 10: bs2 = (x2.tok == 10 ? x2.value : null); case 8: var atoms = this.vwr.ms.at; if (returnAtom) { var dMinMax = NaN; var iMinMax = 2147483647; for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) { var d = (bs2 == null ? atoms[i].distanceSquared (pt2) : (this.e.getBitsetProperty (bs2, op, atoms[i], plane2, x1.value, null, false, x1.index, false)).floatValue ()); if (minMax == 32 ? d >= dMinMax : d <= dMinMax) continue; dMinMax = d; iMinMax = i; } return mp.addXBs (iMinMax == 2147483647 ? new JU.BS () : JU.BSUtil.newAndSetBit (iMinMax)); }if (isAll) { if (bs2 == null) { var data = Clazz.newFloatArray (bs.cardinality (), 0); for (var p = 0, i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1), p++) data[p] = atoms[i].distance (pt2); return mp.addXAF (data); }var data2 = Clazz.newFloatArray (bs.cardinality (), bs2.cardinality (), 0); for (var p = 0, i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1), p++) for (var q = 0, j = bs2.nextSetBit (0); j >= 0; j = bs2.nextSetBit (j + 1), q++) data2[p][q] = atoms[i].distance (atoms[j]); return mp.addXAFF (data2); }if (isMinMax) { var data = Clazz.newFloatArray (bs.cardinality (), 0); for (var i = bs.nextSetBit (0), p = 0; i >= 0; i = bs.nextSetBit (i + 1)) data[p++] = (this.e.getBitsetProperty (bs2, op, atoms[i], plane2, x1.value, null, false, x1.index, false)).floatValue (); return mp.addXAF (data); }return mp.addXObj (this.e.getBitsetProperty (bs, op, pt2, plane2, x1.value, null, false, x1.index, false)); } } }var pt1 = mp.ptValue (x1, null); var plane1 = mp.planeValue (x1); var f = NaN; try { if (isDist) { if (plane2 != null && x3 != null) f = JU.Measure.directedDistanceToPlane (pt1, plane2, JS.SV.ptValue (x3)); else f = (plane1 == null ? (plane2 == null ? pt2.distance (pt1) : JU.Measure.distanceToPlane (plane2, pt1)) : JU.Measure.distanceToPlane (plane1, pt2)); } else { if (plane1 != null && plane2 != null) { f = plane1.x * plane2.x + plane1.y * plane2.y + plane1.z * plane2.z + plane1.w * plane2.w; } else { if (plane1 != null) pt1 = JU.P3.new3 (plane1.x, plane1.y, plane1.z); else if (plane2 != null) pt2 = JU.P3.new3 (plane2.x, plane2.y, plane2.z); f = pt1.dot (pt2); }}} catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } return mp.addXFloat (f); }, "JS.ScriptMathProcessor,~A,~N,~N"); Clazz.defineMethod (c$, "evaluateHelix", function (mp, args) { if (args.length < 1 || args.length > 5) return false; var pt = (args.length > 2 ? 3 : 1); var type = (pt >= args.length ? "array" : JS.SV.sValue (args[pt])); var tok = JS.T.getTokFromName (type); if (args.length > 2) { var pta = mp.ptValue (args[0], null); var ptb = mp.ptValue (args[1], null); if (tok == 0 || args[2].tok != 9 || pta == null || ptb == null) return false; var dq = JU.Quat.newP4 (args[2].value); var data = JU.Measure.computeHelicalAxis (pta, ptb, dq); return (data == null ? false : mp.addXObj (JU.Escape.escapeHelical (type, tok, pta, ptb, data))); }var bs = (Clazz.instanceOf (args[0].value, JU.BS) ? args[0].value : this.vwr.ms.getAtoms (1094715412, new Integer (args[0].asInt ()))); switch (tok) { case 134217751: case 1073741854: case 1665140738: return mp.addXObj (this.getHelixData (bs, tok)); case 134217729: return mp.addXFloat ((this.getHelixData (bs, 134217729)).floatValue ()); case 135176: case 1745489939: return mp.addXObj (this.getHelixData (bs, tok)); case 1275068418: var data = this.getHelixData (bs, 1073742001); if (data == null) return false; return mp.addXAS (data); } return false; }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "getHelixData", function (bs, tokType) { var iAtom = bs.nextSetBit (0); return (iAtom < 0 ? "null" : this.vwr.ms.at[iAtom].group.getHelixData (tokType, this.vwr.getQuaternionFrame (), this.vwr.getInt (553648146))); }, "JU.BS,~N"); Clazz.defineMethod (c$, "evaluateFind", function (mp, args) { var x1 = mp.getX (); var isList = (x1.tok == 7); var isEmpty = (args.length == 0); var sFind = (isEmpty ? "" : JS.SV.sValue (args[0])); var flags = (args.length > 1 && args[1].tok != 1073742335 && args[1].tok != 1073742334 && args[1].tok != 10 ? JS.SV.sValue (args[1]) : ""); var isSequence = !isList && sFind.equalsIgnoreCase ("SEQUENCE"); var isSeq = !isList && sFind.equalsIgnoreCase ("SEQ"); if (sFind.toUpperCase ().startsWith ("SMILES/")) { if (!sFind.endsWith ("/")) sFind += "/"; var s = sFind.substring (6) + "//"; if (JV.JC.isSmilesCanonical (s)) { flags = "SMILES"; sFind = "CHEMICAL"; } else { sFind = "SMILES"; flags = s + flags; }} else if (sFind.toUpperCase ().startsWith ("SMARTS/")) { if (!sFind.endsWith ("/")) sFind += "/"; flags = sFind.substring (6) + (flags.length == 0 ? "//" : flags); sFind = "SMARTS"; }var isSmiles = !isList && sFind.equalsIgnoreCase ("SMILES"); var isSMARTS = !isList && sFind.equalsIgnoreCase ("SMARTS"); var isChemical = !isList && sFind.equalsIgnoreCase ("CHEMICAL"); var isMF = !isList && sFind.equalsIgnoreCase ("MF"); var isCF = !isList && sFind.equalsIgnoreCase ("CELLFORMULA"); var argLast = (args.length > 0 ? args[args.length - 1] : JS.SV.vF); var isON = !isList && (argLast.tok == 1073742335); try { if (isChemical) { var bsAtoms = (x1.tok == 10 ? x1.value : null); var data = (bsAtoms == null ? JS.SV.sValue (x1) : this.vwr.getOpenSmiles (bsAtoms)); data = (data.length == 0 ? "" : this.vwr.getChemicalInfo (data, flags.toLowerCase (), bsAtoms)).trim (); if (data.startsWith ("InChI")) data = JU.PT.rep (JU.PT.rep (data, "InChI=", ""), "InChIKey=", ""); return mp.addXStr (data); }if (isSmiles || isSMARTS || x1.tok == 10) { var iPt = (isSmiles || isSMARTS ? 2 : 1); var bs2 = (iPt < args.length && args[iPt].tok == 10 ? args[iPt++].value : null); var asBonds = ("bonds".equalsIgnoreCase (JS.SV.sValue (args[args.length - 1]))); var isAll = (asBonds || isON); var ret = null; switch (x1.tok) { case 4: var smiles = JS.SV.sValue (x1); if (bs2 != null || isSmiles && args.length == 1) return false; if (flags.equalsIgnoreCase ("mf")) { ret = this.vwr.getSmilesMatcher ().getMolecularFormula (smiles, isSMARTS); } else { var pattern = flags; var allMappings = true; var asMap = false; switch (args.length) { case 4: allMappings = JS.SV.bValue (args[3]); case 3: asMap = JS.SV.bValue (args[2]); break; } var justOne = (!asMap && (!allMappings || !isSMARTS)); try { ret = this.e.getSmilesExt ().getSmilesMatches (pattern, smiles, null, null, isSMARTS ? 2 : 1, !asMap, !allMappings); } catch (ex) { if (Clazz.exceptionOf (ex, Exception)) { System.out.println (ex.getMessage ()); return mp.addXInt (-1); } else { throw ex; } } if (justOne) { var len = (ret).length; return mp.addXInt (!allMappings && len > 0 ? 1 : len); }}break; case 10: var bs = x1.value; if (isMF && flags.length != 0) return mp.addXBs (JU.JmolMolecule.getBitSetForMF (this.vwr.ms.at, bs, flags)); if (isMF || isCF) return mp.addXStr (JU.JmolMolecule.getMolecularFormulaAtoms (this.vwr.ms.at, bs, (isMF ? null : this.vwr.ms.getCellWeights (bs)), isON)); if (isSequence || isSeq) { var isHH = (argLast.asString ().equalsIgnoreCase ("H")); isAll = new Boolean (isAll | isHH).valueOf (); return mp.addXStr (this.vwr.getSmilesOpt (bs, -1, -1, (isAll ? 3145728 | 5242880 | (isHH ? 9437184 : 0) : 0) | (isSeq ? 34603008 : 1048576), null)); }if (isSmiles || isSMARTS) sFind = (args.length > 1 && args[1].tok == 10 ? this.vwr.getSmilesOpt (args[1].value, 0, 0, 0, flags) : flags); flags = flags.toUpperCase (); var bsMatch3D = bs2; if (asBonds) { var map = this.vwr.getSmilesMatcher ().getCorrelationMaps (sFind, this.vwr.ms.at, this.vwr.ms.ac, bs, (isSmiles ? 1 : 2) | 8); ret = (map.length > 0 ? this.vwr.ms.getDihedralMap (map[0]) : Clazz.newIntArray (0, 0)); } else if (flags.equalsIgnoreCase ("map")) { var map = this.vwr.getSmilesMatcher ().getCorrelationMaps (sFind, this.vwr.ms.at, this.vwr.ms.ac, bs, (isSmiles ? 1 : 2) | 128); ret = map; } else if (sFind.equalsIgnoreCase ("crystalClass")) { ret = this.vwr.ms.generateCrystalClass (bs.nextSetBit (0), (args.length != 2 ? null : argLast.tok == 10 ? this.vwr.ms.getAtomSetCenter (argLast.value) : JS.SV.ptValue (argLast))); } else { var smilesFlags = (isSmiles ? (flags.indexOf ("OPEN") >= 0 ? 5 : 1) : 2) | (isON && sFind.length == 0 ? 22020096 : 0); ret = this.e.getSmilesExt ().getSmilesMatches (sFind, null, bs, bsMatch3D, smilesFlags, !isON, false); }break; } if (ret == null) this.e.invArg (); return mp.addXObj (ret); }} catch (ex) { if (Clazz.exceptionOf (ex, Exception)) { this.e.evalError (ex.getMessage (), null); } else { throw ex; } } var isReverse = (flags.indexOf ("v") >= 0); var isCaseInsensitive = (flags.indexOf ("i") >= 0); var asMatch = (flags.indexOf ("m") >= 0); var checkEmpty = (sFind.length == 0); var isPattern = (!checkEmpty && args.length == 2); if (isList || isPattern) { var pm = (isPattern ? this.getPatternMatcher () : null); var pattern = null; var svlist = (isList ? x1.getList () : null); if (isPattern) { try { pattern = pm.compile (sFind, isCaseInsensitive); } catch (ex) { if (Clazz.exceptionOf (ex, Exception)) { this.e.evalError (ex.toString (), null); } else { throw ex; } } }var list = (checkEmpty ? null : JS.SV.strListValue (x1)); var nlist = (checkEmpty ? svlist.size () : list.length); if (JU.Logger.debugging) JU.Logger.debug ("finding " + sFind); var bs = new JU.BS (); var n = 0; var matcher = null; var v = (asMatch ? new JU.Lst () : null); var what = ""; for (var i = 0; i < nlist; i++) { var isMatch; if (checkEmpty) { var o = svlist.get (i); switch (o.tok) { case 6: isMatch = (o.getMap ().isEmpty () != isEmpty); break; case 7: isMatch = ((o.getList ().size () == 0) != isEmpty); break; case 4: isMatch = ((o.asString ().length == 0) != isEmpty); break; default: isMatch = true; } } else if (isPattern) { what = list[i]; matcher = pattern.matcher (what); isMatch = matcher.find (); } else { isMatch = (JS.SV.sValue (svlist.get (i)).indexOf (sFind) >= 0); }if (asMatch && isMatch || !asMatch && isMatch == !isReverse) { n++; bs.set (i); if (asMatch) v.addLast (isReverse ? what.substring (0, matcher.start ()) + what.substring (matcher.end ()) : matcher.group ()); }} if (!isList) { return (asMatch ? mp.addXStr (v.size () == 1 ? v.get (0) : "") : isReverse ? mp.addXBool (n == 1) : asMatch ? mp.addXStr (n == 0 ? "" : matcher.group ()) : mp.addXInt (n == 0 ? 0 : matcher.start () + 1)); }if (asMatch) { var listNew = new Array (n); if (n > 0) for (var i = list.length; --i >= 0; ) if (bs.get (i)) { --n; listNew[n] = (asMatch ? v.get (n) : list[i]); } return mp.addXAS (listNew); }var l = new JU.Lst (); for (var i = bs.nextSetBit (0); i >= 0; i = bs.nextSetBit (i + 1)) l.addLast (svlist.get (i)); return mp.addXList (l); }if (isSequence) { return mp.addXStr (this.vwr.getJBR ().toStdAmino3 (JS.SV.sValue (x1))); }return mp.addXInt (JS.SV.sValue (x1).indexOf (sFind) + 1); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateGetProperty", function (mp, args, tok0, isAtomProperty) { var isSelect = (isAtomProperty && tok0 == 1275082245); var isAuxiliary = (tok0 == 1275068449); var pt = 0; var tok = (args.length == 0 ? 0 : args[0].tok); if (args.length == 2 && (tok == 7 || tok == 6 || tok == 14)) { return mp.addXObj (this.vwr.extractProperty (args[0].value, args[1].value.toString (), -1)); }var bsSelect = (isAtomProperty && args.length == 1 && args[0].tok == 10 ? args[0].value : null); var pname = (bsSelect == null && args.length > 0 ? JS.SV.sValue (args[pt++]) : ""); var propertyName = pname; var lc = propertyName.toLowerCase (); if (!isSelect && lc.indexOf ("[select ") < 0) propertyName = lc; var isJSON = false; if (propertyName.equals ("json") && args.length > pt) { isJSON = true; propertyName = JS.SV.sValue (args[pt++]); }var x = null; if (isAtomProperty) { x = mp.getX (); switch (x.tok) { case 10: break; case 4: var name = x.value; var data = new Array (3); var shapeID; if (name.startsWith ("$")) { name = name.substring (1); shapeID = this.vwr.shm.getShapeIdFromObjectName (name); if (shapeID >= 0) { data[0] = name; this.vwr.shm.getShapePropertyData (shapeID, "index", data); if (data[1] != null && !pname.equals ("index")) { var index = (data[1]).intValue (); data[1] = this.vwr.shm.getShapePropertyIndex (shapeID, pname.intern (), index); }}} else { shapeID = JV.JC.shapeTokenIndex (JS.T.getTokFromName (name)); if (shapeID >= 0) { data[0] = pname; data[1] = Integer.$valueOf (-1); this.vwr.shm.getShapePropertyData (shapeID, pname.intern (), data); }}return (data[1] == null ? mp.addXStr ("") : mp.addXObj (data[1])); case 7: if (bsSelect != null) { var l0 = x.getList (); var lst = new JU.Lst (); for (var i = bsSelect.nextSetBit (0); i >= 0; i = bsSelect.nextSetBit (i + 1)) lst.addLast (l0.get (i)); return mp.addXList (lst); }default: if (isSelect) propertyName = "[SELECT " + propertyName + "]"; return mp.addXObj (this.vwr.extractProperty (x, propertyName, -1)); } if (!lc.startsWith ("bondinfo") && !lc.startsWith ("atominfo")) propertyName = "atomInfo." + propertyName; }var propertyValue = ""; if (propertyName.equalsIgnoreCase ("fileContents") && args.length > 2) { var s = JS.SV.sValue (args[1]); for (var i = 2; i < args.length; i++) s += "|" + JS.SV.sValue (args[i]); propertyValue = s; pt = args.length; } else if (args.length > pt) { switch (args[pt].tok) { case 10: propertyValue = args[pt++].value; if (propertyName.equalsIgnoreCase ("bondInfo") && args.length > pt && args[pt].tok == 10) propertyValue = Clazz.newArray (-1, [propertyValue, args[pt].value]); break; case 6: case 4: if (this.vwr.checkPropertyParameter (propertyName)) propertyValue = args[pt++].value; break; } }if (isAtomProperty) { var bs = x.value; var iAtom = bs.nextSetBit (0); if (iAtom < 0) return mp.addXStr (""); propertyValue = bs; }if (isAuxiliary && !isAtomProperty) propertyName = "auxiliaryInfo.models." + propertyName; propertyName = JU.PT.rep (propertyName, ".[", "["); var property = this.vwr.getProperty (null, propertyName, propertyValue); if (pt < args.length) property = this.vwr.extractProperty (property, args, pt); return mp.addXObj (isJSON ? JS.SV.safeJSON ("value", property) : JS.SV.isVariableType (property) ? property : JU.Escape.toReadable (propertyName, property)); }, "JS.ScriptMathProcessor,~A,~N,~B"); Clazz.defineMethod (c$, "evaluateFormat", function (mp, intValue, args, isLabel) { var x1 = (args.length < 2 || intValue == 1287653388 ? mp.getX () : null); var format = (args.length == 0 ? "%U" : args[0].tok == 7 ? null : JS.SV.sValue (args[0])); if (!isLabel && args.length > 0 && x1 != null && x1.tok != 10 && format != null) { if (args.length == 2) { var listIn = x1.getList (); var formatList = args[1].getList (); if (listIn == null || formatList == null) return false; x1 = JS.SV.getVariableList (this.getSublist (listIn, formatList)); }args = Clazz.newArray (-1, [args[0], x1]); x1 = null; }if (x1 == null) { var pt = (isLabel ? -1 : JS.SV.getFormatType (format)); if (pt >= 0 && args.length != 2) return false; if (pt >= 0 || args.length < 2 || args[1].tok != 7) { var o = JS.SV.format (args, pt); return (format.equalsIgnoreCase ("json") ? mp.addXStr (o) : mp.addXObj (o)); }var a = args[1].getList (); var args2 = Clazz.newArray (-1, [args[0], null]); var sa = new Array (a.size ()); for (var i = sa.length; --i >= 0; ) { args2[1] = a.get (i); sa[i] = JS.SV.format (args2, pt).toString (); } return mp.addXAS (sa); }if (x1.tok == 7 && format == null) { var listIn = x1.getList (); var formatList = args[0].getList (); var listOut = this.getSublist (listIn, formatList); return mp.addXList (listOut); }var bs = (x1.tok == 10 ? x1.value : null); var asArray = JS.T.tokAttr (intValue, 480); return mp.addXObj (format == null ? "" : bs == null ? JS.SV.sprintf (JU.PT.formatCheck (format), x1) : this.e.getCmdExt ().getBitsetIdent (bs, format, x1.value, true, x1.index, asArray)); }, "JS.ScriptMathProcessor,~N,~A,~B"); Clazz.defineMethod (c$, "getSublist", function (listIn, formatList) { var listOut = new JU.Lst (); var map; var v; var list; for (var i = 0, n = listIn.size (); i < n; i++) { var element = listIn.get (i); switch (element.tok) { case 6: map = element.getMap (); list = new JU.Lst (); for (var j = 0, n1 = formatList.size (); j < n1; j++) { v = map.get (JS.SV.sValue (formatList.get (j))); list.addLast (v == null ? JS.SV.newS ("") : v); } listOut.addLast (JS.SV.getVariableList (list)); break; case 7: map = new java.util.Hashtable (); list = element.getList (); for (var j = 0, n1 = Math.min (list.size (), formatList.size ()); j < n1; j++) { map.put (JS.SV.sValue (formatList.get (j)), list.get (j)); } listOut.addLast (JS.SV.getVariable (map)); } } return listOut; }, "JU.Lst,JU.Lst"); Clazz.defineMethod (c$, "evaluateList", function (mp, tok, args) { var len = args.length; var x1 = mp.getX (); var isArray1 = (x1.tok == 7); var x2; switch (tok) { case 1275335685: return (len == 2 && mp.addX (x1.pushPop (args[0], args[1])) || len == 1 && mp.addX (x1.pushPop (null, args[0]))); case 1275334681: return (len == 1 && mp.addX (x1.pushPop (args[0], null)) || len == 0 && mp.addX (x1.pushPop (null, null))); case 1275069441: if (len != 1 && len != 2) return false; break; case 1275069447: case 1275069446: break; default: if (len != 1) return false; } var sList1 = null; var sList2 = null; var sList3 = null; if (len == 2) { var tab = JS.SV.sValue (args[0]); x2 = args[1]; if (tok == 1275069441) { sList1 = (isArray1 ? JS.SV.strListValue (x1) : JU.PT.split (JS.SV.sValue (x1), "\n")); sList2 = (x2.tok == 7 ? JS.SV.strListValue (x2) : JU.PT.split (JS.SV.sValue (x2), "\n")); sList3 = new Array (len = Math.max (sList1.length, sList2.length)); for (var i = 0; i < len; i++) sList3[i] = (i >= sList1.length ? "" : sList1[i]) + tab + (i >= sList2.length ? "" : sList2[i]); return mp.addXAS (sList3); }if (x2.tok != 1073742335) return false; var l = x1.getList (); var isCSV = (tab.length == 0); if (isCSV) tab = ","; if (tok == 1275069446) { var s2 = new Array (l.size ()); for (var i = l.size (); --i >= 0; ) { var a = l.get (i).getList (); if (a == null) s2[i] = l.get (i); else { var sb = new JU.SB (); for (var j = 0, n = a.size (); j < n; j++) { if (j > 0) sb.append (tab); var sv = a.get (j); sb.append (isCSV && sv.tok == 4 ? "\"" + JU.PT.rep (sv.value, "\"", "\"\"") + "\"" : "" + sv.asString ()); } s2[i] = JS.SV.newS (sb.toString ()); }} return mp.addXAV (s2); }var sa = new JU.Lst (); if (isCSV) tab = "\0"; var next = Clazz.newIntArray (2, 0); for (var i = 0, nl = l.size (); i < nl; i++) { var line = l.get (i).asString (); if (isCSV) { next[1] = 0; next[0] = 0; var last = 0; while (true) { var s = JU.PT.getCSVString (line, next); if (s == null) { if (next[1] == -1) { line += (++i < nl ? "\n" + l.get (i).asString () : "\""); next[1] = last; continue; }line = line.substring (0, last) + line.substring (last).$replace (',', '\0'); break; }line = line.substring (0, last) + line.substring (last, next[0]).$replace (',', '\0') + s + line.substring (next[1]); next[1] = last = next[0] + s.length; } }var linaa = line.$plit (tab); var la = new JU.Lst (); for (var j = 0, n = linaa.length; j < n; j++) { var s = linaa[j]; if (s.indexOf (".") < 0) try { la.addLast (JS.SV.newI (Integer.parseInt (s))); continue; } catch (e) { if (Clazz.exceptionOf (e, Exception)) { } else { throw e; } } else try { la.addLast (JS.SV.getVariable (Float.$valueOf (Float.parseFloat (s)))); continue; } catch (ee) { if (Clazz.exceptionOf (ee, Exception)) { } else { throw ee; } } la.addLast (JS.SV.newS (s)); } sa.addLast (JS.SV.getVariableList (la)); } return mp.addXObj (JS.SV.getVariableList (sa)); }x2 = (len == 0 ? JS.SV.newV (1073742327, "all") : args[0]); var isAll = (x2.tok == 1073742327); if (!isArray1 && x1.tok != 4) return mp.binaryOp (this.opTokenFor (tok), x1, x2); var isScalar1 = JS.SV.isScalar (x1); var isScalar2 = JS.SV.isScalar (x2); var list1 = null; var list2 = null; var alist1 = x1.getList (); var alist2 = x2.getList (); if (isArray1) { len = alist1.size (); } else if (isScalar1) { len = 2147483647; } else { sList1 = (JU.PT.split (JS.SV.sValue (x1), "\n")); list1 = Clazz.newFloatArray (len = sList1.length, 0); JU.PT.parseFloatArrayData (sList1, list1); }if (isAll && tok != 1275069446) { var sum = 0; if (isArray1) { for (var i = len; --i >= 0; ) sum += JS.SV.fValue (alist1.get (i)); } else if (!isScalar1) { for (var i = len; --i >= 0; ) sum += list1[i]; }return mp.addXFloat (sum); }if (tok == 1275069446 && x2.tok == 4) { var sb = new JU.SB (); if (isScalar1) { sb.append (JS.SV.sValue (x1)); } else { var s = (isAll ? "" : x2.value.toString ()); for (var i = 0; i < len; i++) sb.append (i > 0 ? s : "").append (JS.SV.sValue (alist1.get (i))); }return mp.addXStr (sb.toString ()); }var scalar = null; if (isScalar2) { scalar = x2; } else if (x2.tok == 7) { len = Math.min (len, alist2.size ()); } else { sList2 = JU.PT.split (JS.SV.sValue (x2), "\n"); list2 = Clazz.newFloatArray (sList2.length, 0); JU.PT.parseFloatArrayData (sList2, list2); len = Math.min (len, list2.length); }var token = this.opTokenFor (tok); var olist = new Array (len); if (isArray1 && isAll) { var llist = new JU.Lst (); return mp.addXList (this.addAllLists (x1.getList (), llist)); }var a = (isScalar1 ? x1 : null); var b; for (var i = 0; i < len; i++) { if (isScalar2) b = scalar; else if (x2.tok == 7) b = alist2.get (i); else if (Float.isNaN (list2[i])) b = JS.SV.getVariable (JS.SV.unescapePointOrBitsetAsVariable (sList2[i])); else b = JS.SV.newF (list2[i]); if (!isScalar1) { if (isArray1) a = alist1.get (i); else if (Float.isNaN (list1[i])) a = JS.SV.getVariable (JS.SV.unescapePointOrBitsetAsVariable (sList1[i])); else a = JS.SV.newF (list1[i]); }if (tok == 1275069446) { if (a.tok != 7) { var l = new JU.Lst (); l.addLast (a); a = JS.SV.getVariableList (l); }}if (!mp.binaryOp (token, a, b)) return false; olist[i] = mp.getX (); } return mp.addXAV (olist); }, "JS.ScriptMathProcessor,~N,~A"); Clazz.defineMethod (c$, "addAllLists", function (list, l) { var n = list.size (); for (var i = 0; i < n; i++) { var v = list.get (i); if (v.tok == 7) this.addAllLists (v.getList (), l); else l.addLast (v); } return l; }, "JU.Lst,JU.Lst"); Clazz.defineMethod (c$, "evaluateLoad", function (mp, args, isFile) { if (args.length < 1 || args.length > 3) return false; var file = JV.FileManager.fixDOSName (JS.SV.sValue (args[0])); var asBytes = (args.length > 1 && args[1].tok == 1073742335); var async = (this.vwr.async || args.length > 2 && args[args.length - 1].tok == 1073742335); var nBytesMax = (args.length > 1 && args[1].tok == 2 ? args[1].asInt () : -1); var asJSON = (args.length > 1 && args[1].asString ().equalsIgnoreCase ("JSON")); if (asBytes) return mp.addXMap (this.vwr.fm.getFileAsMap (file)); var isQues = file.startsWith ("?"); if (this.vwr.isJS && (isQues || async)) { if (isFile && isQues) return mp.addXStr (""); file = this.e.loadFileAsync ("load()_", file, mp.oPt, true); }var str = isFile ? this.vwr.fm.getFilePath (file, false, false) : this.vwr.getFileAsString4 (file, nBytesMax, false, false, true, "script"); return (asJSON ? mp.addXObj (this.vwr.parseJSON (str)) : mp.addXStr (str)); }, "JS.ScriptMathProcessor,~A,~B"); Clazz.defineMethod (c$, "evaluateMath", function (mp, args, tok) { if (tok == 134217749) { if (args.length == 1 && args[0].tok == 4) return mp.addXStr (( new java.util.Date ()) + "\t" + JS.SV.sValue (args[0])); return mp.addXInt ((System.currentTimeMillis () & 0x7FFFFFFF) - (args.length == 0 ? 0 : args[0].asInt ())); }if (args.length != 1) return false; if (tok == 134218250) { if (args[0].tok == 2) return mp.addXInt (Math.abs (args[0].asInt ())); return mp.addXFloat (Math.abs (args[0].asFloat ())); }var x = JS.SV.fValue (args[0]); switch (tok) { case 134218242: return mp.addXFloat ((Math.acos (x) * 180 / 3.141592653589793)); case 134218245: return mp.addXFloat (Math.cos (x * 3.141592653589793 / 180)); case 134218244: return mp.addXFloat (Math.sin (x * 3.141592653589793 / 180)); case 134218246: return mp.addXFloat (Math.sqrt (x)); } return false; }, "JS.ScriptMathProcessor,~A,~N"); Clazz.defineMethod (c$, "evaluateMeasure", function (mp, args, tok) { var nPoints = 0; switch (tok) { case 1745489939: var points = new JU.Lst (); var rangeMinMax = Clazz.newFloatArray (-1, [3.4028235E38, 3.4028235E38]); var strFormat = null; var units = null; var isAllConnected = false; var isNotConnected = false; var rPt = 0; var isNull = false; var rd = null; var nBitSets = 0; var vdw = 3.4028235E38; var asMinArray = false; var asArray = false; for (var i = 0; i < args.length; i++) { switch (args[i].tok) { case 10: var bs = args[i].value; if (bs.length () == 0) isNull = true; points.addLast (bs); nPoints++; nBitSets++; break; case 8: var v = new JU.Point3fi (); v.setT (args[i].value); points.addLast (v); nPoints++; break; case 2: case 3: rangeMinMax[rPt++ % 2] = JS.SV.fValue (args[i]); break; case 4: var s = JS.SV.sValue (args[i]); if (s.equalsIgnoreCase ("vdw") || s.equalsIgnoreCase ("vanderwaals")) vdw = (i + 1 < args.length && args[i + 1].tok == 2 ? args[++i].asInt () : 100) / 100; else if (s.equalsIgnoreCase ("notConnected")) isNotConnected = true; else if (s.equalsIgnoreCase ("connected")) isAllConnected = true; else if (s.equalsIgnoreCase ("minArray")) asMinArray = (nBitSets >= 1); else if (s.equalsIgnoreCase ("asArray")) asArray = (nBitSets >= 1); else if (JU.PT.isOneOf (s.toLowerCase (), ";nm;nanometers;pm;picometers;angstroms;ang;au;") || s.endsWith ("hz")) units = s.toLowerCase (); else strFormat = nPoints + ":" + s; break; default: return false; } } if (nPoints < 2 || nPoints > 4 || rPt > 2 || isNotConnected && isAllConnected) return false; if (isNull) return mp.addXStr (""); if (vdw != 3.4028235E38 && (nBitSets != 2 || nPoints != 2)) return mp.addXStr (""); rd = (vdw == 3.4028235E38 ? new J.atomdata.RadiusData (rangeMinMax, 0, null, null) : new J.atomdata.RadiusData (null, vdw, J.atomdata.RadiusData.EnumType.FACTOR, J.c.VDW.AUTO)); return mp.addXObj ((this.vwr.newMeasurementData (null, points)).set (0, null, rd, strFormat, units, null, isAllConnected, isNotConnected, null, true, 0, 0, null).getMeasurements (asArray, asMinArray)); case 134217729: if ((nPoints = args.length) != 3 && nPoints != 4) return false; break; default: if ((nPoints = args.length) != 2) return false; } var pts = new Array (nPoints); for (var i = 0; i < nPoints; i++) { if ((pts[i] = mp.ptValue (args[i], null)) == null) return false; } switch (nPoints) { case 2: return mp.addXFloat (pts[0].distance (pts[1])); case 3: return mp.addXFloat (JU.Measure.computeAngleABC (pts[0], pts[1], pts[2], true)); case 4: return mp.addXFloat (JU.Measure.computeTorsion (pts[0], pts[1], pts[2], pts[3], true)); } return false; }, "JS.ScriptMathProcessor,~A,~N"); Clazz.defineMethod (c$, "evaluateModulation", function (mp, args) { var type = ""; var t = NaN; var t456 = null; switch (args.length) { case 0: break; case 1: switch (args[0].tok) { case 8: t456 = args[0].value; break; case 4: type = args[0].asString (); break; default: t = JS.SV.fValue (args[0]); } break; case 2: type = JS.SV.sValue (args[0]); t = JS.SV.fValue (args[1]); break; default: return false; } if (t456 == null && t < 1e6) t456 = JU.P3.new3 (t, t, t); var x = mp.getX (); var bs = (x.tok == 10 ? x.value : new JU.BS ()); return mp.addXList (this.vwr.ms.getModulationList (bs, (type + "D").toUpperCase ().charAt (0), t456)); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluatePlane", function (mp, args, tok) { if (tok == 134219265 && args.length != 3 || tok == 134219266 && args.length != 2 && args.length != 3 || args.length == 0 || args.length > 4) return false; var pt1; var pt2; var pt3; var plane; var norm; var vTemp; switch (args.length) { case 1: if (args[0].tok == 10) { var bs = args[0].value; if (bs.cardinality () == 3) { var pts = this.vwr.ms.getAtomPointVector (bs); return mp.addXPt4 (JU.Measure.getPlaneThroughPoints (pts.get (0), pts.get (1), pts.get (2), new JU.V3 (), new JU.V3 (), new JU.P4 ())); }}var pt = JU.Escape.uP (JS.SV.sValue (args[0])); if (Clazz.instanceOf (pt, JU.P4)) return mp.addXPt4 (pt); return mp.addXStr ("" + pt); case 2: if (tok == 134219266) { if (args[1].tok != 9) return false; pt3 = new JU.P3 (); norm = new JU.V3 (); vTemp = new JU.V3 (); plane = args[1].value; if (args[0].tok == 9) { var list = JU.Measure.getIntersectionPP (args[0].value, plane); if (list == null) return mp.addXStr (""); return mp.addXList (list); }pt2 = mp.ptValue (args[0], null); if (pt2 == null) return mp.addXStr (""); return mp.addXPt (JU.Measure.getIntersection (pt2, null, plane, pt3, norm, vTemp)); }case 3: case 4: switch (tok) { case 134219265: return mp.addXPt4 (this.e.getHklPlane (JU.P3.new3 (JS.SV.fValue (args[0]), JS.SV.fValue (args[1]), JS.SV.fValue (args[2])))); case 134219266: pt1 = mp.ptValue (args[0], null); pt2 = mp.ptValue (args[1], null); if (pt1 == null || pt2 == null) return mp.addXStr (""); var vLine = JU.V3.newV (pt2); vLine.normalize (); if (args[2].tok == 9) { pt3 = new JU.P3 (); norm = new JU.V3 (); vTemp = new JU.V3 (); pt1 = JU.Measure.getIntersection (pt1, vLine, args[2].value, pt3, norm, vTemp); if (pt1 == null) return mp.addXStr (""); return mp.addXPt (pt1); }pt3 = mp.ptValue (args[2], null); if (pt3 == null) return mp.addXStr (""); var v = new JU.V3 (); JU.Measure.projectOntoAxis (pt3, pt1, vLine, v); return mp.addXPt (pt3); } switch (args[0].tok) { case 2: case 3: if (args.length == 3) { var r = JS.SV.fValue (args[0]); var theta = JS.SV.fValue (args[1]); var phi = JS.SV.fValue (args[2]); norm = JU.V3.new3 (0, 0, 1); pt2 = JU.P3.new3 (0, 1, 0); var q = JU.Quat.newVA (pt2, phi); q.getMatrix ().rotate (norm); pt2.set (0, 0, 1); q = JU.Quat.newVA (pt2, theta); q.getMatrix ().rotate (norm); pt2.setT (norm); pt2.scale (r); plane = new JU.P4 (); JU.Measure.getPlaneThroughPoint (pt2, norm, plane); return mp.addXPt4 (plane); }break; case 10: case 8: pt1 = mp.ptValue (args[0], null); pt2 = mp.ptValue (args[1], null); if (pt2 == null) return false; pt3 = (args.length > 2 && (args[2].tok == 10 || args[2].tok == 8) ? mp.ptValue (args[2], null) : null); norm = JU.V3.newV (pt2); if (pt3 == null) { plane = new JU.P4 (); if (args.length == 2 || args[2].tok != 2 && args[2].tok != 3 && !args[2].asBoolean ()) { pt3 = JU.P3.newP (pt1); pt3.add (pt2); pt3.scale (0.5); norm.sub (pt1); norm.normalize (); } else if (args[2].tok == 1073742335) { pt3 = pt1; } else { norm.sub (pt1); pt3 = new JU.P3 (); pt3.scaleAdd2 (args[2].asFloat (), norm, pt1); }JU.Measure.getPlaneThroughPoint (pt3, norm, plane); return mp.addXPt4 (plane); }var vAB = new JU.V3 (); var ptref = (args.length == 4 ? mp.ptValue (args[3], null) : null); var nd = JU.Measure.getDirectedNormalThroughPoints (pt1, pt2, pt3, ptref, norm, vAB); return mp.addXPt4 (JU.P4.new4 (norm.x, norm.y, norm.z, nd)); } } if (args.length != 4) return false; var x = JS.SV.fValue (args[0]); var y = JS.SV.fValue (args[1]); var z = JS.SV.fValue (args[2]); var w = JS.SV.fValue (args[3]); return mp.addXPt4 (JU.P4.new4 (x, y, z, w)); }, "JS.ScriptMathProcessor,~A,~N"); Clazz.defineMethod (c$, "evaluatePoint", function (mp, args) { switch (args.length) { default: return false; case 1: if (args[0].tok == 3 || args[0].tok == 2) return mp.addXInt (args[0].asInt ()); var s = JS.SV.sValue (args[0]); if (args[0].tok == 7) s = "{" + s + "}"; var pt = JU.Escape.uP (s); return (Clazz.instanceOf (pt, JU.P3) ? mp.addXPt (pt) : mp.addXStr ("" + pt)); case 2: var pt3; switch (args[1].tok) { case 1073742334: case 1073742335: switch (args[0].tok) { case 8: pt3 = JU.P3.newP (args[0].value); break; case 10: pt3 = this.vwr.ms.getAtomSetCenter (args[0].value); break; default: return false; } if (args[1].tok == 1073742335) { this.vwr.tm.transformPt3f (pt3, pt3); pt3.y = this.vwr.tm.height - pt3.y; if (this.vwr.antialiased) pt3.scale (0.5); } else { if (this.vwr.antialiased) pt3.scale (2); pt3.y = this.vwr.tm.height - pt3.y; this.vwr.tm.unTransformPoint (pt3, pt3); }break; case 8: var sv = args[0].getList (); if (sv == null || sv.size () != 4) return false; var pt1 = JS.SV.ptValue (args[1]); pt3 = JU.P3.newP (JS.SV.ptValue (sv.get (0))); pt3.scaleAdd2 (pt1.x, JS.SV.ptValue (sv.get (1)), pt3); pt3.scaleAdd2 (pt1.y, JS.SV.ptValue (sv.get (2)), pt3); pt3.scaleAdd2 (pt1.z, JS.SV.ptValue (sv.get (3)), pt3); break; default: return false; } return mp.addXPt (pt3); case 3: return mp.addXPt (JU.P3.new3 (args[0].asFloat (), args[1].asFloat (), args[2].asFloat ())); case 4: return mp.addXPt4 (JU.P4.new4 (args[0].asFloat (), args[1].asFloat (), args[2].asFloat (), args[3].asFloat ())); } }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluatePrompt", function (mp, args) { if (args.length != 1 && args.length != 2 && args.length != 3) return false; var label = JS.SV.sValue (args[0]); var buttonArray = (args.length > 1 && args[1].tok == 7 ? JS.SV.strListValue (args[1]) : null); var asButtons = (buttonArray != null || args.length == 1 || args.length == 3 && args[2].asBoolean ()); var input = (buttonArray != null ? null : args.length >= 2 ? JS.SV.sValue (args[1]) : "OK"); var s = "" + this.vwr.prompt (label, input, buttonArray, asButtons); return (asButtons && buttonArray != null ? mp.addXInt (Integer.parseInt (s) + 1) : mp.addXStr (s)); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateQuaternion", function (mp, args, tok) { var pt0 = null; var nArgs = args.length; var nMax = 2147483647; var isRelative = false; if (tok == 134221850) { if (nArgs > 1 && args[nArgs - 1].tok == 4 && (args[nArgs - 1].value).equalsIgnoreCase ("relative")) { nArgs--; isRelative = true; }if (nArgs > 1 && args[nArgs - 1].tok == 2 && args[0].tok == 10) { nMax = args[nArgs - 1].asInt (); if (nMax <= 0) nMax = 2147483646; nArgs--; }}switch (nArgs) { case 0: case 1: case 4: break; case 2: if (tok == 134221850) { if (args[0].tok == 7 && (args[1].tok == 7 || args[1].tok == 1073742335)) break; if (args[0].tok == 10 && (args[1].tok == 2 || args[1].tok == 10)) break; }if ((pt0 = mp.ptValue (args[0], null)) == null || tok != 134221850 && args[1].tok == 8) return false; break; case 3: if (tok != 134221850) return false; if (args[0].tok == 9) { if (args[2].tok != 8 && args[2].tok != 10) return false; break; }for (var i = 0; i < 3; i++) if (args[i].tok != 8 && args[i].tok != 10) return false; break; default: return false; } var q = null; var qs = null; var p4 = null; switch (nArgs) { case 0: return mp.addXPt4 (this.vwr.tm.getRotationQ ().toPoint4f ()); case 1: default: if (tok == 134221850 && args[0].tok == 7) { var data1 = this.e.getQuaternionArray (args[0].getList (), 1073742001); var mean = JU.Quat.sphereMean (data1, null, 0.0001); q = (Clazz.instanceOf (mean, JU.Quat) ? mean : null); break; } else if (tok == 134221850 && args[0].tok == 10) { qs = this.vwr.getAtomGroupQuaternions (args[0].value, nMax); } else if (args[0].tok == 11) { q = JU.Quat.newM (args[0].value); } else if (args[0].tok == 9) { p4 = args[0].value; } else { var s = JS.SV.sValue (args[0]); var v = JU.Escape.uP (s.equalsIgnoreCase ("best") ? this.vwr.getOrientationText (1073741864, null) : s); if (!(Clazz.instanceOf (v, JU.P4))) return false; p4 = v; }if (tok == 134217731) q = JU.Quat.newVA (JU.P3.new3 (p4.x, p4.y, p4.z), p4.w); break; case 2: if (tok == 134221850) { if (args[0].tok == 7 && args[1].tok == 7) { var data1 = this.e.getQuaternionArray (args[0].getList (), 1073742001); var data2 = this.e.getQuaternionArray (args[1].getList (), 1073742001); qs = JU.Quat.div (data2, data1, nMax, isRelative); break; }if (args[0].tok == 7 && args[1].tok == 1073742335) { var data1 = this.e.getQuaternionArray (args[0].getList (), 1073742001); var stddev = Clazz.newFloatArray (1, 0); JU.Quat.sphereMean (data1, stddev, 0.0001); return mp.addXFloat (stddev[0]); }if (args[0].tok == 10 && args[1].tok == 10) { var data1 = this.vwr.getAtomGroupQuaternions (args[0].value, 2147483647); var data2 = this.vwr.getAtomGroupQuaternions (args[1].value, 2147483647); qs = JU.Quat.div (data2, data1, nMax, isRelative); break; }}var pt1 = mp.ptValue (args[1], null); p4 = mp.planeValue (args[0]); if (pt1 != null) q = JU.Quat.getQuaternionFrame (JU.P3.new3 (0, 0, 0), pt0, pt1); else q = JU.Quat.newVA (pt0, JS.SV.fValue (args[1])); break; case 3: if (args[0].tok == 9) { var pt = (args[2].tok == 8 ? args[2].value : this.vwr.ms.getAtomSetCenter (args[2].value)); return mp.addXStr (JU.Escape.drawQuat (JU.Quat.newP4 (args[0].value), "q", JS.SV.sValue (args[1]), pt, 1)); }var pts = new Array (3); for (var i = 0; i < 3; i++) pts[i] = (args[i].tok == 8 ? args[i].value : this.vwr.ms.getAtomSetCenter (args[i].value)); q = JU.Quat.getQuaternionFrame (pts[0], pts[1], pts[2]); break; case 4: if (tok == 134221850) p4 = JU.P4.new4 (JS.SV.fValue (args[1]), JS.SV.fValue (args[2]), JS.SV.fValue (args[3]), JS.SV.fValue (args[0])); else q = JU.Quat.newVA (JU.P3.new3 (JS.SV.fValue (args[0]), JS.SV.fValue (args[1]), JS.SV.fValue (args[2])), JS.SV.fValue (args[3])); break; } if (qs != null) { if (nMax != 2147483647) { var list = new JU.Lst (); for (var i = 0; i < qs.length; i++) list.addLast (qs[i].toPoint4f ()); return mp.addXList (list); }q = (qs.length > 0 ? qs[0] : null); }return mp.addXPt4 ((q == null ? JU.Quat.newP4 (p4) : q).toPoint4f ()); }, "JS.ScriptMathProcessor,~A,~N"); Clazz.defineMethod (c$, "evaluateRandom", function (mp, args) { if (args.length > 3) return false; if (this.rand == null) this.rand = new java.util.Random (); var lower = 0; var upper = 1; switch (args.length) { case 3: this.rand.setSeed (Clazz.floatToInt (JS.SV.fValue (args[2]))); case 2: upper = JS.SV.fValue (args[1]); case 1: lower = JS.SV.fValue (args[0]); case 0: break; default: return false; } return mp.addXFloat ((this.rand.nextFloat () * (upper - lower)) + lower); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateRowCol", function (mp, args, tok) { if (args.length != 1) return false; var n = args[0].asInt () - 1; var x1 = mp.getX (); var f; switch (x1.tok) { case 11: if (n < 0 || n > 2) return false; var m = x1.value; switch (tok) { case 1275068935: f = Clazz.newFloatArray (3, 0); m.getRow (n, f); return mp.addXAF (f); case 1275068934: default: f = Clazz.newFloatArray (3, 0); m.getColumn (n, f); return mp.addXAF (f); } case 12: if (n < 0 || n > 2) return false; var m4 = x1.value; switch (tok) { case 1275068935: f = Clazz.newFloatArray (4, 0); m4.getRow (n, f); return mp.addXAF (f); case 1275068934: default: f = Clazz.newFloatArray (4, 0); m4.getColumn (n, f); return mp.addXAF (f); } case 7: var l1 = x1.getList (); var l2 = new JU.Lst (); for (var i = 0, len = l1.size (); i < len; i++) { var l3 = l1.get (i).getList (); if (l3 == null) return mp.addXStr (""); l2.addLast (n < l3.size () ? l3.get (n) : JS.SV.newS ("")); } return mp.addXList (l2); } return false; }, "JS.ScriptMathProcessor,~A,~N"); Clazz.defineMethod (c$, "evaluateIn", function (mp, args) { var x1 = mp.getX (); switch (args.length) { case 1: var lst = args[0].getList (); if (lst != null) for (var i = 0, n = lst.size (); i < n; i++) if (JS.SV.areEqual (x1, lst.get (i))) return mp.addXInt (i + 1); break; default: for (var i = 0; i < args.length; i++) if (JS.SV.areEqual (x1, args[i])) return mp.addXInt (i + 1); break; } return mp.addXInt (0); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateReplace", function (mp, args) { var isAll = false; var sFind; var sReplace; switch (args.length) { case 0: isAll = true; sFind = sReplace = null; break; case 3: isAll = JS.SV.bValue (args[2]); case 2: sFind = JS.SV.sValue (args[0]); sReplace = JS.SV.sValue (args[1]); break; default: return false; } var x = mp.getX (); if (x.tok == 7) { var list = JS.SV.strListValue (x); var l = new Array (list.length); for (var i = list.length; --i >= 0; ) l[i] = (sFind == null ? JU.PT.clean (list[i]) : isAll ? JU.PT.replaceAllCharacters (list[i], sFind, sReplace) : JU.PT.rep (list[i], sFind, sReplace)); return mp.addXAS (l); }var s = JS.SV.sValue (x); return mp.addXStr (sFind == null ? JU.PT.clean (s) : isAll ? JU.PT.replaceAllCharacters (s, sFind, sReplace) : JU.PT.rep (s, sFind, sReplace)); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateScript", function (mp, args, tok) { if ((tok == 134222350 || tok == 134238732) && args.length != 1 || args.length == 0) return false; var s = JS.SV.sValue (args[0]); var sb = new JU.SB (); switch (tok) { case 134218759: return (args.length == 2 ? s.equalsIgnoreCase ("JSON") && mp.addXObj (this.vwr.parseJSON (JS.SV.sValue (args[1]))) : mp.addXObj (this.vwr.evaluateExpressionAsVariable (s))); case 134222850: var appID = (args.length == 2 ? JS.SV.sValue (args[1]) : "."); if (!appID.equals (".")) sb.append (this.vwr.jsEval (appID + "\1" + s)); if (appID.equals (".") || appID.equals ("*")) this.e.runScriptBuffer (s, sb, true); break; case 134222350: this.e.runScriptBuffer ("show " + s, sb, true); break; case 134238732: return mp.addX (this.vwr.jsEvalSV (s)); } s = sb.toString (); var f; return (Float.isNaN (f = JU.PT.parseFloatStrict (s)) ? mp.addXStr (s) : s.indexOf (".") >= 0 ? mp.addXFloat (f) : mp.addXInt (JU.PT.parseInt (s))); }, "JS.ScriptMathProcessor,~A,~N"); Clazz.defineMethod (c$, "evaluateSort", function (mp, args, tok) { if (args.length > 1) return false; if (tok == 1275068444) { if (args.length == 1 && args[0].tok == 4) { return mp.addX (mp.getX ().sortMapArray (args[0].asString ())); }var n = (args.length == 0 ? 0 : args[0].asInt ()); return mp.addX (mp.getX ().sortOrReverse (n)); }var x = mp.getX (); var match = (args.length == 0 ? null : args[0]); if (x.tok == 4) { var n = 0; var s = JS.SV.sValue (x); if (match == null) return mp.addXInt (0); var m = JS.SV.sValue (match); for (var i = 0; i < s.length; i++) { var pt = s.indexOf (m, i); if (pt < 0) break; n++; i = pt; } return mp.addXInt (n); }var counts = new JU.Lst (); var last = null; var count = null; var xList = JS.SV.getVariable (x.value).sortOrReverse (0).getList (); if (xList == null) return (match == null ? mp.addXStr ("") : mp.addXInt (0)); for (var i = 0, nLast = xList.size (); i <= nLast; i++) { var a = (i == nLast ? null : xList.get (i)); if (match != null && a != null && !JS.SV.areEqual (a, match)) continue; if (JS.SV.areEqual (a, last)) { count.intValue++; continue; } else if (last != null) { var y = new JU.Lst (); y.addLast (last); y.addLast (count); counts.addLast (JS.SV.getVariableList (y)); }count = JS.SV.newI (1); last = a; } if (match == null) return mp.addX (JS.SV.getVariableList (counts)); if (counts.isEmpty ()) return mp.addXInt (0); return mp.addX (counts.get (0).getList ().get (1)); }, "JS.ScriptMathProcessor,~A,~N"); Clazz.defineMethod (c$, "evaluateString", function (mp, tok, args) { var x = mp.getX (); var sArg = (args.length > 0 ? JS.SV.sValue (args[0]) : tok == 1275068932 ? "" : "\n"); switch (args.length) { case 0: break; case 1: if (args[0].tok == 1073742335) { return mp.addX (JS.SV.getVariable (JU.PT.getTokens (x.asString ()))); }break; case 2: if (x.tok == 7) break; if (tok == 1275069447) { x = JS.SV.getVariable (JU.PT.split (JU.PT.rep (x.value, "\n\r", "\n").$replace ('\r', '\n'), "\n")); break; }default: return false; } if (x.tok == 7 && tok != 1275068932 && (tok != 1275069447 || args.length == 2)) { mp.addX (x); return this.evaluateList (mp, tok, args); }var s = (tok == 1275069447 && x.tok == 10 || tok == 1275068932 && x.tok == 7 ? null : JS.SV.sValue (x)); switch (tok) { case 1275069447: if (x.tok == 10) { var bsSelected = x.value; var modelCount = this.vwr.ms.mc; var lst = new JU.Lst (); for (var i = 0; i < modelCount; i++) { var bs = this.vwr.getModelUndeletedAtomsBitSet (i); bs.and (bsSelected); lst.addLast (JS.SV.getVariable (bs)); } return mp.addXList (lst); }return mp.addXAS (JU.PT.split (s, sArg)); case 1275069446: if (s.length > 0 && s.charAt (s.length - 1) == '\n') s = s.substring (0, s.length - 1); return mp.addXStr (JU.PT.rep (s, "\n", sArg)); case 1275068932: if (s != null) return mp.addXStr (JU.PT.trim (s, sArg)); var list = JS.SV.strListValue (x); for (var i = list.length; --i >= 0; ) list[i] = JU.PT.trim (list[i], sArg); return mp.addXAS (list); } return mp.addXStr (""); }, "JS.ScriptMathProcessor,~N,~A"); Clazz.defineMethod (c$, "evaluateSubstructure", function (mp, args, tok, isSelector) { if (args.length == 0 || isSelector && args.length > 1) return false; var bs = new JU.BS (); var pattern = JS.SV.sValue (args[0]); if (pattern.length > 0) try { var bsSelected = (isSelector ? mp.getX ().value : args.length == 2 && args[1].tok == 10 ? args[1].value : null); bs = this.vwr.getSmilesMatcher ().getSubstructureSet (pattern, this.vwr.ms.at, this.vwr.ms.ac, bsSelected, (tok == 134218757 ? 1 : 2)); } catch (ex) { if (Clazz.exceptionOf (ex, Exception)) { this.e.evalError (ex.getMessage (), null); } else { throw ex; } } return mp.addXBs (bs); }, "JS.ScriptMathProcessor,~A,~N,~B"); Clazz.defineMethod (c$, "evaluateSymop", function (mp, args, haveBitSet) { var x1 = (haveBitSet ? mp.getX () : null); if (x1 != null && x1.tok != 10) return false; var bsAtoms = (x1 == null ? null : x1.value); if (bsAtoms == null && this.vwr.ms.mc == 1) bsAtoms = this.vwr.getModelUndeletedAtomsBitSet (0); var narg = args.length; if (narg == 0) { if (bsAtoms.isEmpty ()) return false; var ops = JU.PT.split (JU.PT.trim (this.vwr.getSymTemp ().getSpaceGroupInfo (this.vwr.ms, null, this.vwr.ms.at[bsAtoms.nextSetBit (0)].mi).get ("symmetryInfo"), "\n"), "\n"); var lst = new JU.Lst (); for (var i = 0, n = ops.length; i < n; i++) lst.addLast (JU.PT.split (ops[i], "\t")); return mp.addXList (lst); }var xyz = null; var iOp = -2147483648; var apt = 0; switch (args[0].tok) { case 4: xyz = JS.SV.sValue (args[0]); apt++; break; case 12: xyz = args[0].escape (); apt++; break; case 2: iOp = args[0].asInt (); apt++; break; } if (bsAtoms == null) { if (apt < narg && args[apt].tok == 10) (bsAtoms = new JU.BS ()).or (args[apt].value); if (apt + 1 < narg && args[apt + 1].tok == 10) (bsAtoms == null ? (bsAtoms = new JU.BS ()) : bsAtoms).or (args[apt + 1].value); }var pt1 = null; var pt2 = null; if ((pt1 = (narg > apt ? mp.ptValue (args[apt], bsAtoms) : null)) != null) apt++; if ((pt2 = (narg > apt ? mp.ptValue (args[apt], bsAtoms) : null)) != null) apt++; var nth = (pt2 != null && args.length > apt && iOp == -2147483648 && args[apt].tok == 2 ? args[apt].intValue : 0); if (nth > 0) apt++; if (iOp == -2147483648) iOp = 0; var desc = (narg == apt ? (pt2 != null ? "all" : pt1 != null ? "point" : "matrix") : JS.SV.sValue (args[apt++]).toLowerCase ()); return (bsAtoms != null && !bsAtoms.isEmpty () && apt == args.length && mp.addXObj (this.vwr.getSymTemp ().getSymmetryInfoAtom (this.vwr.ms, bsAtoms.nextSetBit (0), xyz, iOp, pt1, pt2, desc, 0, 0, nth))); }, "JS.ScriptMathProcessor,~A,~B"); Clazz.defineMethod (c$, "evaluateTensor", function (mp, args) { var x = mp.getX (); if (args.length > 2 || x.tok != 10) return false; var bs = x.value; var tensorType = (args.length == 0 ? null : JS.SV.sValue (args[0]).toLowerCase ()); var calc = this.vwr.getNMRCalculation (); if ("unique".equals (tensorType)) return mp.addXBs (calc.getUniqueTensorSet (bs)); var infoType = (args.length < 2 ? null : JS.SV.sValue (args[1]).toLowerCase ()); return mp.addXList (calc.getTensorInfo (tensorType, infoType, bs)); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateUserFunction", function (mp, name, args, tok, isSelector) { var x1 = null; if (isSelector) { x1 = mp.getX (); switch (x1.tok) { case 10: break; case 6: if (args.length > 0) return false; x1 = x1.getMap ().get (name); return (x1 == null ? mp.addXStr ("") : mp.addX (x1)); default: return false; } }name = name.toLowerCase (); mp.wasX = false; var params = new JU.Lst (); for (var i = 0; i < args.length; i++) { params.addLast (args[i]); } if (isSelector) { return mp.addXObj (this.e.getBitsetProperty (x1.value, tok, null, null, x1.value, Clazz.newArray (-1, [name, params]), false, x1.index, false)); }var $var = this.e.getUserFunctionResult (name, params, null); return ($var == null ? false : mp.addX ($var)); }, "JS.ScriptMathProcessor,~S,~A,~N,~B"); Clazz.defineMethod (c$, "evaluateWithin", function (mp, args) { if (args.length < 1 || args.length > 5) return false; var len = args.length; if (len == 1 && args[0].tok == 10) return mp.addX (args[0]); var distance = 0; var withinSpec = args[0].value; var withinStr = "" + withinSpec; var tok = args[0].tok; if (tok == 4) tok = JS.T.getTokFromName (withinStr); var ms = this.vwr.ms; var isVdw = false; var isWithinModelSet = false; var isWithinGroup = false; var isDistance = false; var rd = null; switch (tok) { case 1648363544: isVdw = true; withinSpec = null; case 3: case 2: isDistance = true; if (len < 2 || len == 3 && args[1].tok == 7 && args[2].tok != 7) return false; distance = (isVdw ? 100 : JS.SV.fValue (args[0])); switch (tok = args[1].tok) { case 1073742335: case 1073742334: isWithinModelSet = args[1].asBoolean (); if (len > 2 && JS.SV.sValue (args[2]).equalsIgnoreCase ("unitcell")) tok = 1814695966; len = 0; break; case 4: var s = JS.SV.sValue (args[1]); if (s.startsWith ("$")) return mp.addXBs (this.getAtomsNearSurface (distance, s.substring (1))); if (s.equalsIgnoreCase ("group")) { isWithinGroup = true; tok = 1086324742; } else if (s.equalsIgnoreCase ("vanderwaals") || s.equalsIgnoreCase ("vdw")) { withinSpec = null; isVdw = true; tok = 1648363544; } else if (s.equalsIgnoreCase ("unitcell")) { tok = 1814695966; } else { return false; }break; } break; case 7: if (len == 1) { withinSpec = args[0].asString (); tok = 0; }break; case 1073742328: return (len == 3 && Clazz.instanceOf (args[1].value, JU.BS) && Clazz.instanceOf (args[2].value, JU.BS) && mp.addXBs (this.vwr.getBranchBitSet ((args[2].value).nextSetBit (0), (args[1].value).nextSetBit (0), true))); case 134218757: case 1237320707: case 134218756: var bsSelected = null; var isOK = true; switch (len) { case 2: break; case 3: isOK = (args[2].tok == 10); if (isOK) bsSelected = args[2].value; break; default: isOK = false; } if (!isOK) this.e.invArg (); return mp.addXObj (this.e.getSmilesExt ().getSmilesMatches (JS.SV.sValue (args[1]), null, bsSelected, null, tok == 134218756 ? 2 : 1, mp.asBitSet, false)); } if (Clazz.instanceOf (withinSpec, String)) { if (tok == 0) { tok = 1073742362; if (len > 2) return false; len = 2; }} else if (!isDistance) { return false; }switch (len) { case 1: switch (tok) { case 136314895: case 2097184: case 1678381065: return mp.addXBs (ms.getAtoms (tok, null)); case 1073741863: return mp.addXBs (ms.getAtoms (tok, "")); case 1073742362: return mp.addXBs (ms.getAtoms (1086324744, withinStr)); } return false; case 2: switch (tok) { case 1073742362: tok = 1086324744; break; case 1073741824: case 1086326786: case 1086326785: case 1073741863: case 1086324744: case 1111490587: case 1073742128: case 1073741925: case 1073742189: return mp.addXBs (this.vwr.ms.getAtoms (tok, JS.SV.sValue (args[args.length - 1]))); } break; case 3: switch (tok) { case 1073742335: case 1073742334: case 1086324742: case 1648363544: case 1814695966: case 134217750: case 134219265: case 1073742329: case 8: case 7: break; case 1086324744: withinStr = JS.SV.sValue (args[2]); break; default: return false; } break; } var plane = null; var pt = null; var pts1 = null; var last = args.length - 1; switch (args[last].tok) { case 9: plane = args[last].value; break; case 8: pt = args[last].value; if (JS.SV.sValue (args[1]).equalsIgnoreCase ("hkl")) plane = this.e.getHklPlane (pt); break; case 7: pts1 = (last == 2 && args[1].tok == 7 ? args[1].getList () : null); pt = (last == 2 ? JS.SV.ptValue (args[1]) : last == 1 ? JU.P3.new3 (NaN, 0, 0) : null); break; } if (plane != null) return mp.addXBs (ms.getAtomsNearPlane (distance, plane)); var bs = (args[last].tok == 10 ? args[last].value : null); if (last > 0 && pt == null && pts1 == null && bs == null) return false; if (tok == 1814695966) { var asMap = isWithinModelSet; return ((bs != null || pt != null) && mp.addXObj (this.vwr.ms.getUnitCellPointsWithin (distance, bs, pt, asMap))); }if (pt != null || pts1 != null) { if (args[last].tok == 7) { var sv = args[last].getList (); var pts = new JU.Lst (); var bspt = new J.bspt.Bspt (3, 0); var iter; if (pt != null && Float.isNaN (pt.x)) { var p; var pt3 = new Array (sv.size ()); for (var i = pt3.length; --i >= 0; ) { var p3 = JS.SV.ptValue (sv.get (i)); if (p3 == null) return false; p = new JU.Point3fi (); p.setT (p3); p.i = i; pt3[i] = p; bspt.addTuple (p); } iter = bspt.allocateCubeIterator (); var bsp = JU.BSUtil.newBitSet2 (0, sv.size ()); for (var i = pt3.length; --i >= 0; ) { iter.initialize (p = pt3[i], distance, false); var d2 = distance * distance; var n = 0; while (iter.hasMoreElements ()) { var pt2 = iter.nextElement (); if (bsp.get (pt2.i) && pt2.distanceSquared (p) <= d2 && (++n > 1)) bsp.clear (pt2.i); } } for (var i = bsp.nextSetBit (0); i >= 0; i = bsp.nextSetBit (i + 1)) pts.addLast (JU.P3.newP (pt3[i])); return mp.addXList (pts); }if (distance == 0) { if (pts1 == null) { var d2 = 3.4028235E38; var pt3 = null; for (var i = sv.size (); --i >= 0; ) { var pta = JS.SV.ptValue (sv.get (i)); distance = pta.distanceSquared (pt); if (distance < d2) { pt3 = pta; d2 = distance; }} return (pt3 == null ? mp.addXStr ("") : mp.addXPt (pt3)); }var ptsOut = Clazz.newIntArray (pts1.size (), 0); for (var i = ptsOut.length; --i >= 0; ) { var d2 = 3.4028235E38; var imin = -1; pt = JS.SV.ptValue (pts1.get (i)); for (var j = sv.size (); --j >= 0; ) { var pta = JS.SV.ptValue (sv.get (j)); distance = pta.distanceSquared (pt); if (distance < d2) { imin = j; d2 = distance; }} ptsOut[i] = imin; } return mp.addXAI (ptsOut); }for (var i = sv.size (); --i >= 0; ) { var ptp = JS.SV.ptValue (sv.get (i)); bspt.addTuple (ptp); } iter = bspt.allocateCubeIterator (); iter.initialize (pt, distance, false); var d2 = distance * distance; while (iter.hasMoreElements ()) { var pt2 = iter.nextElement (); if (pt2.distanceSquared (pt) <= d2) pts.addLast (pt2); } iter.release (); return mp.addXList (pts); }return mp.addXBs (this.vwr.getAtomsNearPt (distance, pt)); }if (tok == 1086324744) return mp.addXBs (this.vwr.ms.getSequenceBits (withinStr, bs, new JU.BS ())); if (bs == null) bs = new JU.BS (); if (!isDistance) return mp.addXBs (this.vwr.ms.getAtoms (tok, bs)); if (isWithinGroup) return mp.addXBs (this.vwr.getGroupsWithin (Clazz.floatToInt (distance), bs)); if (isVdw) { rd = new J.atomdata.RadiusData (null, (distance > 10 ? distance / 100 : distance), (distance > 10 ? J.atomdata.RadiusData.EnumType.FACTOR : J.atomdata.RadiusData.EnumType.OFFSET), J.c.VDW.AUTO); if (distance < 0) distance = 0; }return mp.addXBs (this.vwr.ms.getAtomsWithinRadius (distance, bs, isWithinModelSet, rd)); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "evaluateWrite", function (mp, args) { switch (args.length) { case 0: return false; case 1: if (!args[0].asString ().toUpperCase ().equals ("PNGJ")) break; return mp.addXMap (this.vwr.fm.getFileAsMap (null)); } return mp.addXStr (this.e.getCmdExt ().dispatch (134221856, true, args)); }, "JS.ScriptMathProcessor,~A"); Clazz.defineMethod (c$, "getAtomsNearSurface", function (distance, surfaceId) { var data = Clazz.newArray (-1, [surfaceId, null, null]); if (this.e.getShapePropertyData (24, "getVertices", data)) return this.getAtomsNearPts (distance, data[1], data[2]); data[1] = Integer.$valueOf (0); data[2] = Integer.$valueOf (-1); if (this.e.getShapePropertyData (22, "getCenter", data)) return this.vwr.getAtomsNearPt (distance, data[2]); return new JU.BS (); }, "~N,~S"); Clazz.defineMethod (c$, "getAtomsNearPts", function (distance, points, bsInclude) { var bsResult = new JU.BS (); if (points.length == 0 || bsInclude != null && bsInclude.isEmpty ()) return bsResult; if (bsInclude == null) bsInclude = JU.BSUtil.setAll (points.length); var at = this.vwr.ms.at; for (var i = this.vwr.ms.ac; --i >= 0; ) { var atom = at[i]; for (var j = bsInclude.nextSetBit (0); j >= 0; j = bsInclude.nextSetBit (j + 1)) if (atom.distance (points[j]) < distance) { bsResult.set (i); break; } } return bsResult; }, "~N,~A,JU.BS"); Clazz.defineMethod (c$, "getMinMax", function (floatOrSVArray, tok) { var data = null; var sv = null; var ndata = 0; var htPivot = null; while (true) { if (JU.AU.isAF (floatOrSVArray)) { if (tok == 1140850707) return "NaN"; data = floatOrSVArray; ndata = data.length; if (ndata == 0) break; } else if (Clazz.instanceOf (floatOrSVArray, JU.Lst)) { sv = floatOrSVArray; ndata = sv.size (); if (ndata == 0) { if (tok != 1140850707) break; } else { var sv0 = sv.get (0); if (sv0.tok == 8) return this.getMinMaxPoint (sv, tok); if (sv0.tok == 4 && (sv0.value).startsWith ("{")) { var pt = JS.SV.ptValue (sv0); if (Clazz.instanceOf (pt, JU.P3)) return this.getMinMaxPoint (sv, tok); if (Clazz.instanceOf (pt, JU.P4)) return this.getMinMaxQuaternion (sv, tok); break; }}} else { break; }var sum; var minMax; var isMin = false; switch (tok) { case 1140850707: htPivot = new java.util.Hashtable (); sum = minMax = 0; break; case 32: isMin = true; sum = 3.4028235E38; minMax = 2147483647; break; case 64: sum = -3.4028235E38; minMax = -2147483647; break; default: sum = minMax = 0; } var sum2 = 0; var n = 0; var isInt = true; var isPivot = (tok == 1140850707); for (var i = ndata; --i >= 0; ) { var svi = (sv == null ? JS.SV.vF : sv.get (i)); var v = (isPivot ? 1 : data == null ? JS.SV.fValue (svi) : data[i]); if (Float.isNaN (v)) continue; n++; switch (tok) { case 160: case 192: sum2 += (v) * v; case 128: case 96: sum += v; break; case 1140850707: isInt = new Boolean (isInt & (svi.tok == 2)).valueOf (); var key = svi.asString (); var ii = htPivot.get (key); htPivot.put (key, (ii == null ? new Integer (1) : new Integer (ii.intValue () + 1))); break; case 32: case 64: isInt = new Boolean (isInt & (svi.tok == 2)).valueOf (); if (isMin == (v < sum)) { sum = v; if (isInt) minMax = svi.intValue; }break; } } if (tok == 1140850707) { return htPivot; }if (n == 0) break; switch (tok) { case 96: sum /= n; break; case 192: if (n == 1) break; sum = Math.sqrt ((sum2 - sum * sum / n) / (n - 1)); break; case 32: case 64: if (isInt) return Integer.$valueOf (minMax); break; case 128: break; case 160: sum = sum2; break; } return Float.$valueOf (sum); } return "NaN"; }, "~O,~N"); Clazz.defineMethod (c$, "getMinMaxPoint", function (pointOrSVArray, tok) { var data = null; var sv = null; var ndata = 0; if (Clazz.instanceOf (pointOrSVArray, Array)) { data = pointOrSVArray; ndata = data.length; } else if (Clazz.instanceOf (pointOrSVArray, JU.Lst)) { sv = pointOrSVArray; ndata = sv.size (); }if (sv == null && data == null) return "NaN"; var result = new JU.P3 (); var fdata = Clazz.newFloatArray (ndata, 0); for (var xyz = 0; xyz < 3; xyz++) { for (var i = 0; i < ndata; i++) { var pt = (data == null ? JS.SV.ptValue (sv.get (i)) : data[i]); if (pt == null) return "NaN"; switch (xyz) { case 0: fdata[i] = pt.x; break; case 1: fdata[i] = pt.y; break; case 2: fdata[i] = pt.z; break; } } var f = this.getMinMax (fdata, tok); if (!(Clazz.instanceOf (f, Number))) return "NaN"; var value = (f).floatValue (); switch (xyz) { case 0: result.x = value; break; case 1: result.y = value; break; case 2: result.z = value; break; } } return result; }, "~O,~N"); Clazz.defineMethod (c$, "getMinMaxQuaternion", function (svData, tok) { var data; switch (tok) { case 32: case 64: case 128: case 160: return "NaN"; } while (true) { data = this.e.getQuaternionArray (svData, 1073742001); if (data == null) break; var retStddev = Clazz.newFloatArray (1, 0); var result = JU.Quat.sphereMean (data, retStddev, 0.0001); switch (tok) { case 96: return result; case 192: return Float.$valueOf (retStddev[0]); } break; } return "NaN"; }, "JU.Lst,~N"); Clazz.defineMethod (c$, "getPatternMatcher", function () { return (this.pm == null ? this.pm = J.api.Interface.getUtil ("PatternMatcher", this.e.vwr, "script") : this.pm); }); Clazz.defineMethod (c$, "opTokenFor", function (tok) { switch (tok) { case 1275069441: case 1275069446: return JS.T.tokenPlus; case 1275068931: return JS.T.tokenMinus; case 1275068929: return JS.T.tokenTimes; case 1275068930: return JS.T.tokenMul3; case 1275068928: return JS.T.tokenDivide; } return null; }, "~N"); Clazz.defineMethod (c$, "setContactBitSets", function (bsA, bsB, localOnly, distance, rd, warnMultiModel) { var withinAllModels; var bs; if (bsB == null) { bsB = JU.BSUtil.setAll (this.vwr.ms.ac); JU.BSUtil.andNot (bsB, this.vwr.slm.bsDeleted); bsB.andNot (bsA); withinAllModels = false; } else { bs = JU.BSUtil.copy (bsA); bs.or (bsB); var nModels = this.vwr.ms.getModelBS (bs, false).cardinality (); withinAllModels = (nModels > 1); if (warnMultiModel && nModels > 1 && !this.e.tQuiet) this.e.showString (J.i18n.GT._ ("Note: More than one model is involved in this contact!")); }if (!bsA.equals (bsB)) { var setBfirst = (!localOnly || bsA.cardinality () < bsB.cardinality ()); if (setBfirst) { bs = this.vwr.ms.getAtomsWithinRadius (distance, bsA, withinAllModels, (Float.isNaN (distance) ? rd : null)); bsB.and (bs); }if (localOnly) { bs = this.vwr.ms.getAtomsWithinRadius (distance, bsB, withinAllModels, (Float.isNaN (distance) ? rd : null)); bsA.and (bs); if (!setBfirst) { bs = this.vwr.ms.getAtomsWithinRadius (distance, bsA, withinAllModels, (Float.isNaN (distance) ? rd : null)); bsB.and (bs); }bs = JU.BSUtil.copy (bsB); bs.and (bsA); if (bs.equals (bsA)) bsB.andNot (bsA); else if (bs.equals (bsB)) bsA.andNot (bsB); }}return bsB; }, "JU.BS,JU.BS,~B,~N,J.atomdata.RadiusData,~B"); });
let { cd, exec, echo, touch } = require('shelljs') let { readFileSync } = require('fs') let url = require('url') let repoUrl let pkg = JSON.parse(readFileSync('package.json')) if (typeof pkg.repository === 'object') { if (!pkg.repository.hasOwnProperty('url')) { throw new Error("URL does not exist in repository section") } repoUrl = pkg.repository.url } else { repoUrl = pkg.repository } let parsedUrl = url.parse(repoUrl) let repository = parsedUrl.host + parsedUrl.path; let ghToken = process.env.GH_TOKEN echo('Deploying docs!!!') cd('doc') touch('.nojekyll') exec('git init') exec('git add .') exec('git commit -m "docs(docs): update gh-pages"') exec(`git push --force --quiet "https://${ghToken}@${repository}" master:gh-pages`) echo('Docs deployed!!')
/** * @copyright Copyright 2021 Kevin Locke <kevin@kevinlocke.name> * @license MIT * * Package-private symbols. * This file is intentionally excluded from package.json#exports. */ /** Symbol of mock function used in place of modulename for testing. * * @private */ // eslint-disable-next-line import/prefer-default-export export const modulenameMockSymbol = Symbol('modulenameMock');
var w = $.ergo({ etype: 'box', // за счет иерархического связывания оба дочерних виджета будут // иметь один и тот же источник данных data: new Ergo.core.DataSource(''), // задаем отступы для дочерних элементов defaultItem: { style: {'margin-right': 20} }, items: [{ etype: 'html:input', events: { 'dom:input': 'input' // обновляем значение по событию `input` } }, { etype: 'text', $title: { etype: 'html:b', text: 'Данные: ' }, $content: { etype: '.', binding: 'prop:text' } }] }); $context.alert('Введенный текст изменяет содержимое источника данных, который обновляет текст другого связанного с ним виджета.'); w.render('#sample');
var searchData= [ ['secure_5fboot_5fconfig_5fdisable',['SECURE_BOOT_CONFIG_DISABLE',['../a00026.html#abda1d3106b26d6e32fddd71223ecb491',1,'secure_boot.h']]], ['secure_5fboot_5fconfig_5ffull_5fboth',['SECURE_BOOT_CONFIG_FULL_BOTH',['../a00026.html#a5aae2464eb2bb84cec34bfd422697a27',1,'secure_boot.h']]], ['secure_5fboot_5fconfig_5ffull_5fdig',['SECURE_BOOT_CONFIG_FULL_DIG',['../a00026.html#a61ab82e3ca8c3f985cfc8b1a06daaced',1,'secure_boot.h']]], ['secure_5fboot_5fconfig_5ffull_5fsign',['SECURE_BOOT_CONFIG_FULL_SIGN',['../a00026.html#a3eef897b793c9ff7430c09d88bd8bac0',1,'secure_boot.h']]], ['secure_5fboot_5fconfiguration',['SECURE_BOOT_CONFIGURATION',['../a00026.html#a93cbf6aee50e7449217cf18f2ebfc690',1,'secure_boot.h']]], ['secure_5fboot_5fdigest_5fencrypt_5fenabled',['SECURE_BOOT_DIGEST_ENCRYPT_ENABLED',['../a00026.html#aad47571829afb2de827111c11df184de',1,'secure_boot.h']]], ['secure_5fboot_5fpublic_5fkey_5fslot',['SECURE_BOOT_PUBLIC_KEY_SLOT',['../a00017.html#a0bb2754dfd3576e2db410a717cfefc98',1,'crypto_device_app.h']]], ['secure_5fboot_5fsign_5fdigest_5fslot',['SECURE_BOOT_SIGN_DIGEST_SLOT',['../a00017.html#ad3e25c542063abb044288e338e0df87a',1,'crypto_device_app.h']]], ['secure_5fboot_5fupgrade_5fsupport',['SECURE_BOOT_UPGRADE_SUPPORT',['../a00026.html#a07cf8cf7a12bb9592fff7a31a369c1a5',1,'secure_boot.h']]], ['sha256_5fblock_5fsize',['SHA256_BLOCK_SIZE',['../a00296.html#a9c1fe69ad43d4ca74b84303a0ed64f2f',1,'sha2_routines.h']]], ['sha256_5fdigest_5fsize',['SHA256_DIGEST_SIZE',['../a00296.html#a81efbc0fc101b06a914f7ff9e2fbc0e9',1,'sha2_routines.h']]], ['sign_5fcount',['SIGN_COUNT',['../a00101.html#aabff3f5b7f5391c27a0329ff0c997264',1,'atca_command.h']]], ['sign_5fkeyid_5fidx',['SIGN_KEYID_IDX',['../a00101.html#a02f20fbee84fe680d94b94a2b2828040',1,'atca_command.h']]], ['sign_5fmode_5fexternal',['SIGN_MODE_EXTERNAL',['../a00101.html#a9b6844bb107f02832a6d827b8c5b0fda',1,'atca_command.h']]], ['sign_5fmode_5fidx',['SIGN_MODE_IDX',['../a00101.html#ae7cfb9eb789137f5ea9195a7a4f6b11e',1,'atca_command.h']]], ['sign_5fmode_5finclude_5fsn',['SIGN_MODE_INCLUDE_SN',['../a00101.html#a71b7f8f45dbbe8c19c0e5c6c41fcf116',1,'atca_command.h']]], ['sign_5fmode_5finternal',['SIGN_MODE_INTERNAL',['../a00101.html#aced5221c0f15440eb52fa9f460956443',1,'atca_command.h']]], ['sign_5fmode_5finvalidate',['SIGN_MODE_INVALIDATE',['../a00101.html#a1acc7b9af9cf3c6c556bd910ce4f239b',1,'atca_command.h']]], ['sign_5fmode_5fmask',['SIGN_MODE_MASK',['../a00101.html#a88cc1851cedb6f2a73df4618dbc0b165',1,'atca_command.h']]], ['sign_5fmode_5fsource_5fmask',['SIGN_MODE_SOURCE_MASK',['../a00101.html#a35246a9bad0d77d26b59b542928c9e34',1,'atca_command.h']]], ['sign_5fmode_5fsource_5fmsgdigbuf',['SIGN_MODE_SOURCE_MSGDIGBUF',['../a00101.html#a1a38e9575eb4f714377889ce5270e60b',1,'atca_command.h']]], ['sign_5fmode_5fsource_5ftempkey',['SIGN_MODE_SOURCE_TEMPKEY',['../a00101.html#a73670681360e1272aa13d1359e7bb275',1,'atca_command.h']]], ['sign_5frsp_5fsize',['SIGN_RSP_SIZE',['../a00101.html#a66dba5e06f73c5df37c9d18409185f4d',1,'atca_command.h']]], ['start_5fpulse_5ftime_5fout',['START_PULSE_TIME_OUT',['../a00485.html#ab10604796b42fb6b8eed23fc88ebd47f',1,'swi_bitbang_samd21.h']]], ['strcpy_5fp',['strcpy_P',['../a00290.html#a3541bc4d0b928b2faa9ca63a100d1b75',1,'sha1_routines.h']]] ];
import mongoose from 'mongoose'; import Role from '../models/Role'; import Resource from '../models/Resource'; import { roles, resources, permissions } from '../constants' const PermissionSchema = new mongoose.Schema({ role: { type: String, required: true }, resource: { type: String, required: true }, create: { type: Boolean, required: true, default: false }, read: { type: Boolean, required: true, default: true }, write: { type: Boolean, required: true, default: false }, delete: { type: Boolean, required: true, default: false } }); const Permission = mongoose.model('Permission', PermissionSchema); async function initializePermissions() { const userRoles = { creator: await Role.findOne({ title: roles.creator }).select('_id'), participant: await Role.findOne({ title: roles.participant }).select('_id'), viewer: await Role.findOne({ title: roles.viewer }).select('_id'), }; const userResources = { chat: await Resource.findOne({ title: resources.chat }).select('_id'), }; const userPermissions = { [userResources.chat._id]: [ { role: userRoles.creator._id, create: true, read: true, write: true, delete: true }, { role: userRoles.participant._id, create: false, read: true, write: true, delete: false }, { role: userRoles.viewer._id, create: false, read: true, write: false, delete: false } ] }; for (const prop in userPermissions) { if (userPermissions.hasOwnProperty(prop)) { userPermissions[prop].forEach(permission => { const permissionObj = { ...permission, resource: prop}; const options = { upsert: true }; Permission.findOneAndUpdate(permissionObj, permissionObj, options, err => { err && console.log(`Permissions initialization failed: ${err}`); }); }); } } } initializePermissions(); export default Permission;
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M20 15.51c-1.24 0-2.45-.2-3.57-.57-.1-.04-.21-.05-.31-.05-.26 0-.51.1-.71.29l-2.2 2.2c-2.83-1.45-5.15-3.76-6.59-6.59l2.2-2.2c.28-.28.36-.67.25-1.02C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.49c0-.55-.45-1-1-1zM5.03 5h1.5c.07.89.22 1.76.46 2.59l-1.2 1.2c-.41-1.2-.67-2.47-.76-3.79zM19 18.97c-1.32-.09-2.59-.35-3.8-.75l1.19-1.19c.85.24 1.72.39 2.6.45v1.49z" /><path d="M22 4.95C21.79 4.78 19.67 3 16.5 3c-3.18 0-5.29 1.78-5.5 1.95L16.5 12 22 4.95z" /></React.Fragment> , 'WifiCallingOutlined');
import React from 'react' import PropTypes from 'prop-types' import { Form, Button, Row, Col, Icon } from 'antd' import SearchGroup from 'components/Search' const Search = ({ field, keyword, addPower, onSearch, onAdd, }) => { const searchGroupProps = { field, keyword, size: 'large', select: true, selectOptions: [{ value: 'name', name: '用户名' }, { value: 'mobile', name: '手机号' }, { value: 'email', name: '邮箱' }], selectProps: { defaultValue: field || 'name', }, onSearch: (value) => { onSearch(value) }, } return ( <Row gutter={24}> <Col lg={8} md={12} sm={16} xs={24} style={{ marginBottom: 16 }}> <SearchGroup {...searchGroupProps} /> </Col> {addPower && <Col lg={{ offset: 8, span: 8 }} md={12} sm={8} xs={24} style={{ marginBottom: 16, textAlign: 'right' }}> <Button size="large" type="ghost" onClick={onAdd}><Icon type="plus-circle-o" />添加</Button> </Col>} </Row> ) } Search.propTypes = { form: PropTypes.object.isRequired, onSearch: PropTypes.func, onAdd: PropTypes.func, field: PropTypes.string, keyword: PropTypes.string, addPower: PropTypes.bool.isRequired, } export default Form.create()(Search)
function connectToNotifServer(){ var conn = new WebSocket('ws://localhost:8080'); conn.onopen = function(e) { console.log("Connection established!"); conn.send(JSON.stringify({user_hash: sessionStorage.getItem("user_hash"),message:"INIT_MESSAGE"})); }; conn.onclose = function(e) { console.log("Connection closed!"); }; return conn; } function registerNotification(conn,to,msg){ console.log("to: "+to+" msg:"+msg); conn.send(JSON.stringify({user_hash: sessionStorage.getItem("user_hash"),target_hash:to,message:msg})); }
function lensesRoutes($stateProvider) { 'use strict'; var lenses = { name: 'lenses', abstract: 'true', url: '/lenses', template: '<div ui-view></div>', data: { moduleClasses: 'lens', pageClasses: 'lenses', pageTitle: 'Lenses', pageDescription: 'Some description.' } }; var search = { name: 'lenses.search', url: '/:lens?q&f&s', template: '<div lenses-search-view></div>', data: { moduleClasses: 'lens', pageClasses: 'lenses', pageTitle: 'Search', pageDescription: 'Some description.' } }; var edit = { name: 'lenses.edit', url: '/:lens/edit/:record', template: '<div lenses-edit-view></div>', data: { moduleClasses: 'lens', pageClasses: 'lenses', pageTitle: 'Edit', pageDescription: 'Some description.' } }; $stateProvider.state(lenses); $stateProvider.state(search); $stateProvider.state(edit); } lensesRoutes.$inject = ['$stateProvider']; module.exports = lensesRoutes;
import React from 'react'; import { useForm, usePage } from '@inertiajs/inertia-react'; import Layout from '../../components/Layout'; import { route } from '../../../helpers/url'; import NoteCard from '../../../components/Card/NoteCard'; import FileUploadField from '../../components/Form/FileUploadField'; import FlashMessage from '../../components/FlashMessage/FlashMessage'; const Create = () => { const { flash } = usePage().props; const { clearErrors, data, errors, post, progress, reset, setData } = useForm( { file: null, }, ); function handleSubmit(event) { event.preventDefault(); post(route('admin.imports.mute-promotions.store'), { onSuccess: () => reset(), }); } return ( <div className="base-12-grid mx-auto pt-8 pb-12 relative"> <FlashMessage messages={flash} /> <h1 className="col-span-full mb-10 text-purple-500 text-base uppercase"> Mute Promotions </h1> <h2 className="col-span-full font-bold mb-10 text-black text-xl"> Create Import </h2> <div className="col-span-full max-chars mb-10"> <p> Use the following form to upload a .CSV (comma separated value) or .TXT file with a list of users who no longer want to receive promotional messaging from DoSomething. </p> </div> <form className="col-span-full" onSubmit={handleSubmit}> <FileUploadField accept=".csv,.txt" className="max-w-2xl" clearErrors={clearErrors} file={data.file} error={errors.file} id="file" progress={progress} setData={setData} /> <button className="bg-blurple-500 hover:bg-blurple-300 mt-4 px-6 py-4 rounded text-white" type="submit" > Create Request </button> </form> <NoteCard className="bg-gray-200 col-span-full col-start-1 max-w-screen-md mt-20 italic" type="information" > <> <p> Submitting the form creates a request to the system to initiate a task that updates each user in the provided CSV and sets a value for their <code className="text-orange-800">mute_promotions_at</code>{' '} field. </p> <p className="mt-4"> When this field is updated for a user, it will trigger a further request to our third-party messaging service, Customer.io, to delete the user's profile from their system, essentially muting all promotional messaging. </p> </> </NoteCard> </div> ); }; Create.layout = page => ( <Layout children={page} title="Create Mute Promotions Import" /> ); export default Create;
/* globals define */ define(function () { 'use strict'; return function arrayOf(itemCount, itemCallback) { var result = []; for (var i = 0; i < itemCount; i += 1) { result[i] = itemCallback(i); } return result; }; });
define([ "lib/Class" ],function( Class ){ var TextureObject = Class( Object, function( cls, parent ){ cls.constructor = function( width, height ){ parent.constructor.apply(this,arguments); this._id; this._width = width; this._height = height; // TODO 必要? unitに対してobjectをバインドするタイミングでのみ使用したほうがいいのか? gl.activeTexture( gl.TEXTURE0 ); // initialize { // オブジェクトを生成 this._id = gl.createTexture(); checkGlError("gl.createTexture"); var bs = BindScope(this); // 拡縮時描画設定 default gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); checkGlError("gl.texParameterf"); gl.texParameterf(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); checkGlError("gl.texParameterf"); // テクスチャー範囲外描画設定 gl.texParameterf( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE ); checkGlError("gl.texParameterf"); gl.texParameterf( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE ); checkGlError("gl.texParameterf"); // 空の画像データをオブジェクトへ登録 TODO NULLは初期化Dataとして正しくない? gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); // string key( StringUtil::itos(width).append("_").append( StringUtil::itos(height) ) ); // void* initialData = initialDataDict[key]; // if( initialData == NULL ) { // initialData = malloc( 4 * width * height ); // memset( initialData, 0x00, width * 4 * height );// fill // initialDataDict[key] = initialData; // } // gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, initialData ); checkGlError("gl.texImage2D"); bs.unbind(); } TextureObject.put(this); }; cls.getId = function(){ return this._id; }; cls.getWidth = function(){ return this._width; }; cls.getHeight = function(){ return this._height; }; /** * @deprecated */ cls.bind = function(){ // __sw("TextureObject::bind"); if( bindedId == this._id ) return; gl.bindTexture( gl.TEXTURE_2D, this._id ); checkGlError("glBindTexture"); bindedId = this._id; }; /** * @deprecated */ cls.unbind = function(){}; /** * * @param {Number} offsetX * @param {Number} offsetY * @param {*} widthOrObject * @param {Number} [height] * @param {ArrayBufferView} [data] */ cls.subImage2D = function( offsetX, offsetY, widthOrObject, height, data ){ var argLen = arguments.length; var bs = BindScope(this); if( argLen>3 ) gl.texSubImage2D( gl.TEXTURE_2D, 0, offsetX, offsetY, widthOrObject, height, gl.RGBA, gl.UNSIGNED_BYTE, data ); else gl.texSubImage2D( gl.TEXTURE_2D, 0, offsetX, offsetY, gl.RGBA, gl.UNSIGNED_BYTE, widthOrObject ); checkGlError("glTexSubImage2D"); bs.unbind(); }; } ); var bindedId; var BindStack = new (function(){ var stack = []; this.push = function( val ){ stack.push(val); val.bind(); }; this.pop = function(){ stack.pop(); if(stack.length>0)stack[stack.length-1].bind(); }; }); var scope = { unbind:function(){ BindStack.pop(); } }; var BindScope = TextureObject.BindScope = function( viewport ){ BindStack.push(viewport); return scope; }; TextureObject._list = []; TextureObject.getById = function( id ) { var len = this._list.length; for( var i = 0; i < len; i++ ) if( this._list[i].getId() == id ) return this._list[i]; return null; } TextureObject.put = function( obj ) { this._list.push(obj); } TextureObject.release = function( obj ) { var len = this._list.length; for( var i = 0; i < len; i++ ){ if( this._list[i] == obj ) { this._list.splice( i, 1 ); return; } } } return TextureObject; });
define({ "hello": "world" }); // this should take presedence than anonymous definitions define("tests/js/multipleDefine", { "another": "world" });
/* ** Enable array 'style' allocation ** Slightly less messy than spreading inline in the render */ export const assignStyles = styles => { let mergeStyles = {}; styles.forEach(styleObject => { mergeStyles = { ...mergeStyles, ...styleObject }; }); return mergeStyles; };
version https://git-lfs.github.com/spec/v1 oid sha256:b23958a3f77dc54d0e7728bf720e1df33e16550176d5b87effd5a35a102a58fa size 102522
'use strict'; // core var path = require('path'); // npm var async = require('async'); var cheerio = require('cheerio'); var mongoose = require('mongoose'); var request = require('request'); // wuw var utils = require('./wuw_utils'); // how many days should we parse? var daysToParse = process.env.WUWDAYS || 21; // mongodb var mongohost='localhost:27017'; var mongodb=process.env.WUWDB || 'wuw'; var mongoConnection='mongodb://' + mongohost + '/' + mongodb; // running as module or standalone? var standalone = !module.parent; var scriptName = path.basename(module.filename, path.extname(module.filename)); // parsing var parse = function(html, cb) { // create models from our schemas var Lecture = require('./models/model_lecture'); // init cheerio with our html var $ = cheerio.load(html); // get date for this day var curDate = $('h2').text().split(', ')[1]; if(curDate) { var curDateArr = curDate.split('.'); var intDate = curDateArr[1] + '/' + curDateArr[0] + '/' + curDateArr[2]; } // parse each single lecture async.each($('tr').not(':first-child'), function(lectureLine, trcb) { // prepare docents var docents = []; $(lectureLine).children().eq(7).text().trim().split(' , ').forEach(function(docent){ if(docent !== '') { docents.push(docent.replace(/.*Professor/g, '').replace(/ */g, '')); } }); // prepare group & room (not really needed but more readable) var group = $(lectureLine).children().eq(6).text().trim(); var room = $(lectureLine).children().eq(5).text().trim(); // create Lecture from our Model var Lec = new Lecture(); // set attributes Lec.lectureName = $(lectureLine).children().eq(3).text().trim(); Lec.startTime = new Date(intDate + ' ' + $(lectureLine).children().eq(0).text().trim()); Lec.endTime = new Date(intDate + ' ' + $(lectureLine).children().eq(1).text().trim()); Lec.docents = docents; Lec.hashCode = utils.hashCode(Lec.lectureName+curDate+Lec.startTime); Lec._id = mongoose.Types.ObjectId(Lec.hashCode); // create an object from our document var upsertData = Lec.toObject(); // delete attributes to upsert delete upsertData.rooms; delete upsertData.groups; // lectures without a group/room are useless... if(group !== '' && room !== '') { // save lecture to db & call callback Lecture.update({ _id: Lec.id }, { $set: upsertData, $addToSet: { rooms: room, groups: group } }, { upsert: true }, trcb); } else { trcb(); } }, function() { // day done cb(); }); }; // create urls including the date which we want to parse var createUrls = function() { var urls = []; for(var i = 0; i < daysToParse; i++) { // get date to parse var today = new Date(); today.setDate(today.getDate() + i); // assemble datestring & url var currDay = today.getDate() + '.' + (today.getMonth()+1) + '.' + today.getFullYear(); var url = 'https://lsf.hft-stuttgart.de/qisserver/rds?state=currentLectures&type=0&next=CurrentLectures.vm&nextdir=ressourcenManager&navigationPosition=lectures&currentLectures&breadcrumb=currentLectures&topitem=lectures&subitem=currentLectures&P.Print=&&HISCalendar_Date=' + currDay + '&asi='; urls.push(url); } return urls; }; var startParser = function() { // connect to mongodb (if not already) if(mongoose.connection.readyState === 0) { mongoose.connect(mongoConnection); } // create model from our schema (needed for drop) var Lecture = require('./models/model_lecture'); // create the urls to parse var urls = createUrls(); // get current datetime var today = new Date(); console.log('[' + today + '] ' + scriptName + ': started with { daysToParse: ' + daysToParse + ' }'); // simple progress display if run as standalone if (standalone) { process.stdout.write(' '); } // remove upcoming lectures (and get fresh data) Lecture.remove({ startTime: {'$gte': today} }, function (err) { if(err) { console.log(err); } // parse every url (rate-limited, dont fuck the lsf) async.eachLimit(urls, 5, function(url, cb) { // fetch the data request(url, function(error, response, html) { if(!error) { // parse html with all lectures for choosen date parse(html, function() { // simple progress display if run as standalone if (standalone) { process.stdout.write(' *'); } cb(); }); } }); }, function() { // disconnect mongodb if run as standalone if (standalone) { process.stdout.write('\n'); mongoose.disconnect(); } console.log('[' + (new Date()) + '] ' + scriptName + ': completed successfully'); }); }); }; // immediately start parsing if run as standalone if (standalone) { startParser(); } module.exports = { startParser: startParser, parse: parse };
var Ext = window.Ext4 || window.Ext; var __map = function (mapField, records) { var map = {}; Ext.Array.each(records, function (record) { if (record.raw) { map[record.raw[mapField]] = record.raw; } else { map[record[mapField]] = record; } }); return map; }; var __sortByDate = function (dateField, outField, map) { var arr = Ext.Object.getValues(map); var sorted = []; //console.log('__sortByDate:arr', arr); arr.sort(function (a, b) { var da = Rally.util.DateTime.fromIsoString(a[dateField]); var db = Rally.util.DateTime.fromIsoString(b[dateField]); return Rally.util.DateTime.getDifference(da, db, 'day'); }); Ext.Array.each(arr, function (rec) { sorted.push(rec[outField]); }); return sorted; }; var __sumArray = function (arr, selectorFn) { var count = 0; Ext.Array.each(arr, function (item) { var num = parseInt(selectorFn(item) + '', 10); if (!isNaN(num)) { count = count + num; } }); return count; }; Ext.define('IterationBreakdownCalculator', { extend: 'Rally.data.lookback.calculator.BaseCalculator', _mapReleasesByName: Ext.bind(__map, this, ['Name'], 0), _sortReleasesByStartDate: Ext.bind(__sortByDate, this, ['ReleaseStartDate', 'Name'], 0), _mapIterationsByName: Ext.bind(__map, this, ['Name'], 0), _sortIterationsByStartDate: Ext.bind(__sortByDate, this, ['StartDate', 'Name'], 0), _sumArrayByPlanEstimate: Ext.bind(__sumArray, this, [function (item) { return item.PlanEstimate || '0'; }], 1), prepareChartData: function (stores) { var snapshots = []; Ext.Array.each(stores, function (store) { store.each(function (record) { snapshots.push(record.raw); }); }); return this.runCalculation(snapshots); }, _bucketArtifactsIntoIterations: function (records) { var me = this; var rawData = {}; Ext.Array.each(records, function (record) { if (record._type.toLowerCase().indexOf('iteration') !== -1) { return; } var key = me._getBucketKey(record); rawData[key] = me._pushRecord(rawData[key], record); }); return rawData; }, _bucketStoriesIntoReleases: function (records) { var bucket = {}; Ext.Array.each(records, function (record) { if (record._type.toLowerCase().indexOf('portfolioitem') !== -1) { return; } if (record._type.toLowerCase().indexOf('iteration') !== -1) { return; } if (!record.Release) { return; } bucket[record.Release.Name] = bucket[record.Release.Name] || []; bucket[record.Release.Name].push(record); }); return bucket; }, _isIterationInRelease: function (iteration, release) { var iStart = Rally.util.DateTime.fromIsoString(iteration.StartDate); var rStart = Rally.util.DateTime.fromIsoString(release.ReleaseStartDate); var rEnd = Rally.util.DateTime.fromIsoString(release.ReleaseDate); return !!((Rally.util.DateTime.getDifference(iStart, rStart, 'day') >= 0) && (Rally.util.DateTime.getDifference(rEnd, iStart, 'day') >= 1)); }, _getIterations: function (records) { var iterations = []; Ext.Array.each(records, function (record) { if (record._type.toLowerCase() !== 'iteration') { return; } iterations.push(record); }); return iterations; }, _getBucketKey: function (record) { return this._getIterationKey(record.Iteration); }, _getIterationKey: function (iteration) { var rawDate = Rally.util.DateTime.fromIsoString(iteration.EndDate); var timezone = Rally.util.DateTime.parseTimezoneOffset(iteration.EndDate); var localDate = Rally.util.DateTime.add(rawDate, 'minute', timezone * -1); var date = Rally.util.DateTime.formatWithDefault(localDate); return iteration.Name + '<br>' + date; }, _sumIterationByField: function (stories, field, values, noValueLabel) { var sum = {}; var pe; var v; Ext.Array.each(values, function (value) { sum[value] = 0; }); Ext.Array.each(stories, function (story) { pe = parseInt('' + story.PlanEstimate, 10); v = story[field] || noValueLabel; if (Ext.isObject(v)) { console.log(v); } if (pe && !isNaN(pe)) { sum[v] = sum[v] + story.PlanEstimate; } }); return sum; }, _pushRecord: function (arr, itm) { if (!Ext.isArray(arr)) { return [itm]; } else { return arr.concat([itm]); } }, runCalculation: function (records) { //console.log('Running Calculations'); //console.dir(records); var me = this; me.iterations = me._getIterations(records); var iterationMap = me._mapIterationsByName(me.iterations); var iterationOrder = me._sortIterationsByStartDate(iterationMap); var rawData = me._bucketArtifactsIntoIterations(records); var iterationData = {}; var categories; var series = []; Ext.Array.each(iterationOrder, function (iteration) { var key = me._getIterationKey(iterationMap[iteration]); iterationData[key] = me._sumIterationByField(rawData[key], me.field, me.values, me.noValueLabel); }); Ext.Array.each(me.values, function (value) { var v = value || me.noValueLabel; var data = []; Ext.Array.each(iterationOrder, function (iteration) { var key = me._getIterationKey(iterationMap[iteration]); data.push(iterationData[key][v] || 0); }); var label = Ext.Array.map(v.split('_'), function (word) { return Ext.String.capitalize(word.toLowerCase()); }).join(' '); series.push({ type: 'column', name: label, data: data }); }); categories = []; Ext.Array.each(iterationOrder, function (iName) { categories.push(me._getIterationKey(iterationMap[iName])); }); //debugger; return { categories: categories, series: series }; }, });